feat: add reversible event diffusion

This commit is contained in:
Dandaedre 2026-09-22 01:04:30 +02:00
parent 0b62ab9968
commit 70123bf0d5
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
12 changed files with 465 additions and 11 deletions

View File

@ -209,11 +209,11 @@ workspace validation without clamping real population counts.
### Checkpoint 3 — spatial event diffusion
- [ ] Define event origins, speed, frontier, affected-set, and expiry data.
- [ ] Diffuse over roads and slower direct distance using configured
- [x] Define event origins, speed, frontier, affected-set, and expiry data.
- [x] Diffuse over roads and slower direct distance using configured
coefficients and deterministic tie-breaking.
- [ ] Preview each tick with route/reason output before applying it.
- [ ] Test repeated application, convergence, expiry, disconnected graphs, and
- [x] Preview each tick with route/reason output before applying it.
- [x] Test repeated application, convergence, expiry, disconnected graphs, and
deterministic replay across many seeds.
### Checkpoint 4 — PNG map rendering

View File

@ -74,7 +74,7 @@ Run `efo --help`, `efo <command> --help`, or see the
| Repository | Initialise format 1.0; inspect; lock and recover transactional writes | Future 1.x migration tooling; discovery from child directories; integrity repair |
| Timeline | Commit, advance, switch, log, tag, summarise, diff, reviewable/committed revert, backed-up pruning, and explicit hard reset | Branching and merging |
| Entities | Add, edit, list, inspect, diff, and delete six built-in types | Custom types and custom fields; bulk operations |
| Generation and simulation | Generate deterministic seeded worlds; define roads and preview/apply deterministic character travel | Event diffusion and setting template packs |
| Generation and simulation | Generate deterministic seeded worlds; define roads; preview/apply travel and spatial event diffusion | Influx, conflict simulation, and setting template packs |
| Interfaces | Complete CLI; `efo-tui` browser and entity editor | TUI staging/commits; GUI/web (out of scope) |
`efo show all` gives a world overview; per-type commands such as

View File

@ -8,6 +8,7 @@
#![warn(missing_docs, clippy::missing_docs_in_private_items)]
pub mod diffuse;
pub mod entity_generic;
pub mod epoch;
pub mod generate;

View File

@ -0,0 +1,128 @@
//! Preview-first spatial event diffusion.
use std::path::Path;
use clap::{Args, Subcommand};
use lib_efo::{
entity::EntityIdentifier,
simulation::{begin_diffusion, plan_diffusion, tick_diffusion},
stats::EntityType,
workspace::Workspace,
};
use crate::error::AppError;
/// Event diffusion operations.
#[derive(Debug, Subcommand)]
pub enum DiffuseCmd {
/// Preview or start spatial propagation for an event.
Start(DiffuseStartArgs),
/// Preview or advance every active event frontier.
Tick(DiffuseTickArgs),
}
/// New diffusion configuration.
#[derive(Debug, Args)]
#[command(
after_long_help = "EXAMPLES:\n efo diffuse start Plague\n efo diffuse start Plague --road-speed 120 --direct-speed 25 --expires-after 20 --apply"
)]
pub struct DiffuseStartArgs {
/// Event name/prefix or @UUID.
event: EntityIdentifier,
/// Additional percentage applied to each road's speed.
#[arg(long, default_value_t = 100)]
road_speed: u32,
/// Off-road propagation speed percentage.
#[arg(long, default_value_t = 25)]
direct_speed: u32,
/// Stop propagation at this relative tick.
#[arg(long)]
expires_after: Option<u64>,
/// Store the frontier in the worktree; preview is the default.
#[arg(long)]
apply: bool,
}
/// Diffusion tick options.
#[derive(Debug, Args)]
pub struct DiffuseTickArgs {
/// Number of ticks to advance.
#[arg(default_value_t = 1)]
amount: u64,
/// Update the worktree; preview is the default.
#[arg(long)]
apply: bool,
}
/// Dispatch one diffusion operation.
pub fn handle(command: &DiffuseCmd) -> Result<(), AppError> {
match command {
DiffuseCmd::Start(args) => start(args),
DiffuseCmd::Tick(args) => tick(args),
}
}
/// Render and optionally persist a new frontier.
fn start(args: &DiffuseStartArgs) -> 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 state = plan_diffusion(
&workspace.worktree.world,
event,
args.road_speed,
args.direct_speed,
args.expires_after,
)?;
println!(
"Diffusion preview · {} destination(s)",
state.frontier.len()
);
for target in &state.frontier {
let town = workspace
.worktree
.world
.towns
.iter()
.find(|town| town.id == target.town)
.map_or("unknown", |town| town.name.as_str());
let reason = if target.route.is_empty() {
"direct"
} else {
"road"
};
println!(" • tick {:>4} · {town} · {reason}", target.arrival_tick);
}
if !args.apply {
println!("Nothing changed. Re-run with `--apply` to update the worktree.");
return Ok(());
}
begin_diffusion(&mut workspace.worktree.world, event, state);
workspace.save_worktree("begin event diffusion")?;
println!("✓ Diffusion stored in the worktree. Undo: efo restore --worktree --all");
Ok(())
}
/// Preview and optionally apply frontier progress.
fn tick(args: &DiffuseTickArgs) -> Result<(), AppError> {
let mut workspace = Workspace::open(Path::new("."))?;
let mut preview = workspace.worktree.world.clone();
let report = tick_diffusion(&mut preview, args.amount);
println!("Diffusion tick preview · {} tick(s)", args.amount);
println!("├─ Newly reached {}", report.reached.len());
for (event, town) in &report.reached {
println!("│ • event @{event} → town @{town}");
}
println!("└─ Expired {}", report.expired.len());
if !args.apply {
println!("Nothing changed. Re-run with `--apply` to update the worktree.");
return Ok(());
}
workspace.worktree.world = preview;
workspace.save_worktree("advance event diffusion")?;
println!("✓ Diffusion advanced in the worktree. Undo: efo restore --worktree --all");
Ok(())
}

View File

@ -29,6 +29,7 @@ use clap::{Parser, Subcommand};
use crate::{
commands::{
diffuse::DiffuseCmd,
entity_generic::EntitySubCommands,
epoch::cli_epoch::EpochCmd,
generate::GenCmd,
@ -133,6 +134,9 @@ enum TopLevelCmd {
/// Plan or advance deterministic spatial travel.
#[command(subcommand)]
Travel(TravelCmd),
/// Preview or advance spatial event diffusion.
#[command(subcommand)]
Diffuse(DiffuseCmd),
}
/// Program entry point.
@ -193,6 +197,7 @@ fn exec_dispatch(cli: Cli) -> Result<(), AppError> {
TopLevelCmd::Show(cmd) => commands::show::handle_show_cmd(&cmd),
TopLevelCmd::Gen(cmd) => commands::generate::gen_handler(&cmd),
TopLevelCmd::Travel(cmd) => commands::travel::handle(&cmd),
TopLevelCmd::Diffuse(cmd) => commands::diffuse::handle(&cmd),
TopLevelCmd::Chr(cmd) => commands::entity_generic::handle_entity_commands(
&cmd,
&lib_efo::stats::EntityType::Character,

View File

@ -697,3 +697,67 @@ fn roads_and_travel_are_previewed_applied_and_restorable() {
.is_empty()
);
}
#[test]
fn event_diffusion_is_deterministic_previewed_and_not_reapplied() {
let repo = TestRepo::new();
assert_success(&efo(&repo, &["init"]));
assert_success(&efo(&repo, &["town", "add", "Haven", "--position", "0,0"]));
assert_success(&efo(
&repo,
&["town", "add", "Northwatch", "--position", "20,0"],
));
assert_success(&efo(
&repo,
&["event", "add", "Plague", "--position", "0,0"],
));
assert_success(&efo(
&repo,
&[
"travel",
"road-add",
"Haven",
"Northwatch",
"--speed",
"200",
"--apply",
],
));
let preview = efo(&repo, &["diffuse", "start", "Plague"]);
assert_success(&preview);
assert!(stdout(&preview).contains("Diffusion preview"));
assert!(
snapshot(&repo, 0)["diffusions"]
.as_object()
.expect("diffusions")
.is_empty()
);
assert_success(&efo(
&repo,
&[
"diffuse",
"start",
"Plague",
"--expires-after",
"11",
"--apply",
],
));
let tick_preview = efo(&repo, &["diffuse", "tick", "10"]);
assert_success(&tick_preview);
assert!(stdout(&tick_preview).contains("Newly reached 2"));
assert_success(&efo(&repo, &["diffuse", "tick", "10", "--apply"]));
let repeated = efo(&repo, &["diffuse", "tick", "0", "--apply"]);
assert_success(&repeated);
assert!(stdout(&repeated).contains("Newly reached 0"));
assert_success(&efo(&repo, &["restore", "--worktree", "--all"]));
assert!(
snapshot(&repo, 0)["diffusions"]
.as_object()
.expect("diffusions")
.is_empty()
);
}

View File

@ -110,6 +110,25 @@ carry their own speed; disconnected characters fall back to slower direct
travel. Characters have explicit resident, roaming, or travelling state. Use
`efo restore --worktree --all` to discard applied simulation changes.
## Event diffusion
Events propagate from their map position over the same topology. Roads use
their configured speed and direct spatial propagation remains a slower
fallback:
```text
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
```
The preview reports each destination's arrival tick and whether it is reached
by road or directly. Persisted frontiers retain an affected set, so applying or
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.
## Generation and output
`efo gen character|town|event|exotic|calamity|blocker` prints generated content

View File

@ -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) | Addressed for inspection: unified `show` and diff rendering build complete strings before a single output write, and `Displayable::full_display` no longer forces library output through `println!`. | Apply the same boundary opportunistically to mutation confirmations. |
| [#9 Adding influx](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/9) | Open and underspecified. | Define versioned deterministic severity and avoidance rules before commands. |
| [#8 Event diffusion](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/8) | Spatial prerequisite complete: stable roads, explicit mobility, deterministic routing, direct fallback, and previewed ticks are implemented. Diffusion itself remains open. | Implement checkpoint 3 on the shared topology. |
| [#8 Event diffusion](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/8) | Addressed: events have persisted origins, deterministic road/direct frontiers, affected sets, expiry, previewed ticks, replay tests, and worktree-only application. | Extend effects through configurable influx rules rather than embedding setting assumptions. |
| [#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. |
Roads and residency now provide the shared spatial foundation. Next build

View File

@ -19,7 +19,7 @@ use crate::{
epoch_traits::{ConfigWritable, Prettiable},
},
error::EpochError,
simulation::{MobilityState, Road},
simulation::{DiffusionState, MobilityState, Road},
stats::{EntityType, Position, PositionIdentifier, Symbols, TypedLink},
};
@ -92,6 +92,10 @@ pub struct EpochInfo {
#[serde(default)]
#[table(skip)]
pub mobility: BTreeMap<Uuid, MobilityState>,
/// Active event diffusion state keyed by event UUID.
#[serde(default)]
#[table(skip)]
pub diffusions: BTreeMap<Uuid, DiffusionState>,
}
impl Prettiable for EpochInfo {}
@ -113,6 +117,7 @@ impl Default for EpochInfo {
blockers: Vec::new(),
roads: Vec::new(),
mobility: BTreeMap::new(),
diffusions: BTreeMap::new(),
}
}
}

View File

@ -2,7 +2,7 @@
use std::{
cmp::Reverse,
collections::{BTreeMap, BinaryHeap, HashMap, HashSet},
collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet},
};
use serde::{Deserialize, Serialize};
@ -66,6 +66,45 @@ pub struct TravelPlan {
pub uses_roads: bool,
}
/// Scheduled arrival of an event at one town.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DiffusionTarget {
/// Destination town.
pub town: Uuid,
/// Tick, relative to diffusion start, when the event arrives.
pub arrival_tick: u64,
/// Town route used; empty means direct spatial diffusion.
pub route: Vec<Uuid>,
}
/// Persisted frontier and affected-set for one diffusing event.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DiffusionState {
/// Event's immutable origin for this run.
pub origin: Position,
/// Applied simulation ticks.
pub elapsed_ticks: u64,
/// Optional tick at which propagation stops.
pub expires_after: Option<u64>,
/// Deterministically ordered arrival schedule.
pub frontier: Vec<DiffusionTarget>,
/// Towns already reached, preventing repeated effects.
#[serde(default)]
pub affected: BTreeSet<Uuid>,
/// Whether expiry has already stopped this event.
#[serde(default)]
pub expired: bool,
}
/// Result of previewing or applying a diffusion tick.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiffusionTick {
/// Newly reached `(event, town)` pairs.
pub reached: Vec<(Uuid, Uuid)>,
/// Events removed because their expiry was reached.
pub expired: Vec<Uuid>,
}
/// Invalid topology or travel request.
#[derive(Debug, thiserror::Error)]
pub enum SimulationError {
@ -86,6 +125,17 @@ pub enum SimulationError {
/// Travel speed must be positive.
#[error("off-road speed must be greater than zero")]
InvalidSpeed,
/// A referenced event does not exist.
#[error("event @{0} does not exist")]
EventMissing(Uuid),
/// Persisted diffusion state violates an invariant.
#[error("invalid diffusion for event @{event}: {reason}")]
InvalidDiffusion {
/// Event owning the state.
event: Uuid,
/// Violated invariant.
reason: String,
},
}
/// Validate road identities, endpoints, and speeds.
@ -156,6 +206,133 @@ pub fn validate_mobility(world: &EpochInfo) -> Result<(), SimulationError> {
Ok(())
}
/// Validate persisted diffusion references and frontier ordering.
pub fn validate_diffusions(world: &EpochInfo) -> Result<(), SimulationError> {
let events = world
.events
.iter()
.map(|entity| entity.id)
.collect::<HashSet<_>>();
let towns = world
.towns
.iter()
.map(|entity| entity.id)
.collect::<HashSet<_>>();
for (event, state) in &world.diffusions {
if !events.contains(event) {
return Err(SimulationError::EventMissing(*event));
}
let mut previous = None;
for target in &state.frontier {
if !towns.contains(&target.town)
|| target.route.iter().any(|town| !towns.contains(town))
{
return Err(SimulationError::TownMissing(target.town));
}
let key = (target.arrival_tick, target.town);
if previous.is_some_and(|prior| prior > key) {
return Err(SimulationError::InvalidDiffusion {
event: *event,
reason: "frontier is not deterministically ordered".into(),
});
}
previous = Some(key);
}
}
Ok(())
}
/// Build a deterministic diffusion schedule without changing the world.
pub fn plan_diffusion(
world: &EpochInfo,
event: Uuid,
road_speed: u32,
direct_speed: u32,
expires_after: Option<u64>,
) -> Result<DiffusionState, SimulationError> {
validate_roads(world)?;
if road_speed == 0 || direct_speed == 0 {
return Err(SimulationError::InvalidSpeed);
}
let source = world
.events
.iter()
.find(|entity| entity.id == event)
.ok_or(SimulationError::EventMissing(event))?;
let origin = source.position().clone();
let origin_town = world
.towns
.iter()
.filter(|town| town.position() == &origin)
.map(|town| town.id)
.min();
let mut frontier = world
.towns
.iter()
.map(|town| {
let direct = ticks(&origin, town.position(), direct_speed);
let road =
origin_town.and_then(|start| road_route_scaled(world, start, town.id, road_speed));
match road {
Some((cost, route)) if cost <= direct => DiffusionTarget {
town: town.id,
arrival_tick: cost,
route,
},
_ => DiffusionTarget {
town: town.id,
arrival_tick: direct,
route: Vec::new(),
},
}
})
.collect::<Vec<_>>();
frontier.sort_unstable_by_key(|target| (target.arrival_tick, target.town));
Ok(DiffusionState {
origin,
elapsed_ticks: 0,
expires_after,
frontier,
affected: BTreeSet::new(),
expired: false,
})
}
/// Store a previously previewed diffusion schedule.
pub fn begin_diffusion(world: &mut EpochInfo, event: Uuid, state: DiffusionState) {
world.diffusions.insert(event, state);
}
/// Advance all event frontiers once without reaching a town twice.
pub fn tick_diffusion(world: &mut EpochInfo, amount: u64) -> DiffusionTick {
let mut reached = Vec::new();
let mut expired = Vec::new();
for (event, state) in &mut world.diffusions {
if state.expired {
continue;
}
state.elapsed_ticks = state.elapsed_ticks.saturating_add(amount);
let limit = state.expires_after.unwrap_or(u64::MAX);
for target in &state.frontier {
if target.arrival_tick <= state.elapsed_ticks.min(limit)
&& state.affected.insert(target.town)
{
reached.push((*event, target.town));
}
}
if state
.expires_after
.is_some_and(|expiry| state.elapsed_ticks >= expiry)
{
state.expired = true;
expired.push(*event);
}
}
reached.sort_unstable();
expired.sort_unstable();
DiffusionTick { reached, expired }
}
/// Select the fastest road route, falling back to slower direct travel.
pub fn plan_travel(
world: &EpochInfo,
@ -286,6 +463,16 @@ pub fn tick_travel(world: &mut EpochInfo, amount: u64) -> Vec<Uuid> {
/// Find the deterministic shortest road-time path.
fn road_route(world: &EpochInfo, start: Uuid, destination: Uuid) -> Option<(u64, Vec<Uuid>)> {
road_route_scaled(world, start, destination, 100)
}
/// Find a shortest road path with an additional propagation speed multiplier.
fn road_route_scaled(
world: &EpochInfo,
start: Uuid,
destination: Uuid,
speed_scale: u32,
) -> Option<(u64, Vec<Uuid>)> {
if start == destination {
return Some((0, vec![destination]));
}
@ -296,7 +483,11 @@ fn road_route(world: &EpochInfo, start: Uuid, destination: Uuid) -> Option<(u64,
.collect::<HashMap<_, _>>();
let mut graph: HashMap<Uuid, Vec<(Uuid, u64)>> = HashMap::new();
for road in &world.roads {
let cost = ticks(towns[&road.from], towns[&road.to], road.speed_percent);
let effective_speed = u64::from(road.speed_percent)
.saturating_mul(u64::from(speed_scale))
.div_ceil(100)
.min(u64::from(u32::MAX)) as u32;
let cost = ticks(towns[&road.from], towns[&road.to], effective_speed.max(1));
graph.entry(road.from).or_default().push((road.to, cost));
graph.entry(road.to).or_default().push((road.from, cost));
}

View File

@ -14,7 +14,7 @@ use crate::{
entity::EntityIdentifier,
epoch::{EntityIndex, EpochInfo},
repository_format::{FormatError, RepositoryManifest, RepositorySnapshot, decode_manifest},
simulation::{validate_mobility, validate_roads},
simulation::{validate_diffusions, validate_mobility, validate_roads},
stats::EntityType,
transaction::{
RepositoryLock, TransactionError, replace_file, replace_files, replace_files_locked,
@ -827,6 +827,7 @@ fn copy_world_metadata(source: &EpochInfo, destination: &mut EpochInfo) {
fn validate_world(label: &str, world: &EpochInfo) -> Result<(), WorkspaceError> {
validate_roads(world)
.and_then(|()| validate_mobility(world))
.and_then(|()| validate_diffusions(world))
.map_err(|error| WorkspaceError::Inconsistent(format!("{label} {error}")))?;
let index = EntityIndex::build(world);
if !index.duplicate_ids().is_empty() {

View File

@ -1,7 +1,10 @@
use lib_efo::{
entity::Entity,
epoch::EpochInfo,
simulation::{MobilityState, Road, begin_travel, plan_travel, tick_travel, validate_roads},
simulation::{
MobilityState, Road, begin_diffusion, begin_travel, plan_diffusion, plan_travel,
tick_diffusion, tick_travel, validate_roads,
},
stats::EntityType,
};
use uuid::Uuid;
@ -23,6 +26,7 @@ fn world() -> EpochInfo {
entity(3, EntityType::Town, "20,0"),
],
characters: vec![entity(4, EntityType::Character, "0,0")],
events: vec![entity(5, EntityType::Event, "0,0")],
..EpochInfo::default()
};
world.mobility.insert(
@ -98,7 +102,43 @@ fn old_snapshots_default_new_spatial_fields() {
let mut value = serde_json::to_value(EpochInfo::default()).expect("serialize");
value.as_object_mut().expect("object").remove("roads");
value.as_object_mut().expect("object").remove("mobility");
value.as_object_mut().expect("object").remove("diffusions");
let decoded: EpochInfo = serde_json::from_value(value).expect("old snapshot");
assert!(decoded.roads.is_empty());
assert!(decoded.mobility.is_empty());
assert!(decoded.diffusions.is_empty());
}
#[test]
fn diffusion_uses_roads_once_converges_and_expires() {
let mut world = world();
let event = Uuid::from_u128(5);
let state = plan_diffusion(&world, event, 100, 25, Some(11)).expect("frontier");
assert_eq!(state.frontier.len(), 3);
assert!(state.frontier.iter().all(|target| !target.route.is_empty()));
begin_diffusion(&mut world, event, state);
let first = tick_diffusion(&mut world, 5);
assert_eq!(first.reached.len(), 2);
assert!(first.expired.is_empty());
assert!(tick_diffusion(&mut world, 0).reached.is_empty());
let last = tick_diffusion(&mut world, 6);
assert_eq!(last.reached.len(), 1);
assert_eq!(last.expired, [event]);
assert!(tick_diffusion(&mut world, 100).reached.is_empty());
assert_eq!(world.diffusions[&event].affected.len(), 3);
}
#[test]
fn diffusion_replay_is_deterministic_across_varied_worlds() {
for offset in 0..64_u128 {
let mut world = world();
world.events[0].id = Uuid::from_u128(100 + offset);
let event = world.events[0].id;
let first =
plan_diffusion(&world, event, 75 + offset as u32, 20, None).expect("first plan");
let second =
plan_diffusion(&world, event, 75 + offset as u32, 20, None).expect("replayed plan");
assert_eq!(first, second, "variation {offset}");
}
}