From 49b05cafbfbbf6ac01d8d9ae88d5a04a80d4cdc3 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 22 Sep 2026 03:38:52 +0200 Subject: [PATCH] feat: resolve diffusion arrivals --- AGENTS-TASKS.md | 4 +- bin_efo/src/commands/adjudicate.rs | 2 +- bin_efo/src/commands/diffuse.rs | 229 +++++++++++++++++- bin_efo/tests/cli_workflows.rs | 129 ++++++++++ docs/commands.md | 12 + docs/issue-audit.md | 2 +- docs/resolution-conflict-design.md | 32 +-- lib_efo/src/entity/implementations/methods.rs | 5 + lib_efo/src/simulation.rs | 28 +++ 9 files changed, 417 insertions(+), 26 deletions(-) diff --git a/AGENTS-TASKS.md b/AGENTS-TASKS.md index fb38926..e0a4379 100644 --- a/AGENTS-TASKS.md +++ b/AGENTS-TASKS.md @@ -244,9 +244,9 @@ and [`docs/presentation-design.md`](docs/presentation-design.md). - [x] Persist source-event potency outside ordinary statistics, monotonically dampen future policy-default effects, expose it in command output, and make a destroyed ruling expire/prevent diffusion with restore/revert recovery. -- [ ] Resolve diffusion arrivals against protected towns and configured +- [x] Resolve diffusion arrivals against protected towns and configured blockers, explaining avoided/dampened/destroyed outcomes. -- [ ] Resolve resident and positioned characters deterministically; document +- [x] Resolve resident and positioned characters deterministically; document the initial policy for characters currently in transit. - [ ] Add generic multi-side conflict records, participant validation, pure fight/war round resolution, victory, stalemate, and explicit ending. diff --git a/bin_efo/src/commands/adjudicate.rs b/bin_efo/src/commands/adjudicate.rs index 61a0c5b..7568923 100644 --- a/bin_efo/src/commands/adjudicate.rs +++ b/bin_efo/src/commands/adjudicate.rs @@ -239,7 +239,7 @@ fn parse_target(raw: &str) -> Result<(EntityType, EntityIdentifier), AppError> { } /// Parse one explicit effect. -fn parse_effect(raw: &str) -> Result { +pub(crate) fn parse_effect(raw: &str) -> Result { let (stat, delta) = raw.split_once(':').ok_or_else(|| { lib_efo::adjudication::AdjudicationError::Invalid(format!( "effect `{raw}` must use STAT:DELTA, for example health:-8" diff --git a/bin_efo/src/commands/diffuse.rs b/bin_efo/src/commands/diffuse.rs index ccbbbca..77570e6 100644 --- a/bin_efo/src/commands/diffuse.rs +++ b/bin_efo/src/commands/diffuse.rs @@ -2,15 +2,19 @@ use std::path::Path; -use clap::{Args, Subcommand}; +use clap::{Args, Subcommand, ValueEnum}; use lib_efo::{ + adjudication::{ + AdjudicationConfig, AdjudicationDisposition, AdjudicationLevel, AdjudicationSpec, + apply_to_world, preview_at_potency, + }, entity::EntityIdentifier, - simulation::{begin_diffusion, plan_diffusion, tick_diffusion}, + simulation::{MobilityState, begin_diffusion, plan_diffusion, tick_diffusion}, stats::EntityType, workspace::Workspace, }; -use crate::error::AppError; +use crate::{commands::adjudicate::parse_effect, error::AppError}; /// Event diffusion operations. #[derive(Debug, Subcommand)] @@ -19,6 +23,57 @@ pub enum DiffuseCmd { Start(DiffuseStartArgs), /// Preview or advance every active event frontier. Tick(DiffuseTickArgs), + /// Resolve one pending town arrival and its selected characters. + Resolve(DiffuseResolveArgs), +} + +/// Which characters share a town arrival resolution. +#[derive(Debug, Clone, Copy, ValueEnum)] +pub enum CharacterPolicy { + /// Do not target characters. + None, + /// Target characters whose mobility state makes them town residents. + Residents, + /// Target non-travelling characters at the town's exact position. + Positioned, + /// Combine resident and positioned characters. + Both, +} + +/// Game-master ruling for one pending arrival. +#[derive(Debug, Args)] +#[command( + after_long_help = "EXAMPLE:\n efo diffuse resolve Plague Haven --level good --characters both\n efo diffuse resolve Plague Haven --level bad --disposition dampened --effect health:-8 --apply" +)] +pub struct DiffuseResolveArgs { + /// Source event name/prefix or @UUID. + event: EntityIdentifier, + /// Pending town name/prefix or @UUID. + town: EntityIdentifier, + /// Game-master interpretation of the external roll. + #[arg(long, value_enum)] + level: AdjudicationLevel, + /// External result retained verbatim. + #[arg(long, default_value = "not recorded")] + result: String, + /// Applied, dampened, avoided, or destroyed. + #[arg(long, value_enum, default_value = "applied")] + disposition: AdjudicationDisposition, + /// Explicit STAT:DELTA; omit to use progressive policy defaults. + #[arg(long, value_name = "STAT:DELTA")] + effect: Vec, + /// Optional game-master explanation. + #[arg(long, default_value = "")] + note: String, + /// Characters included in the same ruling. Travellers are always excluded. + #[arg(long, value_enum, default_value = "residents")] + characters: CharacterPolicy, + /// Complete replacement adjudication policy JSON. + #[arg(long)] + config: Option, + /// Apply effects and record the resolution; preview is the default. + #[arg(long)] + apply: bool, } /// New diffusion configuration. @@ -59,9 +114,177 @@ pub fn handle(command: &DiffuseCmd) -> Result<(), AppError> { match command { DiffuseCmd::Start(args) => start(args), DiffuseCmd::Tick(args) => tick(args), + DiffuseCmd::Resolve(args) => resolve(args), } } +/// Preview and optionally apply one pending arrival as a single transaction. +fn resolve(args: &DiffuseResolveArgs) -> Result<(), AppError> { + let mut workspace = Workspace::open(Path::new("."))?; + let event = workspace + .worktree + .world + .find_entity_of_type(&Some(args.event.clone()), &EntityType::Event)? + .id; + let town = workspace + .worktree + .world + .find_entity_of_type(&Some(args.town.clone()), &EntityType::Town)? + .clone(); + let diffusion = workspace + .worktree + .world + .diffusions + .get(&event) + .ok_or_else(|| { + lib_efo::adjudication::AdjudicationError::Invalid(format!( + "event @{} has no active diffusion; run `efo diffuse start … --apply` first", + event + )) + })?; + if !diffusion.pending.contains(&town.id) { + return Err(lib_efo::adjudication::AdjudicationError::Invalid(format!( + "{} is not awaiting resolution for this event; advance with `efo diffuse tick … --apply`", + town.name + )).into()); + } + let config = match &args.config { + Some(path) => AdjudicationConfig::load(path)?, + None => AdjudicationConfig::embedded()?, + }; + let effects = args + .effect + .iter() + .map(|raw| parse_effect(raw)) + .collect::, _>>()?; + let spec = AdjudicationSpec { + level: args.level, + disposition: args.disposition, + source: event, + external_result: args.result.clone(), + note: args.note.clone(), + effects, + policy_id: config.policy_id.clone(), + }; + let potency = workspace + .worktree + .world + .event_adjudications + .get(&event) + .map_or(10_000, |state| state.potency_basis_points); + let mut targets = vec![(EntityType::Town, town.id, town.name.clone())]; + for character in selected_characters(&workspace.worktree.world, &town, args.characters) { + targets.push((EntityType::Character, character.id, character.name.clone())); + } + targets[1..].sort_unstable_by_key(|target| target.1); + let blockers = workspace + .worktree + .world + .blockers + .iter() + .filter(|blocker| { + blocker.position() == town.position() + || blocker.links().iter().any(|link| link.other_id == town.id) + || town.links().iter().any(|link| link.other_id == blocker.id) + }) + .map(|blocker| blocker.name.as_str()) + .collect::>(); + let mut reports = Vec::new(); + let mut output = format!( + "Arrival resolution preview · {} → {}\n", + workspace + .worktree + .world + .find_entity_strict(event, Some(EntityType::Event))? + .name, + town.name + ); + output.push_str(&format!("├─ Source potency: {}%\n", potency / 100)); + if blockers.is_empty() { + output.push_str("├─ Protection context: none\n"); + } else { + output.push_str(&format!("├─ Protection context: {}\n", blockers.join(", "))); + } + output.push_str(&format!( + "├─ Targets: {} (travellers excluded)\n", + targets.len() + )); + for (kind, id, name) in &targets { + let target = workspace + .worktree + .world + .find_entity_strict(*id, Some(*kind))?; + let report = preview_at_potency(&config, &spec, target, diffusion.elapsed_ticks, potency)?; + output.push_str(&format!("│ • {name} ({kind:?})")); + if report.changes.is_empty() { + output.push_str(" · no stat changes\n"); + } else { + for change in &report.changes { + output.push_str(&format!( + " · {:?} {} → {}", + change.stat, change.before, change.after + )); + } + output.push('\n'); + } + reports.push((*kind, report)); + } + output.push_str(&format!("└─ Disposition: {:?}\n", args.disposition)); + if !args.apply { + output.push_str("Nothing changed. Re-run with `--apply` to resolve this arrival.\n"); + print!("{output}"); + return Ok(()); + } + let mut updated = workspace.worktree.world.clone(); + for (kind, report) in &reports { + updated = apply_to_world(&updated, &config, report, *kind)?; + } + let state = updated.diffusions.get_mut(&event).ok_or_else(|| { + lib_efo::adjudication::AdjudicationError::Invalid( + "diffusion disappeared during resolution".into(), + ) + })?; + state.pending.remove(&town.id); + for (_, report) in &reports { + state.resolved.insert(report.target, report.id); + } + workspace.worktree.world = updated; + workspace.save_worktree("resolve diffusion arrival")?; + output.push_str("✓ Arrival resolved in the worktree. Undo: efo restore --worktree --all\n"); + print!("{output}"); + Ok(()) +} + +/// Select stable character targets; in-transit characters are conservative exclusions. +fn selected_characters<'a>( + world: &'a lib_efo::epoch::EpochInfo, + town: &lib_efo::entity::Entity, + policy: CharacterPolicy, +) -> Vec<&'a lib_efo::entity::Entity> { + if matches!(policy, CharacterPolicy::None) { + return Vec::new(); + } + world + .characters + .iter() + .filter(|character| match world.mobility.get(&character.id) { + Some(MobilityState::Travelling { .. }) => false, + Some(MobilityState::Resident { place }) => { + matches!(policy, CharacterPolicy::Residents | CharacterPolicy::Both) + && *place == town.id + } + Some(MobilityState::Roaming { position }) => { + matches!(policy, CharacterPolicy::Positioned | CharacterPolicy::Both) + && position == town.position() + } + None => { + matches!(policy, CharacterPolicy::Positioned | CharacterPolicy::Both) + && character.position() == town.position() + } + }) + .collect() +} + /// Render and optionally persist a new frontier. fn start(args: &DiffuseStartArgs) -> Result<(), AppError> { let mut workspace = Workspace::open(Path::new("."))?; diff --git a/bin_efo/tests/cli_workflows.rs b/bin_efo/tests/cli_workflows.rs index 94b571d..4a8a404 100644 --- a/bin_efo/tests/cli_workflows.rs +++ b/bin_efo/tests/cli_workflows.rs @@ -884,6 +884,34 @@ fn event_diffusion_is_deterministic_previewed_and_not_reapplied() { &repo, &["event", "add", "Plague", "--position", "0,0"], )); + assert_success(&efo( + &repo, + &["blocker", "add", "Wardstone", "--position", "0,0"], + )); + assert_success(&efo( + &repo, + &[ + "chr", + "add", + "Cora", + "--position", + "0,0", + "--stats", + "health:40", + ], + )); + assert_success(&efo( + &repo, + &[ + "chr", + "add", + "Aria", + "--position", + "0,0", + "--stats", + "health:40", + ], + )); assert_success(&efo( &repo, &[ @@ -896,6 +924,27 @@ fn event_diffusion_is_deterministic_previewed_and_not_reapplied() { "--apply", ], )); + assert_success(&efo( + &repo, + &["travel", "plan", "Aria", "Northwatch", "--apply"], + )); + assert_success(&efo(&repo, &["travel", "tick", "100", "--apply"])); + assert_success(&efo( + &repo, + &[ + "chr", + "add", + "Bran", + "--position", + "0,0", + "--stats", + "health:40", + ], + )); + assert_success(&efo( + &repo, + &["travel", "plan", "Bran", "Northwatch", "--apply"], + )); let preview = efo(&repo, &["diffuse", "start", "Plague"]); assert_success(&preview); @@ -922,6 +971,86 @@ fn event_diffusion_is_deterministic_previewed_and_not_reapplied() { assert_success(&tick_preview); assert!(stdout(&tick_preview).contains("Newly reached 2")); assert_success(&efo(&repo, &["diffuse", "tick", "10", "--apply"])); + let resolution_preview = efo( + &repo, + &[ + "diffuse", + "resolve", + "Plague", + "Haven", + "--level", + "bad", + "--characters", + "positioned", + "--disposition", + "avoided", + ], + ); + assert_success(&resolution_preview); + let resolution_text = stdout(&resolution_preview); + assert!(resolution_text.contains("Protection context: Wardstone")); + assert!(resolution_text.contains("Cora (Character)")); + assert!(!resolution_text.contains("Aria (Character)")); + assert!(!resolution_text.contains("Bran (Character)")); + assert!(resolution_text.contains("Health 40 → 40")); + assert!(resolution_text.contains("Nothing changed")); + let pending_before = snapshot(&repo, 0)["diffusions"] + .as_object() + .expect("diffusions") + .values() + .next() + .expect("diffusion")["pending"] + .as_array() + .expect("pending") + .len(); + assert_eq!(pending_before, 2); + + let resolution_apply = efo( + &repo, + &[ + "diffuse", + "resolve", + "Plague", + "Haven", + "--level", + "bad", + "--characters", + "positioned", + "--disposition", + "avoided", + "--apply", + ], + ); + assert_success(&resolution_apply); + let diffusion = snapshot(&repo, 0)["diffusions"] + .as_object() + .expect("diffusions") + .values() + .next() + .expect("diffusion") + .clone(); + assert_eq!(diffusion["pending"].as_array().expect("pending").len(), 1); + assert_eq!( + diffusion["resolved"].as_object().expect("resolved").len(), + 2 + ); + + let resident_preview = efo( + &repo, + &[ + "diffuse", + "resolve", + "Plague", + "Northwatch", + "--level", + "good", + "--characters", + "residents", + ], + ); + assert_success(&resident_preview); + assert!(stdout(&resident_preview).contains("Aria (Character)")); + assert!(!stdout(&resident_preview).contains("Cora (Character)")); let repeated = efo(&repo, &["diffuse", "tick", "0", "--apply"]); assert_success(&repeated); assert!(stdout(&repeated).contains("Newly reached 0")); diff --git a/docs/commands.md b/docs/commands.md index 1838f2a..08d4d8d 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -121,6 +121,8 @@ efo diffuse start Plague --road-speed 100 --direct-speed 25 --expires-after 20 efo diffuse start Plague --road-speed 100 --direct-speed 25 --expires-after 20 --apply efo diffuse tick 3 efo diffuse tick 3 --apply +efo diffuse resolve Plague Haven --level good --characters residents +efo diffuse resolve Plague Haven --level good --characters residents --apply ``` The preview reports each destination's arrival tick and whether it is reached @@ -129,6 +131,16 @@ previewing the same tick again cannot reach a town twice. Expired state remains inspectable and can be restored, staged, or committed like any other worktree change. +Applied ticks leave newly reached towns pending until the game master resolves +them. `diffuse resolve` shows colocated or linked blockers as protection +context, then previews the town and characters selected by `--characters +none|residents|positioned|both`. Protection never silently chooses an outcome: +use `--disposition applied|dampened|avoided|destroyed`. Avoided targets are +still recorded and cannot be resolved twice. Travelling characters are +conservatively excluded because interpolated route positions are not yet +stored. One `--apply` writes all target effects and resolution records +atomically; normal worktree restore undoes the batch. + ## External rolls and game-master adjudication Epoch Forge does not roll or infer an outcome. The player rolls outside the diff --git a/docs/issue-audit.md b/docs/issue-audit.md index 408a28c..fb21149 100644 --- a/docs/issue-audit.md +++ b/docs/issue-audit.md @@ -19,7 +19,7 @@ absent. | [#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) | Functionally complete: `adjudicate`/`influx` records the external roll and all six levels/dispositions, supports progressive or explicit effects, persists source potency, and makes destroyed events stop diffusion. Audit, stale-state, restoration, and repository validation are covered. | Close the live tracker issue after review. | -| [#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`. | +| [#8 Event diffusion](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/8) | Functionally complete: deterministic spread creates pending arrivals; `diffuse resolve` uses adjudication potency, protection context, explicit avoidance/destruction, and stable resident/positioned character selection with atomic restoreable application. | Close the live tracker issue after review; interpolated in-transit positions remain a separate travel enhancement. | | [#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. | Implementation order is #9's shared resolution engine, the remaining #8 diff --git a/docs/resolution-conflict-design.md b/docs/resolution-conflict-design.md index 8726318..f4dffc9 100644 --- a/docs/resolution-conflict-design.md +++ b/docs/resolution-conflict-design.md @@ -181,18 +181,13 @@ expires an existing frontier, and prevents a new diffusion from starting. ## 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: +The implemented `DiffusionState` stores origin, elapsed ticks, expiry, ordered +town frontier, affected towns, pending arrivals, and target-to-adjudication +resolution records. The character policy is selected per resolution. Destroyed +source state and diffusion expiry together provide the stop reason; the full +adjudication remains in its durable audit record instead of being duplicated. -```text -resolved: BTreeMap -stopped: Option -character_policy: Residents | Positioned | Both | None -adjudication: Option -``` - -When a tick reaches a town: +When a tick reaches a town, `diffuse resolve` now: 1. derive town and character targets according to `character_policy`; 2. show blockers/protection as context for the master's ruling; @@ -208,10 +203,9 @@ 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 -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. +positioned characters use exact position/town association. The implemented +policy conservatively excludes in-transit characters until interpolated travel +positions exist; help and reports say so. Acceptance gates add tests for protected and unprotected towns, resident and roaming characters, destroyed propagation, expiry before arrival, zero-tick @@ -297,10 +291,10 @@ upgrade path under issue #17. disposition and prove no roll/effect is invented. 3. **Complete:** persist idempotent adjudication records and expose preview/apply/list, with `influx` as a visible alias. -4. **Partially complete:** source attenuation now affects future default - resolutions and destroyed sources stop diffusion. Next integrate automatic - arrival targets, then resident/positioned characters and protection - explanations. +4. **Complete:** ticks create pending arrivals; source attenuation affects + future defaults; resolution atomically covers towns and selected + resident/positioned characters, explains positioned/linked protection, + records avoided targets, and stops diffusion when destroyed. 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 diff --git a/lib_efo/src/entity/implementations/methods.rs b/lib_efo/src/entity/implementations/methods.rs index 11b13da..47eae07 100644 --- a/lib_efo/src/entity/implementations/methods.rs +++ b/lib_efo/src/entity/implementations/methods.rs @@ -53,6 +53,11 @@ impl Entity { } } + /// Read the entity's typed relationships without exposing mutable metadata. + pub fn links(&self) -> &[stats::TypedLink] { + &self.metadata.links + } + /// Removes a link (UUID) from the entity's metadata. /// /// If the supplied `id_to_remove` exists in `self.metadata.links`, it is diff --git a/lib_efo/src/simulation.rs b/lib_efo/src/simulation.rs index 6df7c06..b0c7dd4 100644 --- a/lib_efo/src/simulation.rs +++ b/lib_efo/src/simulation.rs @@ -91,6 +91,12 @@ pub struct DiffusionState { /// Towns already reached, preventing repeated effects. #[serde(default)] pub affected: BTreeSet, + /// Reached towns waiting for a game-master ruling. + #[serde(default)] + pub pending: BTreeSet, + /// Towns and characters resolved to durable adjudication records. + #[serde(default)] + pub resolved: BTreeMap, /// Whether expiry has already stopped this event. #[serde(default)] pub expired: bool, @@ -243,6 +249,25 @@ pub fn validate_diffusions(world: &EpochInfo) -> Result<(), SimulationError> { } previous = Some(key); } + if state + .pending + .iter() + .any(|town| !towns.contains(town) || !state.affected.contains(town)) + { + return Err(SimulationError::InvalidDiffusion { + event: *event, + reason: "pending arrival refers to a missing town".into(), + }); + } + if state.resolved.iter().any(|(target, record)| { + world.find_entity_strict(*target, None).is_err() + || !world.adjudications.contains_key(record) + }) { + return Err(SimulationError::InvalidDiffusion { + event: *event, + reason: "resolved target refers to a missing adjudication".into(), + }); + } } Ok(()) } @@ -306,6 +331,8 @@ pub fn plan_diffusion( expires_after, frontier, affected: BTreeSet::new(), + pending: BTreeSet::new(), + resolved: BTreeMap::new(), expired: false, }) } @@ -329,6 +356,7 @@ pub fn tick_diffusion(world: &mut EpochInfo, amount: u64) -> DiffusionTick { if target.arrival_tick <= state.elapsed_ticks.min(limit) && state.affected.insert(target.town) { + state.pending.insert(target.town); reached.push((*event, target.town)); } }