From b8df3cc142ca495a6a85695c050b82f095463453 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Thu, 24 Sep 2026 19:35:42 +0200 Subject: [PATCH] test: harden epoch resolution compatibility and reduction boundaries --- AGENTS-TASKS.md | 3 + README.md | 4 +- docs/architecture.md | 13 +++- docs/epoch-resolution-tasks.md | 3 + docs/repository.md | 2 +- docs/roadmap.md | 8 ++- lib_efo/src/epoch_resolution.rs | 10 ++- lib_efo/src/repository_format.rs | 6 +- lib_efo/src/workspace.rs | 3 +- lib_efo/tests/epoch_resolution.rs | 116 ++++++++++++++++++++++++++++++ 10 files changed, 154 insertions(+), 14 deletions(-) diff --git a/AGENTS-TASKS.md b/AGENTS-TASKS.md index 76fac13..55b9e2c 100644 --- a/AGENTS-TASKS.md +++ b/AGENTS-TASKS.md @@ -268,6 +268,9 @@ and [`docs/presentation-design.md`](docs/presentation-design.md). complete-resolution stage/restore, historical validation, and CLI permutation tests. - [x] Add pinned event-local ChaCha12 named draws; keep GM rolls external and preserve the existing worldgen algorithm. Actual worker pools remain future work. +- Final validation: 167 all-feature workspace tests, formatting, and strict + Clippy pass. Coverage includes all six three-ruling permutations, three mixed + CLI orders, format upgrades, legacy records, stale snapshots, and overflow. - [x] Document immutable batch inputs, event/occurrence RNG identities, exact delta reduction, normalization, retries, phase barriers, and atomic publication diff --git a/README.md b/README.md index 49d659e..7da55d9 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ future timeline when needed. The current release manages organisations, characters, towns, events, calamities, and blockers with statistics and relationships. Repository format -1.0 provides worktree/index staging, immutable commits, restore, conflict-safe +1.1 provides worktree/index staging, immutable commits, restore, conflict-safe revert, switching, and recoverable future pruning from initialisation. A separate TUI searches entities across HEAD, staged, and working state, and offers previewed entity creation/editing with one-step undo. Custom fields and TUI @@ -71,7 +71,7 @@ Run `efo --help`, `efo --help`, or see the | Area | Available now | Not available yet | |---|---|---| -| Repository | Initialise format 1.0; inspect; lock and recover transactional writes | Future 1.x migration tooling; discovery from child directories; integrity repair | +| Repository | Initialise format 1.1; 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; roads, travel, event diffusion/arrival resolution; record external rolls and adjudications; run multi-side fights and wars | Setting template packs and interpolated in-transit positions | diff --git a/docs/architecture.md b/docs/architecture.md index 901dcfe..d84883e 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -24,9 +24,9 @@ metadata as the model becomes organisation-agnostic. Phase 4's approved persistence boundary is specified in the [staging, history, and recovery design](staging-design.md). It separates HEAD, the index, and the editable worktree, and defines the atomic transaction rules -that implementation must preserve. The sole pre-release repository format is -version 1.0; its structured major/minor discriminator leaves room for explicit -1.x migrations without retaining an unreleased prototype reader. +that implementation must preserve. Repository format 1.1 adds a persisted epoch-resolution baseline; 1.0 remains +readable and upgrades atomically on resolution publication or new history. +The structured version rejects readers that cannot preserve the new state. The [TUI contract](tui-design.md) covers browsing and previewed entity editing. `EntityDraft` validates forms in the library; `Workspace::apply_entity_change` checks the editor snapshot and writes the worktree under one transaction lock. @@ -39,3 +39,10 @@ ptrace backend cannot reliably attribute child-process execution. Routine CI should run formatting, all-target workspace tests, strict Clippy, and a release build. Tarpaulin and `rust_autobadges` remain local significant-release-only tools. See [AGENTS.md](../AGENTS.md) for contributor rules. + +`epoch_resolution` owns independent baseline previews and exact contribution +reduction for adjudication, diffusion arrivals, and conflict rounds. CLI handlers +render local and aggregate outcomes and call `Workspace::apply_resolution` for +locked stale-snapshot validation and publication. `event_rng` provides immutable +named ChaCha12 draws from frozen event inputs; adjudication remains externally +rolled. See [the execution contract](deterministic-execution-design.md). diff --git a/docs/epoch-resolution-tasks.md b/docs/epoch-resolution-tasks.md index 70ba6a1..32af4ec 100644 --- a/docs/epoch-resolution-tasks.md +++ b/docs/epoch-resolution-tasks.md @@ -68,3 +68,6 @@ versions are pinned; golden vectors were cross-checked with an independent Python FNV/ChaCha12 reference calculation. GM rulings and existing worldgen do not call this API. No worker pool, transfer allocation, or automatic event scheduling is introduced by this feature. + +Final validation: formatting, 167 locked all-feature workspace tests, and strict +Clippy pass. All implementation increments are committed on the feature branch. diff --git a/docs/repository.md b/docs/repository.md index 0370823..9bfa365 100644 --- a/docs/repository.md +++ b/docs/repository.md @@ -73,7 +73,7 @@ The optional `epoch_resolution` field stores ruleset set of enrolled adjudication IDs. The baseline has no nested resolution state. Each new adjudication identifies its `epoch_baseline`; absent fields on 1.0 records mean historical sequential semantics. Old records are never enrolled -implicitly. Committed snapshots retain the interval's audit inputs; a new +implicitly; their already-applied effects become part of the first new baseline. Committed snapshots retain the interval's audit inputs; a new interval replaces the worktree's baseline rather than nesting previous ones. Existing 1.0 repositories open without writes. Applying a resolution upgrades diff --git a/docs/roadmap.md b/docs/roadmap.md index d965a3e..021e24a 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -23,7 +23,7 @@ Nerd Font output has a portable build option, relationships are type-validated, and every mutation has documented and tested recovery guidance. The [Phase 4 format contract](staging-design.md) is implemented. Native format -1.0 initialization, locking, recovery, staging, immutable commits, revert, and +1.1 initialization, locking, recovery, staging, immutable commits, revert, and recoverable pruning are implemented. The unreleased prototype reader and its temporary migration were removed before the first release. Future compatible changes use 1.x versions and regain explicit migration tooling when needed. @@ -59,3 +59,9 @@ direct terminal printing. PNG map rendering follows those tracker issues. Completions and structured output are the best first stretch investments. A TUI and branching should wait until staging, revert, and locking are reliable. + +Epoch-wide independent ruling reduction is implemented across adjudication, +diffusion resolution, and conflict rounds, with format-1.0 compatibility reads. +Named event-local RNG is available as a library foundation. Worker pools, +automatic event scheduling, and transfer allocation remain future work; see +[the completed implementation checklist](epoch-resolution-tasks.md). diff --git a/lib_efo/src/epoch_resolution.rs b/lib_efo/src/epoch_resolution.rs index cf52eee..3fbbbe6 100644 --- a/lib_efo/src/epoch_resolution.rs +++ b/lib_efo/src/epoch_resolution.rs @@ -158,13 +158,17 @@ pub fn apply( .iter() .find(|entry| entry.target == report.target && entry.stat == change.stat) .map_or(change.before, |entry| entry.after); - if **target.get_stats().get_field(&change.stat.list_stat()) != change.before - || **current.get_stats().get_field(&change.stat.list_stat()) != expected - { + if **target.get_stats().get_field(&change.stat.list_stat()) != change.before { return Err(AdjudicationError::Stale { target: report.target, }); } + if **current.get_stats().get_field(&change.stat.list_stat()) != expected { + return Err(invalid(format!( + "target @{} {:?} was edited since the epoch baseline; commit or restore the worktree before resolving this field", + report.target, change.stat + ))); + } } updated.adjudications.insert(report.id, report.clone()); let state = updated diff --git a/lib_efo/src/repository_format.rs b/lib_efo/src/repository_format.rs index b301363..b76b859 100644 --- a/lib_efo/src/repository_format.rs +++ b/lib_efo/src/repository_format.rs @@ -22,10 +22,10 @@ impl std::fmt::Display for FormatVersion { } } -/// The only repository format supported by this pre-release build. +/// Latest writable repository format; older minors in this major remain readable. pub const CURRENT_FORMAT_VERSION: FormatVersion = FormatVersion { major: 1, minor: 1 }; -/// The version-2 repository manifest. +/// The versioned repository manifest. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct RepositoryManifest { /// On-disk format discriminator. @@ -63,7 +63,7 @@ impl RepositoryManifest { } } -/// A complete version-2 index or worktree snapshot. +/// A complete versioned index or worktree snapshot. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct RepositorySnapshot { /// Snapshot format discriminator. diff --git a/lib_efo/src/workspace.rs b/lib_efo/src/workspace.rs index cbb1b2e..bcc5496 100644 --- a/lib_efo/src/workspace.rs +++ b/lib_efo/src/workspace.rs @@ -1,4 +1,4 @@ -//! Format-2 HEAD, index, and worktree access. +//! Format-1.x HEAD, index, and worktree access. use std::{ collections::{BTreeMap, HashMap}, @@ -231,6 +231,7 @@ impl Workspace { /// Copy the complete worktree into the index. pub fn stage_all(&mut self) -> Result<(), WorkspaceError> { self.index.world = self.worktree.world.clone(); + self.index.format_version = self.worktree.format_version; self.save_index("stage --all") } diff --git a/lib_efo/tests/epoch_resolution.rs b/lib_efo/tests/epoch_resolution.rs index 5130dc5..5115c62 100644 --- a/lib_efo/tests/epoch_resolution.rs +++ b/lib_efo/tests/epoch_resolution.rs @@ -388,3 +388,119 @@ fn event_rng_reads_frozen_inputs_and_compounds_its_identity_only_next_epoch() { original ); } + +#[test] +fn three_way_reduction_never_clamps_partial_sums() { + let initial = world(100); + let config = AdjudicationConfig::embedded().expect("config"); + let reports = [100, -200, 10] + .into_iter() + .enumerate() + .map(|(occurrence, delta)| { + ( + EntityType::Town, + preview( + &initial, + &config, + &spec(1, delta), + Uuid::from_u128(3), + occurrence as u64, + ) + .expect("report"), + ) + }) + .collect::>(); + let expected = apply(&initial, &config, &reports).expect("batch"); + assert_eq!(health(&expected), 30); + for order in [ + [0, 1, 2], + [0, 2, 1], + [1, 0, 2], + [1, 2, 0], + [2, 0, 1], + [2, 1, 0], + ] { + let mut updated = initial.clone(); + for index in order { + updated = apply(&updated, &config, &[reports[index].clone()]).expect("incremental"); + } + assert_eq!( + serde_json::to_value(updated).expect("updated"), + serde_json::to_value(&expected).expect("expected") + ); + } +} + +#[test] +fn legacy_rulings_are_baseline_history_and_never_reenrolled() { + let config = AdjudicationConfig::embedded().expect("config"); + let initial = world(100); + let old = lib_efo::adjudication::preview(&config, &spec(1, -10), &initial.towns[0], 0) + .expect("legacy report"); + let old_world = + lib_efo::adjudication::apply_to_world(&initial, &config, &old, EntityType::Town) + .expect("legacy apply"); + let old_bytes = serde_json::to_vec(&old_world).expect("legacy representation"); + let old_world: EpochInfo = serde_json::from_slice(&old_bytes).expect("read legacy record"); + let next = + preview(&old_world, &config, &spec(2, -10), Uuid::from_u128(3), 0).expect("new ruling"); + let next_id = next.id; + let updated = apply(&old_world, &config, &[(EntityType::Town, next)]).expect("apply"); + assert_eq!(health(&updated), 80); + assert_eq!(updated.adjudications[&old.id], old); + assert_eq!( + updated.epoch_resolution.as_ref().expect("state").records, + [next_id].into_iter().collect() + ); + let mut corrupt = updated.clone(); + corrupt.epoch_resolution = None; + assert!(resolution::validate(&corrupt).is_err()); + let mut corrupt = updated.clone(); + corrupt + .event_adjudications + .get_mut(&Uuid::from_u128(2)) + .expect("source") + .potency_basis_points = 1; + assert!(resolution::validate(&corrupt).is_err()); + let mut corrupt = updated; + corrupt + .epoch_resolution + .as_mut() + .expect("state") + .records + .clear(); + assert!(resolution::validate(&corrupt).is_err()); +} + +#[test] +fn record_limits_and_population_aggregate_overflow_leave_inputs_untouched() { + let mut config = AdjudicationConfig::embedded().expect("config"); + let initial = world(100); + let a = preview(&initial, &config, &spec(1, 5), Uuid::from_u128(3), 0).expect("a"); + let b = preview(&initial, &config, &spec(2, 5), Uuid::from_u128(3), 0).expect("b"); + config.max_records = 1; + assert!( + apply( + &initial, + &config, + &[(EntityType::Town, a), (EntityType::Town, b)] + ) + .is_err() + ); + assert_eq!(health(&initial), 100); + config.max_records = 10; + let reports = [1, 2] + .into_iter() + .map(|source| { + let mut ruling = spec(source, isize::MAX); + ruling.effects[0].stat = StatName::Population; + ( + EntityType::Town, + preview(&initial, &config, &ruling, Uuid::from_u128(3), 0) + .expect("local population"), + ) + }) + .collect::>(); + assert!(apply(&initial, &config, &reports).is_err()); + assert!(initial.epoch_resolution.is_none()); +}