A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
feat(sim): civilian upkeep runs on a Historical ledger game (#1725 PR 7, producer 05) (#2946)
Eyal Golan94e0673f048b
diff --git a/changelog.d/1725-pr7-civilian-upkeep.md b/changelog.d/1725-pr7-civilian-upkeep.mdnew file mode 100644index 000000000..65dbcdd17--- /dev/null+++ b/changelog.d/1725-pr7-civilian-upkeep.md@@ -0,0 +1,3 @@+- GDD 0.3 starting population (Refs #1725, Refs #1689): civilian upkeep (R-MONEY-002) now runs on the inactive dark+ start's Historical ledger and pays what the aggregate start pays, IL 0m with today's rates. It counts places, not+ people, so no ledger record changes. No new-game wiring, so there is no change in the game.diff --git a/docs/rules/mvp.md b/docs/rules/mvp.mdindex 2e5756471..707380a3c 100644--- a/docs/rules/mvp.md+++ b/docs/rules/mvp.md@@ -436,7 +436,7 @@ R-SCORE-001: The score is the sum of the parts Q-SCORE-1 names (owner, 17 OctobeR-MONEY-001: The GDD's Money is the Treasury (`model.yaml` money `treasury`, in IL millions): the player sees it as Money, כסף in Hebrew, on the top bar, the Budget screen and in the causes (spec §1.2, "Treasury becomes Money"; owner, 15 October 2026, Q-MONEY-4 and Q-HUD-3). Debt stays in the sim and the state hash under Money. Foreign currency also remains state, but it is player-facing: R-MONEY-004 shows the reserve on the Defence screen, permits conversion into Money, and keeps the top bar's Foreign currency meter (owner, 2 November 2026: "Spend the dollars (Recommended)" and "Keep it"). The sourced 1951 currency crisis still happens (D-C3, Q-MONEY-1). The MVP keeps both abstractions approved on #884: the per-head tax represents ordinary revenue, while jobs pay the player-sensitive income in R-CITY-002. The rates remain `tax_per_capita_per_year` 0.0000545 IL million per person-year, `income_per_job_per_year` 0.06 IL million per employed 1,000-person unit-year, and `spending_per_capita_per_year` 0.0001036 IL million per person-year, all labelled design values in `rules.yaml` (owner, 18 October 2026, option 3 and the per-head-tax draft). The same rule applies under `gdd-0.3`, which shares this economy (D1, owner, 1 November 2026, "Approve all six (Recommended)"; #1702); Amir's jobs-only income and import-only credit are post-MVP.-R-MONEY-002: In step 7, after Food consumption and imports, the Treasury pays each existing civilian kind's annual upkeep for the turn's share of a year; an unfinished project pays none, and R-MONEY-003 covers a shortfall. In the MVP, cities, completed permanent-housing projects, completed industry projects, completed transit camps, military camps and Hakhsharot each have an explicit upkeep of **IL 0m per year** in `rules.yaml`. These are design values, not historical claims. Phase 5 decides military-unit upkeep separately (#742; owner, 18 October 2026, #884 option 3). It applies under `gdd-0.3` too, and the six rates stay IL 0m (the owner's 30 October 2026 "Keep ruling" on UPKEEP; D1; #1702).+R-MONEY-002: In step 7, after Food consumption and imports, the Treasury pays each existing civilian kind's annual upkeep for the turn's share of a year; an unfinished project pays none, and R-MONEY-003 covers a shortfall. In the MVP, cities, completed permanent-housing projects, completed industry projects, completed transit camps, military camps and Hakhsharot each have an explicit upkeep of **IL 0m per year** in `rules.yaml`. These are design values, not historical claims. Phase 5 decides military-unit upkeep separately (#742; owner, 18 October 2026, #884 option 3). It applies under `gdd-0.3` too, and the six rates stay IL 0m (the owner's 30 October 2026 "Keep ruling" on UPKEEP; D1; #1702). It runs on a game with an initialized Historical ledger (the dark start, R-POP-002; #1725 PR 7) and pays what the aggregate game with the same places pays: it counts places, not people, and changes no ledger record.R-MONEY-003: A GDD cost above the Treasury is paid, and the shortfall moves to debt, as map actions do: the Treasury stops at 0, and a cause names what the shortfall was borrowed for (Q-MONEY-3, owner decision "Allow borrowing", 15 October 2026, for training and pioneer work; the Phase 2 plan applies it to every GDD cost). It covers the deficit, map actions, training (R-TRAIN-001), pioneer work (R-SITE-001), an event option's Treasury cost and an arms workshop's cycle (R-ARMS-006). The same rule applies under `gdd-0.3` (D1; #1702): `debt_ceiling` is only the economic-defeat threshold (R-END-001), so every cost still borrows past it, except an Arms purchase whose borrowing would take the debt past it, which is refused (R-ARMS-002, #2198), and an arms workshop's cycle whose borrowing would take the debt past it, which waits unpaid that month (R-ARMS-006). A shortfall changes nothing but the Treasury and the debt, and a refused order changes nothing (`Gdd03MoneyLedgerTests`).@@ -605,7 +605,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/`, `units_1948/` or `field/` 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. The dark start (#1725 PR 5) is the internal, fixture-only `Simulation.NewGame` overload that initializes the Historical ledger (R-POP-004) in place before `Pools.Init`: `Pools.Init` then reads the ledger's need, one ration for each living own population id (R-FOOD-001, #2470), after the ledger reconciles, and `StartingForces.Init` places the forces once each own starting formation's strength is its ledger soldiers, refusing otherwise. Both read only a ledger initialized with mode Historical, the dark start's; a synthetic or Open ledger is refused by both, as by the other aggregate systems, with the state unchanged. `EventSystem.Trigger` still refuses a ledger, so a dark start fires no opening event; the public `NewGame` is unchanged. The step-7 Food settlement given a month's synthetic context is another exception to that refusal: 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-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 dark start (#1725 PR 5) is the internal, fixture-only `Simulation.NewGame` overload that initializes the Historical ledger (R-POP-004) in place before `Pools.Init`: `Pools.Init` then reads the ledger's need, one ration for each living own population id (R-FOOD-001, #2470), after the ledger reconciles, and `StartingForces.Init` places the forces once each own starting formation's strength is its ledger soldiers, refusing otherwise. Both read only a ledger initialized with mode Historical, the dark start's; a synthetic or Open ledger is refused by both, as by the other aggregate systems, with the state unchanged. An aggregate system whose own rule says it runs on that Historical ledger (#1725 PR 7, civilian upkeep, R-MONEY-002, the first) also reads only that ledger; a synthetic or Open ledger is still refused by it. `EventSystem.Trigger` still refuses a ledger, so a dark start fires no opening event; the public `NewGame` is unchanged. The step-7 Food settlement given a month's synthetic context is another exception to that refusal: 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. A location's optional city (a `regions.yaml` member location of its region that is a census city of `cities.yaml` or one of that region's field hosts, where R-POP-004 houses own people: a settlement hosts only F19 and F20, owner, 7 November 2026, #1689: "These two only (Recommended)"; any other, including a locality, a `sites.yaml` id or a map location, is refused when a fixture is created, naming the city and the region, R-POP-002) is written after its other fields as `|city=` with a length-prefixed id, only when set, as R-UNIT-002's `|home=` is, so a location without a city keeps its canonical text and hash. 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/LedgerCivilianUpkeepTests.cs b/sim/Statecraft.Sim.Tests/LedgerCivilianUpkeepTests.csnew file mode 100644index 000000000..fe562b5d1--- /dev/null+++ b/sim/Statecraft.Sim.Tests/LedgerCivilianUpkeepTests.cs@@ -0,0 +1,114 @@+using Statecraft.Sim;++/// <summary>#1725 PR 7, producer draft 05: civilian upkeep (R-MONEY-002) runs on a game with an initialized Historical+/// ledger, the dark start and the ledger fixture. It counts places, not people, so it pays what the aggregate start of the+/// same content pays and changes no ledger record (R-POP-002).</summary>+public class LedgerCivilianUpkeepTests+{+ static Content Gdd03() => HistoricalPopulationTests.Real(true);++ static GameState Dark(Content c) => Simulation.NewGame(c, 1, Mode.Historical, darkStart: true);++ // A copy of the real gdd-0.3 content with six distinct non-zero R-MONEY-002 rates (the shipped ones are all IL 0m).+ static Content WithRates()+ {+ var root = RealContentTests.ContentRoot();+ return ContentLoader.Load(rel =>+ {+ var path = Path.Combine(root, rel);+ var text = File.Exists(path) ? File.ReadAllText(path) : null;+ if (rel == "eras.yaml") return text!.Replace("loop: gdd", "loop: gdd, ruleset: gdd-0.3");+ if (rel != "rules.yaml") return text;+ foreach (var (key, rate) in new[] { ("city", "1.0"), ("housing", "2.0"), ("industry", "3.0"), ("transit_camp", "4.0"),+ ("military_camp", "5.0"), ("hakhshara", "6.0") })+ {+ var line = $" {key}_upkeep_per_year: 0.0 ";+ Assert.Contains(line, text!);+ text = text!.Replace(line, $" {key}_upkeep_per_year: {rate} ");+ }+ return text;+ }, Directory.GetFiles(Path.Combine(root, "events"), "*.yaml").Select(p => "events/" + Path.GetFileName(p)));+ }++ // One completed project of each paying kind in the first census city, on both states, so every rate is read.+ static void Build(Content c, GameState s)+ {+ var city = c.Cities[0].Id;+ foreach (var (id, kind) in new[] { (9001, "housing"), (9002, "industry"), (9003, "transit_camp") })+ s.CityProjects.Add(id, new CityProject(id, kind, city, 0, 0, 0, s.Date));+ }++ // R-MONEY-002 (IL 0m under gdd-0.3, the owner's 30 October 2026 "Keep ruling"), R-POP-002: the ledger fixture's+ // step-7 upkeep payment runs, pays nothing with the shipped rates, and leaves every record as it was.+ [Fact]+ public void TheLedgerFixturePaysCivilianUpkeep()+ {+ var c = Gdd03();+ var s = HistoricalPopulation.LedgerFixture(c);+ s.Date = c.Rules.Start;+ var ledger = s.PopulationLedger.Canonical(); var treasury = s.Treasury; var debt = s.Debt;+ var why = new List<Cause>();+ EconomySystem.PayCivilianUpkeep(c, s, c.RulesAt(s.Date).Mvp!, 1 / 12.0, why);+ Assert.Empty(why);+ Assert.Equal((treasury, debt), (s.Treasury, s.Debt));+ s.PopulationLedger.Reconcile();+ Assert.Equal(ledger, s.PopulationLedger.Canonical());+ }++ // R-MONEY-002: the dark start pays the aggregate start's upkeep, 0 with the shipped rates.+ [Fact]+ public void TheDarkStartPaysTheAggregateUpkeepWithTheShippedRates()+ {+ var c = Gdd03();+ var dark = Dark(c); var pub = Simulation.NewGame(c, 1, Mode.Historical);+ Build(c, dark); Build(c, pub);+ var r = c.RulesAt(dark.Date).Mvp!;+ Assert.Equal(0, Cities.AnnualUpkeep(c, pub, r));+ Assert.Equal(Cities.AnnualUpkeep(c, pub, r), Cities.AnnualUpkeep(c, dark, r));+ dark.PopulationLedger.Reconcile();+ }++ // R-MONEY-002, R-MONEY-003: with non-zero rates in a content copy, the dark start pays exactly the aggregate start's+ // upkeep, a short Treasury borrows the rest as in the aggregate game, and no ledger record changes.+ [Fact]+ public void TheDarkStartPaysAndBorrowsTheAggregateUpkeepWithNonZeroRates()+ {+ var c = WithRates();+ Assert.True(c.UsesPopulationLedger);+ var dark = Dark(c); var pub = Simulation.NewGame(c, 1, Mode.Historical);+ Build(c, dark); Build(c, pub);+ var r = c.RulesAt(dark.Date).Mvp!;+ var expected = Cities.AnnualUpkeep(c, pub, r);+ Assert.True(expected >= c.Cities.Count * 1.0 + 2 + 3 + 4); // every city plus the three projects+ Assert.Equal(expected, Cities.AnnualUpkeep(c, dark, r));+ Assert.True(expected / 12.0 > 1); // the Treasury of 1 below is short++ var ledger = dark.PopulationLedger.Canonical();+ foreach (var s in new[] { dark, pub }) { s.Treasury = 1; s.Debt = 2; }+ var darkWhy = new List<Cause>(); var pubWhy = new List<Cause>();+ EconomySystem.PayCivilianUpkeep(c, dark, r, 1 / 12.0, darkWhy);+ EconomySystem.PayCivilianUpkeep(c, pub, r, 1 / 12.0, pubWhy);+ Assert.Equal(0, dark.Treasury);+ Assert.Equal(2 + expected / 12.0 - 1, dark.Debt, 9);+ Assert.Equal((pub.Treasury, pub.Debt), (dark.Treasury, dark.Debt));+ Assert.Equal(pubWhy.Select(x => (x.System, x.Target, x.Delta, x.Message)), darkWhy.Select(x => (x.System, x.Target, x.Delta, x.Message)));+ Assert.Contains(darkWhy, x => x.Message.Contains("civilian upkeep", StringComparison.Ordinal));+ dark.PopulationLedger.Reconcile();+ Assert.Equal(ledger, dark.PopulationLedger.Canonical());+ }++ // R-POP-002 (#1725 PR 7 review S2): only a ledger initialized with mode Historical is let through. An initialized Open+ // ledger, like a synthetic one (no mode), is still refused before anything is read, with the state unchanged.+ [Theory]+ [InlineData(true)] [InlineData(false)]+ public void AnOpenOrSyntheticLedgerIsStillRefused(bool open)+ {+ var c = PopulationLedgerTests.Content();+ var s = PopulationLedger.CreateFixture(c, PopulationLedgerTests.Bindings(),+ new[] { new PopulationInventoryRow("fixture", 0, PopulationLedgerTests.Person()) }, mode: open ? Mode.Open : null);+ Assert.Equal((true, false), (s.PopulationLedger.IsInitialized, s.PopulationLedger.IsHistorical));+ var before = s.Describe(); var hash = s.Hash();+ Assert.Contains("integration is held", Assert.Throws<NotSupportedException>(() => Cities.AnnualUpkeep(c, s, new MvpRules())).Message);+ Assert.Equal(before, s.Describe()); Assert.Equal(hash, s.Hash());+ }+}diff --git a/sim/Statecraft.Sim/Cities.cs b/sim/Statecraft.Sim/Cities.csindex 7ea043c06..5df9a9655 100644--- a/sim/Statecraft.Sim/Cities.cs+++ b/sim/Statecraft.Sim/Cities.cs@@ -151,10 +151,12 @@ namespace Statecraft.Sim}/// <summary>R-MONEY-002: annual Money upkeep for the civilian places that exist at the start of step 7. Only completed- /// projects and camp sites count. The six rates are explicit content design values; all are 0 in the MVP.</summary>+ /// projects and camp sites count. The six rates are explicit content design values; all are 0 in the MVP. It counts+ /// places, not people, so it runs on an initialized Historical ledger (the dark start, #1725 PR 7) and reads no+ /// record; a synthetic or Open ledger stays refused (R-POP-002).</summary>public static double AnnualUpkeep(Content c, GameState s, MvpRules r){- PopulationLedger.RefuseAggregate(s);+ PopulationLedger.RefuseUnlessHistorical(s);var total = s.Cities.Count * r.CityUpkeepPerYear!.Value;foreach (var p in s.CityProjects.Values){