# 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), [#8](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/8), and [#12](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/12). It distinguishes the spatial propagation already implemented from the outcome resolution still required. No command described here is implemented merely by appearing in this document. ## Product contract Simulation is deterministic, 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 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. 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. ## Shared deterministic resolution engine ### Influx levels `InfluxLevel` is a stable serialized enum and a Clap value enum: | 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 | 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. ### Inputs and stable records 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 } ResolutionRecord { id, source, target, tick_or_round, seed, pressure, resistance, outcome, attenuation, proposed_changes, applied, ruleset_id } ResolutionOutcome = Affected | 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. `proposed_changes` is a typed list of field/stat deltas, not formatted text. Every change carries before/projected-after values and the 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 The first ruleset is deliberately simple and configurable: 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. 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. Interpretation of `Destroyed` depends on the source: - for an incoming event, propagation stops and the event is marked exhausted; - for a conflict participant, it means removed from that conflict, not deleted 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. ### Configuration Add `lib_efo/assets/simulation/default.json` and a versioned `SimulationConfig` independent of repository and worldgen versions. It owns: - 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. 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 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 ``` `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. Target scopes support stable entity selectors and semantic groups (`towns`, `characters`, `organisations`, `reached`) without requiring custom fields. Ambiguous names abort. `reached` consumes the affected set of an event's 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; - 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. ## Issue #8: finish diffusion resolution The existing `DiffusionState` already stores origin, elapsed ticks, expiry, ordered town frontier, affected towns, and road/direct route reasons. Preserve that representation and extend it additively with: ```text resolved: BTreeMap stopped: Option character_policy: Residents | Positioned | Both | None influx: 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; 5. stop the event if its resolution is `Destroyed`; 6. include route, protection source, roll explanation, 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. Characters are resolved in stable UUID order. Residents use mobility state; positioned characters use exact position/town association; travellers are only targeted when the configured policy includes their current segment/location. The initial slice may conservatively exclude in-transit characters until interpolated travel positions exist, but help and reports must say so. Acceptance gates add tests for protected and unprotected towns, resident and roaming characters, destroyed propagation, expiry before arrival, zero-tick replay, large tick convergence, and deterministic output under shuffled vector insertion order. ## Issue #12: fight and war Conflict reuses resolution records instead of directly coupling entities. ```text ConflictState { id, name, kind, sides, seed, round, status, location, ruleset_id, objectives, records } ConflictKind = Fight | War ConflictStatus = Planned | Active | Stalemate | Won { side } | Ended ParticipantRef { entity_type, id, side, committed_weight } ``` Any stored entity type may participate. Duplicate participants, empty sides, missing IDs, zero committed weight, and fewer than two sides are invalid. Side labels are user strings so organisations, coalitions, departments, or individuals fit the same model. A fight is a bounded, normally single-resolution conflict. A war is persistent and advances in explicit rounds. Neither automatically creates/deletes normal entities. Resolution may propose stat changes and may generate ordinary Event entities through configuration; these appear in the worktree diff like other changes. Proposed CLI: ```text efo conflict start NAME --kind fight --side red:town:Haven --side blue:org:Guild --seed N efo conflict preview CONFLICT [--rounds N] efo conflict advance CONFLICT [--rounds N] --apply efo conflict show CONFLICT efo conflict end CONFLICT --reason TEXT [--apply] efo fight ... # focused alias/help surface efo war ... # focused alias/help surface ``` 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. 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, restore/stage/commit/revert, and malformed persisted conflict state. ## Persistence and compatibility Additive state belongs in `EpochInfo` with `#[serde(default)]`, as roads, mobility, and diffusion already do: ```text resolution_records: BTreeMap conflicts: BTreeMap ``` Never persist RNG objects, hash maps with unstable iteration, display strings, or pathfinder caches. Workspace validation checks all cross-references, record uniqueness, monotonic conflict rounds, resolved-target links, ruleset IDs, and configured safety limits. `fsck` exercises the same validation for every historical epoch. These additions remain backward-readable through defaults while the project is unreleased. Freeze the exact format before the first release; after that point, any semantic reinterpretation requires a 1.x migration fixture and previewed 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. 4. Integrate resolution into diffusion towns, then resident/positioned characters and protection explanations. 5. Add generic conflict state and pure round resolution. 6. Expose conflict/fight/war preview/apply commands and recovery tests. 7. Run default and portable gates, corruption fixtures, help snapshots, and release builds; update the live tracker only after each issue's acceptance gates pass.