A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
GDD 0.3 start, PR 5: the dark start, an internal NewGame with the Historical ledger before Pools.Init (Refs #1725, Refs #1689) (#2938)
Eyal Golana8ae29d5b72c
diff --git a/changelog.d/1689-dark-start.md b/changelog.d/1689-dark-start.mdnew file mode 100644index 000000000..3244b2ac6--- /dev/null+++ b/changelog.d/1689-dark-start.md@@ -0,0 +1,5 @@+- GDD 0.3 starting population (Refs #1689, Refs #1725): an internal, test-only "dark start" builds a GDD 0.3 Historical+ game with its population ledger in place before the Food stock is set, so the stock starts at three months of the+ ledger's need (`cover_months` 3 in `content/rules.yaml`, one ration per person record). It still places the starting+ brigades, checked against the ledger's soldiers, and fires no opening event yet. The public new game is unchanged,+ so there is no change in the game.diff --git a/docs/population-ledger.md b/docs/population-ledger.mdindex 2905a5f7f..ae771fda2 100644--- a/docs/population-ledger.md+++ b/docs/population-ledger.md@@ -14,4 +14,4 @@ No save/reload round trip for population identity is claimed. The existing seed/## Historical start inventory (R-POP-004)-`HistoricalPopulation.Inventory` is internal and reads the shipped content under exact `gdd-0.3`: one free-civilian row per census city start unit (R-CITY-007) and one active-soldier row per population unit of each Israeli starting formation of `map/units_1948.yaml` (R-UNIT-006), at `rules.yaml`'s 1,000 people a unit (owner, 1 November 2026, D2). Rows carry a source key (`census/<city id>`, `units_1948/<row id>`) and a within-source ordinal, in R-POP-001's order. Enemy formations and dated arrivals (R-UNIT-009) are not in it. It builds no `PopulationUnit` itself. `HistoricalPopulation.LedgerFixture` (internal, fixture-only) turns it into an initialized Historical ledger and binds each record to a region of `content/regions.yaml`: a census record takes the region whose `member_locations` hold its city, and its location names that city (`PopulationLocation.City`), a formation record the region whose member hexes hold its starting anchor hex (R-POP-004); a source with no region is refused. Census records start with their reception done (`reception.turns`), so R-VET-001's received-free-civilian work XP can apply to them. Each formation record carries one issued military item (`units_1948/<row id>/<ordinal>`, recorded as paid), apart from the spare Arms (#1717). A formation record's military qualification is its type's `unit_types.yaml` class, and its combat XP is `gdd03-start.yaml`'s `formation_combat_xp` (#1689 rows 5 to 8, R-POP-004). `NewGame` does not call it, because an initialized ledger refuses the aggregate systems a `gdd-0.3` game still runs (R-POP-002). The test `HistoricalPopulationTests` checks it, city by city and formation by formation, against the aggregate start of the same content.+`HistoricalPopulation.Inventory` is internal and reads the shipped content under exact `gdd-0.3`: one free-civilian row per census city start unit (R-CITY-007) and one active-soldier row per population unit of each Israeli starting formation of `map/units_1948.yaml` (R-UNIT-006), at `rules.yaml`'s 1,000 people a unit (owner, 1 November 2026, D2). Rows carry a source key (`census/<city id>`, `units_1948/<row id>`) and a within-source ordinal, in R-POP-001's order. Enemy formations and dated arrivals (R-UNIT-009) are not in it. It builds no `PopulationUnit` itself. `HistoricalPopulation.LedgerFixture` (internal, fixture-only) turns it into an initialized Historical ledger and binds each record to a region of `content/regions.yaml`: a census record takes the region whose `member_locations` hold its city, and its location names that city (`PopulationLocation.City`), a formation record the region whose member hexes hold its starting anchor hex (R-POP-004); a source with no region is refused. Census records start with their reception done (`reception.turns`), so R-VET-001's received-free-civilian work XP can apply to them. Each formation record carries one issued military item (`units_1948/<row id>/<ordinal>`, recorded as paid), apart from the spare Arms (#1717). A formation record's military qualification is its type's `unit_types.yaml` class, and its combat XP is `gdd03-start.yaml`'s `formation_combat_xp` (#1689 rows 5 to 8, R-POP-004). The public `NewGame` does not call it, because an initialized ledger refuses the aggregate systems a `gdd-0.3` game still runs (R-POP-002). The dark start, `NewGame`'s internal fixture-only overload (#1725 PR 5), initializes the same ledger in place (`HistoricalPopulation.Initialize`, all or nothing) before `Pools.Init`, which then starts Food at `cover_months` of the ledger's rations; it places the starting forces against the ledger's soldiers and fires no opening event, since `EventSystem.Trigger` still refuses a ledger. The test `HistoricalPopulationTests` checks it, city by city and formation by formation, against the aggregate start of the same content.diff --git a/docs/rules/mvp.md b/docs/rules/mvp.mdindex c61cf1cf3..b0a32921f 100644--- a/docs/rules/mvp.md+++ b/docs/rules/mvp.md@@ -446,7 +446,7 @@ The top bar shows the net position, Treasury minus debt (`HudModel.From`), so itThe national Food pool (D-C2, "National pools", decided 15 October 2026), built on the maintainer's food rule of 16 October 2026 (#382, option (b): "food_supply adds a stock term: it rises and falls with months of cover (new design values `k_food`, `cover_months`), rationing and events still act on top, and the unmet share lowers it further").-R-FOOD-001: Food is a national stock of whole units (`GameState.Food`); one unit is one population unit's food for one month, and there is no storage cap (Q-POOL-2, decided 15 October 2026). A new game starts the stock at `cover_months` of the start's need, the need being the national head count in population units (`people_per_unit`), rounded half away from zero. `k_food` and `cover_months` are required in the GDD loop (`rules.yaml` `mvp:`, labelled design values); a missing or out-of-range value is a load error. `cover_months` runs from 1 to 120 (`Pools.MaxCoverMonths`), so its multiply cannot wrap the stock (#2804); the stock itself still has no cap.+R-FOOD-001: Food is a national stock of whole units (`GameState.Food`); one unit is one population unit's food for one month, and there is no storage cap (Q-POOL-2, decided 15 October 2026). A new game starts the stock at `cover_months` of the start's need, the need being the national head count in population units (`people_per_unit`), rounded half away from zero; with an initialized `gdd-0.3` ledger (the dark start, R-POP-002) the need is the ledger's, one ration for each living own population id (#2470). `k_food` and `cover_months` are required in the GDD loop (`rules.yaml` `mvp:`, labelled design values); a missing or out-of-range value is a load error. `cover_months` runs from 1 to 120 (`Pools.MaxCoverMonths`), so its multiply cannot wrap the stock (#2804); the stock itself still has no cap.R-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.@@ -603,11 +603,11 @@ 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. 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-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-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.-R-POP-004: The Historical start inventory under exact `gdd-0.3` (#1689; owner, 1 November 2026, D2: "Approve all six (Recommended)", and D4). It is read from the same content as the aggregate start: each census city (R-CITY-006) gives its R-CITY-007 start units as free civilians, and each Israeli starting formation of `map/units_1948.yaml` (R-UNIT-006) gives its strength as active soldiers. The 20 farmer units are added to the census total (owner, 7 November 2026: "On top, change the rule (Recommended)", which reverses this rule's earlier "no more and no less"); the inventory does not hold them until they are wired in. Enemy formations are not own population, and a dated arrival (R-UNIT-009) is not in the start inventory: it takes new ids when it arrives (Q11). Counts use `rules.yaml`'s `people_per_unit` (1,000, D2), as R-CITY-007 and R-UNIT-006 do; the `gdd-0.3` catalogue's `population.people_per_unit` (10,000) is Open mode's (D2). A city's records have source key `census/<city id>` and a formation's `units_1948/<row id>`, each with within-source ordinals from 0, so R-POP-001's order (source key by ordinal string comparison, then ordinal) gives the ascending population ids that Q10's "N units" commands take. Legacy and `gdd-0.1` content refuse it. It reads no RNG and changes no state. It is not yet wired into `Simulation.NewGame`: an initialized ledger refuses every aggregate system (R-POP-002), so a new `gdd-0.3` game keeps the aggregate start until the producers are integrated. A fixture builder (`HistoricalPopulation.LedgerFixture`, internal, fixture-only) turns the inventory into an initialized Historical ledger with mode Historical (R-POP-001's 1,000 a record), each record in a region of `content/regions.yaml` (#1691): a census record takes the region whose `member_locations` hold its city (`census/tel_aviv` is `tel_aviv_jaffa`; Jaffa gets no records), and its location names that city, and a formation record takes the region whose member hexes hold the formation's starting anchor hex (owner, 3 November 2026, #1689 open question 1: "Its anchor hex's region (Recommended)"). A source with no region is refused; no region is invented. Census records are free civilians with no assignment and their reception done: they start at `reception.turns`, the "actual reception turns before free-civilian status" (`docs/gdd/balance.md:91`), the ledger's cap (R-POP-002), since R-VET-001 gives work XP only to a received free civilian (an agent reading of `balance.md:91`, not an owner ruling); formation records keep 0, which no ruling sets. Formation records are active soldiers whose service target is their own formation. Each formation record carries one issued military item, id `units_1948/<row id>/<ordinal>`, owned and recorded as paid; census records carry none. Issued items are apart from the spare Arms: the fixture leaves the Arms stock untouched, and a new game still starts with `arms_start`'s 12 (#1717, 27M-24: "The starting formations are equipped, and the Arms stock starts at 12"). Still not in the inventory or the fixture: the work assignments of the employed share and the opening field farmers (fields, #1691/#1717; the owner's 1:2:1 novice/trained/veteran ratio then applies per host, which gives 1 / 18 / 1 nationally: owner, 7 November 2026, "Per host, 1/18/1 (Recommended)", [#1689](https://github.com/eyalgolan/statecraft-israel/issues/1689#issuecomment-6704985642)). The formations' rows 5 to 8 are in the fixture (owner, 7 November 2026, #1689 comment 6704389240: "Veteran for all 8 (Recommended)" and "1 each, Negev 0 (Recommended)", Negev's 0 a labelled stand-in). The veteran level lives on the formation, a `veteran_soldier` (R-UNIT-006) that is each soldier's ActiveService target, so a formation record's military qualification is its type's `unit_types.yaml` class (`infantry`), the source basic-training graduates use, with no new level field (maintainer call, eyalgolan-30's coordinator, 7 November 2026). Its combat XP is `content/gdd03-start.yaml`'s `formation_combat_xp`: 1 for Golani, Carmeli, Alexandroni, Kiryati, Givati, Etzioni and Harel, 0 for Negev. The loader requires the list, refuses a row that is not an own opening formation, a duplicate, a missing formation or a value outside 0 to `military.combat_xp_full`, and the fixture refuses without it (no fallback). Only the ledger fixture reads it: the units `NewGame` starts with keep 0 combat XP (same maintainer call); a `veteran_soldier` gains none (R-UNIT-011). The paragraphs below record the owner's decision on each. The ledger scale for this start is no longer Deferred: a Historical ledger fixture counts each record at `rules.yaml`'s `people_per_unit` for the start day, 1,000 people (R-POP-001; D2: "The Historical MVP keeps main's start: census cities at 1,000 people a unit (`R-CITY-007`)").+R-POP-004: The Historical start inventory under exact `gdd-0.3` (#1689; owner, 1 November 2026, D2: "Approve all six (Recommended)", and D4). It is read from the same content as the aggregate start: each census city (R-CITY-006) gives its R-CITY-007 start units as free civilians, and each Israeli starting formation of `map/units_1948.yaml` (R-UNIT-006) gives its strength as active soldiers. The 20 farmer units are added to the census total (owner, 7 November 2026: "On top, change the rule (Recommended)", which reverses this rule's earlier "no more and no less"); the inventory does not hold them until they are wired in. Enemy formations are not own population, and a dated arrival (R-UNIT-009) is not in the start inventory: it takes new ids when it arrives (Q11). Counts use `rules.yaml`'s `people_per_unit` (1,000, D2), as R-CITY-007 and R-UNIT-006 do; the `gdd-0.3` catalogue's `population.people_per_unit` (10,000) is Open mode's (D2). A city's records have source key `census/<city id>` and a formation's `units_1948/<row id>`, each with within-source ordinals from 0, so R-POP-001's order (source key by ordinal string comparison, then ordinal) gives the ascending population ids that Q10's "N units" commands take. Legacy and `gdd-0.1` content refuse it. It reads no RNG and changes no state. It is not yet wired into the public `Simulation.NewGame` (only the internal dark start of R-POP-002 calls it): an initialized ledger refuses every aggregate system (R-POP-002), so a new `gdd-0.3` game keeps the aggregate start until the producers are integrated. A fixture builder (`HistoricalPopulation.LedgerFixture`, internal, fixture-only) turns the inventory into an initialized Historical ledger with mode Historical (R-POP-001's 1,000 a record), each record in a region of `content/regions.yaml` (#1691): a census record takes the region whose `member_locations` hold its city (`census/tel_aviv` is `tel_aviv_jaffa`; Jaffa gets no records), and its location names that city, and a formation record takes the region whose member hexes hold the formation's starting anchor hex (owner, 3 November 2026, #1689 open question 1: "Its anchor hex's region (Recommended)"). A source with no region is refused; no region is invented. Census records are free civilians with no assignment and their reception done: they start at `reception.turns`, the "actual reception turns before free-civilian status" (`docs/gdd/balance.md:91`), the ledger's cap (R-POP-002), since R-VET-001 gives work XP only to a received free civilian (an agent reading of `balance.md:91`, not an owner ruling); formation records keep 0, which no ruling sets. Formation records are active soldiers whose service target is their own formation. Each formation record carries one issued military item, id `units_1948/<row id>/<ordinal>`, owned and recorded as paid; census records carry none. Issued items are apart from the spare Arms: the fixture leaves the Arms stock untouched, and a new game still starts with `arms_start`'s 12 (#1717, 27M-24: "The starting formations are equipped, and the Arms stock starts at 12"). Still not in the inventory or the fixture: the work assignments of the employed share and the opening field farmers (fields, #1691/#1717; the owner's 1:2:1 novice/trained/veteran ratio then applies per host, which gives 1 / 18 / 1 nationally: owner, 7 November 2026, "Per host, 1/18/1 (Recommended)", [#1689](https://github.com/eyalgolan/statecraft-israel/issues/1689#issuecomment-6704985642)). The formations' rows 5 to 8 are in the fixture (owner, 7 November 2026, #1689 comment 6704389240: "Veteran for all 8 (Recommended)" and "1 each, Negev 0 (Recommended)", Negev's 0 a labelled stand-in). The veteran level lives on the formation, a `veteran_soldier` (R-UNIT-006) that is each soldier's ActiveService target, so a formation record's military qualification is its type's `unit_types.yaml` class (`infantry`), the source basic-training graduates use, with no new level field (maintainer call, eyalgolan-30's coordinator, 7 November 2026). Its combat XP is `content/gdd03-start.yaml`'s `formation_combat_xp`: 1 for Golani, Carmeli, Alexandroni, Kiryati, Givati, Etzioni and Harel, 0 for Negev. The loader requires the list, refuses a row that is not an own opening formation, a duplicate, a missing formation or a value outside 0 to `military.combat_xp_full`, and the fixture refuses without it (no fallback). Only the ledger fixture reads it: the units `NewGame` starts with keep 0 combat XP (same maintainer call); a `veteran_soldier` gains none (R-UNIT-011). The paragraphs below record the owner's decision on each. The ledger scale for this start is no longer Deferred: a Historical ledger fixture counts each record at `rules.yaml`'s `people_per_unit` for the start day, 1,000 people (R-POP-001; D2: "The Historical MVP keeps main's start: census cities at 1,000 people a unit (`R-CITY-007`)").The four opening-ledger values were Deferred pending a separate sourced draft for owner approval (4 November 2026, Q24; the coordinator asked: "How should the four deferred opening-ledger values be approved before Historical NewGame initializes the ledger?"; the owner answered: "do the recommended for all"; the chosen option read: "Request and approve a separate sourced draft for employed assignments, farmer identities, formation qualifications and combat XP before wiring NewGame"; [recorded on #1689](https://github.com/eyalgolan/statecraft-israel/issues/1689#issuecomment-6623135448)). Farmer home cities needed a source-backed city-by-field proposal for owner approval (4 November 2026, Q26; the coordinator asked: "How should the census-city home of each opening field’s farmer be selected when its region contains several cities?"; the owner answered: "do the recommended for all"; the chosen option read: "Have an agent prepare a source-backed city-by-field proposal for owner approval"; [recorded on #1717](https://github.com/eyalgolan/statecraft-israel/issues/1717#issuecomment-6623136302)).Owner decision on both drafts, 7 November 2026: "all reccomended in "Decisions for the owner: the GDD 0.3 starting population (#1689) and where the field farmers live (#1717)" - approved" ([recorded on #1689](https://github.com/eyalgolan/statecraft-israel/issues/1689#issuecomment-6703676150)). This wires nothing into `Simulation.NewGame`.diff --git a/sim/Statecraft.Sim.Tests/DarkStartTests.cs b/sim/Statecraft.Sim.Tests/DarkStartTests.csnew file mode 100644index 000000000..623c375af--- /dev/null+++ b/sim/Statecraft.Sim.Tests/DarkStartTests.cs@@ -0,0 +1,161 @@+using Statecraft.Sim;++/// <summary>#1689 / #1725 PR 5, the dark start: the internal NewGame overload that initializes the Historical ledger in+/// place (HistoricalPopulation.Initialize) before Pools.Init, under exact gdd-0.3 only. The public NewGame is unchanged+/// and still starts with no ledger (R-POP-004); the dark start is fixture and overload only.</summary>+public class DarkStartTests+{+ static Content Gdd03() => HistoricalPopulationTests.Real(true);++ static GameState Dark(Content c) => Simulation.NewGame(c, 1, Mode.Historical, darkStart: true);++ // R-POP-003, docs/determinism.md: the same content and seed give the same dark start, hash for hash; its ledger is+ // initialized and written, so it is not the public start's hash.+ [Fact]+ public void DarkStartHashRepeats()+ {+ var c = Gdd03();+ var s = Dark(c);+ Assert.True(s.PopulationLedger.IsInitialized);+ Assert.Equal(s.Hash(), Dark(Gdd03()).Hash());+ Assert.Equal(s.Describe(), Dark(c).Describe());+ Assert.NotEqual(Simulation.NewGame(c, 1, Mode.Historical).Hash(), s.Hash());+ }++ // R-POP-001, R-POP-004: the dark start's ledger reconciles, and it holds exactly the Historical ledger fixture's+ // records, binding for binding (the in-place initializer and LedgerFixture build the same ledger).+ [Fact]+ public void DarkStartLedgerReconcilesAndIsTheFixturesLedger()+ {+ var c = Gdd03();+ var l = Dark(c).PopulationLedger;+ l.Reconcile();+ var fixture = HistoricalPopulation.LedgerFixture(c).PopulationLedger;+ Assert.Equal(fixture.Canonical(), l.Canonical());+ Assert.Equal(HistoricalPopulation.Inventory(c).Count, l.Units.Count);+ }++ // R-FOOD-001 (a new game starts the stock at cover_months of the start's need) under gdd-0.3 with an initialized+ // ledger (#2470: the need is one ration for each living own population id, Pools.Rations): the ledger is in place+ // before Pools.Init, so the dark start's Food is cover_months (rules.yaml mvp.cover_months, 3) times the ledger's need.+ [Fact]+ public void DarkStartFoodIsThreeTimesTheLedgersNeed()+ {+ var c = Gdd03();+ var s = Dark(c);+ Assert.Equal(3, c.RulesAt(c.Rules.Start).Mvp!.CoverMonths);+ var need = Pools.Rations(s.PopulationLedger.Units);+ Assert.Equal(s.PopulationLedger.Units.Count, need);+ Assert.Equal(need, s.FoodNeed);+ Assert.Equal(3 * need, s.Food);+ Assert.Equal(0, s.FoodUnmet);+ // the aggregate start's need is the national head count, a different number: the dark start reads the ledger's+ Assert.NotEqual(Simulation.NewGame(c, 1, Mode.Historical).FoodNeed, s.FoodNeed);+ }++ // R-UNIT-006, R-POP-004: the dark start still places the starting forces, ids 0 to n-1 in content order, and each+ // own opening formation's strength is its active-soldier records in the ledger, the formation their service target.+ [Fact]+ public void DarkStartPlacesTheStartingForcesAndTheyMatchTheLedgersSoldiers()+ {+ var c = Gdd03();+ var s = Dark(c);+ var aggregate = Simulation.NewGame(c, 1, Mode.Historical);+ Assert.Equal(aggregate.Units.Keys, s.Units.Keys);+ Assert.Equal(aggregate.Units.Values.Select(u => u.Canonical()), s.Units.Values.Select(u => u.Canonical()));+ var own = s.Units.Values.Where(u => u.Side == Movement.PlayerSide).ToList();+ Assert.NotEmpty(own);+ foreach (var u in own)+ {+ var target = HistoricalPopulation.FormationPrefix + c.StartingForces[u.Id].Row;+ Assert.Equal(u.Strength, s.PopulationLedger.Units.Count(p => p.Status == PopulationStatus.ActiveSoldier+ && p.Assignment.Kind == PopulationAssignmentKind.ActiveService && p.Assignment.Target == target));+ }+ }++ // R-POP-002: EventSystem.Trigger still refuses a ledger game (its producer is a later PR), so the dark start fires no+ // opening event. The aggregate parts the ledger does not refuse keep the public start's values.+ [Fact]+ public void DarkStartFiresNoEventAndKeepsTheAggregateStartElsewhere()+ {+ var c = Gdd03();+ var s = Dark(c);+ var aggregate = Simulation.NewGame(c, 1, Mode.Historical);+ Assert.Empty(s.FiredEvents);+ Assert.Equal(aggregate.Arms, s.Arms);+ Assert.Equal(aggregate.Treasury, s.Treasury);+ Assert.Equal(aggregate.Rung, s.Rung);+ Assert.Equal(aggregate.Cities.Keys, s.Cities.Keys);+ }++ // R-POP-001: only exact gdd-0.3 has a ledger, so gdd-0.1 and legacy content refuse a dark start; the public NewGame is+ // the overload's aggregate path, hash for hash, and still has no ledger (R-POP-004).+ [Fact]+ public void DarkStartNeedsGdd03AndThePublicStartIsUnchanged()+ {+ Assert.Throws<InvalidOperationException>(() => Dark(HistoricalPopulationTests.Real(false)));+ Assert.Throws<InvalidOperationException>(() => Dark(RealContentTests.Legacy()));+ var c = Gdd03();+ var pub = Simulation.NewGame(c, 1, Mode.Historical);+ Assert.False(pub.PopulationLedger.IsInitialized);+ Assert.Equal(pub.Hash(), Simulation.NewGame(c, 1, Mode.Historical, darkStart: false).Hash());+ }++ // R-POP-002: the in-place initializer refuses a ledger that is already initialized, leaving it as it was.+ [Fact]+ public void InPlaceInitializerRefusesASecondInitialization()+ {+ var c = Gdd03();+ var s = HistoricalPopulation.LedgerFixture(c);+ var before = s.Hash();+ Assert.Throws<InvalidOperationException>(() => HistoricalPopulation.Initialize(c, s));+ Assert.Equal(before, s.Hash());+ }+ // R-FOOD-001 under gdd-0.3 (#2470): an initialized ledger's need is one ration for each living own population id+ // (Pools.Rations), not the head count over rules.yaml's people_per_unit. At the Historical scale the two agree (each+ // record is people_per_unit people, and GameState.TotalPopulation reads the ledger), so this test sets the rules'+ // people_per_unit to twice the scale the ledger froze at initialization (R-POP-003 writes it): the aggregate head+ // count over the rules' unit is then half the records, and Pools.Init must still give one ration a record.+ [Fact]+ public void PoolsInitNeedCountsLedgerRecordsNotTheHeadCountOverTheRulesUnit()+ {+ var c = Gdd03();+ var s = HistoricalPopulation.LedgerFixture(c);+ s.Date = c.Rules.Start;+ var mvp = c.RulesAt(s.Date).Mvp!;+ var records = s.PopulationLedger.Units.Count;+ Assert.Equal(records * (double)mvp.PeoplePerUnit, s.TotalPopulation);+ mvp.PeoplePerUnit *= 2;+ Assert.NotEqual(records, (int)Math.Round(s.TotalPopulation / c.RulesAt(s.Date).Mvp!.PeoplePerUnit, MidpointRounding.AwayFromZero));+ Pools.Init(c, s);+ Assert.Equal(records, s.FoodNeed);+ Assert.Equal(mvp.CoverMonths!.Value * records, s.Food);+ }++ // R-POP-002, PopulationLedger.Initialize: all or nothing. A candidate that fails validation (here one real census+ // record with reception progress past reception.turns) leaves the public start's ledger exactly as it was, still+ // uninitialized, so the real Historical initializer then succeeds once and a second initialization is refused.+ [Fact]+ public void InPlaceInitializerLeavesTheLedgerUntouchedOnAnInvalidCandidate()+ {+ var c = Gdd03();+ var s = Simulation.NewGame(c, 1, Mode.Historical);+ var census = HistoricalPopulation.Inventory(c).First(r => r.Status == PopulationStatus.FreeCivilian);+ var region = c.PlayerRegions.AtLocation(census.Source.Substring(HistoricalPopulation.CensusPrefix.Length))!.Id;+ var where = new PopulationLocation(region);+ var bindings = new PopulationBindings(new[] { where }, Array.Empty<PopulationTarget>(), Array.Empty<string>(), Array.Empty<string>());+ var bad = new PopulationUnit(0, PopulationStatus.FreeCivilian, c.RequirePopulationInteger("reception.turns") + 1, where,+ PopulationAssignment.Unassigned, CivilianProfession.None, CivilianTier.None, 0, "", 0, PopulationEquipment.None);+ var before = s.Describe(); var hash = s.Hash(); var ledger = s.PopulationLedger.Canonical().ToList();+ Assert.Throws<ArgumentException>(() => s.PopulationLedger.Initialize(c, bindings,+ new[] { new PopulationInventoryRow(census.Source, census.Ordinal, bad) }, 0, Mode.Historical));+ Assert.False(s.PopulationLedger.IsInitialized);+ Assert.Equal(ledger, s.PopulationLedger.Canonical());+ Assert.Equal(before, s.Describe()); Assert.Equal(hash, s.Hash());+ HistoricalPopulation.Initialize(c, s);+ Assert.Equal(HistoricalPopulation.LedgerFixture(c).PopulationLedger.Canonical(), s.PopulationLedger.Canonical());+ var initialized = s.Hash();+ Assert.Throws<InvalidOperationException>(() => HistoricalPopulation.Initialize(c, s));+ Assert.Equal(initialized, s.Hash());+ }+}diff --git a/sim/Statecraft.Sim.Tests/HistoricalPopulationTests.cs b/sim/Statecraft.Sim.Tests/HistoricalPopulationTests.csindex 3d9282b6a..c1ce5866d 100644--- a/sim/Statecraft.Sim.Tests/HistoricalPopulationTests.cs+++ b/sim/Statecraft.Sim.Tests/HistoricalPopulationTests.cs@@ -80,6 +80,24 @@ public class HistoricalPopulationTests.Select(f => HistoricalPopulation.FormationPrefix + f.Row).OrderBy(s => s, StringComparer.Ordinal), formations);}+ // S2-2 (review of #2937): one predicate says what an own opening formation is (Israeli, no dated arrival, with a+ // strength): the inventory's formation sources, the loader's formation_combat_xp rows and the formations+ // StartingForces.Init checks against the ledger all read HistoricalPopulation.OpeningFormations.+ [Fact]+ public void OneHelperNamesTheOwnOpeningFormations()+ {+ var c = Real(true);+ var opening = HistoricalPopulation.OpeningFormations(c).Select(f => f.Row).OrderBy(r => r, StringComparer.Ordinal).ToList();+ Assert.NotEmpty(opening);+ Assert.All(HistoricalPopulation.OpeningFormations(c), f => Assert.True(f.Side == Movement.PlayerSide && f.Arrives == null && f.Strength > 0));+ var sources = HistoricalPopulation.Inventory(c).Select(r => r.Source)+ .Where(x => x.StartsWith(HistoricalPopulation.FormationPrefix, StringComparison.Ordinal))+ .Select(x => x.Substring(HistoricalPopulation.FormationPrefix.Length)).Distinct(StringComparer.Ordinal).OrderBy(r => r, StringComparer.Ordinal);+ Assert.Equal(opening, sources);+ Assert.Equal(opening, c.Gdd03FormationCombatXp!.Keys);+ Assert.Equal(opening, HistoricalPopulation.OpeningFormationRows(c).OrderBy(r => r, StringComparer.Ordinal));+ }+// R-POP-004, R-UNIT-006, R-UNIT-009: enemy formations are not own population, and a dated arrival is not in the start// inventory (it takes new ids when it arrives, Q11).[Fact]diff --git a/sim/Statecraft.Sim.Tests/PopulationLedgerBoundaryTests.cs b/sim/Statecraft.Sim.Tests/PopulationLedgerBoundaryTests.csindex 65b02aa5c..b59b41308 100644--- a/sim/Statecraft.Sim.Tests/PopulationLedgerBoundaryTests.cs+++ b/sim/Statecraft.Sim.Tests/PopulationLedgerBoundaryTests.cs@@ -32,7 +32,7 @@ public class PopulationLedgerBoundaryTests{case "population.init": PopulationSystem.Init(c,s); break;case "population.apply": PopulationSystem.Apply(c,s,s.Date.AddMonths(1),.1,why); break;- case "pools.init": Pools.Init(c,s); break;+ case "pools.init": Pools.Init(c,s); break; // S5-3: only the dark start's Historical ledger is readcase "pools.consume": Pools.Consume(c,s,rules,why); break;case "pools.harvest": Pools.Harvest(c,s,rules,why); break;case "pools.buy": Pools.BuyArms(c,s,1,why); break;@@ -44,7 +44,7 @@ public class PopulationLedgerBoundaryTestscase "cities.condition": Cities.UpdateCondition(c,s,rules,why); break;case "cities.arrive": Cities.Arrive(c,s,rules,s.Date.AddMonths(1),why); break;case "cities.upkeep": Cities.AnnualUpkeep(c,s,rules); break;- case "starting.init": StartingForces.Init(c,s); break;+ case "starting.init": StartingForces.Init(c,s); break; // S5-3: as pools.initcase "starting.arrive": StartingForces.Arrive(c,s,s.Date.AddMonths(1)); break;case "training.start": Training.Start(c,s,"missing","missing",1,why); break;case "training.cancel": Training.Cancel(c,s,0,why); break;@@ -76,6 +76,41 @@ public class PopulationLedgerBoundaryTestsAssert.Equal(before,s.Describe()); Assert.Equal(hash,s.Hash()); Assert.Same(cause,Assert.Single(why));}+ // R-POP-002 re-pointed for the dark start (#1725 PR 5): Pools.Init and StartingForces.Init accept an initialized+ // Historical ledger. Pools.Init's need is the ledger's (Pools.Rations, #2470), never the aggregate head count, and the+ // stock starts at cover_months of it (R-FOOD-001). StartingForces.Init places the forces (R-UNIT-006) once each own+ // formation's strength is its ledger soldiers (R-POP-004).+ [Fact]+ public void PoolsAndStartingForcesInitReadAnInitializedLedger()+ {+ var c = HistoricalPopulationTests.Real(true);+ var s = HistoricalPopulation.LedgerFixture(c);+ s.Date = c.Rules.Start;+ s.Population["fixture"] = 9_000_000; // read by neither need: TotalPopulation reads an initialized ledger (DarkStartTests pins the ledger-need path)+ Pools.Init(c, s);+ Assert.Equal(Pools.Rations(s.PopulationLedger.Units), s.FoodNeed);+ Assert.Equal(c.RulesAt(c.Rules.Start).Mvp!.CoverMonths!.Value * s.FoodNeed, s.Food);+ StartingForces.Init(c, s);+ Assert.Equal(c.StartingForces.Count, s.NextId);+ Assert.Equal(c.StartingForces.Count(f => f.Arrives == null), s.Units.Count);+ }++ // R-POP-004, R-POP-001: a ledger that no longer serves a starting formation with its strength (here one soldier lost) is+ // refused by StartingForces.Init with no unit added.+ [Fact]+ public void StartingForcesInitRefusesALedgerThatDoesNotMatchTheFormations()+ {+ var c = HistoricalPopulationTests.Real(true);+ var s = HistoricalPopulation.LedgerFixture(c);+ s.Date = c.Rules.Start;+ var soldier = s.PopulationLedger.Units.First(p => p.Status == PopulationStatus.ActiveSoldier);+ s.PopulationLedger.RegisterCombatLoss(soldier.Id, "fixture");+ var before = s.Describe();+ Assert.Contains("R-POP-004", Assert.Throws<InvalidOperationException>(() => StartingForces.Init(c, s)).Message);+ Assert.Equal(before, s.Describe());+ Assert.Empty(s.Units);+ }+// R-POP-003: reject lossy UTF-16 before accepting any persistent reference, but retain valid supplementary text.[Theory] [InlineData(0xD800, false)] [InlineData(0xD801, false)] [InlineData(0xDC00, false)] [InlineData(0xD800, true)]public void MalformedReferencesAreRejectedAtomically(int codeUnit, bool framed)diff --git a/sim/Statecraft.Sim/HistoricalPopulation.cs b/sim/Statecraft.Sim/HistoricalPopulation.csindex 19f37df9c..345b3f1a0 100644--- a/sim/Statecraft.Sim/HistoricalPopulation.cs+++ b/sim/Statecraft.Sim/HistoricalPopulation.cs@@ -32,10 +32,14 @@ namespace Statecraft.Siminternal const string CensusPrefix = "census/";internal const string FormationPrefix = "units_1948/";- /// <summary>The map/units_1948.yaml rows that give the start inventory soldiers: Israeli, in the start (no dated- /// arrival), with a strength.</summary>- internal static IEnumerable<string> OpeningFormationRows(Content c) => c.StartingForces- .Where(f => f.Side == Movement.PlayerSide && f.Arrives == null && f.Strength > 0).Select(f => f.Row);+ /// <summary>The own opening formations, the one predicate for them (review S2-2): the map/units_1948.yaml rows that+ /// give the start inventory soldiers, Israeli, in the start (no dated arrival), with a strength. The inventory, the+ /// loader's formation_combat_xp check and StartingForces.Init's ledger check all read it.</summary>+ internal static IEnumerable<StartingForce> OpeningFormations(Content c) => c.StartingForces+ .Where(f => f.Side == Movement.PlayerSide && f.Arrives == null && f.Strength > 0);++ /// <summary>The row ids of <see cref="OpeningFormations"/>.</summary>+ internal static IEnumerable<string> OpeningFormationRows(Content c) => OpeningFormations(c).Select(f => f.Row);internal static IReadOnlyList<HistoricalPopulationRow> Inventory(Content c){@@ -43,9 +47,8 @@ namespace Statecraft.Simif (!c.UsesPopulationLedger) throw new InvalidOperationException("The Historical population inventory requires gdd-0.3.");var counts = new List<(string Source, int Units, PopulationStatus Status)>();foreach (var city in c.Cities) counts.Add((CensusPrefix + city.Id, city.Civilians, PopulationStatus.FreeCivilian));- foreach (var f in c.StartingForces)- if (f.Side == Movement.PlayerSide && f.Arrives == null)- counts.Add((FormationPrefix + f.Row, f.Strength, PopulationStatus.ActiveSoldier));+ foreach (var f in OpeningFormations(c))+ counts.Add((FormationPrefix + f.Row, f.Strength, PopulationStatus.ActiveSoldier));if (counts.Select(x => x.Source).Distinct(StringComparer.Ordinal).Count() != counts.Count)throw new InvalidOperationException("Duplicate Historical population source.");var rows = new List<HistoricalPopulationRow>();@@ -61,10 +64,22 @@ namespace Statecraft.Sim/// are free civilians with no assignment and their reception done (reception.turns), and soldiers serving in their own/// formation, with no profession, tier or qualification (#1717 and #1692 add those). Each soldier carries one issued military item, id/// <c>units_1948/<row>/<ordinal></c>, owned and recorded as paid, apart from the spare Arms (#1717, 27M-24).- /// mode Historical gives #2299's 1,000-a-record scale (D2). Fixture-only: NewGame does not call it (R-POP-002).</summary>+ /// mode Historical gives #2299's 1,000-a-record scale (D2). Fixture-only: the public NewGame does not call it (R-POP-002).</summary>internal static GameState LedgerFixture(Content c){+ var s = new GameState(c) { Mode = Mode.Historical };+ Initialize(c, s);+ return s;+ }++ /// <summary>#1725 PR 5: <see cref="LedgerFixture"/>'s ledger, initialized in place on <paramref name="s"/>, a gdd-0.3+ /// Historical state with no ledger yet; the dark start (Simulation.NewGame's internal overload) calls it before+ /// Pools.Init. All or nothing (PopulationLedger.Initialize): a refusal leaves the state as it was.</summary>+ internal static void Initialize(Content c, GameState s)+ {+ if (s == null) throw new ArgumentNullException(nameof(s));var inventory = Inventory(c);+ if (s.Mode != Mode.Historical) throw new InvalidOperationException("The Historical ledger needs a Historical game (R-POP-004).");var sources = new HashSet<string>(inventory.Select(r => r.Source), StringComparer.Ordinal); // only sources with recordsvar regions = new SortedDictionary<string, string>(StringComparer.Ordinal);foreach (var city in c.Cities)@@ -112,7 +127,7 @@ namespace Statecraft.Simr.Status == PopulationStatus.ActiveSoldier ? soldier[r.Source].CombatXp : 0, r.Status == PopulationStatus.ActiveSoldier? new PopulationEquipment(militaryId: r.Source + "/" + r.Ordinal.ToString(CultureInfo.InvariantCulture), militaryPaid: true): PopulationEquipment.None)));- return PopulationLedger.CreateFixture(c, bindings, rows, mode: Mode.Historical);+ s.PopulationLedger.Initialize(c, bindings, rows, 0, Mode.Historical);}}}diff --git a/sim/Statecraft.Sim/Pools.cs b/sim/Statecraft.Sim/Pools.csindex 317593d9b..8890af154 100644--- a/sim/Statecraft.Sim/Pools.cs+++ b/sim/Statecraft.Sim/Pools.cs@@ -34,13 +34,16 @@ namespace Statecraft.Sim/// (#2804 item 5).</summary>public const int MaxFieldFoodPerTurn = 1000;- /// <summary>R-FOOD-001: the stock starts at cover_months of the start's need, so food_supply starts at its level.</summary>+ /// <summary>R-FOOD-001: the stock starts at cover_months of the start's need, so food_supply starts at its level. With an+ /// initialized gdd-0.3 ledger (the dark start, #1725 PR 5) the need is the ledger's, one ration for each living own+ /// population id (<see cref="Rations"/>, #2470), after the ledger reconciles; otherwise the aggregate head count. Any other+ /// initialized ledger (synthetic or Open) is refused with the state unchanged (R-POP-002).</summary>public static void Init(Content c, GameState s){- PopulationLedger.RefuseAggregate(s);- if (!c.IsGdd) return;+ if (!c.IsGdd) { PopulationLedger.RefuseAggregate(s); return; }+ PopulationLedger.RefuseUnlessHistorical(s); // S5-3: a synthetic or Open ledger stays heldvar r = c.RulesAt(s.Date).Mvp!;- s.FoodNeed = Need(s, r);+ s.FoodNeed = s.PopulationLedger.IsInitialized ? LedgerNeed(s) : Need(s, r);s.Food = r.CoverMonths!.Value * s.FoodNeed;s.FoodUnmet = 0;s.Arms = r.ArmsStart!.Value; // R-ARMS-001; the loader requires it in the GDD loop@@ -102,6 +105,14 @@ namespace Statecraft.Simpublic static bool BorrowsPastDebtCeiling(Content c, GameState turnStart, IReadOnlyList<Command> orders, int count)=> BuyArmsRefusal(c, turnStart, orders, count) == RefusedDebtCeiling;+ /// <summary>R-FOOD-001 under gdd-0.3 (#2470): an initialized ledger's need, its living own population ids, after it+ /// reconciles, so an invalid ledger sets no Food.</summary>+ static int LedgerNeed(GameState s)+ {+ s.PopulationLedger.Reconcile();+ return Rations(s.PopulationLedger.Units);+ }+/// <summary>The nation's need for one turn: its head count in population units, rounded half away from zero.</summary>static int Need(GameState s, MvpRules r) => (int)Math.Round(s.TotalPopulation / r.PeoplePerUnit, MidpointRounding.AwayFromZero);diff --git a/sim/Statecraft.Sim/PopulationLedger.cs b/sim/Statecraft.Sim/PopulationLedger.csindex 4f2af2846..0d8b6b307 100644--- a/sim/Statecraft.Sim/PopulationLedger.cs+++ b/sim/Statecraft.Sim/PopulationLedger.cs@@ -143,6 +143,9 @@ namespace Statecraft.Sim}// A snapshot wrapper prevents casts back to the writable container; records are immutable.public IReadOnlyList<PopulationUnit> Units => new ReadOnlyCollection<PopulationUnit>(units.Values.ToList());+ /// <summary>Initialized with mode Historical (the R-POP-004 start's scale). Not written to the canonical text: the+ /// scale it implies already is.</summary>+ internal bool IsHistorical { get; private set; }internal PopulationLedger(bool enabled) { this.enabled = enabled; }internal PopulationLedger Clone(){@@ -158,6 +161,12 @@ namespace Statecraft.Simif (state.PopulationLedger.IsInitialized)throw new NotSupportedException("Population-ledger fixtures cannot run aggregate systems; gdd-0.3 integration is held.");}+ /// <summary>#1725 PR 5 (review S5-3): Pools.Init and StartingForces.Init read an initialized ledger only in the dark+ /// start's shape, a Historical one (R-POP-004); a synthetic or Open ledger is refused as by <see cref="RefuseAggregate"/>.</summary>+ internal static void RefuseUnlessHistorical(GameState state)+ {+ if (!state.PopulationLedger.IsHistorical) RefuseAggregate(state);+ }void RequireInitialized(){if (!enabled || !IsInitialized) throw new InvalidOperationException("Population ledger mutations require an initialized gdd-0.3 fixture.");@@ -279,8 +288,22 @@ namespace Statecraft.Sim{if (!c.UsesPopulationLedger) throw new InvalidOperationException("Population fixtures require gdd-0.3 identity.");if (nextPopulationId < 0) throw new ArgumentOutOfRangeException(nameof(nextPopulationId));- var s = new GameState(c); var l = s.PopulationLedger;+ var s = new GameState(c);if (mode is Mode m) s.Mode = m;+ s.PopulationLedger.Initialize(c, bindings, rows, nextPopulationId, mode);+ return s;+ }++ /// <summary>#1725 PR 5: <see cref="CreateFixture"/>'s initialization, in place on a state's own ledger, so the dark+ /// start (Simulation.NewGame's internal overload) can initialize the ledger of the game it is building. Same+ /// checks and scale rule as CreateFixture. All or nothing: it builds and validates a candidate ledger and copies it+ /// in only when valid. Refuses a ledger that is not gdd-0.3's or is already initialized.</summary>+ internal void Initialize(Content c, PopulationBindings bindings, IEnumerable<PopulationInventoryRow> rows, int nextPopulationId, Mode? mode)+ {+ if (!c.UsesPopulationLedger || !enabled) throw new InvalidOperationException("Population fixtures require gdd-0.3 identity.");+ if (IsInitialized || units.Count != 0) throw new InvalidOperationException("The population ledger is already initialized.");+ if (nextPopulationId < 0) throw new ArgumentOutOfRangeException(nameof(nextPopulationId));+ var l = new PopulationLedger(true);l.bindings = bindings ?? throw new ArgumentNullException(nameof(bindings));bindings.ValidateCities(c);var ordered = rows.OrderBy(x => x.Source, StringComparer.Ordinal).ThenBy(x => x.Ordinal).ToList();@@ -297,8 +320,11 @@ namespace Statecraft.Siml.sources.Add(PopulationText.Fields(row.Source, row.Ordinal), l.NextPopulationId);l.units.Add(l.NextPopulationId, row.Template.WithId(l.NextPopulationId)); l.NextPopulationId = next;}- l.Validate(l.units); l.IsInitialized = true;- return s;+ l.Validate(l.units);+ this.bindings = l.bindings; units = l.units; sources = l.sources; losses = l.losses;+ peoplePerUnit = l.peoplePerUnit; receptionLimit = l.receptionLimit; NextPopulationId = l.NextPopulationId;+ IsHistorical = mode == Mode.Historical;+ IsInitialized = true;}// R-POP-001's no-fallback rule, as for the catalogue value: a missing or nonpositive value is refused, never replaced.internal static int HistoricalPeoplePerUnit(Content c) => c.RulesAt(c.Rules.Start).Mvp?.PeoplePerUnit is int ppu && ppu > 0 ? ppudiff --git a/sim/Statecraft.Sim/Simulation.cs b/sim/Statecraft.Sim/Simulation.csindex 369c38d74..d62bd4f31 100644--- a/sim/Statecraft.Sim/Simulation.cs+++ b/sim/Statecraft.Sim/Simulation.cs@@ -7,21 +7,30 @@ namespace Statecraft.Sim/// <summary>The public entry point the Unity layer calls: start a game, then step it one turn at a time.</summary>public static class Simulation{- public static GameState NewGame(Content c, ulong seed, Mode mode)+ public static GameState NewGame(Content c, ulong seed, Mode mode) => NewGame(c, seed, mode, darkStart: false);++ /// <summary>#1689, #1725 PR 5: with <paramref name="darkStart"/>, the dark start of an exact gdd-0.3 Historical game,+ /// internal and fixture-only (the public NewGame passes false): the Historical ledger (R-POP-004) is initialized in+ /// place before Pools.Init, so the Food stock starts at cover_months of the ledger's need (R-FOOD-001, #2470), and+ /// the starting forces are placed against its soldiers. EventSystem.Trigger still refuses a ledger (R-POP-002) until+ /// its producer is integrated, so a dark start fires no opening event. Legacy and gdd-0.1 content refuse it.</summary>+ internal static GameState NewGame(Content c, ulong seed, Mode mode, bool darkStart){if (c == null) throw new ArgumentNullException(nameof(c));if (mode == Mode.Open) throw new NotSupportedException("Open mode arrives with milestone M4.");+ if (darkStart && !c.UsesPopulationLedger) throw new InvalidOperationException("A dark start needs exact gdd-0.3 (R-POP-001).");var s = new GameState(c) { Date = c.Rules.Start, RngState = seed, Mode = mode };var why = new List<Cause>();EffectsSystem.Init(c, s);EconomySystem.Init(c, s);PopulationSystem.Init(c, s);Cities.Init(c, s);+ if (darkStart) HistoricalPopulation.Initialize(c, s); // before Pools.Init, which reads the ledger's needPools.Init(c, s);StartingForces.Init(c, s); // R-UNIT-006: before any event can grant a unit, so the forces take ids 0 to n-1SecuritySystem.Init(c, s, why);if (c.UsesAttention) AttentionSystem.Refill(c, s);- EventSystem.Trigger(c, s, why);+ if (!darkStart) EventSystem.Trigger(c, s, why); // R-POP-002: refuses an initialized ledgerreturn s;}diff --git a/sim/Statecraft.Sim/StartingForces.cs b/sim/Statecraft.Sim/StartingForces.csindex 9f07252eb..88c1b163c 100644--- a/sim/Statecraft.Sim/StartingForces.cs+++ b/sim/Statecraft.Sim/StartingForces.cs@@ -150,10 +150,12 @@ namespace Statecraft.Sim/// <summary>Adds the starting forces to a new game, in the content's order, taking the next ids: the unit with id i/// of a new game is <c>c.StartingForces[i]</c>. An arriving row's id is taken too, so it is free when it arrives- /// (R-UNIT-009).</summary>+ /// (R-UNIT-009). With an initialized gdd-0.3 ledger (the dark start, #1725 PR 5), each own starting formation's+ /// strength must be its active-soldier records serving in it (R-POP-004), or nothing is added. Any other initialized+ /// ledger (synthetic or Open) is refused, with nothing added (R-POP-002).</summary>public static void Init(Content c, GameState s){- PopulationLedger.RefuseAggregate(s);+ if (s.PopulationLedger.IsInitialized) { PopulationLedger.RefuseUnlessHistorical(s); RequireLedgerSoldiers(c, s); }foreach (var f in c.StartingForces){var id = s.NextId++;@@ -161,6 +163,21 @@ namespace Statecraft.Sim}}+ /// <summary>R-POP-004: an own formation in the start inventory gives its strength as active soldiers whose service+ /// target is its source key (HistoricalPopulation.FormationPrefix plus its row), so the formations the game places and+ /// the ledger's soldiers are the same people.</summary>+ static void RequireLedgerSoldiers(Content c, GameState s)+ {+ var serving = s.PopulationLedger.Units.Where(p => p.Status == PopulationStatus.ActiveSoldier && p.Assignment.Target != null)+ .GroupBy(p => p.Assignment.Target!, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.Count(), StringComparer.Ordinal);+ foreach (var f in HistoricalPopulation.OpeningFormations(c))+ {+ var key = HistoricalPopulation.FormationPrefix + f.Row;+ if ((serving.TryGetValue(key, out var n) ? n : 0) != f.Strength)+ throw new InvalidOperationException($"Starting formation '{f.Row}' has strength {f.Strength} but the population ledger serves it with {n} (R-POP-004).");+ }+ }+/// <summary>R-UNIT-009 (#1241, owner, 21 October 2026, answer 1(a)): resolver step 9b. A row dated after the start/// arrives in the resolution of the turn from s.Date to <paramref name="next"/> that reaches its day, once, as unit/// <c>c.StartingForces[i]</c>'s id i, on its anchor's hex with its strength. Like a starting force it ignores the stack