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 ledger: the Historical start inventory from the census cities and units_1948.yaml (R-POP-004, Refs #1689) (#2129)
Eyal Golan09649335e367
diff --git a/changelog.d/1689-ledger-setup.md b/changelog.d/1689-ledger-setup.mdnew file mode 100644index 000000000..753abc135--- /dev/null+++ b/changelog.d/1689-ledger-setup.md@@ -0,0 +1,4 @@+- GDD 0.3 population ledger (#1689): the sim can now list the Historical start's own population under the `gdd-0.3`+ ruleset (R-POP-004): one record per census city unit and per unit of each Israeli starting formation in+ `map/units_1948.yaml`, at 1,000 people a unit (owner ruling D2). Nothing in the game calls it yet, and the shipped+ `gdd-0.1` game is unchanged.diff --git a/docs/population-ledger.md b/docs/population-ledger.mdindex 43f9fc83a..42aa13c5f 100644--- a/docs/population-ledger.md+++ b/docs/population-ledger.md@@ -10,4 +10,8 @@ Validation builds a candidate map first, including teacher resolution and uniqueGameState.Clone owns a copied ledger; frozen bindings and records can be shared. Canonical output covers the full binding inventory, all unit fields, source/loss records, initialization flag, scale/reception requirement and allocator in one shared Describe/Hash writer. Reference strings use invariant length-prefixed encoding with an explicit null marker; embedded delimiters cannot alias another record. All accepted reference/provenance strings reject malformed UTF-16 before admission, so UTF-8 hashing cannot collapse invalid surrogate sequences; valid supplementary characters remain lossless. Enum declaration order is never serialized. Older identities enter none of this writer. The new empty gdd-0.3 section changes unpublished schema-4 draft hashes only; no legacy/schema-3 migration or byte change is intended.-No save/reload round trip for population identity is claimed. The existing seed/content/command replay envelope is unchanged; step 3 must introduce actual identity-addressed replayable producers before population fixtures can be saved as campaigns. Captured Food selection and arrival meal timing, course/combat/prisoner integration, production initialization and all of #1704 remain held. This foundation does not implement R-POP-004 or close #1689.+No save/reload round trip for population identity is claimed. The existing seed/content/command replay envelope is unchanged; step 3 must introduce actual identity-addressed replayable producers before population fixtures can be saved as campaigns. Captured Food selection and arrival meal timing, course/combat/prisoner integration, production initialization and all of #1704 remain held. This foundation does not close #1689.++## 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` and initializes no ledger: each record still needs a region/location binding (#1690, #1691), and 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.diff --git a/docs/rules/mvp.md b/docs/rules/mvp.mdindex 663a20ca1..abed9826a 100644--- a/docs/rules/mvp.md+++ b/docs/rules/mvp.md@@ -543,14 +543,16 @@ R-CAMERA-001: Only exact `gdd-0.3` fixes gameplay yaw at zero (north), including## Population identity foundation (gdd-0.3 only)-These contracts cover #1689 steps 1–2 only. Production era selection, Food consumption and command/save/reload integration remain held; helper coverage does not complete #1689. See [population-ledger.md](../population-ledger.md).+These contracts cover #1689 steps 1–2 and the Historical start inventory (R-POP-004) only. Production era selection, Food consumption and command/save/reload integration remain held; helper coverage does not complete #1689. See [population-ledger.md](../population-ledger.md).-R-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 reads one positive Agreed integer from `population.people_per_unit` in its catalogue (currently 10,000); old identities retain the common rules scale. Missing, fractional, nonpositive, overflowing or Deferred values have no fallback.+R-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 reads one positive Agreed integer from `population.people_per_unit` in its catalogue (currently 10,000, Open mode's scale under D2; the Historical start counts at 1,000, R-POP-004); old identities retain the common rules scale. Missing, fractional, nonpositive, overflowing or Deferred values have no fallback.R-POP-002: A ledger record has exactly one typed status and assignment, validated location, home and captor references, whole reception-turn ticks capped by the catalogue requirement, civilian profession-specific tier and actual-work XP, separate military qualification/combat XP, and distinct issued civilian/military equipment and paid facts. Unknown references, unresolved teacher ids, incompatible statuses/assignments, inconsistent region/hex/facility bindings, invalid progress/tiers and duplicate issued-item ownership are refused before mutation. Moves and atomic status/location/assignment transitions retain identity/history. Capture retains home context without inventing a prison hex or refunding equipment. Ledger changes never touch resources, causes, RNG or Attention. Initialization is internal and fixture-only; initialized ledger fixtures refuse aggregate Simulation commands and turns. Old identities refuse ledger mutation. Prices, progression awards, return destinations, tool lock-in and captive-equipment outcomes remain with their owning issues.R-POP-003: Clone copies all ledger containers; immutable records and frozen bindings may be shared. The canonical writer emits a gdd-0.3-only section ordered by numeric population id, with fixed field order, stable machine tokens, invariant integer formatting and length-prefixed reference strings. It covers every record/assignment/equipment/reference field, binding, creation/loss provenance and allocator even after the last combat loss. Legacy/gdd-0.1 emit no ledger section or allocator marker. R-SAVE-001/002 still govern identity mismatch refusal and replay: no ledger snapshot or new command syntax is added in this foundation, and fixture injection is not replay evidence. Existing unpublished schema-4 draft hashes change; no migration promise is made.+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, no more and no less. 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. Still Deferred: the region or location binding of each record (#1690, #1691; `content/regions.yaml` has no region), the work assignments of the employed share, which census units are farmers (fields, #1691/#1717; the owner's 1:2:1 novice/trained/veteran ratio per city then applies), the formations' military qualification, combat experience and issued equipment (#1717), and the ledger scale for this start (R-POP-001 reads the catalogue's 10,000).+#1706 slices 0/1 (coordinator decision, 26 Oct 2026, Q5): the synthetic combat catalogue foundation is inactive in the actual game. R-COMBAT-001 through R-COMBAT-008 retain their current runtime meanings. See [the catalogue foundation](../gdd03-catalogue.md#1706-slices-01-inactive-combat-catalogue-foundation) for its data contract and sources.## Map editor infrastructure (gdd-0.3 authoring only)diff --git a/sim/Statecraft.Sim.Tests/HistoricalPopulationTests.cs b/sim/Statecraft.Sim.Tests/HistoricalPopulationTests.csnew file mode 100644index 000000000..659594bc5--- /dev/null+++ b/sim/Statecraft.Sim.Tests/HistoricalPopulationTests.cs@@ -0,0 +1,141 @@+using Statecraft.Sim;++/// <summary>#1689, the Historical start inventory under exact gdd-0.3 (R-POP-004): the real census cities and the real+/// map/units_1948.yaml starting formations, read from the shipped content with only eras.yaml's ruleset switched.+/// The inventory is not yet wired into Simulation.NewGame (see R-POP-004 and docs/population-ledger.md).</summary>+public class HistoricalPopulationTests+{+ static Content Real(bool modern)+ {+ var root = RealContentTests.ContentRoot();+ return ContentLoader.Load(rel =>+ {+ var path = Path.Combine(root, rel);+ var text = File.Exists(path) ? File.ReadAllText(path) : null;+ return modern && rel == "eras.yaml" ? text!.Replace("loop: gdd", "loop: gdd, ruleset: gdd-0.3") : text;+ }, Directory.GetFiles(Path.Combine(root, "events"), "*.yaml").Select(p => "events/" + Path.GetFileName(p)));+ }++ static int Count(IReadOnlyList<HistoricalPopulationRow> rows, string source) => rows.Count(r => r.Source == source);++ // R-POP-004, R-CITY-007, R-UNIT-006, R-CITY-008: one record per census population unit in each city and per population+ // unit of each Israeli starting formation, no more and no less, checked against the aggregate start of the same content.+ [Fact]+ public void RealInventoryHoldsTheCensusCitiesAndTheStartingFormationsNoMoreNoLess()+ {+ var c = Real(true);+ Assert.Equal(SaveGame.Gdd03Ruleset, c.Ruleset);+ var rows = HistoricalPopulation.Inventory(c);+ var start = Simulation.NewGame(c, 1, Mode.Historical); // the aggregate start; the ledger stays uninitialized++ Assert.NotEmpty(start.Cities);+ foreach (var city in start.Cities.Values)+ {+ Assert.Equal(city.Civilians, Count(rows, HistoricalPopulation.CensusPrefix + city.Id));+ Assert.Equal(0, city.Refugees); // R-CITY-007: a city starts with no refugees, so every census record is a civilian+ }+ var own = start.Units.Values.Where(u => u.Side == Movement.PlayerSide).ToList();+ Assert.NotEmpty(own);+ foreach (var u in own)+ Assert.Equal(u.Strength, Count(rows, HistoricalPopulation.FormationPrefix + c.StartingForces[u.Id].Row));++ var expected = start.Cities.Values.Sum(x => x.Civilians) + own.Sum(u => u.Strength);+ Assert.Equal(expected, rows.Count);+ Assert.All(rows.Where(r => r.Source.StartsWith(HistoricalPopulation.CensusPrefix, StringComparison.Ordinal)),+ r => Assert.Equal(PopulationStatus.FreeCivilian, r.Status));+ Assert.All(rows.Where(r => r.Source.StartsWith(HistoricalPopulation.FormationPrefix, StringComparison.Ordinal)),+ r => Assert.Equal(PopulationStatus.ActiveSoldier, r.Status));+ Assert.All(rows, r => Assert.True(r.Source.StartsWith(HistoricalPopulation.CensusPrefix, StringComparison.Ordinal)+ || r.Source.StartsWith(HistoricalPopulation.FormationPrefix, StringComparison.Ordinal)));+ }++ // R-POP-004, R-CITY-006, R-CITY-007: an anchor independent of the loader. The census sources are exactly the twelve+ // managed Jewish cities of cities.yaml (no Arab or mixed town is own population), and named cities' counts are their+ // sourced people (cities.yaml) at 1,000 a unit, to the nearest unit with a half up and at least 1, written out here.+ [Fact]+ public void CensusSourcesAreTheTwelveCitiesAtTheirCensusUnits()+ {+ var rows = HistoricalPopulation.Inventory(Real(true));+ var cities = rows.Select(r => r.Source).Where(s => s.StartsWith(HistoricalPopulation.CensusPrefix, StringComparison.Ordinal))+ .Distinct(StringComparer.Ordinal).Select(s => s.Substring(HistoricalPopulation.CensusPrefix.Length)).OrderBy(s => s, StringComparer.Ordinal);+ Assert.Equal(new[] { "hadera", "haifa", "jerusalem", "netanya", "petah_tikva", "rehovot", "rishon_lezion", "rosh_pinna",+ "safed", "tel_aviv", "tiberias", "zikhron_yaakov" }, cities);+ Assert.Equal(248, Count(rows, HistoricalPopulation.CensusPrefix + "tel_aviv")); // 248,459 people+ Assert.Equal(99, Count(rows, HistoricalPopulation.CensusPrefix + "haifa")); // 98,618: rounds up+ Assert.Equal(84, Count(rows, HistoricalPopulation.CensusPrefix + "jerusalem")); // 83,984: rounds up+ Assert.Equal(6, Count(rows, HistoricalPopulation.CensusPrefix + "tiberias")); // 5,555: rounds up+ Assert.Equal(1, Count(rows, HistoricalPopulation.CensusPrefix + "rosh_pinna")); // 350: at least 1+ }++ // R-POP-004, R-UNIT-006: the formation sources are exactly the Israeli starting rows, compared by row id.+ [Fact]+ public void FormationSourcesAreExactlyTheOwnStartingRows()+ {+ var c = Real(true);+ var rows = HistoricalPopulation.Inventory(c);+ var formations = rows.Select(r => r.Source).Where(s => s.StartsWith(HistoricalPopulation.FormationPrefix, StringComparison.Ordinal))+ .Distinct(StringComparer.Ordinal).OrderBy(s => s, StringComparer.Ordinal);+ Assert.Equal(c.StartingForces.Where(f => f.Side == Movement.PlayerSide && f.Arrives == null)+ .Select(f => HistoricalPopulation.FormationPrefix + f.Row).OrderBy(s => s, StringComparer.Ordinal), formations);+ }++ // 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]+ public void EnemyFormationsAndDatedArrivalsAreNotInTheStartInventory()+ {+ var c = Real(true);+ var rows = HistoricalPopulation.Inventory(c);+ var enemy = c.StartingForces.Where(f => f.Side != Movement.PlayerSide).ToList();+ var arrivals = c.StartingForces.Where(f => f.Side == Movement.PlayerSide && f.Arrives != null).ToList();+ Assert.NotEmpty(enemy);+ Assert.Contains(arrivals, f => f.Row == "brigade_7"); // R-UNIT-009: the 7th Brigade arrives on 24 May 1948+ foreach (var f in enemy.Concat(arrivals))+ Assert.Equal(0, Count(rows, HistoricalPopulation.FormationPrefix + f.Row));+ }++ // R-POP-004 with D2 (owner, 1 November 2026): the Historical start counts at rules.yaml's people_per_unit, 1,000 a unit,+ // not the gdd-0.3 catalogue's 10,000 (Open mode's). R-UNIT-006's own examples: Golani's 4,095 is 4, Kiryati's 2,504 is 3.+ [Fact]+ public void TheHistoricalStartCountsAtOneThousandPeopleAUnit()+ {+ var c = Real(true);+ Assert.Equal(1000, c.RulesAt(c.Rules.Start).Mvp!.PeoplePerUnit);+ Assert.Equal(10000, c.PopulationPeoplePerUnit);+ var rows = HistoricalPopulation.Inventory(c);+ Assert.Equal(4, Count(rows, HistoricalPopulation.FormationPrefix + "golani"));+ Assert.Equal(3, Count(rows, HistoricalPopulation.FormationPrefix + "kiryati"));+ }++ // R-POP-001, R-POP-004: inventory order is source key by ordinal string comparison, then a contiguous within-source+ // ordinal from 0, so ascending population ids follow it (Q10). Repeated reads are identical (docs/determinism.md).+ [Fact]+ public void InventoryOrderIsSourceKeyThenOrdinalAndRepeatable()+ {+ var c = Real(true);+ var rows = HistoricalPopulation.Inventory(c);+ var sorted = rows.OrderBy(r => r.Source, StringComparer.Ordinal).ThenBy(r => r.Ordinal).ToList();+ Assert.Equal(sorted, rows);+ foreach (var g in rows.GroupBy(r => r.Source, StringComparer.Ordinal))+ Assert.Equal(Enumerable.Range(0, g.Count()), g.Select(r => r.Ordinal));+ var again = HistoricalPopulation.Inventory(Real(true));+ Assert.Equal(rows.Select(r => (r.Source, r.Ordinal, r.Status)), again.Select(r => (r.Source, r.Ordinal, r.Status)));+ }++ // R-POP-001, R-POP-004: only exact gdd-0.3 has a population ledger; the shipped gdd-0.1 content refuses the inventory.+ [Fact]+ public void Gdd01ContentRefusesTheInventory()+ {+ var c = Real(false);+ Assert.Equal(SaveGame.GddRuleset, c.Ruleset);+ Assert.Throws<InvalidOperationException>(() => HistoricalPopulation.Inventory(c));+ }++ // R-POP-002, R-POP-004: a new gdd-0.3 game still starts on the aggregate records with an uninitialized ledger;+ // initializing it at NewGame waits on the producer integration (R-POP-002 refusal).+ [Fact]+ public void NewGameDoesNotInitializeTheLedgerYet()+ {+ Assert.False(Simulation.NewGame(Real(true), 1, Mode.Historical).PopulationLedger.IsInitialized);+ }+}diff --git a/sim/Statecraft.Sim/HistoricalPopulation.cs b/sim/Statecraft.Sim/HistoricalPopulation.csnew file mode 100644index 000000000..707fd91c4--- /dev/null+++ b/sim/Statecraft.Sim/HistoricalPopulation.cs@@ -0,0 +1,51 @@+using System;+using System.Collections.Generic;+using System.Linq;++namespace Statecraft.Sim+{+ /// <summary>One population unit of the Historical start inventory (R-POP-004): its source key, its ordinal within that+ /// source and its starting status. The ledger's id order is source key, then ordinal (R-POP-001).</summary>+ internal sealed class HistoricalPopulationRow+ {+ /// <summary><see cref="HistoricalPopulation.CensusPrefix"/> plus a city id, or <see cref="HistoricalPopulation.FormationPrefix"/>+ /// plus a map/units_1948.yaml row id.</summary>+ public string Source { get; }+ public int Ordinal { get; }+ public PopulationStatus Status { get; }+ internal HistoricalPopulationRow(string source, int ordinal, PopulationStatus status)+ {+ Source = source; Ordinal = ordinal; Status = status;+ }+ }++ /// <summary>R-POP-004 (#1689; owner, 1 November 2026, D2 and D4): the own population a gdd-0.3 Historical game starts with,+ /// read from the content the aggregate start reads. Each census city gives its R-CITY-007 start units as free civilians;+ /// each Israeli starting formation of map/units_1948.yaml (R-UNIT-006) gives its strength as active soldiers. Enemy+ /// formations are not own population, and a dated arrival (R-UNIT-009) is not in the start. Counts use rules.yaml's+ /// people_per_unit (1,000, D2), as Cities and StartingForces already do. No RNG, no state, no culture formatting.+ /// Nothing in the game calls it yet: an initialized ledger refuses every aggregate system (R-POP-002), so NewGame keeps+ /// the aggregate start until the producers are integrated.</summary>+ internal static class HistoricalPopulation+ {+ internal const string CensusPrefix = "census/";+ internal const string FormationPrefix = "units_1948/";++ internal static IReadOnlyList<HistoricalPopulationRow> Inventory(Content c)+ {+ if (c == null) throw new ArgumentNullException(nameof(c));+ if (!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));+ if (counts.Select(x => x.Source).Distinct(StringComparer.Ordinal).Count() != counts.Count)+ throw new InvalidOperationException("Duplicate Historical population source.");+ var rows = new List<HistoricalPopulationRow>();+ foreach (var (source, units, status) in counts.OrderBy(x => x.Source, StringComparer.Ordinal))+ for (int i = 0; i < units; i++) rows.Add(new HistoricalPopulationRow(source, i, status));+ return rows.AsReadOnly();+ }+ }+}