From 9481146bced8b5ade6880923f92ea8cd91da1f5f Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 22 Sep 2026 02:51:21 +0200 Subject: [PATCH] fix: model influx as external adjudication --- AGENTS-TASKS.md | 19 +- docs/README.md | 2 +- docs/issue-audit.md | 4 +- docs/resolution-conflict-design.md | 199 +++++---- docs/roadmap.md | 5 +- lib_efo/assets/simulation/README.md | 16 +- lib_efo/assets/simulation/default.json | 34 +- lib_efo/src/adjudication.rs | 467 +++++++++++++++++++++ lib_efo/src/influx.rs | 543 ------------------------- lib_efo/src/lib.rs | 2 +- lib_efo/tests/adjudication.rs | 115 ++++++ lib_efo/tests/influx.rs | 272 ------------- 12 files changed, 710 insertions(+), 968 deletions(-) create mode 100644 lib_efo/src/adjudication.rs delete mode 100644 lib_efo/src/influx.rs create mode 100644 lib_efo/tests/adjudication.rs delete mode 100644 lib_efo/tests/influx.rs diff --git a/AGENTS-TASKS.md b/AGENTS-TASKS.md index c51a39d..0eeffba 100644 --- a/AGENTS-TASKS.md +++ b/AGENTS-TASKS.md @@ -226,14 +226,17 @@ and [`docs/presentation-design.md`](docs/presentation-design.md). - [x] Approve the shared prework contract in `docs/resolution-conflict-design.md`. -- [x] Add a separately versioned, embedded `SimulationConfig` with strict +- [x] Add a separately versioned, embedded `AdjudicationConfig` with strict validation, external replacement, safety limits, and release packaging. -- [x] Implement all six stable `InfluxLevel` values, configured pressure bands, - deterministic target sub-seeds, resistance, attenuation, and typed reports. -- [ ] Persist idempotent, stale-state-checked resolution records with workspace +- [x] Correct the original influx assumption: an adjudication records a + player-made external roll plus the master's level, disposition, explanation, + and explicit effects; Epoch Forge never rolls or invents an effect. +- [x] Implement all six stable master-assigned levels, explicit effects, + disposition-controlled attenuation, clamping, and stale-checkable reports. +- [ ] Persist idempotent, stale-state-checked adjudication records with workspace and historical `fsck` validation. -- [ ] Add preview/apply/show/clear influx commands plus the documented `roll` - compatibility alias and complete help examples. +- [ ] Add preview/apply/show/clear `adjudicate` commands plus the familiar + `influx` alias and complete help examples. - [ ] Resolve diffusion arrivals against protected towns and configured blockers, explaining avoided/dampened/destroyed outcomes. - [ ] Resolve resident and positioned characters deterministically; document @@ -242,8 +245,8 @@ and [`docs/presentation-design.md`](docs/presentation-design.md). fight/war round resolution, victory, stalemate, and explicit ending. - [ ] Add conflict commands and focused fight/war aliases with preview-first, worktree-only application and restore/stage/commit/revert coverage. -- [ ] Cover every influx boundary and outcome, shuffled insertion order, - replay, repeated application, stale state, corruption, allocation limits, +- [ ] Cover every adjudication level/disposition, repeated application, stale + state, corruption, allocation limits, multi-side conflict, and diffusion/conflict integration. ### Presentation completion (#10) diff --git a/docs/README.md b/docs/README.md index 1adfd99..228b984 100644 --- a/docs/README.md +++ b/docs/README.md @@ -13,7 +13,7 @@ behavior clearly. and accessibility contract. - [Simulation and world generation](simulation-worldgen-design.md): seeded fuzzing, roads, movement, diffusion, map rendering, and config packaging. -- [Influx, diffusion resolution, and conflict](resolution-conflict-design.md): +- [Adjudication/influx, diffusion resolution, and conflict](resolution-conflict-design.md): implementation contract for tracker issues #9, #8, and #12. - [Presentation and export](presentation-design.md): remaining buffered, coherent, saveable output contract for tracker issue #10. diff --git a/docs/issue-audit.md b/docs/issue-audit.md index 1ae33c8..8c7f9da 100644 --- a/docs/issue-audit.md +++ b/docs/issue-audit.md @@ -15,10 +15,10 @@ absent. | [#15 Clamp stats](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/15) | Addressed: CLI/TUI mutations clamp normalized persistent stats to `0..=120`, event/blocker modifiers and growth to `-120..=120`, and population remains an unbounded non-negative count (or a bounded negative modifier). Workspace validation rejects bypassed invalid state. | Move these defaults into schemas if custom-stat domains become configurable. | | [#14 Build fsck](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/14) | Addressed for read-only validation: every epoch is parsed and checked for duplicate IDs, collection types, ordinary links, governors, and capitals. | Put serializer rewriting in a separately previewed repair command, not `fsck`. | | [#13 Add all cards into pre-events](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/13) | Explicitly deferred by the maintainer for this milestone. | Revisit only when requested. | -| [#12 Add fight/war](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/12) | Not implemented. The implementation-ready design uses generic multi-side conflict records and reuses deterministic influx resolution. | Deliver after the influx engine and diffusion integration; see `resolution-conflict-design.md`. | +| [#12 Add fight/war](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/12) | Not implemented. The implementation-ready design uses generic multi-side conflict records and reuses explicit game-master adjudications. | Deliver after adjudication persistence and diffusion integration; see `resolution-conflict-design.md`. | | [#11 Epoch Diffing](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/11) | Addressed: epoch and layer comparisons share a deterministic, serializable typed diff with changed-field details and importance classification. | Extend the type rather than parsing terminal output when structured formats arrive. | | [#10 Display functions](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/10) | Partially addressed: unified `show`, entity detail, and diff rendering are buffered. Most commands and several legacy library helpers still print directly; saving/structured output is absent. | Implement the renderer/sink migration and acceptance inventory in `presentation-design.md`. | -| [#9 Adding influx](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/9) | Foundation implemented: versioned embedded/override rules, all six levels, deterministic target-isolated rolls, weighted pressure/resistance, four outcomes, attenuation, and serializable typed reports. Persistence and CLI remain open. | Persist idempotent resolution records, then implement preview/apply/show/clear. | +| [#9 Adding influx](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/9) | Corrected foundation implemented: “influx” is a player-made external roll adjudicated by the master. The library records all six master-assigned levels, explicit effects, applied/dampened/avoided/destroyed dispositions, clamped previews, and stale checks; it never rolls. | Persist idempotent adjudication records, then implement `adjudicate` preview/apply/show/clear with `influx` as an alias. | | [#8 Event diffusion](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/8) | Partially addressed: deterministic road/direct town frontiers, affected sets, expiry, previewed ticks, and reversible application exist. Influx-aware outcomes, protected-town avoidance, and character targeting remain. | Integrate the shared resolution engine using the explicit #8 acceptance gates in `resolution-conflict-design.md`. | | [#6 HashMap/HashSet](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/6) | Addressed without format churn: `EntityIndex` provides ephemeral UUID/name hash indexes and duplicate-ID detection over the stable vector representation. Repository validation uses the index and hash lookup for relationships. | Rebuild indexes after mutation; never persist them. | diff --git a/docs/resolution-conflict-design.md b/docs/resolution-conflict-design.md index 272b357..9386c2b 100644 --- a/docs/resolution-conflict-design.md +++ b/docs/resolution-conflict-design.md @@ -1,4 +1,4 @@ -# Influx, diffusion resolution, and conflict design +# Adjudication (“influx”), diffusion resolution, and conflict design This is the implementation contract for tracker issues [#9](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/9), @@ -10,49 +10,52 @@ appearing in this document. ## Product contract -Simulation is deterministic, inspectable, and subordinate to the Git-like -workflow: +An **adjudication** (formerly called an “influx”) is a player-made roll outside +Epoch Forge. The game master interprets that result, chooses its level, +disposition, targets, and exact effects, then uses Epoch Forge to preview and +record the ruling. Epoch Forge must never invent, reroll, or reinterpret it. + +Adjudication is inspectable and subordinate to the Git-like workflow: - preview is the default and never writes; - `--apply` changes only the complete worktree snapshot under the repository writer lock; - staging and committing remain explicit separate operations; -- previews state the seed, inputs, rule source, selected targets, decisions, - and exact projected changes; -- replaying the same state, configuration, command, and seed produces the same +- previews state the external result, master note, selected targets, + disposition, policy, and exact projected changes; +- replaying the same explicit ruling against the same state produces the same report and semantic world; - applying an already-recorded resolution is idempotent; - users can discard applied work with `efo restore --worktree --all`, or retain it through `stage` and `commit`; -- simulation never deletes an entity merely because a roll failed. A - `Destroyed` outcome marks the simulation record/event complete and previews - any proposed entity deletion as a separate explicit operation. +- adjudication never deletes a target entity. A master-selected `Destroyed` + disposition marks the source event/conflict exhausted; entity deletion is a + separate explicit operation. The model remains setting-agnostic. “War”, “plague”, “merger”, “strike”, and -“market shock” are labels/configurations over the same participant, pressure, -resistance, and effect primitives. Fantasy-specific unit classes or damage -types do not belong in the core. +“market shock” are labels over the same participant, explicit ruling, and +effect primitives. Fantasy-specific unit classes or damage types do not belong +in the core. -## Shared deterministic resolution engine +## Shared adjudication recorder ### Influx levels -`InfluxLevel` is a stable serialized enum and a Clap value enum: +`AdjudicationLevel` is a stable serialized enum and a Clap value enum. It is +assigned by the master; it does not imply a numeric roll or automatic effect: -| Level | Default pressure band | Intent | -|---|---:|---| -| `excellent` | +80..+120 | exceptional beneficial effect | -| `good` | +35..+79 | beneficial effect | -| `mid` | -20..+34 | weak or mixed effect | -| `bad` | -55..-21 | harmful effect | -| `worsen` | -90..-56 | strongly harmful/escalating effect | -| `apocalypse` | -120..-91 | extreme harmful effect | +| Level | Intent | +|---|---| +| `excellent` | exceptional beneficial ruling | +| `good` | beneficial ruling | +| `mid` | weak, neutral, or mixed ruling | +| `bad` | harmful ruling | +| `worsen` | strongly harmful/escalating ruling | +| `apocalypse` | extreme harmful ruling | The names are compatibility vocabulary from the issue, not hard-coded story -meaning. Configuration owns the exact inclusive bands. Negative and positive -levels use the same algorithm; polarity only changes the proposed statistic -deltas. Parsed aliases may include `medium` for `mid` and `worse` for -`worsen`, while serialized values remain canonical. +meaning. Parsed aliases include `medium` for `mid` and `worse` for `worsen`, +while serialized values remain canonical. ### Inputs and stable records @@ -60,49 +63,43 @@ The library owns serializable types; CLI code only resolves selectors and renders reports: ```text -InfluxSpec { - level, seed, source_event, ruleset_id, - target_scope, repeat_policy +AdjudicationSpec { + level, disposition, source_event, + external_result, note, chosen_effects, policy_id } -ResolutionRecord { - id, source, target, tick_or_round, seed, - pressure, resistance, outcome, attenuation, - proposed_changes, applied, ruleset_id +AdjudicationRecord { + id, source, target, tick_or_round, + level, disposition, external_result, note, + before_and_after_changes, policy_id } -ResolutionOutcome = Affected | Dampened | Avoided | Destroyed +Disposition = Applied | Dampened | Avoided | Destroyed ``` -Records use stable UUIDs and are ordered by `(tick_or_round, source, target, -id)`. The RNG is `StdRng::seed_from_u64`; each target derives a sub-seed from -the command seed plus stable source/target IDs, so adding an unrelated target -does not perturb existing results. Rust's randomized hash iteration must never -influence a roll. +Records use stable content-derived UUIDs and are ordered by +`(tick_or_round, source, target, id)`. Identical adjudications therefore cannot +be accidentally applied twice. No RNG exists in this subsystem. -`proposed_changes` is a typed list of field/stat deltas, not formatted text. -Every change carries before/projected-after values and the clamping policy. +Chosen effects are typed field/stat deltas, not formatted text. Every previewed +change carries before/applied-delta/projected-after values and the normal +clamping policy. Application verifies the target still has the recorded before value; stale state aborts the whole transaction with recovery guidance. -### Pressure, resistance, and attenuation +### Disposition and attenuation -The first ruleset is deliberately simple and configurable: +The game master explicitly chooses the disposition: -1. Select a pressure value from the level's configured band. -2. Add source-stat contributions configured by stat name and weight. -3. Calculate target resistance from configured stats, blockers, and explicit - protection relationships. -4. Add a deterministic bounded roll. -5. Compare `pressure - resistance` against configured thresholds: - `Destroyed`, `Avoided`, `Dampened`, or `Affected`. -6. Multiply configured effects by the resulting attenuation and clamp through - the existing stat-domain policy. +- `Applied`: apply every chosen effect in full; +- `Dampened`: apply chosen effects using the configured attenuation; +- `Avoided`: record the target's avoidance and apply no effects; +- `Destroyed`: stop/exhaust the source and apply no target effects. -No hidden global randomness or wall-clock time enters the calculation. -Missing optional stats contribute zero and appear in the explanation. Invalid -stat names, unordered ranges, non-finite weights, excessive target counts, or -unknown ruleset versions fail before a preview is produced. +Epoch Forge applies no hidden inference. Protection and blockers are context +shown to the master, not an automatic roll. Invalid stat names, duplicate +effects, excessive effect counts, stale targets, and unknown policies fail +before mutation. Interpretation of `Destroyed` depends on the source: @@ -111,43 +108,41 @@ Interpretation of `Destroyed` depends on the source: from the repository; - for a target, entity deletion is never implicit. -`Dampened` writes an attenuation mark to the event/conflict state. Later -resolution uses that mark; it does not repeatedly edit the source's base stats. +`Dampened` writes an attenuation mark to the event/conflict state. It does not +edit the source's base stats. ### Configuration -Add `lib_efo/assets/simulation/default.json` and a versioned -`SimulationConfig` independent of repository and worldgen versions. It owns: +`lib_efo/assets/simulation/default.json` contains a versioned +`AdjudicationConfig` independent of repository and worldgen versions. It owns +only policy and safety—not game-master decisions: -- the six influx bands and aliases; -- pressure/resistance stat weights; -- outcome thresholds and attenuation ratios; -- effects by target entity type; -- blocker/protection behavior; -- conflict round limits, stalemate rules, and default victory thresholds; -- allocation limits for targets, participants, records, and rounds. +- dampened attenuation; +- maximum effects, records, and text sizes; +- a stable policy identifier. The binary embeds canonical offline defaults and accepts `--config PATH`. External config is a complete replacement, not a partially merged surprise. Errors identify the file and JSON field. Release packaging should add this file beside the existing worldgen configuration. -## Issue #9: influx and roll surface +## Issue #9: adjudication surface Proposed CLI: ```text -efo influx preview EVENT --level bad [--target SELECTOR ...] [--seed N] -efo influx apply EVENT --level bad [--target SELECTOR ...] [--seed N] -efo influx show EVENT -efo influx clear EVENT [--yes] -efo roll influx EVENT --level bad ... # visible compatibility alias +efo adjudicate preview EVENT --target town:Haven --level bad \ + --result "d20=4" --disposition dampened --effect health:-20 +efo adjudicate apply EVENT ... +efo adjudicate show EVENT +efo adjudicate clear EVENT [--yes] +efo influx ... # visible legacy/domain alias ``` `preview` and `apply` are intentionally separate words; `apply` still prints -the complete preview before its success line. If no seed is supplied, preview -prints a generated seed that can be copied into `apply`; it must not imply that -a second seed will reproduce the first preview unless supplied explicitly. +the complete preview before its success line. `--result` is descriptive text, +not a value the program interprets. `--effect` is repeatable and always +explicit. Target scopes support stable entity selectors and semantic groups (`towns`, `characters`, `organisations`, `reached`) without requiring custom fields. @@ -156,14 +151,14 @@ diffusion state. Acceptance gates: -- all six levels parse, serialize, appear in help, and reach their configured - bands at boundary tests; -- the same seed/config/state yields byte-equivalent typed reports; -- avoidance, damping, destruction, and ordinary effect outcomes are covered; +- all six levels parse, serialize, and appear in help; +- the same explicit ruling/policy/state yields byte-equivalent typed reports; +- applied, dampened, avoided, and destroyed dispositions are covered; - records prevent accidental reapplication and stale application is atomic; - invalid config and excessive scope fail before allocation/mutation; - preview leaves repository bytes unchanged; apply is restoreable; -- source attenuation persists without corrupting source entity statistics. +- source attenuation persists without corrupting source entity statistics; +- tests prove that the program never generates a roll or an unrequested effect. ## Issue #8: finish diffusion resolution @@ -172,26 +167,26 @@ ordered town frontier, affected towns, and road/direct route reasons. Preserve that representation and extend it additively with: ```text -resolved: BTreeMap +resolved: BTreeMap stopped: Option character_policy: Residents | Positioned | Both | None -influx: Option +adjudication: Option ``` When a tick reaches a town: 1. derive town and character targets according to `character_policy`; -2. inspect blockers/protection before rolling; -3. resolve each stable target through the influx engine; -4. record `Avoided` targets as resolved, preventing repeated rolls; +2. show blockers/protection as context for the master's ruling; +3. apply the explicit adjudication to each selected stable target; +4. record `Avoided` targets as resolved, preventing repeated application; 5. stop the event if its resolution is `Destroyed`; -6. include route, protection source, roll explanation, and projected effects in +6. include route, protection source, external result, master note, and projected effects in the tick report. -Protection is explicit and generic. The first implementation treats positioned -`Blocker` entities and typed links selected by configuration as resistance -contributors. A protected town is not silently omitted: the report says which -blocker/link contributed and whether the result was avoided or dampened. +Protection is explicit and generic. Positioned `Blocker` entities and typed +links are shown to the master as context. A protected town is not silently +omitted: the report says which blocker/link is relevant and records whether +the master ruled that the result was avoided or dampened. Characters are resolved in stable UUID order. Residents use mobility state; positioned characters use exact position/town association; travellers are only @@ -206,11 +201,11 @@ insertion order. ## Issue #12: fight and war -Conflict reuses resolution records instead of directly coupling entities. +Conflict reuses adjudication records instead of directly coupling entities. ```text ConflictState { - id, name, kind, sides, seed, round, status, + id, name, kind, sides, round, status, location, ruleset_id, objectives, records } @@ -233,7 +228,7 @@ changes. Proposed CLI: ```text -efo conflict start NAME --kind fight --side red:town:Haven --side blue:org:Guild --seed N +efo conflict start NAME --kind fight --side red:town:Haven --side blue:org:Guild efo conflict preview CONFLICT [--rounds N] efo conflict advance CONFLICT [--rounds N] --apply efo conflict show CONFLICT @@ -246,11 +241,11 @@ Starting and ending are preview-first worktree changes. Advancing resolves all sides in stable order, snapshots participant inputs for stale-state detection, and produces typed round reports. Victory and stalemate come solely from the versioned ruleset. A command cannot advance an ended conflict or silently -re-roll an already recorded round. +reapply an already recorded round. Acceptance gates cover two and three-sided conflicts, mixed entity types, fight completion, multi-round war, victory/stalemate, participant removal, -seed replay, insertion-order independence, clamping, stale-state refusal, +identical-ruling replay, insertion-order independence, clamping, stale-state refusal, restore/stage/commit/revert, and malformed persisted conflict state. ## Persistence and compatibility @@ -276,11 +271,13 @@ upgrade path under issue #17. ## Delivery slices -1. **Complete:** add and validate `SimulationConfig`, `InfluxLevel`, typed - reports, deterministic sub-seeding, and reproducible release packaging; no - commands or mutation. -2. Add pure influx preview/resolution tests for every outcome and level. -3. Persist idempotent resolution records and expose preview/apply/show/clear. +1. **Corrected and complete:** add and validate `AdjudicationConfig`, all six + master-assigned levels, explicit dispositions/effects, stale-checkable typed + reports, and reproducible release packaging; no commands or mutation. +2. **Complete:** add pure adjudication preview/application tests for every + disposition and prove no roll/effect is invented. +3. Persist idempotent adjudication records and expose + preview/apply/show/clear. 4. Integrate resolution into diffusion towns, then resident/positioned characters and protection explanations. 5. Add generic conflict state and pure round resolution. diff --git a/docs/roadmap.md b/docs/roadmap.md index 19b59c4..d965a3e 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -38,8 +38,9 @@ workflows. The simulation track has deterministic world generation, road topology, character travel, and spatial event frontiers. The next approved work is the -[shared resolution and conflict design](resolution-conflict-design.md): influx -first, then protected-town/character diffusion outcomes, then fight/war. The +[shared adjudication and conflict design](resolution-conflict-design.md): +player-roll adjudication first, then protected-town/character diffusion +outcomes, then fight/war. The [presentation design](presentation-design.md) is implemented alongside those slices so every new preview is buffered and exportable rather than adding more direct terminal printing. PNG map rendering follows those tracker issues. diff --git a/lib_efo/assets/simulation/README.md b/lib_efo/assets/simulation/README.md index 9e442de..c3d4f46 100644 --- a/lib_efo/assets/simulation/README.md +++ b/lib_efo/assets/simulation/README.md @@ -5,14 +5,12 @@ Epoch Forge release. Pass an edited complete replacement to future simulation commands with `--config PATH`; unknown fields and invalid ranges are rejected. The schema version is independent from the repository and application -versions. It defines: +versions. This policy does not define or perform a roll: the player rolls +outside Epoch Forge and the game master supplies its interpretation and exact +effects. The configuration defines: -- the six canonical influx pressure bands; -- source-pressure, target-resistance, and proposed-effect stat weights in basis - points (`10000` means one whole unit per stat unit); -- the deterministic roll interval; -- strictly ordered destroyed, avoided, dampened, and affected thresholds; -- dampened attenuation and defensive allocation limits. +- dampened attenuation in basis points (`10000` means the full chosen effect); +- defensive limits for explicit effects, durable records, and text. -Keep `ruleset_id` stable while semantics remain identical. Change it whenever -an edited configuration should not be mistaken for the embedded ruleset. +Keep `policy_id` stable while semantics remain identical. Change it whenever an +edited policy should not be mistaken for the embedded policy. diff --git a/lib_efo/assets/simulation/default.json b/lib_efo/assets/simulation/default.json index f8f31c0..974c069 100644 --- a/lib_efo/assets/simulation/default.json +++ b/lib_efo/assets/simulation/default.json @@ -1,32 +1,8 @@ { "schema_version": { "major": 1, "minor": 0 }, - "ruleset_id": "epoch-forge/default-1", - "levels": [ - { "level": "apocalypse", "min": -120, "max": -91 }, - { "level": "worsen", "min": -90, "max": -56 }, - { "level": "bad", "min": -55, "max": -21 }, - { "level": "mid", "min": -20, "max": 34 }, - { "level": "good", "min": 35, "max": 79 }, - { "level": "excellent", "min": 80, "max": 120 } - ], - "source_weights": [ - { "stat": "threat", "basis_points": 2500 }, - { "stat": "strength", "basis_points": 2500 } - ], - "resistance_weights": [ - { "stat": "fortification", "basis_points": 2500 }, - { "stat": "health", "basis_points": 2500 } - ], - "effects": [ - { "stat": "health", "basis_points": 5000 }, - { "stat": "happiness", "basis_points": 2500 } - ], - "roll": { "min": -10, "max": 10 }, - "thresholds": { - "destroyed_max": -80, - "avoided_max": -30, - "dampened_max": 20, - "dampened_basis_points": 5000 - }, - "limits": { "max_targets": 10000, "max_records": 100000 } + "policy_id": "epoch-forge/adjudication-default-1", + "dampened_basis_points": 5000, + "max_effects": 64, + "max_records": 100000, + "max_text_bytes": 16384 } diff --git a/lib_efo/src/adjudication.rs b/lib_efo/src/adjudication.rs new file mode 100644 index 0000000..f4577e9 --- /dev/null +++ b/lib_efo/src/adjudication.rs @@ -0,0 +1,467 @@ +//! Player-rolled, game-master-adjudicated event resolutions. +//! +//! Epoch Forge never rolls these outcomes. It records an external result and +//! previews/applies only the explicit effects chosen by the game master. + +use std::{collections::HashSet, fs, path::Path, str::FromStr}; + +use serde::{Deserialize, Serialize}; +use uuid::Uuid; + +use crate::{ + entity::Entity, + repository_format::FormatVersion, + stats::{ListStats, Modification, StatPair}, +}; + +/// Configuration schema understood by this build. +pub const CURRENT_ADJUDICATION_CONFIG_VERSION: FormatVersion = FormatVersion { major: 1, minor: 0 }; +/// Offline-safe canonical safety policy. +pub const DEFAULT_ADJUDICATION_CONFIG_JSON: &str = + include_str!("../assets/simulation/default.json"); + +/// Master-assigned interpretation of the external roll's magnitude. +#[derive( + Debug, + Clone, + Copy, + PartialEq, + Eq, + PartialOrd, + Ord, + Hash, + Serialize, + Deserialize, + clap::ValueEnum, +)] +#[serde(rename_all = "snake_case")] +pub enum AdjudicationLevel { + /// Exceptionally beneficial result. + Excellent, + /// Beneficial result. + Good, + /// Weak, neutral, or mixed result. + #[value(alias = "medium")] + Mid, + /// Harmful result. + Bad, + /// Strongly harmful or escalating result. + #[value(alias = "worse")] + Worsen, + /// Extreme harmful result. + Apocalypse, +} + +/// Master-selected disposition of the source against this target. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, clap::ValueEnum)] +#[serde(rename_all = "snake_case")] +pub enum AdjudicationDisposition { + /// Apply every chosen effect in full. + Applied, + /// Apply chosen effects with the configured attenuation. + Dampened, + /// Record that this target avoided the event; apply no effects. + Avoided, + /// Record that the external resolution exhausted/destroyed the source. + Destroyed, +} + +/// Supported editable statistic names. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum StatName { + /// Population count or modifier. + Population, + /// Population growth rate. + GrowthRate, + /// Crime. + Crime, + /// Happiness. + Happiness, + /// Food. + Food, + /// Industry. + Industry, + /// Science. + Science, + /// Trade. + Trade, + /// Army. + Army, + /// Strength. + Strength, + /// Fortification. + Fortification, + /// Threat. + Threat, + /// Bureaucracy. + Bureaucracy, + /// Transportation. + Transportation, + /// Sprawl. + Sprawl, + /// Health. + Health, +} + +impl StatName { + /// Convert to the existing statistics selector. + pub fn list_stat(self) -> ListStats { + match self { + Self::Population => ListStats::Population, + Self::GrowthRate => ListStats::Growthrate, + Self::Crime => ListStats::Crime, + Self::Happiness => ListStats::Happiness, + Self::Food => ListStats::Food, + Self::Industry => ListStats::Industry, + Self::Science => ListStats::Science, + Self::Trade => ListStats::Trade, + Self::Army => ListStats::Army, + Self::Strength => ListStats::Strength, + Self::Fortification => ListStats::Fortification, + Self::Threat => ListStats::Threat, + Self::Bureaucracy => ListStats::Bureaucracy, + Self::Transportation => ListStats::Transportation, + Self::Sprawl => ListStats::Sprawl, + Self::Health => ListStats::Health, + } + } +} + +impl FromStr for StatName { + type Err = AdjudicationError; + + fn from_str(value: &str) -> Result { + match value.trim().to_ascii_lowercase().replace('-', "_").as_str() { + "population" | "pop" => Ok(Self::Population), + "growth_rate" | "growth" => Ok(Self::GrowthRate), + "crime" => Ok(Self::Crime), + "happiness" => Ok(Self::Happiness), + "food" => Ok(Self::Food), + "industry" => Ok(Self::Industry), + "science" => Ok(Self::Science), + "trade" => Ok(Self::Trade), + "army" => Ok(Self::Army), + "strength" => Ok(Self::Strength), + "fortification" => Ok(Self::Fortification), + "threat" => Ok(Self::Threat), + "bureaucracy" => Ok(Self::Bureaucracy), + "transportation" => Ok(Self::Transportation), + "sprawl" => Ok(Self::Sprawl), + "health" => Ok(Self::Health), + _ => Err(AdjudicationError::Invalid(format!( + "unknown effect statistic `{value}`" + ))), + } + } +} + +/// Safety limits and dampening policy for adjudications. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AdjudicationConfig { + /// Independent configuration schema version. + pub schema_version: FormatVersion, + /// Stable policy identity recorded with each resolution. + pub policy_id: String, + /// Effect multiplier for a dampened disposition, in basis points. + pub dampened_basis_points: isize, + /// Maximum effects supplied for one target. + pub max_effects: usize, + /// Maximum persisted records in one world. + pub max_records: usize, + /// Maximum UTF-8 byte length for roll descriptions and notes. + pub max_text_bytes: usize, +} + +/// Configuration, validation, or stale-application failure. +#[derive(Debug, thiserror::Error)] +pub enum AdjudicationError { + /// Reading an external policy failed. + #[error("cannot read adjudication config `{path}`: {source}")] + Io { + /// Affected path. + path: std::path::PathBuf, + /// Filesystem error. + #[source] + source: std::io::Error, + }, + /// JSON did not match the policy schema. + #[error("invalid adjudication config `{path}`: {source}")] + Json { + /// Embedded label or external path. + path: std::path::PathBuf, + /// Decode error. + #[source] + source: serde_json::Error, + }, + /// Semantic validation failed. + #[error("invalid adjudication: {0}")] + Invalid(String), + /// Target changed after the preview was created. + #[error("target @{target} changed after preview; run the adjudication preview again")] + Stale { + /// Stale target. + target: Uuid, + }, +} + +impl AdjudicationConfig { + /// Load and validate the embedded policy. + pub fn embedded() -> Result { + Self::decode( + DEFAULT_ADJUDICATION_CONFIG_JSON.as_bytes(), + Path::new(""), + ) + } + + /// Load and validate a complete external replacement. + pub fn load(path: &Path) -> Result { + let bytes = fs::read(path).map_err(|source| AdjudicationError::Io { + path: path.to_owned(), + source, + })?; + Self::decode(&bytes, path) + } + + /// Decode bytes with source-aware diagnostics. + pub fn decode(bytes: &[u8], path: &Path) -> Result { + let config: Self = + serde_json::from_slice(bytes).map_err(|source| AdjudicationError::Json { + path: path.to_owned(), + source, + })?; + config.validate()?; + Ok(config) + } + + /// Validate policy identity, attenuation, and hard allocation limits. + pub fn validate(&self) -> Result<(), AdjudicationError> { + if self.schema_version != CURRENT_ADJUDICATION_CONFIG_VERSION { + return Err(AdjudicationError::Invalid(format!( + "schema {} is unsupported; expected {}", + self.schema_version, CURRENT_ADJUDICATION_CONFIG_VERSION + ))); + } + if self.policy_id.trim().is_empty() || self.policy_id.len() > 128 { + return Err(AdjudicationError::Invalid( + "policy_id must contain 1..=128 characters".into(), + )); + } + if !(0..=10_000).contains(&self.dampened_basis_points) { + return Err(AdjudicationError::Invalid( + "dampened_basis_points must be within 0..=10000".into(), + )); + } + if self.max_effects == 0 + || self.max_effects > 1_000 + || self.max_records == 0 + || self.max_records > 10_000_000 + || self.max_text_bytes == 0 + || self.max_text_bytes > 1_000_000 + { + return Err(AdjudicationError::Invalid( + "configured limits are zero or exceed hard safety limits".into(), + )); + } + Ok(()) + } +} + +/// One explicit effect chosen by the game master. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub struct ChosenEffect { + /// Statistic to modify. + pub stat: StatName, + /// Signed requested delta before dampening and domain clamping. + pub delta: isize, +} + +/// Complete player-roll interpretation for one source and target. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct AdjudicationSpec { + /// Master-assigned magnitude category. + pub level: AdjudicationLevel, + /// Master-selected disposition. + pub disposition: AdjudicationDisposition, + /// Event or conflict source. + pub source: Uuid, + /// Human description of the external roll, such as `d20=17`. + pub external_result: String, + /// Optional master explanation. + pub note: String, + /// Explicit effects; Epoch Forge never invents these. + pub effects: Vec, + /// Policy expected by the caller. + pub policy_id: String, +} + +/// One projected and stale-checkable statistic change. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub struct ProjectedChange { + /// Statistic to modify. + pub stat: StatName, + /// Value observed during preview. + pub before: isize, + /// Requested delta after disposition attenuation. + pub applied_delta: isize, + /// Domain-clamped value that will be written. + pub after: isize, +} + +/// Pure preview and durable record payload for one target. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct AdjudicationReport { + /// Stable content-derived identity. + pub id: Uuid, + /// Event or conflict source. + pub source: Uuid, + /// Target entity. + pub target: Uuid, + /// Simulation tick or conflict round. + pub tick_or_round: u64, + /// Master-assigned magnitude. + pub level: AdjudicationLevel, + /// Master-selected disposition. + pub disposition: AdjudicationDisposition, + /// External result retained verbatim. + pub external_result: String, + /// Master explanation retained verbatim. + pub note: String, + /// Stale-checkable projected changes. + pub changes: Vec, + /// Policy used to interpret dampening and limits. + pub policy_id: String, +} + +/// Preview an external result without mutating the supplied target. +pub fn preview( + config: &AdjudicationConfig, + spec: &AdjudicationSpec, + target: &Entity, + tick_or_round: u64, +) -> Result { + config.validate()?; + validate_spec(config, spec)?; + let attenuation = match spec.disposition { + AdjudicationDisposition::Applied => 10_000, + AdjudicationDisposition::Dampened => config.dampened_basis_points, + AdjudicationDisposition::Avoided | AdjudicationDisposition::Destroyed => 0, + }; + let mut projected = target.clone(); + let mut changes = Vec::new(); + for effect in &spec.effects { + let stat = effect.stat.list_stat(); + let before = **projected.get_stats().get_field(&stat); + let applied_delta = scale(effect.delta, attenuation); + projected.change_stat_strict( + StatPair { + stat, + value: applied_delta.into(), + }, + Modification::Delta, + ); + projected.update_metastats(); + let after = **projected.get_stats().get_field(&stat); + changes.push(ProjectedChange { + stat: effect.stat, + before, + applied_delta, + after, + }); + } + let encoded = serde_json::to_vec(&(spec, target.id, tick_or_round)).map_err(|error| { + AdjudicationError::Invalid(format!("cannot identify adjudication: {error}")) + })?; + Ok(AdjudicationReport { + id: content_id(&encoded), + source: spec.source, + target: target.id, + tick_or_round, + level: spec.level, + disposition: spec.disposition, + external_result: spec.external_result.clone(), + note: spec.note.clone(), + changes, + policy_id: config.policy_id.clone(), + }) +} + +/// Apply a preview only when the target still matches every recorded input. +pub fn apply_to_target( + report: &AdjudicationReport, + target: &mut Entity, +) -> Result<(), AdjudicationError> { + if target.id != report.target + || report + .changes + .iter() + .any(|change| **target.get_stats().get_field(&change.stat.list_stat()) != change.before) + { + return Err(AdjudicationError::Stale { + target: report.target, + }); + } + for change in &report.changes { + target.change_stat_strict( + StatPair { + stat: change.stat.list_stat(), + value: change.after.into(), + }, + Modification::Replace, + ); + } + target.update_metastats(); + Ok(()) +} + +/// Validate a master-authored interpretation before previewing it. +fn validate_spec( + config: &AdjudicationConfig, + spec: &AdjudicationSpec, +) -> Result<(), AdjudicationError> { + if spec.policy_id != config.policy_id { + return Err(AdjudicationError::Invalid(format!( + "requested policy `{}` does not match `{}`", + spec.policy_id, config.policy_id + ))); + } + if spec.external_result.len() > config.max_text_bytes || spec.note.len() > config.max_text_bytes + { + return Err(AdjudicationError::Invalid( + "external result or note exceeds max_text_bytes".into(), + )); + } + if spec.effects.len() > config.max_effects { + return Err(AdjudicationError::Invalid( + "too many explicit effects".into(), + )); + } + let unique = spec + .effects + .iter() + .map(|effect| effect.stat) + .collect::>(); + if unique.len() != spec.effects.len() { + return Err(AdjudicationError::Invalid( + "an adjudication may change each statistic at most once".into(), + )); + } + Ok(()) +} + +/// Apply a basis-point multiplier with saturating multiplication. +fn scale(value: isize, basis_points: isize) -> isize { + value.saturating_mul(basis_points) / 10_000 +} + +/// Generate a stable UUID from canonical serialized content. +fn content_id(bytes: &[u8]) -> Uuid { + let mut high = 0xcbf2_9ce4_8422_2325_u64; + let mut low = 0x8422_2325_cbf2_9ce4_u64; + for byte in bytes { + high = (high ^ u64::from(*byte)).wrapping_mul(0x0000_0100_0000_01b3); + low = (low ^ u64::from(*byte)).wrapping_mul(0x0000_0100_0000_01d3); + } + Uuid::from_u128((u128::from(high) << 64) | u128::from(low)) +} diff --git a/lib_efo/src/influx.rs b/lib_efo/src/influx.rs deleted file mode 100644 index b9945d5..0000000 --- a/lib_efo/src/influx.rs +++ /dev/null @@ -1,543 +0,0 @@ -//! Versioned, deterministic influx resolution shared by events and conflicts. - -use std::{collections::BTreeSet, fs, path::Path}; - -use rand::{Rng, SeedableRng, rngs::StdRng}; -use serde::{Deserialize, Serialize}; -use uuid::Uuid; - -use crate::{ - entity::Entity, - repository_format::FormatVersion, - stats::{ListStats, OverallStats}, -}; - -/// Configuration schema understood by this build. -pub const CURRENT_SIMULATION_CONFIG_VERSION: FormatVersion = FormatVersion { major: 1, minor: 0 }; -/// Offline-safe canonical simulation rules. -pub const DEFAULT_SIMULATION_CONFIG_JSON: &str = include_str!("../assets/simulation/default.json"); - -/// Compatibility vocabulary for event intensity and polarity. -#[derive( - Debug, - Clone, - Copy, - PartialEq, - Eq, - PartialOrd, - Ord, - Hash, - Serialize, - Deserialize, - clap::ValueEnum, -)] -#[serde(rename_all = "snake_case")] -pub enum InfluxLevel { - /// Exceptional beneficial pressure. - Excellent, - /// Beneficial pressure. - Good, - /// Weak or mixed pressure. - #[value(alias = "medium")] - Mid, - /// Harmful pressure. - Bad, - /// Strongly harmful or escalating pressure. - #[value(alias = "worse")] - Worsen, - /// Extreme harmful pressure. - Apocalypse, -} - -/// Supported persisted statistic names for configurable rules. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum StatName { - /// Population count or modifier. - Population, - /// Population growth rate. - GrowthRate, - /// Crime. - Crime, - /// Happiness. - Happiness, - /// Food. - Food, - /// Industry. - Industry, - /// Science. - Science, - /// Trade. - Trade, - /// Army. - Army, - /// Strength. - Strength, - /// Fortification. - Fortification, - /// Threat. - Threat, - /// Bureaucracy. - Bureaucracy, - /// Transportation. - Transportation, - /// Sprawl. - Sprawl, - /// Health. - Health, -} - -impl StatName { - /// Convert to the existing statistics selector. - fn list_stat(self) -> ListStats { - match self { - Self::Population => ListStats::Population, - Self::GrowthRate => ListStats::Growthrate, - Self::Crime => ListStats::Crime, - Self::Happiness => ListStats::Happiness, - Self::Food => ListStats::Food, - Self::Industry => ListStats::Industry, - Self::Science => ListStats::Science, - Self::Trade => ListStats::Trade, - Self::Army => ListStats::Army, - Self::Strength => ListStats::Strength, - Self::Fortification => ListStats::Fortification, - Self::Threat => ListStats::Threat, - Self::Bureaucracy => ListStats::Bureaucracy, - Self::Transportation => ListStats::Transportation, - Self::Sprawl => ListStats::Sprawl, - Self::Health => ListStats::Health, - } - } -} - -/// Inclusive pressure range for one influx level. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct InfluxBand { - /// Level configured by this row. - pub level: InfluxLevel, - /// Inclusive minimum pressure. - pub min: isize, - /// Inclusive maximum pressure. - pub max: isize, -} - -/// Weighted statistic contribution in basis points. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct StatWeight { - /// Statistic to read. - pub stat: StatName, - /// Multiplier where 10,000 is one whole unit per stat unit. - pub basis_points: isize, -} - -/// Deterministic bounded-roll configuration. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct RollRange { - /// Inclusive minimum roll. - pub min: isize, - /// Inclusive maximum roll. - pub max: isize, -} - -/// Ordered outcome thresholds. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct OutcomeThresholds { - /// Largest margin that exhausts the source. - pub destroyed_max: isize, - /// Largest margin that the target completely avoids. - pub avoided_max: isize, - /// Largest margin that produces a dampened effect. - pub dampened_max: isize, - /// Dampened effect multiplier in basis points. - pub dampened_basis_points: isize, -} - -/// Allocation limits enforced before resolution. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct SimulationLimits { - /// Largest accepted target set. - pub max_targets: usize, - /// Largest accepted persisted record collection. - pub max_records: usize, -} - -/// Complete versioned deterministic simulation rules. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct SimulationConfig { - /// Independent configuration schema version. - pub schema_version: FormatVersion, - /// Stable identifier recorded in reports. - pub ruleset_id: String, - /// Exactly one pressure band per influx level. - pub levels: Vec, - /// Source statistics added to pressure. - pub source_weights: Vec, - /// Target statistics added to resistance. - pub resistance_weights: Vec, - /// Proposed target changes derived from resolved pressure. - pub effects: Vec, - /// Bounded random contribution. - pub roll: RollRange, - /// Outcome decision thresholds. - pub thresholds: OutcomeThresholds, - /// Defensive allocation limits. - pub limits: SimulationLimits, -} - -/// Configuration or resolution failure. -#[derive(Debug, thiserror::Error)] -pub enum InfluxError { - /// Reading an external configuration failed. - #[error("cannot read simulation config `{path}`: {source}")] - Io { - /// Affected path. - path: std::path::PathBuf, - /// Filesystem error. - #[source] - source: std::io::Error, - }, - /// JSON did not match the configuration schema. - #[error("invalid simulation config `{path}`: {source}")] - Json { - /// Embedded label or external path. - path: std::path::PathBuf, - /// Decode error. - #[source] - source: serde_json::Error, - }, - /// Semantic validation rejected otherwise valid JSON. - #[error("invalid simulation configuration: {0}")] - Invalid(String), -} - -impl SimulationConfig { - /// Load and validate the embedded offline rules. - pub fn embedded() -> Result { - Self::decode( - DEFAULT_SIMULATION_CONFIG_JSON.as_bytes(), - Path::new(""), - ) - } - - /// Load and validate a complete external replacement. - pub fn load(path: &Path) -> Result { - let bytes = fs::read(path).map_err(|source| InfluxError::Io { - path: path.to_owned(), - source, - })?; - Self::decode(&bytes, path) - } - - /// Decode bytes with source-aware diagnostics. - pub fn decode(bytes: &[u8], path: &Path) -> Result { - let config: Self = serde_json::from_slice(bytes).map_err(|source| InfluxError::Json { - path: path.to_owned(), - source, - })?; - config.validate()?; - Ok(config) - } - - /// Validate schema, ranges, thresholds, weights, and allocation limits. - pub fn validate(&self) -> Result<(), InfluxError> { - if self.schema_version != CURRENT_SIMULATION_CONFIG_VERSION { - return Err(InfluxError::Invalid(format!( - "schema {} is unsupported; expected {}", - self.schema_version, CURRENT_SIMULATION_CONFIG_VERSION - ))); - } - if self.ruleset_id.trim().is_empty() || self.ruleset_id.len() > 128 { - return Err(InfluxError::Invalid( - "ruleset_id must contain 1..=128 characters".into(), - )); - } - let expected = [ - InfluxLevel::Excellent, - InfluxLevel::Good, - InfluxLevel::Mid, - InfluxLevel::Bad, - InfluxLevel::Worsen, - InfluxLevel::Apocalypse, - ]; - let found = self - .levels - .iter() - .map(|band| band.level) - .collect::>(); - if found != BTreeSet::from(expected) || self.levels.len() != expected.len() { - return Err(InfluxError::Invalid( - "levels must contain each influx level exactly once".into(), - )); - } - for band in &self.levels { - if band.min > band.max || band.min < -120 || band.max > 120 { - return Err(InfluxError::Invalid(format!( - "{:?} pressure must be ordered within -120..=120", - band.level - ))); - } - } - let mut ordered = self.levels.clone(); - ordered.sort_unstable_by_key(|band| band.min); - if ordered.windows(2).any(|pair| pair[0].max >= pair[1].min) { - return Err(InfluxError::Invalid( - "influx pressure bands must not overlap".into(), - )); - } - for (label, weights) in [ - ("source_weights", &self.source_weights), - ("resistance_weights", &self.resistance_weights), - ("effects", &self.effects), - ] { - if weights.len() > 64 - || weights - .iter() - .any(|weight| weight.basis_points.unsigned_abs() > 10_000) - { - return Err(InfluxError::Invalid(format!( - "{label} must contain at most 64 weights within -10000..=10000 basis points" - ))); - } - let unique = weights - .iter() - .map(|weight| weight.stat) - .collect::>(); - if unique.len() != weights.len() { - return Err(InfluxError::Invalid(format!( - "{label} contains a duplicate statistic" - ))); - } - } - if self.roll.min > self.roll.max || self.roll.min < -120 || self.roll.max > 120 { - return Err(InfluxError::Invalid( - "roll must be ordered within -120..=120".into(), - )); - } - let thresholds = self.thresholds; - if !(thresholds.destroyed_max < thresholds.avoided_max - && thresholds.avoided_max < thresholds.dampened_max) - || !(0..=10_000).contains(&thresholds.dampened_basis_points) - { - return Err(InfluxError::Invalid( - "outcome thresholds must be strictly ordered and attenuation within 0..=10000" - .into(), - )); - } - if self.limits.max_targets == 0 - || self.limits.max_targets > 1_000_000 - || self.limits.max_records == 0 - || self.limits.max_records > 10_000_000 - { - return Err(InfluxError::Invalid( - "simulation limits are zero or exceed hard safety limits".into(), - )); - } - Ok(()) - } - - /// Find the pressure band for one level after validation. - fn band(&self, level: InfluxLevel) -> InfluxBand { - self.levels - .iter() - .find(|band| band.level == level) - .copied() - .unwrap_or(InfluxBand { - level, - min: 0, - max: 0, - }) - } -} - -/// Repeat behavior requested by a resolution caller. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum RepeatPolicy { - /// Refuse a duplicate persisted source/target/tick record. - Once, - /// Permit a new explicitly identified resolution. - Allow, -} - -/// Stable inputs for one influx resolution. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct InfluxSpec { - /// Configured severity/polarity. - pub level: InfluxLevel, - /// User-visible deterministic seed. - pub seed: u64, - /// Event or conflict source UUID. - pub source: Uuid, - /// Ruleset expected by the caller. - pub ruleset_id: String, - /// Duplicate application policy. - pub repeat_policy: RepeatPolicy, -} - -/// Resolution classification. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum ResolutionOutcome { - /// Full configured effect. - Affected, - /// Reduced configured effect. - Dampened, - /// Target completely resisted the effect. - Avoided, - /// Resistance exhausted the source. - Destroyed, -} - -/// One typed projected statistic delta. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -pub struct ProposedChange { - /// Statistic to modify. - pub stat: StatName, - /// Signed delta before target-domain clamping. - pub delta: isize, -} - -/// Pure deterministic explanation and proposed effects for one target. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct ResolutionReport { - /// Stable deterministic record identity. - pub id: Uuid, - /// Source identity. - pub source: Uuid, - /// Target identity. - pub target: Uuid, - /// Simulation tick or conflict round. - pub tick_or_round: u64, - /// User-visible root seed. - pub seed: u64, - /// Pressure selected from the influx band. - pub base_pressure: isize, - /// Weighted source-stat contribution. - pub source_contribution: isize, - /// Weighted target resistance. - pub resistance: isize, - /// Deterministic bounded roll. - pub roll: isize, - /// Final pressure minus resistance. - pub margin: isize, - /// Classified result. - pub outcome: ResolutionOutcome, - /// Applied effect multiplier in basis points. - pub attenuation_basis_points: isize, - /// Typed proposed target changes. - pub proposed_changes: Vec, - /// Ruleset used for this report. - pub ruleset_id: String, -} - -/// Resolve one target without mutating either entity or repository state. -pub fn resolve( - config: &SimulationConfig, - spec: &InfluxSpec, - source: &Entity, - target: &Entity, - tick_or_round: u64, -) -> Result { - config.validate()?; - if spec.source != source.id { - return Err(InfluxError::Invalid( - "influx source UUID does not match the supplied entity".into(), - )); - } - if spec.ruleset_id != config.ruleset_id { - return Err(InfluxError::Invalid(format!( - "requested ruleset `{}` does not match `{}`", - spec.ruleset_id, config.ruleset_id - ))); - } - let sub_seed = resolution_seed(spec.seed, source.id, target.id, tick_or_round); - let mut rng = StdRng::seed_from_u64(sub_seed); - let band = config.band(spec.level); - let base_pressure = rng.random_range(band.min as i64..=band.max as i64) as isize; - let source_contribution = weighted(source.get_stats(), &config.source_weights); - let resistance = weighted(target.get_stats(), &config.resistance_weights); - let roll = rng.random_range(config.roll.min as i64..=config.roll.max as i64) as isize; - let margin = base_pressure - .saturating_add(source_contribution) - .saturating_add(roll) - .saturating_sub(resistance); - let (outcome, attenuation_basis_points) = if margin <= config.thresholds.destroyed_max { - (ResolutionOutcome::Destroyed, 0) - } else if margin <= config.thresholds.avoided_max { - (ResolutionOutcome::Avoided, 0) - } else if margin <= config.thresholds.dampened_max { - ( - ResolutionOutcome::Dampened, - config.thresholds.dampened_basis_points, - ) - } else { - (ResolutionOutcome::Affected, 10_000) - }; - let proposed_changes = config - .effects - .iter() - .map(|effect| ProposedChange { - stat: effect.stat, - delta: scale( - scale(base_pressure, effect.basis_points), - attenuation_basis_points, - ), - }) - .filter(|change| change.delta != 0) - .collect(); - Ok(ResolutionReport { - id: resolution_id(sub_seed, source.id, target.id), - source: source.id, - target: target.id, - tick_or_round, - seed: spec.seed, - base_pressure, - source_contribution, - resistance, - roll, - margin, - outcome, - attenuation_basis_points, - proposed_changes, - ruleset_id: config.ruleset_id.clone(), - }) -} - -/// Sum weighted implemented statistics with saturating arithmetic. -fn weighted(stats: &OverallStats, weights: &[StatWeight]) -> isize { - weights.iter().fold(0_isize, |total, weight| { - total.saturating_add(scale( - **stats.get_field(&weight.stat.list_stat()), - weight.basis_points, - )) - }) -} - -/// Apply a basis-point multiplier with saturating multiplication. -fn scale(value: isize, basis_points: isize) -> isize { - value.saturating_mul(basis_points) / 10_000 -} - -/// Derive an iteration-independent seed from stable resolution inputs. -fn resolution_seed(seed: u64, source: Uuid, target: Uuid, tick_or_round: u64) -> u64 { - let mut hash = 0xcbf2_9ce4_8422_2325_u64 ^ seed ^ tick_or_round.rotate_left(17); - for byte in source.as_bytes().iter().chain(target.as_bytes()) { - hash ^= u64::from(*byte); - hash = hash.wrapping_mul(0x0000_0100_0000_01b3); - } - hash -} - -/// Produce a stable UUID without consuming external randomness. -fn resolution_id(seed: u64, source: Uuid, target: Uuid) -> Uuid { - let high = resolution_seed(seed, source, target, 0); - let low = resolution_seed(seed.rotate_left(29), target, source, 1); - Uuid::from_u128((u128::from(high) << 64) | u128::from(low)) -} diff --git a/lib_efo/src/lib.rs b/lib_efo/src/lib.rs index 9f81ee4..ed89ff2 100644 --- a/lib_efo/src/lib.rs +++ b/lib_efo/src/lib.rs @@ -14,10 +14,10 @@ use crate::epoch::EpochInfo; #[macro_use] #[allow(unused_assignments)] pub mod error; +pub mod adjudication; pub mod diff; pub mod entity; pub mod epoch; -pub mod influx; pub mod naming; pub mod output; pub mod repository_format; diff --git a/lib_efo/tests/adjudication.rs b/lib_efo/tests/adjudication.rs new file mode 100644 index 0000000..38ef417 --- /dev/null +++ b/lib_efo/tests/adjudication.rs @@ -0,0 +1,115 @@ +use std::fs; + +use lib_efo::{ + adjudication::{ + AdjudicationConfig, AdjudicationDisposition, AdjudicationLevel, AdjudicationSpec, + ChosenEffect, StatName, apply_to_target, preview, + }, + entity::Entity, + stats::{EntityType, ListStats, Modification, StatPair}, +}; +use uuid::Uuid; + +fn entity(id: u128, health: isize) -> Entity { + let mut entity = Entity::default(); + entity.id = Uuid::from_u128(id); + entity.entity_type = EntityType::Town; + entity.change_stat_strict( + StatPair { + stat: ListStats::Health, + value: health.into(), + }, + Modification::Replace, + ); + entity.update_metastats(); + entity +} + +fn spec(config: &AdjudicationConfig, disposition: AdjudicationDisposition) -> AdjudicationSpec { + AdjudicationSpec { + level: AdjudicationLevel::Bad, + disposition, + source: Uuid::from_u128(1), + external_result: "d20=4".into(), + note: "The master rules that the walls absorb part of the shock.".into(), + effects: vec![ChosenEffect { + stat: StatName::Health, + delta: -40, + }], + policy_id: config.policy_id.clone(), + } +} + +#[test] +fn embedded_and_external_policies_validate() { + let config = AdjudicationConfig::embedded().expect("embedded"); + let directory = tempfile::tempdir().expect("tempdir"); + let path = directory.path().join("adjudication.json"); + fs::write(&path, serde_json::to_vec_pretty(&config).expect("encode")).expect("write"); + assert_eq!(AdjudicationConfig::load(&path).expect("external"), config); +} + +#[test] +fn master_effects_are_never_invented_and_disposition_controls_application() { + let config = AdjudicationConfig::embedded().expect("config"); + for (disposition, expected_delta) in [ + (AdjudicationDisposition::Applied, -40), + (AdjudicationDisposition::Dampened, -20), + (AdjudicationDisposition::Avoided, 0), + (AdjudicationDisposition::Destroyed, 0), + ] { + let target = entity(2, 100); + let report = preview(&config, &spec(&config, disposition), &target, 3).expect("preview"); + assert_eq!(report.changes.len(), 1); + assert_eq!(report.changes[0].applied_delta, expected_delta); + assert_eq!(report.changes[0].after, 100 + expected_delta); + assert_eq!(report.external_result, "d20=4"); + } +} + +#[test] +fn previews_are_stable_apply_exactly_and_refuse_stale_targets() { + let config = AdjudicationConfig::embedded().expect("config"); + let mut target = entity(2, 100); + let report = preview( + &config, + &spec(&config, AdjudicationDisposition::Dampened), + &target, + 3, + ) + .expect("preview"); + assert_eq!( + report, + preview( + &config, + &spec(&config, AdjudicationDisposition::Dampened), + &target, + 3, + ) + .expect("replay") + ); + apply_to_target(&report, &mut target).expect("apply"); + assert_eq!(**target.get_stats().get_field(&ListStats::Health), 80); + assert!(apply_to_target(&report, &mut target).is_err()); +} + +#[test] +fn explicit_effects_are_clamped_and_invalid_master_input_is_rejected() { + let config = AdjudicationConfig::embedded().expect("config"); + let target = entity(2, 10); + let report = preview( + &config, + &spec(&config, AdjudicationDisposition::Applied), + &target, + 0, + ) + .expect("preview"); + assert_eq!(report.changes[0].after, 0); + + let mut duplicate = spec(&config, AdjudicationDisposition::Applied); + duplicate.effects.push(duplicate.effects[0]); + assert!(preview(&config, &duplicate, &target, 0).is_err()); + let mut wrong_policy = spec(&config, AdjudicationDisposition::Applied); + wrong_policy.policy_id = "other".into(); + assert!(preview(&config, &wrong_policy, &target, 0).is_err()); +} diff --git a/lib_efo/tests/influx.rs b/lib_efo/tests/influx.rs deleted file mode 100644 index 9f8888b..0000000 --- a/lib_efo/tests/influx.rs +++ /dev/null @@ -1,272 +0,0 @@ -use std::{fs, path::Path}; - -use lib_efo::{ - entity::Entity, - influx::{ - InfluxLevel, InfluxSpec, OutcomeThresholds, RepeatPolicy, ResolutionOutcome, - SimulationConfig, StatName, StatWeight, resolve, - }, - stats::{EntityType, ListStats, Modification, StatPair}, -}; -use uuid::Uuid; - -fn entity(id: u128, kind: EntityType, stats: &[(ListStats, isize)]) -> Entity { - let mut entity = Entity::default(); - entity.id = Uuid::from_u128(id); - entity.name = format!("entity-{id}"); - entity.entity_type = kind; - for (stat, value) in stats { - entity.change_stat_strict( - StatPair { - stat: *stat, - value: (*value).into(), - }, - Modification::Replace, - ); - } - entity.update_metastats(); - entity -} - -fn spec(config: &SimulationConfig, level: InfluxLevel, seed: u64) -> InfluxSpec { - InfluxSpec { - level, - seed, - source: Uuid::from_u128(1), - ruleset_id: config.ruleset_id.clone(), - repeat_policy: RepeatPolicy::Once, - } -} - -#[test] -fn embedded_config_covers_every_level_and_external_files_are_complete_replacements() { - let config = SimulationConfig::embedded().expect("embedded config"); - for level in [ - InfluxLevel::Excellent, - InfluxLevel::Good, - InfluxLevel::Mid, - InfluxLevel::Bad, - InfluxLevel::Worsen, - InfluxLevel::Apocalypse, - ] { - assert_eq!( - config - .levels - .iter() - .filter(|band| band.level == level) - .count(), - 1 - ); - } - - let directory = tempfile::tempdir().expect("tempdir"); - let path = directory.path().join("simulation.json"); - fs::write(&path, serde_json::to_vec_pretty(&config).expect("encode")).expect("write"); - assert_eq!(SimulationConfig::load(&path).expect("external"), config); - assert!(SimulationConfig::load(Path::new("/definitely/missing/config.json")).is_err()); -} - -#[test] -fn semantic_validation_rejects_every_unsafe_configuration_family() { - let config = SimulationConfig::embedded().expect("config"); - let mut invalid = config.clone(); - invalid.levels.pop(); - assert!(invalid.validate().is_err()); - - let mut invalid = config.clone(); - invalid.levels[0].max = invalid.levels[1].min; - assert!(invalid.validate().is_err()); - - let mut invalid = config.clone(); - invalid.roll.min = 5; - invalid.roll.max = -5; - assert!(invalid.validate().is_err()); - - let mut invalid = config.clone(); - invalid.thresholds.avoided_max = invalid.thresholds.destroyed_max; - assert!(invalid.validate().is_err()); - - let mut invalid = config.clone(); - invalid.source_weights[0].basis_points = isize::MIN; - assert!(invalid.validate().is_err()); - - let mut invalid = config.clone(); - invalid.source_weights.push(invalid.source_weights[0]); - assert!(invalid.validate().is_err()); - - let mut invalid = config; - invalid.limits.max_targets = 0; - assert!(invalid.validate().is_err()); -} - -#[test] -fn reports_are_serializable_and_mismatched_inputs_fail_before_resolution() { - let config = SimulationConfig::embedded().expect("config"); - let source = entity(1, EntityType::Event, &[]); - let target = entity(2, EntityType::Town, &[]); - let report = resolve( - &config, - &spec(&config, InfluxLevel::Good, 12), - &source, - &target, - 4, - ) - .expect("report"); - let encoded = serde_json::to_vec(&report).expect("serialize"); - let decoded: lib_efo::influx::ResolutionReport = - serde_json::from_slice(&encoded).expect("deserialize"); - assert_eq!(decoded, report); - - let mut wrong_source = spec(&config, InfluxLevel::Good, 12); - wrong_source.source = Uuid::from_u128(99); - assert!(resolve(&config, &wrong_source, &source, &target, 4).is_err()); - let mut wrong_rules = spec(&config, InfluxLevel::Good, 12); - wrong_rules.ruleset_id = "unknown".into(); - assert!(resolve(&config, &wrong_rules, &source, &target, 4).is_err()); -} - -#[test] -fn every_level_stays_inside_its_pressure_band_and_replays_exactly() { - let config = SimulationConfig::embedded().expect("config"); - let source = entity(1, EntityType::Event, &[]); - let target = entity(2, EntityType::Town, &[]); - for band in &config.levels { - for seed in 0..128 { - let first = resolve( - &config, - &spec(&config, band.level, seed), - &source, - &target, - 7, - ) - .expect("resolution"); - let replay = resolve( - &config, - &spec(&config, band.level, seed), - &source, - &target, - 7, - ) - .expect("replay"); - assert_eq!(first, replay); - assert!((band.min..=band.max).contains(&first.base_pressure)); - } - } -} - -#[test] -fn stable_target_subseeds_are_independent_of_resolution_order() { - let config = SimulationConfig::embedded().expect("config"); - let source = entity(1, EntityType::Event, &[(ListStats::Threat, 40)]); - let targets = [ - entity(2, EntityType::Town, &[(ListStats::Health, 10)]), - entity(3, EntityType::Town, &[(ListStats::Health, 80)]), - ]; - let forward = targets - .iter() - .map(|target| { - resolve( - &config, - &spec(&config, InfluxLevel::Bad, 42), - &source, - target, - 3, - ) - .expect("forward") - }) - .collect::>(); - let reverse = targets - .iter() - .rev() - .map(|target| { - resolve( - &config, - &spec(&config, InfluxLevel::Bad, 42), - &source, - target, - 3, - ) - .expect("reverse") - }) - .collect::>(); - assert_eq!(forward[0], reverse[1]); - assert_eq!(forward[1], reverse[0]); - assert_ne!(forward[0].id, forward[1].id); -} - -#[test] -fn thresholds_produce_all_four_outcomes_and_typed_effects() { - let base = SimulationConfig::embedded().expect("config"); - let source = entity(1, EntityType::Event, &[]); - let target = entity(2, EntityType::Town, &[]); - for (expected, attenuation) in [ - (ResolutionOutcome::Destroyed, 0), - (ResolutionOutcome::Avoided, 0), - (ResolutionOutcome::Dampened, 5_000), - (ResolutionOutcome::Affected, 10_000), - ] { - let mut config = base.clone(); - config.roll.min = 0; - config.roll.max = 0; - config.source_weights.clear(); - config.resistance_weights.clear(); - config.effects = vec![StatWeight { - stat: StatName::Health, - basis_points: 10_000, - }]; - let pressure = resolve( - &config, - &spec(&config, InfluxLevel::Mid, 9), - &source, - &target, - 0, - ) - .expect("pressure") - .base_pressure; - config.thresholds = match expected { - ResolutionOutcome::Destroyed => OutcomeThresholds { - destroyed_max: pressure, - avoided_max: pressure + 1, - dampened_max: pressure + 2, - dampened_basis_points: 5_000, - }, - ResolutionOutcome::Avoided => OutcomeThresholds { - destroyed_max: pressure - 1, - avoided_max: pressure, - dampened_max: pressure + 1, - dampened_basis_points: 5_000, - }, - ResolutionOutcome::Dampened => OutcomeThresholds { - destroyed_max: pressure - 2, - avoided_max: pressure - 1, - dampened_max: pressure, - dampened_basis_points: 5_000, - }, - ResolutionOutcome::Affected => OutcomeThresholds { - destroyed_max: pressure - 3, - avoided_max: pressure - 2, - dampened_max: pressure - 1, - dampened_basis_points: 5_000, - }, - }; - let report = resolve( - &config, - &spec(&config, InfluxLevel::Mid, 9), - &source, - &target, - 0, - ) - .expect("outcome"); - assert_eq!(report.outcome, expected); - assert_eq!(report.attenuation_basis_points, attenuation); - if attenuation == 0 { - assert!(report.proposed_changes.is_empty()); - } else { - assert_eq!(report.proposed_changes[0].stat, StatName::Health); - assert_eq!( - report.proposed_changes[0].delta, - pressure * attenuation / 10_000 - ); - } - } -}