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): CBS arrivals and natural increase become people records on a Historical ledger game (#1725 PR 7, producer 02) (#2954)
Eyal Golan597b9367a57c
diff --git a/changelog.d/1725-pr7-cbs-arrivals.md b/changelog.d/1725-pr7-cbs-arrivals.mdnew file mode 100644index 000000000..a85653065--- /dev/null+++ b/changelog.d/1725-pr7-cbs-arrivals.md@@ -0,0 +1,3 @@+- GDD 0.3 starting population (Refs #1725, Refs #1689): on the inactive dark start's Historical ledger, each whole unit of+ CBS immigrants that arrives in a turn becomes one refugee record in its city, split over the cities as today, and the+ national count adds none of them a second time. No new-game wiring, so there is no change in the game.diff --git a/changelog.d/1725-pr7-natural-increase.md b/changelog.d/1725-pr7-natural-increase.mdnew file mode 100644index 000000000..4491eab2a--- /dev/null+++ b/changelog.d/1725-pr7-natural-increase.md@@ -0,0 +1,3 @@+- GDD 0.3 starting population (Refs #1725, Refs #1689): on the inactive dark start's Historical ledger, natural increase+ (0.0169 a year of everyone alive) now adds whole free civilians to the cities, split as the immigrants are, carrying the+ part of a person each turn leaves over to the next. No new-game wiring, so there is no change in the game.diff --git a/docs/rules/mvp.md b/docs/rules/mvp.mdindex 65a77d295..631b7e60a 100644--- a/docs/rules/mvp.md+++ b/docs/rules/mvp.md@@ -102,9 +102,9 @@ GDD 0.3 fixture clarification for R-CITY-001/002: the owner’s 28 October Q34 aSynthetic regional fixtures additionally enforce R-CITY-001/002 and R-CITY-006: Industry and Workshop occupancy is counted separately in each worker’s initialized region and cannot exceed its effective `PlayerRegionPool` job slots, including facility contributions. Reassignment excludes the mover’s current reservation before checking the destination; refusals preserve the complete state. Farm and Builder retain their explicit slot bounds. This adds no real job/facility mapping, command, production payment or gameplay activation; fixtures without regional pools keep their existing slot-only behavior.-R-CITY-003: Arrivals from the CBS series (`aliyah.yaml`) become refugees in the cities. Let `P(t)` be the people the series brings from `city_arrivals_from` to the date `t` (0 before it), summed over the origin groups in ordinal order. `city_arrivals_from` is 8 November 1948, the census day the cities' start values count: the census already holds the people who arrived from 15 May, so the cities take none before it (Q-ARRV-3, owner, 15 October 2026). The cities' arrived units by `t` are `U(t) = floor(P(t) / people_per_unit)`, and a turn from date `d` to date `e` adds `U(e) - U(d)` refugees over all cities. `people_per_unit` and `city_arrivals_from` are the same in every era (the loader refuses an era that changes either), so over any run of turns the refugees added are `U(end) - U(start)`: no unit is lost or counted twice. The units are split in proportion to the cities' census `people` (Q-ARRV-1): the first `U` units are handed out one at a time, unit `n` to the city with the largest remainder `n * people / total people - units it holds`, a tie to the lower city id (ordinal), and a turn gives each city its share of `U(e)` minus its share of `U(d)`. Building the split up one unit at a time keeps it cumulative: a fresh largest-remainder split of each total could take a unit back from a city as the total grows (the Alabama paradox; on the twelve cities it first happens at 7 units). The loader refuses a GDD game with no city.+R-CITY-003: Arrivals from the CBS series (`aliyah.yaml`) become refugees in the cities. Let `P(t)` be the people the series brings from `city_arrivals_from` to the date `t` (0 before it), summed over the origin groups in ordinal order. `city_arrivals_from` is 8 November 1948, the census day the cities' start values count: the census already holds the people who arrived from 15 May, so the cities take none before it (Q-ARRV-3, owner, 15 October 2026). The cities' arrived units by `t` are `U(t) = floor(P(t) / people_per_unit)`, and a turn from date `d` to date `e` adds `U(e) - U(d)` refugees over all cities. `people_per_unit` and `city_arrivals_from` are the same in every era (the loader refuses an era that changes either), so over any run of turns the refugees added are `U(end) - U(start)`: no unit is lost or counted twice. The units are split in proportion to the cities' census `people` (Q-ARRV-1): the first `U` units are handed out one at a time, unit `n` to the city with the largest remainder `n * people / total people - units it holds`, a tie to the lower city id (ordinal), and a turn gives each city its share of `U(e)` minus its share of `U(d)`. Building the split up one unit at a time keeps it cumulative: a fresh largest-remainder split of each total could take a unit back from a city as the total grows (the Alabama paradox; on the twelve cities it first happens at 7 units). The loader refuses a GDD game with no city. With an initialized Historical ledger (the dark start, R-POP-002; #1725 PR 7) each arrived unit is one refugee record instead of a count (GDD Q11: arrivals "take new ids as refugees in a city"), registered with source key `cbs/<city id>` and, as its ordinal, the unit's place in that city's cumulative share from `city_arrivals_from`, so the same units get the same keys whichever turn brings them and a replay of a turn adds nobody twice (R-POP-001). The record is located in its city, in the region that lists it, with reception 0 and no assignment, profession or tier. The split and the city messages are as above; the aggregate city fields are not written, and `PopulationSystem` adds no second count of these people (R-CITY-008). A synthetic or Open ledger is still refused.-R-CITY-008: Under legacy/gdd-0.1, `GameState.Population` is the one record of the nation's people: it takes every arrival from 15 May 1948 and is the count the CBS anchors check. The cities are the part of it placed in towns, so their people (civilians, craftsmen, refugees, recruits and the groups in training, times `people_per_unit`) never exceed it (Q-ARRV-2, owner, 15 October 2026). No person is counted twice. A stayed town's annexation (R-CTRL-016) adds its approved people to `GameState.Population` (owner, 4 November 2026, #2608, the option labelled "Yes, add them (Recommended)"; `EndOccupationTests.AnnexingAStayedPlaceAddsItsPeopleToThePopulationAndAFledOneAddsNone`). They go in a group of their own, `annexed`, not an aliyah origin, and an initialized gdd-0.3 ledger fixture is left alone (`EndOccupationTests.AnnexingIntoAnInitializedGdd03LedgerLeavesThePopulationAlone`); both are this change's design, not the owner's ruling. The total (`GameState.TotalPopulation`) counts them wherever the game reads it (owner, 4 November 2026, the option labelled "Count them everywhere", https://github.com/eyalgolan/statecraft-israel/pull/2620#pullrequestreview-5777301237), so it is the whole population, no longer the Jewish population alone. In initialized gdd-0.3 fixtures, the own-population ledger is authoritative instead: profession, employment, training and captivity are attributes/statuses of the same ids (R-POP-001), never extra people. No old headcount is rounded into ledger records.+R-CITY-008: Under legacy/gdd-0.1, `GameState.Population` is the one record of the nation's people: it takes every arrival from 15 May 1948 and is the count the CBS anchors check. The cities are the part of it placed in towns, so their people (civilians, craftsmen, refugees, recruits and the groups in training, times `people_per_unit`) never exceed it (Q-ARRV-2, owner, 15 October 2026). No person is counted twice. A stayed town's annexation (R-CTRL-016) adds its approved people to `GameState.Population` (owner, 4 November 2026, #2608, the option labelled "Yes, add them (Recommended)"; `EndOccupationTests.AnnexingAStayedPlaceAddsItsPeopleToThePopulationAndAFledOneAddsNone`). They go in a group of their own, `annexed`, not an aliyah origin, and an initialized gdd-0.3 ledger fixture is left alone (`EndOccupationTests.AnnexingIntoAnInitializedGdd03LedgerLeavesThePopulationAlone`); both are this change's design, not the owner's ruling. The total (`GameState.TotalPopulation`) counts them wherever the game reads it (owner, 4 November 2026, the option labelled "Count them everywhere", https://github.com/eyalgolan/statecraft-israel/pull/2620#pullrequestreview-5777301237), so it is the whole population, no longer the Jewish population alone. In initialized gdd-0.3 fixtures, the own-population ledger is authoritative instead: profession, employment, training and captivity are attributes/statuses of the same ids (R-POP-001), never extra people. No old headcount is rounded into ledger records. On an initialized Historical ledger (the dark start, R-POP-002; #1725 PR 7) `PopulationSystem.Apply` adds no second count of the CBS arrivals, which are R-CITY-003's refugee records, and leaves `GameState.Population` alone; it adds the natural increase at the national rate (GDD Q11, 0.0169 a year) as records, under four rulings (owner, 8 November 2026): "Carry the fraction (Recommended)": the part of a record a turn owes is kept from turn to turn, and a record is added each time the carried sum reaches one. "Same split as arrivals (Recommended)": the new records are split over the cities by R-CITY-003's largest-remainder split of all natural-increase records so far. "Free civilian (Recommended)": each new record is a free civilian of its city, with no work experience and no reception wait. "Everyone alive (Recommended)": the base is every living record of the ledger, soldiers included. A turn owes the carry plus the rate times the turn's share of a year times that base, in the aggregate natural increase's double arithmetic; a record's source key is `increase/<city id>` with its place in that city's share as the ordinal. The carry and the count of these records are in the gdd-0.3 ledger's canonical text (R-POP-003) once natural increase has run, the carry as the 16 hex digits of its IEEE bits and omitted when zero (`docs/determinism.md`), so no earlier ledger and no legacy or gdd-0.1 game hashes differently. A negative rate has no ruling and is refused. Saving and reloading a ledger game is still held (the note before R-POP-001: "command/save/reload integration remain held").R-CITY-004: Each turn, on the housing step, a city's refugees become civilians without a job (R-CITY-009's default may then give them jobs), `floor(pool x m)` of them at the Immigration minister's multiplier since the ministers (R-MIN-002; all of them before); the rest wait as refugees for the next turns. There is no hard cap (D-D1, Q-HOUSE-1, owner, 15 October 2026): the people beyond the city's housing stay in the city as its overflow (R-HOUSE-002), and residents are housed automatically (Q-HOUSE-4).diff --git a/sim/Statecraft.Sim.Tests/LedgerArrivalsTests.cs b/sim/Statecraft.Sim.Tests/LedgerArrivalsTests.csnew file mode 100644index 000000000..2e6c5df56--- /dev/null+++ b/sim/Statecraft.Sim.Tests/LedgerArrivalsTests.cs@@ -0,0 +1,171 @@+using Statecraft.Sim;++/// <summary>#1725 PR 7, producer draft 02, arrivals only (the coordinator's ruling (a), 8 November 2026): on a game with an+/// initialized Historical ledger, each whole unit <c>Cities.Arrive</c> brings from the CBS series (R-CITY-003) is one+/// refugee record, located in its city by <c>Cities.Apportion</c>'s split, reception 0, with a stable source key and+/// ordinal, so a replay of the turn adds nobody twice. <c>PopulationSystem.Apply</c> adds no second count of the same+/// people (R-CITY-008: the ledger is authoritative, "never extra people"). Natural increase on the ledger is+/// <see cref="LedgerNaturalIncreaseTests"/>.</summary>+public class LedgerArrivalsTests+{+ static Content Gdd03() => HistoricalPopulationTests.Real(true);++ // A turn after the census day (city_arrivals_from, 8 November 1948) that brings CBS arrivals to the cities.+ internal static readonly DateTime From = new DateTime(1949, 1, 1);+ internal static readonly DateTime To = new DateTime(1949, 2, 1);++ // The dark start (#1725 PR 5): an initialized Historical ledger beside the game's city records, moved to the turn.+ internal static GameState Fixture(Content c)+ {+ var s = Simulation.NewGame(c, 1, Mode.Historical, darkStart: true);+ s.Date = From;+ return s;+ }++ internal static List<PopulationUnit> Arrived(GameState s) =>+ s.PopulationLedger.Units.Where(u => u.Status == PopulationStatus.Refugee).ToList();++ static Content NoNaturalIncrease()+ {+ var c = Gdd03();+ c.Rules.NaturalIncreasePerYear = 0;+ foreach (var r in c.EraRules.Values) r.NaturalIncreasePerYear = 0;+ return c;+ }++ // R-CITY-003 on the ledger: the turn's whole arrived units become one refugee record each, split over the cities by+ // Apportion as the aggregate game splits them, with the aggregate game's Why lines, reception 0, located in the city.+ // R-CITY-008: the records are the people; the aggregate city fields are not written, and the total rises by exactly the+ // arrived units times people_per_unit.+ [Fact]+ public void ArrivedUnitsBecomeOneRefugeeRecordEachInTheApportionSplit()+ {+ var c = Gdd03();+ var r = c.RulesAt(From).Mvp!;+ var s = Fixture(c);+ var twin = Simulation.NewGame(c, 1, Mode.Historical); twin.Date = From;+ var units = Cities.ArrivedUnits(c, From, To, r.PeoplePerUnit);+ Assert.True(units > 0);+ var before = twin.Cities.Values.ToDictionary(x => x.Id, x => x.Refugees, StringComparer.Ordinal);+ var cities = s.Cities.Values.Select(x => (x.Id, x.Refugees)).ToList();+ var next = s.PopulationLedger.NextPopulationId;+ var total = s.TotalPopulation;+ var why = new List<Cause>(); var twinWhy = new List<Cause>();++ Cities.Arrive(c, s, r, To, why);+ Cities.Arrive(c, twin, r, To, twinWhy);++ var arrived = Arrived(s);+ Assert.Equal(units, arrived.Count);+ Assert.Equal(Enumerable.Range(next, units), arrived.Select(u => u.Id));+ Assert.All(arrived, u =>+ {+ Assert.Equal(0, u.ReceptionTicks);+ Assert.Equal(PopulationAssignmentKind.Unassigned, u.Assignment.Kind);+ Assert.Equal(CivilianProfession.None, u.Profession);+ Assert.Equal(c.PlayerRegions.AtLocation(u.Location!.City!)!.Id, u.Location.Region);+ });+ var byCity = arrived.GroupBy(u => u.Location!.City!).ToDictionary(g => g.Key, g => g.Count(), StringComparer.Ordinal);+ foreach (var x in twin.Cities.Values)+ Assert.Equal(x.Refugees - before[x.Id], byCity.GetValueOrDefault(x.Id));+ Assert.Equal(twinWhy.Select(x => (x.System, x.Target, x.Delta, x.Message, x.Key)), why.Select(x => (x.System, x.Target, x.Delta, x.Message, x.Key)));+ Assert.Equal(cities, s.Cities.Values.Select(x => (x.Id, x.Refugees)));+ s.PopulationLedger.Reconcile();+ Assert.Equal(total + units * r.PeoplePerUnit, s.TotalPopulation);+ }++ // R-CITY-003, R-POP-001: a record's source is the city's CBS arrivals and its ordinal the unit's place in the city's+ // cumulative share, so the same turn replayed from the same state, or run again on the state it produced, adds nobody+ // twice; and two turns in a row give the split of the whole run (no unit lost or counted twice).+ [Fact]+ public void ReplayingTheTurnAddsNobodyTwice()+ {+ var c = Gdd03();+ var r = c.RulesAt(From).Mvp!;+ var s = Fixture(c);+ var saved = s.Clone();+ Cities.Arrive(c, s, r, To, new List<Cause>());+ var once = s.PopulationLedger.Canonical().ToList();++ var replay = saved.Clone();+ Cities.Arrive(c, replay, r, To, new List<Cause>());+ Assert.Equal(once, replay.PopulationLedger.Canonical());++ var again = new List<Cause>();+ Cities.Arrive(c, s, r, To, again);+ Assert.Equal(once, s.PopulationLedger.Canonical());+ Assert.Empty(again);++ var later = new DateTime(1949, 3, 1);+ s.Date = To;+ Cities.Arrive(c, s, r, later, new List<Cause>());+ s.PopulationLedger.Reconcile();+ var split = Cities.Apportion(c, Cities.ArrivedUnits(c, From, later, r.PeoplePerUnit)+ + Cities.ArrivedUnits(c, c.RulesAt(From).Mvp!.CityArrivalsFrom, From, r.PeoplePerUnit));+ var had = Cities.Apportion(c, Cities.ArrivedUnits(c, c.RulesAt(From).Mvp!.CityArrivalsFrom, From, r.PeoplePerUnit));+ var byCity = Arrived(s).GroupBy(u => u.Location!.City!).ToDictionary(g => g.Key, g => g.Count(), StringComparer.Ordinal);+ foreach (var kv in split) Assert.Equal(kv.Value - had[kv.Key], byCity.GetValueOrDefault(kv.Key));+ }++ // R-CITY-008 on the ledger: with no natural increase, Apply adds no second count of the turn's CBS arrivals. They are+ // counted once, as Cities.Arrive's records, so the turn's total rises by the arrived units times people_per_unit only.+ [Fact]+ public void ApplyCountsTheArrivalsOnceAsTheRecords()+ {+ var c = NoNaturalIncrease();+ var r = c.RulesAt(From).Mvp!;+ var s = Fixture(c);+ Assert.NotEmpty(PopulationSystem.Arrivals(c, From, To));+ var population = s.Population.ToList();+ var total = s.TotalPopulation;+ var why = new List<Cause>();+ Cities.Arrive(c, s, r, To, why);+ var arrivedWhy = why.Count;+ var ledger = s.PopulationLedger.Canonical().ToList();++ PopulationSystem.Apply(c, s, To, 31 / 365.0, why);++ Assert.Equal(population, s.Population.ToList());+ Assert.Equal(ledger, s.PopulationLedger.Canonical());+ Assert.Equal(arrivedWhy, why.Count);+ s.PopulationLedger.Reconcile();+ Assert.Equal(total + Cities.ArrivedUnits(c, From, To, r.PeoplePerUnit) * r.PeoplePerUnit, s.TotalPopulation);+ }++ // R-POP-002: only a ledger initialized with mode Historical is let through. An Open ledger, like a synthetic one (the+ // boundary tests' rows population.apply and cities.arrive), is still refused by both, with the state unchanged.+ [Theory]+ [InlineData("population.apply")] [InlineData("cities.arrive")]+ public void AnOpenLedgerIsStillRefused(string call)+ {+ var c = PopulationLedgerTests.Content();+ var s = PopulationLedger.CreateFixture(c, PopulationLedgerTests.Bindings(),+ new[] { new PopulationInventoryRow("fixture", 0, PopulationLedgerTests.Person()) }, mode: Mode.Open);+ Assert.Equal((true, false), (s.PopulationLedger.IsInitialized, s.PopulationLedger.IsHistorical));+ var why = new List<Cause>();+ var before = s.Describe(); var hash = s.Hash();+ void Invoke()+ {+ if (call == "population.apply") PopulationSystem.Apply(c, s, s.Date.AddMonths(1), .1, why);+ else Cities.Arrive(c, s, new MvpRules(), s.Date.AddMonths(1), why);+ }+ Assert.Contains("integration is held", Assert.Throws<NotSupportedException>(Invoke).Message);+ Assert.Equal(before, s.Describe()); Assert.Equal(hash, s.Hash()); Assert.Empty(why);+ }++ /// <summary>PopulationLedger.RegisterArrivals takes only PopulationInventoryRow items, and a row is refused at+ /// construction for each item RegisterArrival refuses: a blank source, a negative ordinal, or malformed UTF-16. So+ /// the batch registration makes the same per-item checks without repeating them.</summary>+ [Theory]+ [InlineData("", 0)]+ [InlineData(" ", 0)]+ [InlineData("ship", -1)]+ public void AnArrivalRowRefusesWhatRegisterArrivalRefuses(string source, int ordinal) =>+ Assert.ThrowsAny<ArgumentException>(() => new PopulationInventoryRow(source, ordinal, PopulationLedgerTests.Person()));++ /// <summary>The malformed UTF-16 case, built in code: xUnit's test data turns a lone surrogate into U+FFFD, which is+ /// valid text, so it cannot be an InlineData value.</summary>+ [Fact]+ public void AnArrivalRowRefusesALoneSurrogateSource() =>+ Assert.ThrowsAny<ArgumentException>(() => new PopulationInventoryRow("ship" + (char)0xD800, 0, PopulationLedgerTests.Person()));+}diff --git a/sim/Statecraft.Sim.Tests/LedgerNaturalIncreaseTests.cs b/sim/Statecraft.Sim.Tests/LedgerNaturalIncreaseTests.csnew file mode 100644index 000000000..7f331f013--- /dev/null+++ b/sim/Statecraft.Sim.Tests/LedgerNaturalIncreaseTests.cs@@ -0,0 +1,142 @@+using Statecraft.Sim;++/// <summary>#1725 PR 7, producer draft 02, natural increase: on a game with an initialized Historical ledger,+/// <c>PopulationSystem.Apply</c> grows the ledger at the national rate (docs/GDD.md, Q11: natural increase "stays the national+/// rate, 0.0169 a year") in whole records. The owner, 8 November 2026: "Carry the fraction (Recommended)" (the remainder is+/// kept from turn to turn and a record is added each time it reaches one), "Same split as arrivals (Recommended)" (the new+/// records are split over the cities by <c>Cities.Apportion</c>), "Free civilian (Recommended)" (each is a free civilian of+/// that city with no work experience and no reception wait), "Everyone alive (Recommended)" (the base is every living record).+/// R-CITY-008.</summary>+public class LedgerNaturalIncreaseTests+{+ static Content Gdd03() => HistoricalPopulationTests.Real(true);++ // A week: 0.0169 a year of the dark start's living records is below one record, so the carry crosses one after a few turns.+ const double Week = 7 / 365.0;++ // The increase a turn owes, in records, as the owner's carry describes it: the aggregate's rate (NaturalIncreasePerYear+ // times the turn's share of a year) times every living record, in doubles.+ static double Owed(Content c, GameState s, double yearFraction) =>+ c.RulesAt(s.Date).NaturalIncreasePerYear * yearFraction * s.PopulationLedger.Units.Count;++ static string Bits(double v) => BitConverter.DoubleToInt64Bits(v).ToString("X16", System.Globalization.CultureInfo.InvariantCulture);++ // "Carry the fraction (Recommended)": turns whose increase stays below one record add none and carry it; the turn whose+ // carried sum first reaches one adds exactly one record and carries the rest. "Same split as arrivals (Recommended)"+ // and "Free civilian (Recommended)": the record is a free civilian of the city Apportion gives its first unit, reception+ // done, no work experience, keyed increase/<city> with that city's ordinal.+ [Fact]+ public void TheCarryAddsOneRecordAtTheTurnItCrossesOne()+ {+ var c = Gdd03();+ var s = LedgerArrivalsTests.Fixture(c);+ var living = s.PopulationLedger.Units.Count;+ var next = s.PopulationLedger.NextPopulationId;+ var per = Owed(c, s, Week);+ Assert.True(per > 0 && per < 1);+ var carry = 0.0;+ var turns = 0;+ var why = new List<Cause>();+ while (true)+ {+ turns++;+ PopulationSystem.Apply(c, s, s.Date.AddDays(7), Week, why);+ if (carry + per >= 1) break;+ carry += per;+ Assert.Equal(living, s.PopulationLedger.Units.Count);+ Assert.Equal(carry, s.PopulationLedger.NaturalIncreaseCarry);+ }+ Assert.True(turns > 1);+ Assert.Equal(living + 1, s.PopulationLedger.Units.Count);+ Assert.Equal(carry + per - 1, s.PopulationLedger.NaturalIncreaseCarry);+ Assert.Empty(why);+ var born = s.PopulationLedger.Get(next);+ var city = Cities.Apportion(c, 1).Single(kv => kv.Value == 1).Key;+ Assert.Equal(PopulationStatus.FreeCivilian, born.Status);+ Assert.Equal(c.RequirePopulationInteger("reception.turns"), born.ReceptionTicks);+ Assert.Equal((city, c.PlayerRegions.AtLocation(city)!.Id), (born.Location!.City, born.Location.Region));+ Assert.Equal((PopulationAssignmentKind.Unassigned, CivilianProfession.None, CivilianTier.None, 0),+ (born.Assignment.Kind, born.Profession, born.Tier, born.WorkXp));+ Assert.True(s.PopulationLedger.HasArrived(PopulationSystem.IncreasePrefix + city, 0));+ s.PopulationLedger.Reconcile();+ }++ // "Everyone alive (Recommended)": the base is every living record, soldiers included, and a record lost in combat no+ // longer counts.+ [Fact]+ public void TheBaseIsEveryLivingRecord()+ {+ var c = Gdd03();+ var s = LedgerArrivalsTests.Fixture(c);+ Assert.Contains(s.PopulationLedger.Units, u => u.Status == PopulationStatus.ActiveSoldier);+ var lost = s.Clone();+ lost.PopulationLedger.RegisterCombatLoss(lost.PopulationLedger.Units[0].Id, "fixture-loss");+ PopulationSystem.Apply(c, s, s.Date.AddDays(7), Week, new List<Cause>());+ PopulationSystem.Apply(c, lost, lost.Date.AddDays(7), Week, new List<Cause>());+ var rate = c.RulesAt(s.Date).NaturalIncreasePerYear * Week;+ Assert.Equal(rate * s.PopulationLedger.Units.Count, s.PopulationLedger.NaturalIncreaseCarry);+ Assert.Equal(rate * (s.PopulationLedger.Units.Count - 1), lost.PopulationLedger.NaturalIncreaseCarry);+ }++ // R-POP-003: Clone keeps the carry and the records it has added, the gdd-0.3 ledger section writes them, and a replay+ // from the clone adds the same records with the same keys (nobody twice). A ledger with no increase yet, and every+ // gdd-0.1 game, writes no natural-increase line, so their hashes are as before.+ [Fact]+ public void CloneAndTheCanonicalTextKeepTheCarry()+ {+ var c = Gdd03();+ var s = LedgerArrivalsTests.Fixture(c);+ Assert.DoesNotContain("natural-increase", s.Describe());+ Assert.DoesNotContain("natural-increase", Simulation.NewGame(HistoricalPopulationTests.Real(false), 1, Mode.Historical).Describe());+ PopulationSystem.Apply(c, s, s.Date.AddDays(7), Week, new List<Cause>());+ Assert.Contains("natural-increase", s.Describe());+ // docs/determinism.md: a nonzero carry is written as the 16 hex digits of its IEEE bits.+ var line = s.PopulationLedger.Canonical().Single(x => x.Contains("natural-increase"));+ Assert.Contains("16:" + Bits(Owed(c, LedgerArrivalsTests.Fixture(c), Week)), line);+ var saved = s.Clone();+ Assert.Equal(s.PopulationLedger.NaturalIncreaseCarry, saved.PopulationLedger.NaturalIncreaseCarry);+ Assert.Equal(s.Hash(), saved.Hash());+ // Two turns that add no record and differ only in the carry hash apart.+ var shorter = LedgerArrivalsTests.Fixture(c);+ PopulationSystem.Apply(c, shorter, shorter.Date.AddDays(7), Week / 2, new List<Cause>());+ Assert.Equal(s.PopulationLedger.Units.Select(u => u.Id), shorter.PopulationLedger.Units.Select(u => u.Id));+ Assert.NotEqual(s.PopulationLedger.NaturalIncreaseCarry, shorter.PopulationLedger.NaturalIncreaseCarry);+ Assert.NotEqual(s.Hash(), shorter.Hash());+ for (var i = 0; i < 6; i++)+ {+ PopulationSystem.Apply(c, s, s.Date.AddDays(7), Week, new List<Cause>());+ PopulationSystem.Apply(c, saved, saved.Date.AddDays(7), Week, new List<Cause>());+ }+ Assert.True(s.PopulationLedger.NaturalIncreaseRecords > 0);+ Assert.Equal(s.PopulationLedger.Canonical(), saved.PopulationLedger.Canonical());+ Assert.Equal(s.Hash(), saved.Hash());+ }++ // R-CITY-003, R-CITY-008: a turn's CBS arrivals are counted once, as Cities.Arrive's refugee records, and its natural+ // increase once, as Apply's free civilian records on every living record (the turn's arrivals included, since Arrive+ // runs first); GameState.Population is not touched, and the total rises by exactly those records' people.+ [Fact]+ public void ArrivalsAndIncreaseAreEachCountedOnce()+ {+ var c = Gdd03();+ var r = c.RulesAt(LedgerArrivalsTests.From).Mvp!;+ var s = LedgerArrivalsTests.Fixture(c);+ var to = LedgerArrivalsTests.From.AddMonths(3); // a quarter: both the arrivals and the increase are above one record+ var population = s.Population.ToList();+ var total = s.TotalPopulation;+ var yf = (to - LedgerArrivalsTests.From).Days / 365.0;+ Cities.Arrive(c, s, r, to, new List<Cause>());+ var units = Cities.ArrivedUnits(c, LedgerArrivalsTests.From, to, r.PeoplePerUnit);+ Assert.Equal(units, LedgerArrivalsTests.Arrived(s).Count);+ var owed = Owed(c, s, yf);+ var whole = (int)Math.Floor(owed);+ Assert.True(units > 0 && whole > 0);+ PopulationSystem.Apply(c, s, to, yf, new List<Cause>());+ Assert.Equal(units, LedgerArrivalsTests.Arrived(s).Count);+ Assert.Equal(whole, s.PopulationLedger.NaturalIncreaseRecords);+ Assert.Equal(owed - whole, s.PopulationLedger.NaturalIncreaseCarry);+ Assert.Equal(population, s.Population.ToList());+ s.PopulationLedger.Reconcile();+ Assert.Equal(total + (units + whole) * r.PeoplePerUnit, s.TotalPopulation);+ }+}diff --git a/sim/Statecraft.Sim/Cities.cs b/sim/Statecraft.Sim/Cities.csindex 176cc8cd8..7f2d870ca 100644--- a/sim/Statecraft.Sim/Cities.cs+++ b/sim/Statecraft.Sim/Cities.cs@@ -1,5 +1,6 @@using System;using System.Collections.Generic;+using System.Globalization;using System.Linq;namespace Statecraft.Sim@@ -380,24 +381,67 @@ namespace Statecraft.Sim/// <summary>R-CITY-003 (D-A5, Q-ARRV-1): the turn's immigrants (the CBS series, aliyah.yaml) arrive as refugees, in whole/// units, spread over the cities by <see cref="Apportion"/>. The cities count them from mvp.city_arrivals_from, the/// census day their start values already include (Q-ARRV-3); PopulationSystem adds every arrival to the national head- /// count from the game's start, and the cities are the part of it placed in towns (R-CITY-008, Q-ARRV-2).</summary>+ /// count from the game's start, and the cities are the part of it placed in towns (R-CITY-008, Q-ARRV-2).+ /// With an initialized Historical ledger (#1725 PR 7) each arrived unit is one refugee record instead, see+ /// <see cref="LedgerArrive"/>; the aggregate city fields are not written.</summary>public static void Arrive(Content c, GameState s, MvpRules r, DateTime next, List<Cause> why){- PopulationLedger.RefuseAggregate(s);+ PopulationLedger.RefuseUnlessHistorical(s); // #1725 PR 7: the ledger's records are then the arrivalsvar units = ArrivedUnits(c, s.Date, next, r.PeoplePerUnit);if (units == 0) return;var before = UnitsBy(c, s.Date, r.PeoplePerUnit);var had = Apportion(c, before);- foreach (var kv in Apportion(c, before + units))+ var share = Apportion(c, before + units);+ var ledger = s.PopulationLedger.IsHistorical ? LedgerArrive(c, s, r, had, share) : null;+ foreach (var kv in share){- var added = kv.Value - had[kv.Key];+ var added = ledger == null ? kv.Value - had[kv.Key] : ledger.GetValueOrDefault(kv.Key);if (added == 0) continue;var x = s.Cities[kv.Key];- s.Cities[x.Id] = x.WithCounts(x.Civilians, x.Employed, x.Refugees + added);+ if (ledger == null) s.Cities[x.Id] = x.WithCounts(x.Civilians, x.Employed, x.Refugees + added);why.Add(new Cause("city", x.Id, added, FormattableString.Invariant($"{PlayerText.Settlement(c, x.Id)}: {Groups(added)} of immigrants arrived and wait for homes"), key: CauseKeys.ImmigrantsWaiting, args: new[] { CauseKeys.Number(added) }));}}+ /// <summary>The source key prefix of a CBS arrival record (#1725 PR 7): this prefix plus the city id. Its ordinal is+ /// the unit's place in the city's cumulative <see cref="Apportion"/> share from mvp.city_arrivals_from, so a unit's key+ /// depends only on the dates, never on the turn that brings it.</summary>+ internal const string ArrivalPrefix = "cbs/";++ /// <summary>R-CITY-003 on an initialized Historical ledger (#1725 PR 7; GDD Q11: "arrivals take new ids as refugees in a+ /// city"): each of the turn's arrived units in <see cref="Apportion"/>'s split is one refugee record located in its city+ /// (the region that lists it, R-POP-004), reception 0, no assignment, profession or tier. Keys are+ /// <see cref="ArrivalPrefix"/> plus the city id, ordinals the city's units from <paramref name="had"/> to+ /// <paramref name="share"/>, in city id order, so a replay of the turn adds nobody twice: an already registered key is+ /// skipped (R-POP-001: a source stays registered after its id is lost). R-CITY-008: the records are the people, so+ /// no aggregate city field is written. All or nothing: a refused record, or a city with no city record in the game,+ /// adds none. Returns the records added per city.</summary>+ static Dictionary<string, int> LedgerArrive(Content c, GameState s, MvpRules r, SortedDictionary<string, int> had, SortedDictionary<string, int> share)+ {+ var ledger = s.PopulationLedger;+ if (ledger.PeoplePerUnit != r.PeoplePerUnit)+ throw new InvalidOperationException("A ledger record is " + ledger.PeoplePerUnit.ToString(CultureInfo.InvariantCulture)+ + " people but an arrived unit is " + r.PeoplePerUnit.ToString(CultureInfo.InvariantCulture) + " (R-CITY-003, R-POP-001).");+ var rows = new List<PopulationInventoryRow>();+ var added = new Dictionary<string, int>(StringComparer.Ordinal);+ foreach (var kv in share)+ {+ for (var ordinal = had[kv.Key]; ordinal < kv.Value; ordinal++)+ {+ if (ledger.HasArrived(ArrivalPrefix + kv.Key, ordinal)) continue;+ if (!s.Cities.ContainsKey(kv.Key)) throw new InvalidOperationException("No city record for " + kv.Key + " (R-CITY-003).");+ var region = c.PlayerRegions.AtLocation(kv.Key)?.Id+ ?? throw new InvalidOperationException("No region in regions.yaml for city " + kv.Key + " (R-POP-004).");+ rows.Add(new PopulationInventoryRow(ArrivalPrefix + kv.Key, ordinal, new PopulationUnit(0, PopulationStatus.Refugee, 0,+ new PopulationLocation(region, city: kv.Key), PopulationAssignment.Unassigned, CivilianProfession.None,+ CivilianTier.None, 0, "", 0, PopulationEquipment.None)));+ added[kv.Key] = added.GetValueOrDefault(kv.Key) + 1;+ }+ }+ ledger.RegisterArrivals(rows);+ return added;+ }+/// <summary>R-CITY-003 (Q-ARRV-1): the cities' shares of their first <paramref name="units"/> arrived units, by id. The/// weights are the cities' census people. Units are handed out one at a time, each to the city whose share of the/// units so far most exceeds what it holds (the largest remainder), a tie to the lower id (ordinal). A freshdiff --git a/sim/Statecraft.Sim/PopulationLedger.cs b/sim/Statecraft.Sim/PopulationLedger.csindex 9acf98fc5..5cbd7e893 100644--- a/sim/Statecraft.Sim/PopulationLedger.cs+++ b/sim/Statecraft.Sim/PopulationLedger.cs@@ -1,6 +1,7 @@using System;using System.Collections.Generic;using System.Collections.ObjectModel;+using System.Globalization;using System.Linq;namespace Statecraft.Sim@@ -127,6 +128,12 @@ namespace Statecraft.Simint peoplePerUnit;/// <summary>People one record stands for in this ledger (CreateFixture's scale).</summary>internal int PeoplePerUnit { get { RequireInitialized(); return peoplePerUnit; } }+ /// <summary>#1725 PR 7, natural increase (R-CITY-008; owner, 8 November 2026: "Carry the fraction (Recommended)"): the+ /// records' worth of natural increase owed but not yet a whole record, carried from turn to turn: a double, as the+ /// aggregate natural increase is, written as its IEEE bits (docs/determinism.md's carry rule).</summary>+ internal double NaturalIncreaseCarry { get; private set; }+ /// <summary>The natural-increase records added so far: their split over the cities is Cities.Apportion of this count.</summary>+ internal int NaturalIncreaseRecords { get; private set; }public bool IsInitialized { get; private set; }public int NextPopulationId { get; private set; }public double TotalPeople => (double)units.Count * peoplePerUnit;@@ -221,6 +228,41 @@ namespace Statecraft.Simunits = candidate; sources.Add(key, id); NextPopulationId = next;return id;}+ /// <summary>Whether the manifest item <paramref name="source"/>, <paramref name="ordinal"/> has arrived, even if its+ /// population id was lost since.</summary>+ internal bool HasArrived(string source, int ordinal) => sources.ContainsKey(PopulationText.Fields(source, ordinal));+ /// <summary><see cref="RegisterArrival"/> for several items, in order, all or nothing (#1725 PR 7, Cities.Arrive): every+ /// record is validated in one candidate before any is committed, so a refused item adds none of the others.</summary>+ internal IReadOnlyList<int> RegisterArrivals(IReadOnlyList<PopulationInventoryRow> rows)+ {+ RequireInitialized();+ var candidate = new SortedDictionary<int, PopulationUnit>(units);+ var registered = new SortedDictionary<string, int>(sources, StringComparer.Ordinal);+ var next = NextPopulationId;+ var ids = new List<int>();+ foreach (var row in rows)+ {+ var key = PopulationText.Fields(row.Source, row.Ordinal);+ if (registered.ContainsKey(key)) throw new ArgumentException("Source item already registered.");+ // int.MaxValue is the exhausted next-id sentinel; never overflow after partially inserting a record.+ var id = next; next = checked(next + 1);+ candidate[id] = row.Template.WithId(id); registered.Add(key, id); ids.Add(id);+ }+ Validate(candidate);+ units = candidate; sources = registered; NextPopulationId = next;+ return ids.AsReadOnly();+ }+ /// <summary>#1725 PR 7, natural increase: registers <paramref name="rows"/> as <see cref="RegisterArrivals"/> does, all or+ /// nothing, then counts them in <see cref="NaturalIncreaseRecords"/> and keeps <paramref name="carry"/>, the fraction of a+ /// record still owed (0 up to 1).</summary>+ internal void RegisterNaturalIncrease(IReadOnlyList<PopulationInventoryRow> rows, double carry)+ {+ RequireInitialized();+ if (!(carry >= 0 && carry < 1)) throw new ArgumentOutOfRangeException(nameof(carry), "The carried natural increase is a fraction of one record.");+ var records = checked(NaturalIncreaseRecords + rows.Count);+ RegisterArrivals(rows);+ NaturalIncreaseCarry = carry; NaturalIncreaseRecords = records;+ }public void RegisterCombatLoss(int id, string source){RequireInitialized(); Get(id);@@ -334,6 +376,14 @@ namespace Statecraft.Sim{yield return PopulationText.Fields("initialized", IsInitialized, "next", NextPopulationId,"people-per-unit", peoplePerUnit, "reception-limit", receptionLimit);+ // #1725 PR 7: written only once natural increase has run, so every ledger before it hashes as before. The carry+ // follows docs/determinism.md's carry rule: a nonzero carry is the 16 hex digits of its IEEE bits, -0.0 as 0.0+ // (as GameState's Num and GddState's segment carry write theirs), and a zero carry is omitted.+ if (NaturalIncreaseRecords != 0 || NaturalIncreaseCarry != 0)+ yield return NaturalIncreaseCarry == 0+ ? PopulationText.Fields("natural-increase", "records", NaturalIncreaseRecords)+ : PopulationText.Fields("natural-increase", "records", NaturalIncreaseRecords, "carry",+ BitConverter.DoubleToInt64Bits(NaturalIncreaseCarry).ToString("X16", CultureInfo.InvariantCulture));if (bindings != null) foreach (var b in bindings.Canonical()) yield return b;foreach (var p in units.Values) yield return PopulationText.Fields("unit", p.Canonical());foreach (var source in sources) yield return PopulationText.Fields("source", source.Key, source.Value);diff --git a/sim/Statecraft.Sim/PopulationSystem.cs b/sim/Statecraft.Sim/PopulationSystem.csindex 2c8e0e921..13790a4b7 100644--- a/sim/Statecraft.Sim/PopulationSystem.cs+++ b/sim/Statecraft.Sim/PopulationSystem.cs@@ -7,6 +7,10 @@ namespace Statecraft.Sim/// <summary>Population by origin group, plus the annexed residents' own group (R-CITY-008). Historical mode takes arrivals from the sourced aliyah series.</summary>public static class PopulationSystem{+ /// <summary>The source key prefix of a natural-increase record on a Historical ledger (#1725 PR 7): this prefix plus the+ /// city id; its ordinal is the record's place in that city's Cities.Apportion share of all natural-increase records.</summary>+ internal const string IncreasePrefix = "increase/";+public static void Init(Content c, GameState s){PopulationLedger.RefuseAggregate(s);@@ -31,9 +35,14 @@ namespace Statecraft.Simreturn result;}+ /// <summary>Natural increase, then the turn's CBS arrivals, by origin group. With an initialized Historical ledger+ /// (#1725 PR 7) the ledger's records are the people (R-CITY-008: "never extra people"): the arrivals are Cities.Arrive's+ /// refugee records (R-CITY-003), counted once there, so this adds only the natural increase, as records+ /// (<see cref="LedgerIncrease"/>), and leaves GameState.Population and the causes alone.</summary>public static void Apply(Content c, GameState s, DateTime to, double yearFraction, List<Cause> why){- PopulationLedger.RefuseAggregate(s);+ PopulationLedger.RefuseUnlessHistorical(s);+ if (s.PopulationLedger.IsHistorical) { LedgerIncrease(c, s, yearFraction); return; }var rate = c.RulesAt(s.Date).NaturalIncreasePerYear * yearFraction;foreach (var k in s.Population.Keys.ToList()) s.Population[k] *= 1 + rate;foreach (var kv in Arrivals(c, s.Date, to).OrderBy(k => k.Key, StringComparer.Ordinal))@@ -42,5 +51,40 @@ namespace Statecraft.Simif (kv.Value > 0) why.Add(new Cause("population", kv.Key, kv.Value, FormattableString.Invariant($"{kv.Value:N0} immigrants arrived ({PlayerText.Region(c, kv.Key)})"), key: CauseKeys.Arrived));}}++ /// <summary>R-CITY-008 on an initialized Historical ledger (#1725 PR 7): natural increase at the national rate (GDD Q11,+ /// "stays the national rate, 0.0169 a year") in whole records. The owner, 8 November 2026: "Everyone alive+ /// (Recommended)": the base is every living record. "Carry the fraction (Recommended)": the turn owes the carry plus the+ /// rate times the turn's share of a year times that base, in records; each whole record of it is added and the rest+ /// carried. In doubles, with the aggregate's operations in a fixed+ /// order, the carry written as IEEE bits (docs/determinism.md). "Same split as arrivals+ /// (Recommended)": the records are split over the cities by Cities.Apportion of all natural-increase records so far,+ /// keyed <see cref="IncreasePrefix"/> plus the city id with that city's ordinal, so a replay adds the same records.+ /// "Free civilian (Recommended)": each is a free civilian of its city with no work experience and no reception wait,+ /// in the shape of a census record (HistoricalPopulation.Initialize: reception.turns done, no assignment, profession,+ /// tier, qualification or equipment). All or nothing. A negative rate or turn has no ruling and is refused.</summary>+ static void LedgerIncrease(Content c, GameState s, double yearFraction)+ {+ var ledger = s.PopulationLedger;+ // The aggregate's own rate, in the same double arithmetic and order (Apply: `var rate =+ // c.RulesAt(s.Date).NaturalIncreasePerYear * yearFraction;`).+ var rate = c.RulesAt(s.Date).NaturalIncreasePerYear * yearFraction;+ if (!(rate >= 0))+ throw new InvalidOperationException("A negative natural increase on the ledger has no rule (R-CITY-008).");+ var owed = ledger.NaturalIncreaseCarry + rate * ledger.Units.Count;+ var whole = checked((int)Math.Floor(owed));+ var had = Cities.Apportion(c, ledger.NaturalIncreaseRecords);+ var rows = new List<PopulationInventoryRow>();+ foreach (var kv in Cities.Apportion(c, checked(ledger.NaturalIncreaseRecords + whole)))+ for (var ordinal = had[kv.Key]; ordinal < kv.Value; ordinal++)+ {+ var region = c.PlayerRegions.AtLocation(kv.Key)?.Id+ ?? throw new InvalidOperationException("No region in regions.yaml for city " + kv.Key + " (R-POP-004).");+ rows.Add(new PopulationInventoryRow(IncreasePrefix + kv.Key, ordinal, new PopulationUnit(0, PopulationStatus.FreeCivilian,+ ledger.ReceptionLimit, new PopulationLocation(region, city: kv.Key), PopulationAssignment.Unassigned,+ CivilianProfession.None, CivilianTier.None, 0, "", 0, PopulationEquipment.None)));+ }+ ledger.RegisterNaturalIncrease(rows, owed - whole);+ }}}