A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Sim: gdd-0.3 Food need from the population ledger, one ration per living own id (Fixes #2470) (#2678)
Beri26bee4276ae6
diff --git a/changelog.d/2470-ledger-food.md b/changelog.d/2470-ledger-food.mdnew file mode 100644index 000000000..da66ab55e--- /dev/null+++ b/changelog.d/2470-ledger-food.md@@ -0,0 +1,7 @@+### Changed++- GDD 0.3: the monthly Food settlement can now read its need from the month's frozen population snapshot, one ration for+ each living person record whatever it is doing (working, on a course, travelling, serving), counted once each, so a+ change during the month does not move that month's need (Fixes #2470). The+ stock still stops at zero, and the import refill and the foreign-currency crisis work as before. No game uses the+ ledger yet, so play is unchanged.diff --git a/docs/population-ledger.md b/docs/population-ledger.mdindex e92112f8f..805decd09 100644--- a/docs/population-ledger.md+++ b/docs/population-ledger.md@@ -1,6 +1,6 @@# Population identity foundation — #1689 steps 1–2-This is a fixture-only data/helper contract under exact `gdd-0.3` identity (R-POP-001/002/003), not a playable campaign. No production era, shipped content, catalogue or save envelope changes. The existing synthetic Attention/Arms harnesses still exercise their pre-ledger aggregate model; that does not activate population identity. A state with an initialized ledger is rejected by Simulation.Step, Preview and DelegatedTo and at direct aggregate population/resource producer boundaries before any mutation (PopulationLedger.RefuseAggregate). The guarded sites include Cities, PopulationSystem, Pools, starting forces, training, qualification/demobilisation, military/combat/prisoners, event mutation, the economy and objectives (the readers of GameState.TotalPopulation, which reads the ledger once it is initialized) and the turn resolver. Direct integration into Cities, PopulationSystem, Training, Combat, Prisoners, Pools and other systems remains held.+This is a fixture-only data/helper contract under exact `gdd-0.3` identity (R-POP-001/002/003), not a playable campaign. No production era, shipped content, catalogue or save envelope changes. The existing synthetic Attention/Arms harnesses still exercise their pre-ledger aggregate model; that does not activate population identity. A state with an initialized ledger is rejected by Simulation.Step, Preview and DelegatedTo and at direct aggregate population/resource producer boundaries before any mutation (PopulationLedger.RefuseAggregate). The guarded sites include Cities, PopulationSystem, Pools, starting forces, training, qualification/demobilisation, military/combat/prisoners, event mutation, the economy and objectives (the readers of GameState.TotalPopulation, which reads the ledger once it is initialized) and the turn resolver. Direct integration into Cities, PopulationSystem, Training, Combat, Prisoners, Pools and other systems remains held, except the step-7 Food settlement given a month's synthetic context: the internal `Pools.Consume` overload reads its need from the month's frozen opening snapshot (`Gdd03SyntheticMonthContext.OpeningPeople`), one ration per living own population id in it (R-FOOD-002, #2470). The public `Pools.Consume`, `Pools.Init`, `Harvest`, `BuyArms` and `FoodTerm` still refuse.`PopulationLedger.CreateFixture` is internal (test assembly friend access), constructs a fresh GameState without Simulation.NewGame, validates explicit frozen location/target/captor/qualification bindings and builds inventory in source-key/ordinal order. It never converts census headcounts, historical formations, cohorts or events into people. Fixture rows are visibly synthetic, supplied in test code; no new files are loaded or hashed as content. Each reception tick is one whole reception turn, capped by the Agreed catalogue `reception.turns`; course limits are explicit synthetic target data, not production defaults.@@ -10,7 +10,7 @@ Validation builds a candidate map first, including teacher resolution and uniqueGameState.Clone owns a copied ledger; frozen bindings and records can be shared. Canonical output covers the full binding inventory, all unit fields, source/loss records, initialization flag, scale/reception requirement and allocator in one shared Describe/Hash writer. Reference strings use invariant length-prefixed encoding with an explicit null marker; embedded delimiters cannot alias another record. All accepted reference/provenance strings reject malformed UTF-16 before admission, so UTF-8 hashing cannot collapse invalid surrogate sequences; valid supplementary characters remain lossless. Enum declaration order is never serialized. Older identities enter none of this writer. The new empty gdd-0.3 section changes unpublished schema-4 draft hashes only; no legacy/schema-3 migration or byte change is intended.-No save/reload round trip for population identity is claimed. The existing seed/content/command replay envelope is unchanged; step 3 must introduce actual identity-addressed replayable producers before population fixtures can be saved as campaigns. Captured Food selection and arrival meal timing, course/combat/prisoner integration, production initialization and all of #1704 remain held. This foundation does not close #1689.+No save/reload round trip for population identity is claimed. The existing seed/content/command replay envelope is unchanged; step 3 must introduce actual identity-addressed replayable producers before population fixtures can be saved as campaigns. Captured Food selection and arrival meal timing, course/combat/prisoner integration, production initialization and all of #1704 remain held. The #2470 fixture counts a captured own record as one national ration, the reading of `docs/gdd/balance.md` `population.food_per_turn` ("Food per own population unit, every status") that the owner chose on 5 November 2026 (the recommended option, [recorded on #2678](https://github.com/eyalgolan/statecraft-israel/pull/2678#issuecomment-6652800885) as "Captured own-population records do eat the national ration"); this is settled. This foundation does not close #1689.## Historical start inventory (R-POP-004)diff --git a/docs/rules/mvp.md b/docs/rules/mvp.mdindex f5c40660a..5decbc521 100644--- a/docs/rules/mvp.md+++ b/docs/rules/mvp.md@@ -448,6 +448,8 @@ R-FOOD-001: Food is a national stock of whole units (`GameState.Food`); one unitR-FOOD-002: In step 7 the nation eats the turn's need from the stock as far as it goes: the stock stops at 0, and the rest is the unmet share, kept in the state with the need (Q-POOL-5, decided 15 October 2026). Then a monthly import brings the stock back to `cover_months` of the need, unless foreign currency is exhausted (the `fx_crisis` situation at the turn's start), when nothing is imported (Q-POOL-4, decided 15 October 2026). Imports are already paid for in foreign currency per head (`imports_per_capita_per_year`), so they are not charged again. In the GDD loop the crisis cuts the imports, not `food_supply` directly: `fx_crisis_food_per_year` acts in the legacy loop only.+For R-FOOD-001 and R-FOOD-002 under gdd-0.3 with an initialized population ledger (#2470), the need is the month's: one ration for each living own population id in the month's frozen opening snapshot (the #1716 synthetic month context, `OpeningPeople`), whatever its status or assignment (idle, at work, teaching, on a course, travelling, serving, in reception or held by the enemy), each id once and in any storage order, so a ledger change before step 7 (a combat loss, an arrival) does not move that month's need. The live ledger is reconciled first, so an invalid one moves no Food. The settlement after it is the one above: the stock stops at 0, `FoodNeed` and `FoodUnmet` record that need, and the import refills to `cover_months` of it unless the foreign-currency crisis is on. Counting changes no id, status or assignment. Legacy and gdd-0.1 keep the aggregate head count. Counting a captured own soldier is the owner's decision (5 November 2026, the recommended option, [recorded on #2678](https://github.com/eyalgolan/statecraft-israel/pull/2678#issuecomment-6652800885) as "Captured own-population records do eat the national ration"), the reading of `docs/gdd/balance.md` `population.food_per_turn` ("Food per own population unit, every status"); the ledger's head count (`TotalPeople`) already includes them. No turn reaches this yet: only synthetic fixtures create a month context, and without one an initialized ledger is refused (R-POP-002).+R-FOOD-003: `food_supply` stays the 0 to 1 level the UI, the situations and the events read (Q-POOL-3, decided 15 October 2026), with a stock term inside its effect sum: `k_food * (stock - full) / full - unmet / need`, where `full` is `cover_months` of the last need. The term is exactly 0 at a full stock, `-k_food` when the stock is empty, and the unmet share lowers it further; rationing, the other effects and event shifts act on top as before, and the level's clamp to 0..1 bounds the result. The GDD loop requires the `food_supply` indicator.## Arms@@ -599,7 +601,7 @@ These contracts cover #1689 steps 1–2 and the Historical start inventory (R-POR-POP-001: Only exact `gdd-0.3` enables the population-ledger capability, independently of the broad GDD loop and Attention (R-LOOP-002/005). An immutable own-population record has a dedicated nonnegative ordinal id. Synthetic fixture inventory is ordered by source key (ordinal string comparison), then within-source ordinal. Registered arrivals allocate monotonically; only explicit combat losses remove living ids. Sources remain registered after loss, and ids are never reused. Reconciliation checks the exact created-minus-lost id set against the living ledger, not just equal totals. Status/region counts include every matching record once. The gdd-0.3 scale of a synthetic or Open fixture reads one positive Agreed integer from `population.people_per_unit` in its catalogue (currently 10,000, Open mode's scale under D2); a Historical fixture reads `rules.yaml`'s `people_per_unit` for the start day (1,000), as R-UNIT-006 does (owner, 1 November 2026, D2: "Approve all six (Recommended)", "The Historical MVP keeps main's start: census cities at 1,000 people a unit (`R-CITY-007`)"; R-POP-004); rows with a `census/` or `units_1948/` source key are the Historical start's and are refused in any other fixture. Old identities retain the common rules scale. Missing, fractional, nonpositive, overflowing or Deferred values have no fallback, in either source.-R-POP-002: A ledger record has exactly one typed status and assignment, validated location, home and captor references, whole reception-turn ticks capped by the catalogue requirement, civilian profession-specific tier and actual-work XP, separate military qualification/combat XP, and distinct issued civilian/military equipment and paid facts. Unknown references, unresolved teacher ids, incompatible statuses/assignments, inconsistent region/hex/facility bindings, invalid progress/tiers and duplicate issued-item ownership are refused before mutation. Moves and atomic status/location/assignment transitions retain identity/history. Capture retains home context without inventing a prison hex or refunding equipment. Ledger changes never touch resources, causes, RNG or Attention. Initialization is internal and fixture-only; initialized ledger fixtures refuse aggregate Simulation commands and turns. Old identities refuse ledger mutation. Prices, progression awards, return destinations, tool lock-in and captive-equipment outcomes remain with their owning issues. A craftsman's tier is novice, apprentice or expert (R-CRAFT-003); a farmer's or pioneer's is novice, trained or veteran.+R-POP-002: A ledger record has exactly one typed status and assignment, validated location, home and captor references, whole reception-turn ticks capped by the catalogue requirement, civilian profession-specific tier and actual-work XP, separate military qualification/combat XP, and distinct issued civilian/military equipment and paid facts. Unknown references, unresolved teacher ids, incompatible statuses/assignments, inconsistent region/hex/facility bindings, invalid progress/tiers and duplicate issued-item ownership are refused before mutation. Moves and atomic status/location/assignment transitions retain identity/history. Capture retains home context without inventing a prison hex or refunding equipment. Ledger changes never touch resources, causes, RNG or Attention. Initialization is internal and fixture-only; initialized ledger fixtures refuse aggregate Simulation commands and turns. The step-7 Food settlement given a month's synthetic context is the exception: it reads its need from that month's frozen snapshot (R-FOOD-002, #2470). Old identities refuse ledger mutation. Prices, progression awards, return destinations, tool lock-in and captive-equipment outcomes remain with their owning issues. A craftsman's tier is novice, apprentice or expert (R-CRAFT-003); a farmer's or pioneer's is novice, trained or veteran.R-POP-003: Clone copies all ledger containers; immutable records and frozen bindings may be shared. The canonical writer emits a gdd-0.3-only section ordered by numeric population id, with fixed field order, stable machine tokens, invariant integer formatting and length-prefixed reference strings. It covers every record/assignment/equipment/reference field, binding, creation/loss provenance and allocator even after the last combat loss. Legacy/gdd-0.1 emit no ledger section or allocator marker. R-SAVE-001/002 still govern identity mismatch refusal and replay: no ledger snapshot or new command syntax is added in this foundation, and fixture injection is not replay evidence. Existing unpublished schema-4 draft hashes change; no migration promise is made.diff --git a/sim/Statecraft.Sim.Tests/PoolsTests.cs b/sim/Statecraft.Sim.Tests/PoolsTests.csindex 065aea36e..e56a12a91 100644--- a/sim/Statecraft.Sim.Tests/PoolsTests.cs+++ b/sim/Statecraft.Sim.Tests/PoolsTests.cs@@ -520,4 +520,92 @@ public class PoolsTestsfinally { Thread.CurrentThread.CurrentCulture = culture; }}++ // ---- gdd-0.3: the need from the population ledger (#2470) ----++ static readonly PopulationLocation North = new PopulationLocation("north", 0, 0, "camp");++ static PopulationInventoryRow LedgerRow(int ordinal, PopulationStatus status, PopulationAssignment assignment)+ {+ var captured = status == PopulationStatus.Captured;+ var where = assignment.Kind == PopulationAssignmentKind.Travel ? new PopulationLocation("south", 1, 0, "port") : North;+ return new PopulationInventoryRow("fixture", ordinal, new PopulationUnit(0, status, 0, captured ? null : where, assignment,+ CivilianProfession.None, CivilianTier.None, 0, "basic", 0, PopulationEquipment.None, captured ? "captor" : null, captured ? North : null));+ }++ /// <summary>Eight living own records, each differently assigned: idle, at work, teaching, on a course, travelling,+ /// serving, in reception and held by the enemy.</summary>+ static GameState LedgerState() => PopulationLedger.CreateFixture(PopulationLedgerTests.Content(), PopulationLedgerTests.Bindings(), new[] {+ LedgerRow(0, PopulationStatus.FreeCivilian, PopulationAssignment.Unassigned),+ LedgerRow(1, PopulationStatus.FreeCivilian, new PopulationAssignment(PopulationAssignmentKind.Work, "field")),+ LedgerRow(2, PopulationStatus.FreeCivilian, new PopulationAssignment(PopulationAssignmentKind.Teaching, "teacher")),+ LedgerRow(3, PopulationStatus.Trainee, new PopulationAssignment(PopulationAssignmentKind.Course, "course")),+ LedgerRow(4, PopulationStatus.CivilianInTransit, new PopulationAssignment(PopulationAssignmentKind.Travel, "travel")),+ LedgerRow(5, PopulationStatus.ActiveSoldier, new PopulationAssignment(PopulationAssignmentKind.ActiveService, "service")),+ LedgerRow(6, PopulationStatus.Refugee, new PopulationAssignment(PopulationAssignmentKind.Reception, "reception")),+ LedgerRow(7, PopulationStatus.Captured, PopulationAssignment.Unassigned) });++ /// <summary>The month's frozen opening snapshot of the ledger, taken when the month's context is created.</summary>+ static Gdd03SyntheticMonthContext Month(GameState s) => Gdd03SyntheticMonthContext.CreateSynthetic(SaveGame.Gdd03Ruleset, 0,+ s.PopulationLedger.Units, new[] { "course", "field", "reception", "teacher" }.Select(f => new Gdd03SyntheticFacilitySnapshot(f, true, 1)),+ Array.Empty<int>(), Array.Empty<Gdd03SyntheticHousingSnapshot>(), Array.Empty<Gdd03SyntheticPendingEntry>());++ // R-FOOD-001 (one unit is one population unit's food for a month) and R-FOOD-002 under gdd-0.3: every living own ledger+ // id eats one ration whatever its assignment, the stock stops at 0, and the import refills to cover_months of that need.+ [Fact]+ public void ALedgerGameEatsOneRationPerLivingOwnPopulationId()+ {+ var s = LedgerState(); s.Food = 5;+ var people = s.PopulationLedger.Units;+ var why = new List<Cause>();+ Pools.Consume(PopulationLedgerTests.Content(), s, new MvpRules { CoverMonths = 3 }, Month(s), why);+ Assert.Equal((8, 3), (s.FoodNeed, s.FoodUnmet)); // 5 eaten of 8+ Assert.Equal(24, s.Food); // refilled to 3 months of 8+ Assert.Contains(why, x => x.Key == CauseKeys.FoodShortage);+ Assert.Equal(people, s.PopulationLedger.Units); // counting moves no id, status or assignment+ }++ // R-FOOD-002: the foreign-currency crisis still stops the import in a ledger game.+ [Fact]+ public void ALedgerGameImportsNoFoodInTheForeignCurrencyCrisis()+ {+ var s = LedgerState(); s.Food = 20; s.ActiveSituations.Add(EconomySystem.FxCrisis);+ Pools.Consume(PopulationLedgerTests.Content(), s, new MvpRules { CoverMonths = 3 }, Month(s), new List<Cause>());+ Assert.Equal((12, 8, 0), (s.Food, s.FoodNeed, s.FoodUnmet));+ }++ // R-FOOD-001: the count is one per id whatever order the snapshot holds them in, and a snapshot that repeats an id or+ // holds no record is refused rather than counted.+ [Fact]+ public void LedgerRationsIgnoreOrderAndRefuseARepeatedId()+ {+ var people = LedgerState().PopulationLedger.Units;+ Assert.Equal(8, Pools.Rations(people));+ Assert.Equal(8, Pools.Rations(people.Reverse()));+ Assert.Throws<ArgumentException>(() => Pools.Rations(people.Append(people[3])));+ Assert.Throws<ArgumentException>(() => Pools.Rations(people.Append(null!)));+ Assert.Throws<ArgumentNullException>(() => Pools.Rations(null!));+ }++ // R-POP-002: a ledger state given content of another ruleset is still refused before any Food moves.+ [Fact]+ public void ALedgerStateUnderAnotherRulesetStillRefusesConsume()+ {+ var s = LedgerState(); s.Food = 5; var hash = s.Hash();+ Assert.Throws<NotSupportedException>(() => Pools.Consume(PopulationLedgerTests.Content(SaveGame.GddRuleset), s, new MvpRules { CoverMonths = 3 }, Month(s), new List<Cause>()));+ Assert.Equal(hash, s.Hash());+ }++ // R-FOOD-002 under gdd-0.3 (#2470): the need comes from the month's frozen snapshot, not the live ledger. A combat loss after the month+ // opened leaves the live ledger at 7 ids; the month still eats its 8 opening rations.+ [Fact]+ public void ALedgerGameEatsTheMonthsFrozenSnapshotNotTheLiveLedger()+ {+ var s = LedgerState(); s.Food = 0;+ var month = Month(s);+ s.PopulationLedger.RegisterCombatLoss(5, "fixture-loss");+ Assert.Equal(7, s.PopulationLedger.Units.Count);+ Pools.Consume(PopulationLedgerTests.Content(), s, new MvpRules { CoverMonths = 3 }, month, new List<Cause>());+ Assert.Equal((8, 8, 24), (s.FoodNeed, s.FoodUnmet, s.Food));+ }}diff --git a/sim/Statecraft.Sim/Pools.cs b/sim/Statecraft.Sim/Pools.csindex 68a762922..0b50f5267 100644--- a/sim/Statecraft.Sim/Pools.cs+++ b/sim/Statecraft.Sim/Pools.cs@@ -108,13 +108,35 @@ namespace Statecraft.Sim}}+ /// <summary>R-FOOD-001 under gdd-0.3 (#2470): the month's need of a population ledger, one ration (one population+ /// unit's food) for each living own population id in <paramref name="snapshot"/>, whatever its status or+ /// assignment. The order of the snapshot does not matter; a repeated id or a missing record is refused.</summary>+ internal static int Rations(IEnumerable<PopulationUnit> snapshot)+ {+ if (snapshot == null) throw new ArgumentNullException(nameof(snapshot));+ var ids = new HashSet<int>();+ foreach (var p in snapshot)+ if (p == null || !ids.Add(p.Id)) throw new ArgumentException("A Food snapshot holds each population id once.", nameof(snapshot));+ return ids.Count;+ }+/// <summary>R-FOOD-002, step 7: the nation eats the turn's need from the stock, as far as the stock goes (it stops at/// 0, and the rest is unmet), then the import brings the stock back to cover_months of the need, unless foreign- /// currency is exhausted (the fx_crisis situation at the turn's start), when no Food is imported.</summary>- public static void Consume(Content c, GameState s, MvpRules r, List<Cause> why)+ /// currency is exhausted (the fx_crisis situation at the turn's start), when no Food is imported. The need is the+ /// aggregate head count; a state with an initialized population ledger is refused here (R-POP-002).</summary>+ public static void Consume(Content c, GameState s, MvpRules r, List<Cause> why) => Consume(c, s, r, null, why);++ /// <summary>R-FOOD-002 under gdd-0.3 (#2470): with a <paramref name="month"/> context the need is <see cref="Rations"/>+ /// of the month's frozen opening snapshot (<see cref="Gdd03SyntheticMonthContext.OpeningPeople"/>), not the live+ /// ledger, so a ledger change before step 7 does not move the month's need. The live ledger is checked first+ /// (<see cref="PopulationLedger.Reconcile"/>) so a bad ledger moves no Food. Without a month it is the aggregate need.</summary>+ internal static void Consume(Content c, GameState s, MvpRules r, Gdd03SyntheticMonthContext? month, List<Cause> why){- PopulationLedger.RefuseAggregate(s);- var need = Need(s, r);+ if (month == null) PopulationLedger.RefuseAggregate(s);+ else if (!c.UsesPopulationLedger || !s.PopulationLedger.IsInitialized)+ throw new NotSupportedException("A monthly Food snapshot needs an initialized gdd-0.3 population ledger.");+ else s.PopulationLedger.Reconcile();+ var need = month != null ? Rations(month.OpeningPeople) : Need(s, r);var eaten = Math.Min(need, s.Food);s.Food -= eaten;s.FoodNeed = need;