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): military upkeep runs on a Historical ledger game (#1699 part 1, #1725 PR 7) (#2973)
Eyal Golanfd274c055060
diff --git a/changelog.d/1699-military-upkeep-ledger.md b/changelog.d/1699-military-upkeep-ledger.mdnew file mode 100644index 000000000..dd08adbf5--- /dev/null+++ b/changelog.d/1699-military-upkeep-ledger.md@@ -0,0 +1,3 @@+- GDD 0.3 starting population (Refs #1699, Refs #1725): military upkeep (R-UNIT-010) now runs on the inactive dark+ start's Historical ledger and pays what the aggregate start pays: IL 0.05m for each formation on the map, whatever its+ strength. No soldier record is read or written. No new-game wiring, so there is no change in the game.diff --git a/docs/rules/mvp.md b/docs/rules/mvp.mdindex f8dda23f9..52924431e 100644--- a/docs/rules/mvp.md+++ b/docs/rules/mvp.md@@ -278,7 +278,7 @@ R-UNIT-008: Artillery and the armoured car are acquired by training at a militarR-UNIT-009: A row of `map/units_1948.yaml` that meets R-UNIT-006 except that its `strength`'s `as_of` is after the start day arrives on that day (#1241, owner, 21 October 2026, answer 1(a): "enters the game on that date with its sourced strength, read from its row as a dated arrival"): in the GDD loop's resolution (step 9, after the immigrants' arrivals) of the turn that starts before that day and ends on or after it, once, on the hex of the anchor whose window covers that day, with that strength in population units and its side's type, as a starting force. Such rows follow the starting rows in `Content.StartingForces`, and their unit ids are reserved when the game starts, so unit i is still row i and the release gate names them too. An arrival ignores the stack limit and the hex's other units, as a starting force does. A row whose `as_of` is before the start starts nothing; the loader refuses an `as_of` that is not a `YYYY-MM-DD` date, naming the file and the row. Only a player-side (`side: israel`) row arrives: the loader refuses an enemy-side row whose `as_of` is after the start, naming the file and the row, and the resolver refuses to add one (R-ENEMY-004). Today the 7th Brigade arrives: 1,650 on 24 May 1948 at Hulda, 2 units from the 15 June 1948 turn. Under exact `gdd-0.3` it also runs on a game with an initialized Historical ledger (R-POP-002, R-POP-004; #1725 PR 7, producer 08), where the arriving brigade's people are ledger records (owner, 8 November 2026, answers to the coordinator): "Soldiers of brigade (Recommended)", so each is an active soldier whose ActiveService target is the brigade (`units_1948/<row id>`); "New people (Recommended)", so the brigade brings new records, one per strength unit at the ledger's 1,000 people a record (the 7th Brigade's 1,650 men are 2 units, so 2 records), with new ids, none taken from the civilians; "1, like the others", so the 7th Brigade's soldiers start with combat XP 1, its `content/gdd03-start.yaml` `formation_combat_xp` row, as the starting brigades' do, and the qualification of its type's class (`infantry`), as theirs; "Apart from Arms (Recommended)", so each carries one issued military item, `units_1948/<row id>/<ordinal>`, owned and recorded as paid, and the Arms stock is untouched, as at the start. Coordinator calls, 8 November 2026 (not owner rulings): the dark start binds each own dated brigade at the start (its service target and arrival region, with no record), so the arrival only registers its records; the records are located in the region of the arrival anchor's hex, region-only, as a starting formation's (the 7th Brigade's Hulda hex is in `central_plain`); and a brigade whose records are already registered adds nothing, so a replay of the turn adds nobody twice. Its records are registered all or nothing before its unit is added; its reception is 0 and it has no profession, as a starting soldier. Its unit is the aggregate game's, with combat XP 0. A synthetic or Open ledger is still refused.-R-UNIT-010: In step 7, after production, Food consumption/imports and civilian upkeep, and before housing, each Israeli military formation pays `military_upkeep_per_turn` Money, including a formation that graduated this turn. The owner-accepted initial rate is IL 0.05m per formation per turn, independent of strength and turn length, a labelled design value under Q-GEN-1 (19 October 2026, https://github.com/eyalgolan/statecraft-israel/pull/1130#issuecomment-6269103829). Civilian, enemy and default records without a military side pay none. R-MONEY-003 borrows a shortfall; no strength is removed or Arms consumed for upkeep (Q-UNIT-3; owner, 15 October 2026). The loader requires a finite rate >= 0. R-ARMS-003 remains the training/refund rule; the Phase 5 plan's suggested reuse of that id is obsolete.+R-UNIT-010: In step 7, after production, Food consumption/imports and civilian upkeep, and before housing, each Israeli military formation pays `military_upkeep_per_turn` Money, including a formation that graduated this turn. The owner-accepted initial rate is IL 0.05m per formation per turn, independent of strength and turn length, a labelled design value under Q-GEN-1 (19 October 2026, https://github.com/eyalgolan/statecraft-israel/pull/1130#issuecomment-6269103829). Civilian, enemy and default records without a military side pay none. R-MONEY-003 borrows a shortfall; no strength is removed or Arms consumed for upkeep (Q-UNIT-3; owner, 15 October 2026). The loader requires a finite rate >= 0. R-ARMS-003 remains the training/refund rule; the Phase 5 plan's suggested reuse of that id is obsolete. Under exact `gdd-0.3` with an initialized Historical population ledger (the dark start, R-POP-004; #1699, #1725 PR 7), the count is unchanged: it counts the formations on the map, each paying the same rate whatever its strength, and reads or writes no soldier record (owner, 8 November 2026, on #1725: "Formations, unchanged (Recommended)"). A synthetic or Open ledger is still refused (R-POP-002).R-UNIT-011: Under exact `gdd-0.3` only, a military unit gains combat experience from the engagements it survives (#1707; owner, 2 November 2026: "Build it now (Recommended)", on today's aggregate units, `gdd-0.1` unchanged). After an engagement's one draw, its losses, retreats and surrenders (R-COMBAT-002, R-COMBAT-003), each attacker and defender still in the state, in ascending id, gains the Agreed catalogue `military.combat_xp_gain` (1), up to `military.combat_xp_full` (5): both sides, the player's instant attack and step 2's alike, a retreated defender included, and artillery firing alone too (owner, 1 November 2026, #1668 answers https://github.com/eyalgolan/statecraft-israel/pull/1668#issuecomment-6553884547: Q14 "Yes. Artillery fires alone from range, and it earns experience for each engagement it survives, like any unit."; Q15 "It stops."). A destroyed or surrendered unit gains nothing. Moves, orders, service and training give none. A `veteran_soldier` is a veteran already and gains none; a type with no veteran form stops at the full count (agent default, #1707 plan OQ1; enemy units count too, OQ2). An Israeli recruit that reaches the full count becomes a `veteran_soldier` with R-UNIT-004's promotion and its Why cause (no line for a single gain, OQ3), after the engagement, so it fought that engagement as a recruit. Every record change keeps the count (a refill too, R-TRAIN-004, OQ4), and a veteran stops accumulating service (OQ5). It draws nothing. The loader refuses either value when it is missing, Deferred or not a positive integer, with no fallback. The count is state, hashed as R-UNIT-002 says; a save replays its commands, so the save format is unchanged.@@ -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. An aggregate system whose own rule says it runs on that Historical ledger (#1725 PR 7: civilian upkeep, R-MONEY-002, the first, and food_supply's stock term, R-FOOD-003; training, R-TRAIN-001 to R-TRAIN-004) also reads only that ledger; a synthetic or Open ledger is still refused by it. Prisoners.Take and Prisoners.Upkeep are such systems (#1710, R-POW-001, R-POW-002, R-POW-005): a capture turns the surrendered formation's serving records into captives with their captor and home, all or nothing, and records no loss. `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). The live month snapshot (`Gdd03SyntheticMonthContext.CreateLive`, #1725 PR 7; owner, 8 November 2026, "One snapshot per turn (Recommended)") reads only a ledger initialized with mode Historical and changes no record; a synthetic or Open ledger and an aggregate game are refused (R-FOOD-002). 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, and food_supply's stock term, R-FOOD-003; training, R-TRAIN-001 to R-TRAIN-004; military upkeep, R-UNIT-010) also reads only that ledger; a synthetic or Open ledger is still refused by it. Prisoners.Take and Prisoners.Upkeep are such systems (#1710, R-POW-001, R-POW-002, R-POW-005): a capture turns the surrendered formation's serving records into captives with their captor and home, all or nothing, and records no loss. `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). The live month snapshot (`Gdd03SyntheticMonthContext.CreateLive`, #1725 PR 7; owner, 8 November 2026, "One snapshot per turn (Recommended)") reads only a ledger initialized with mode Historical and changes no record; a synthetic or Open ledger and an aggregate game are refused (R-FOOD-002). 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/LedgerMilitaryUpkeepTests.cs b/sim/Statecraft.Sim.Tests/LedgerMilitaryUpkeepTests.csnew file mode 100644index 000000000..c56075f63--- /dev/null+++ b/sim/Statecraft.Sim.Tests/LedgerMilitaryUpkeepTests.cs@@ -0,0 +1,103 @@+using Statecraft.Sim;++/// <summary>#1699 part 1, #1725 PR 7: military upkeep (R-UNIT-010) runs on a game with an initialized Historical ledger,+/// the dark start. Owner, 8 November 2026, on #1725: "Formations, unchanged (Recommended)". Each Israeli formation on+/// the map pays the same rate whatever its strength, and no soldier record is read or written (R-POP-002). The rate stays+/// rules.yaml's military_upkeep_per_turn.</summary>+public class LedgerMilitaryUpkeepTests+{+ static Content Gdd03() => HistoricalPopulationTests.Real(true);++ static GameState Dark(Content c) => Simulation.NewGame(c, 1, Mode.Historical, darkStart: true);++ static int Formations(Content c, GameState s) =>+ s.Units.Values.Count(u => u.Side == "israel" && c.UnitTypes.Any(t => t.Id == u.Type && t.Side == "israel"));++ static IEnumerable<(string, string, double, string, string, string)> Lines(List<Cause> why) =>+ why.Select(x => (x.System, x.Target, x.Delta, x.Message, x.Key, string.Join("|", x.Args)));++ // R-UNIT-010: the dark start pays the number of its own formations times the rate, exactly as the aggregate start of+ // the same content with the same units, with the same Why lines; the ledger is unchanged.+ [Fact]+ public void TheDarkStartPaysTheAggregateUpkeepPerFormation()+ {+ var c = Gdd03();+ var dark = Dark(c); var pub = Simulation.NewGame(c, 1, Mode.Historical);+ var r = c.RulesAt(dark.Date).Mvp!;+ Assert.Equal(0.05, r.MilitaryUpkeepPerTurn);+ Assert.Equal(pub.Units.Keys, dark.Units.Keys);+ var count = Formations(c, dark);+ Assert.True(count > 0);+ Assert.Equal(Formations(c, pub), count);+ foreach (var s in new[] { dark, pub }) { s.Treasury = 100; s.Debt = 2; }+ var ledger = dark.PopulationLedger.Canonical();+ var darkWhy = new List<Cause>(); var pubWhy = new List<Cause>();+ Military.PayUpkeep(c, dark, r, darkWhy);+ Military.PayUpkeep(c, pub, r, pubWhy);+ Assert.Equal(100 - count * 0.05, dark.Treasury, 9);+ Assert.Equal(2.0, dark.Debt);+ Assert.Equal((pub.Treasury, pub.Debt), (dark.Treasury, dark.Debt));+ Assert.Equal(Lines(pubWhy), Lines(darkWhy));+ Assert.Contains(darkWhy, x => x.Key == CauseKeys.MilitaryUpkeep && x.Delta == -count * 0.05);+ dark.PopulationLedger.Reconcile();+ Assert.Equal(ledger, dark.PopulationLedger.Canonical());+ }++ // R-UNIT-010 with R-MONEY-003: a short Treasury borrows the rest, as in the aggregate game, with the same Why lines.+ [Fact]+ public void AShortTreasuryBorrowsAsTheAggregateGame()+ {+ var c = Gdd03();+ var dark = Dark(c); var pub = Simulation.NewGame(c, 1, Mode.Historical);+ var r = c.RulesAt(dark.Date).Mvp!;+ var cost = Formations(c, dark) * r.MilitaryUpkeepPerTurn!.Value;+ foreach (var s in new[] { dark, pub }) { s.Treasury = 0.01; s.Debt = 2; }+ Assert.True(cost > 0.01);+ var ledger = dark.PopulationLedger.Canonical();+ var darkWhy = new List<Cause>(); var pubWhy = new List<Cause>();+ Military.PayUpkeep(c, dark, r, darkWhy);+ Military.PayUpkeep(c, pub, r, pubWhy);+ Assert.Equal(0.0, dark.Treasury);+ Assert.Equal(2 + cost - 0.01, dark.Debt, 9);+ Assert.Equal((pub.Treasury, pub.Debt), (dark.Treasury, dark.Debt));+ Assert.Equal(Lines(pubWhy), Lines(darkWhy));+ Assert.True(darkWhy.Count >= 2); // the upkeep line and the borrow line+ dark.PopulationLedger.Reconcile();+ Assert.Equal(ledger, dark.PopulationLedger.Canonical());+ }++ // "Formations, unchanged (Recommended)": strength is not read. Halving one formation's strength on the map changes+ // neither the cost nor the ledger, so the upkeep reads no soldier record.+ [Fact]+ public void UpkeepIsPerFormationWhateverItsStrength()+ {+ var c = Gdd03();+ var s = Dark(c);+ var r = c.RulesAt(s.Date).Mvp!;+ var u = s.Units.Values.First(x => x.Side == "israel" && x.Strength > 1);+ s.Units[u.Id] = new Unit(u.Id, u.Type, u.Q, u.R, u.Service, u.Side, 1, u.Order, u.OrderTarget, u.HomeCity, u.Full, u.CombatXp);+ s.Treasury = 100;+ var ledger = s.PopulationLedger.Canonical();+ var why = new List<Cause>();+ Military.PayUpkeep(c, s, r, why);+ Assert.Equal(100 - Formations(c, s) * 0.05, s.Treasury, 9);+ Assert.Equal(ledger, s.PopulationLedger.Canonical());+ }++ // R-POP-002: 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(); var why = new List<Cause>();+ Assert.Contains("integration is held",+ Assert.Throws<NotSupportedException>(() => Military.PayUpkeep(c, s, new MvpRules(), why)).Message);+ Assert.Empty(why);+ Assert.Equal(before, s.Describe()); Assert.Equal(hash, s.Hash());+ }+}diff --git a/sim/Statecraft.Sim/Military.cs b/sim/Statecraft.Sim/Military.csindex 348ead452..98731b0a6 100644--- a/sim/Statecraft.Sim/Military.cs+++ b/sim/Statecraft.Sim/Military.cs@@ -39,10 +39,12 @@ namespace Statecraft.Siminternal const string VeteranSoldier = "veteran_soldier";/// <summary>R-UNIT-010: step 7 pays per Israeli military formation, including this turn's graduates. The national- /// Treasury borrows a shortfall (R-MONEY-003); upkeep never consumes Arms (Q-UNIT-3).</summary>+ /// Treasury borrows a shortfall (R-MONEY-003); upkeep never consumes Arms (Q-UNIT-3). It counts formation tokens, not+ /// soldiers, so it runs on an initialized Historical ledger (the dark start, #1699, #1725 PR 7) and reads no record;+ /// a synthetic or Open ledger stays refused (R-POP-002).</summary>public static void PayUpkeep(Content c, GameState s, MvpRules r, List<Cause> why){- PopulationLedger.RefuseAggregate(s);+ PopulationLedger.RefuseUnlessHistorical(s);var count = s.Units.Values.Count(u => u.Side == "israel" && c.UnitTypes.Any(t => t.Id == u.Type && t.Side == "israel"));var cost = count * r.MilitaryUpkeepPerTurn!.Value;if (cost == 0) return;