From 6210f5e73751fa016d8d3f4a54f94abc8932cc2e Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 22 Sep 2026 00:20:11 +0200 Subject: [PATCH] fix: enforce entity stat domains --- AGENTS-TASKS.md | 4 ++ bin_efo/tests/cli_workflows.rs | 23 +++++++ docs/commands.md | 5 +- docs/issue-audit.md | 6 +- lib_efo/src/entity/edit.rs | 1 + .../src/entity/implementations/accesors.rs | 7 +- lib_efo/src/stats.rs | 65 +++++++++++++++++++ lib_efo/src/stats/implementations/test.rs | 25 +++++++ lib_efo/src/workspace.rs | 6 ++ 9 files changed, 137 insertions(+), 5 deletions(-) diff --git a/AGENTS-TASKS.md b/AGENTS-TASKS.md index 6503909..bf22cd2 100644 --- a/AGENTS-TASKS.md +++ b/AGENTS-TASKS.md @@ -53,6 +53,10 @@ validates links in every historical epoch. The remaining tracker items are mapped to implemented, partial, blocked, and planned work in [`docs/issue-audit.md`](docs/issue-audit.md). +**Tracker checkpoint — stat domains: complete.** Issue #15 now has one +enforced policy across CLI edits, TUI drafts, derived-stat recalculation, and +workspace validation without clamping real population counts. + ## Phase 0 — audit and guardrails - [x] Inventory workspace crates, commands, persistence files, CI, and tests. diff --git a/bin_efo/tests/cli_workflows.rs b/bin_efo/tests/cli_workflows.rs index 143e02f..8da019a 100644 --- a/bin_efo/tests/cli_workflows.rs +++ b/bin_efo/tests/cli_workflows.rs @@ -595,6 +595,29 @@ fn unified_show_filters_entities_and_summarises_epochs() { assert!(stdout(&full_epoch).contains("\"commit_message\": \"Populate ports\"")); } +#[test] +fn entity_mutations_enforce_stat_domains() { + let repo = TestRepo::new(); + assert_success(&efo(&repo, &["init"])); + assert_success(&efo( + &repo, + &[ + "town", + "add", + "Boundsville", + "--stats", + "population:250000", + "strength:-5", + "health:999", + ], + )); + let world = snapshot(&repo, 0); + let stats = &world["towns"][0]["stats"]; + assert_eq!(stats["population"], 250_000); + assert_eq!(stats["strength"], 0); + assert_eq!(stats["health"], 120); +} + #[test] fn fsck_validates_links_inside_historical_epochs() { let repo = TestRepo::new(); diff --git a/docs/commands.md b/docs/commands.md index 87a9561..9e94d00 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -52,7 +52,10 @@ Common add/edit options include `--stats key:value ...`, `--position x,y`, `--duration`, `--bounds`, `--effect`, faction/reach/description/relationship options, and prestige controls. `edit --delta` adds supplied stats rather than replacing them. See nested help (for example `efo chr add --help`) for exact -syntax and values. Entity mutations edit only the worktree. Use `efo diff`, +syntax and values. Persistent normalized stats are clamped to `0..=120`; +growth and event/blocker modifiers use `-120..=120`; population remains an +unbounded non-negative count for persistent entities. Entity mutations edit +only the worktree. Use `efo diff`, `efo stage --all`, `efo stage --world`, or `efo stage --kind KIND ID...`, and `efo diff --staged` to prepare history. `efo restore --staged ...` copies diff --git a/docs/issue-audit.md b/docs/issue-audit.md index 14ee5d8..83a74c6 100644 --- a/docs/issue-audit.md +++ b/docs/issue-audit.md @@ -12,7 +12,7 @@ absent. | [#18 Implement show](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/18) | Addressed for the CLI: `show` defaults to all, dispatches every collection, filters by name/text/position, reads historical epochs, and renders epoch summaries at three detail levels. | Consider structured output and richer stat predicates later. | | [#17 Serialization errors/upgrades](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/17) | Version detection and actionable rejection are complete. No legacy release exists, so a speculative upgrader was intentionally removed. | Add explicit `1.x` migrations when the first real format change exists. | | [#16 Rewrite backend](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/16) | Addressed by `Workspace`, typed snapshots, transactional writes, broad integration coverage, and removal of the remaining unjustified legacy `unsafe fn` declarations. | Avoid rewriting stable code wholesale; continue adding focused tests. | -| [#15 Clamp stats](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/15) | Open. Effect bounds exist, but a documented global stat-domain policy does not. | Define per-stat versus configurable bounds before enforcement. | +| [#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) | Needs current source data and a definition of “pre-event”; the issue has no acceptance details. | Fold cards into versioned worldgen configuration after clarification. | | [#12 Add fight/war](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/12) | Open simulation feature. | Model it as configured events/relationships after custom fields and influx semantics settle. | @@ -22,6 +22,6 @@ absent. | [#8 Event diffusion](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/8) | Planned in the simulation roadmap; blocked on roads, residency, and deterministic routing. | Complete simulation checkpoints 2–3 in order. | | [#6 HashMap/HashSet](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/6) | Vectors remain the stable serialized representation; replacing them would churn the format. | Add ephemeral UUID/name indexes only if profiling justifies them. | -Preferred order: finish display buffering/structured output, specify stat -bounds and custom fields, implement roads/residency, then build influx, +Preferred order: finish display buffering/structured output and custom fields, +implement roads/residency, then build influx, fight/war, and diffusion on those foundations. diff --git a/lib_efo/src/entity/edit.rs b/lib_efo/src/entity/edit.rs index 99bf269..1065f8a 100644 --- a/lib_efo/src/entity/edit.rs +++ b/lib_efo/src/entity/edit.rs @@ -142,6 +142,7 @@ impl EntityDraft { } entity.stats = serde_json::from_value(statistics).map_err(|error| format!("Statistics: {error}"))?; + entity.update_metastats(); Ok(entity) } } diff --git a/lib_efo/src/entity/implementations/accesors.rs b/lib_efo/src/entity/implementations/accesors.rs index 1347013..e32d7d0 100644 --- a/lib_efo/src/entity/implementations/accesors.rs +++ b/lib_efo/src/entity/implementations/accesors.rs @@ -252,7 +252,12 @@ impl Entity { /// Defer the update of all stats pub fn update_metastats(&mut self) { - self.stats.update(); + self.stats.clamp_for(self.entity_type); + } + + /// Return whether this entity's persisted statistics satisfy its domain. + pub fn stats_are_bounded(&self) -> bool { + self.stats.is_bounded_for(self.entity_type) } /// Return whether the entity matches an optional identifier. diff --git a/lib_efo/src/stats.rs b/lib_efo/src/stats.rs index 9db8bcf..ce38cb9 100644 --- a/lib_efo/src/stats.rs +++ b/lib_efo/src/stats.rs @@ -251,6 +251,71 @@ fn color_cell_categories(cell: CellStruct, value: &GenericStat) -> CellStruct { } impl OverallStats { + /// Clamp user-editable values to the supported simulation domain. + /// + /// Population is an unbounded non-negative count. Growth and event/blocker + /// modifiers may be negative; other normalised values use `0..=120`. + pub fn clamp_for(&mut self, kind: EntityType) { + let modifier = matches!(kind, EntityType::Event | EntityType::Blocker); + self.population = GenericStat(if modifier { + (*self.population).max(-120) + } else { + (*self.population).max(0) + }); + self.growth_rate = GenericStat((*self.growth_rate).clamp(-120, 120)); + let minimum = if modifier { -120 } else { 0 }; + for value in [ + &mut self.crime, + &mut self.happiness, + &mut self.food, + &mut self.industry, + &mut self.science, + &mut self.trade, + &mut self.army, + &mut self.strength, + &mut self.fortification, + &mut self.threat, + &mut self.bureaucracy, + &mut self.transportation, + &mut self.sprawl, + &mut self.health, + ] { + *value = GenericStat((**value).clamp(minimum, 120)); + } + self.update(); + } + + /// Whether all editable values already satisfy the persisted domain. + pub fn is_bounded_for(&self, kind: EntityType) -> bool { + let mut copy = self.clone(); + copy.clamp_for(kind); + let fields = [ + ListStats::Demographics, + ListStats::Population, + ListStats::Growthrate, + ListStats::Crime, + ListStats::Happiness, + ListStats::Economy, + ListStats::Food, + ListStats::Industry, + ListStats::Science, + ListStats::Trade, + ListStats::Military, + ListStats::Army, + ListStats::Strength, + ListStats::Fortification, + ListStats::Threat, + ListStats::Infrastructure, + ListStats::Bureaucracy, + ListStats::Transportation, + ListStats::Sprawl, + ListStats::Health, + ]; + fields + .iter() + .all(|field| self.get_field(field) == copy.get_field(field)) + } + /// Create Stats with a given rng distribution pub(crate) fn create_rng( rng: &RngLevel, diff --git a/lib_efo/src/stats/implementations/test.rs b/lib_efo/src/stats/implementations/test.rs index 1e23207..ba89a19 100644 --- a/lib_efo/src/stats/implementations/test.rs +++ b/lib_efo/src/stats/implementations/test.rs @@ -267,6 +267,31 @@ fn documented_full_stat_names_parse() { } } +#[test] +fn stat_domains_preserve_counts_and_clamp_normalised_values() { + let mut persistent = stats::OverallStats { + population: stats::GenericStat(250_000), + growth_rate: stats::GenericStat(-999), + strength: stats::GenericStat(-4), + health: stats::GenericStat(999), + ..Default::default() + }; + persistent.clamp_for(stats::EntityType::Town); + assert_eq!(*persistent.population, 250_000); + assert_eq!(*persistent.growth_rate, -120); + assert_eq!(*persistent.strength, 0); + assert_eq!(*persistent.health, 120); + assert!(persistent.is_bounded_for(stats::EntityType::Town)); + + let mut modifier = stats::OverallStats { + food: stats::GenericStat(-999), + ..Default::default() + }; + modifier.clamp_for(stats::EntityType::Event); + assert_eq!(*modifier.food, -120); + assert!(modifier.is_bounded_for(stats::EntityType::Event)); +} + #[test] fn test_liststats_unknown_alias() { // Pick a string that is not in the list of known aliases. diff --git a/lib_efo/src/workspace.rs b/lib_efo/src/workspace.rs index fd233db..9e079c0 100644 --- a/lib_efo/src/workspace.rs +++ b/lib_efo/src/workspace.rs @@ -845,6 +845,12 @@ fn validate_world(label: &str, world: &EpochInfo) -> Result<(), WorkspaceError> entity.name ))); } + if !entity.stats_are_bounded() { + return Err(WorkspaceError::Inconsistent(format!( + "{label} entity `{}` contains statistics outside its allowed domain", + entity.name + ))); + } } } for entity in world