A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Give each gdd-0.3 population unit its own record in one ledger (fixture-only foundation) (#1773)
Eyal Golandd07a753b338
diff --git a/changelog.d/1689.md b/changelog.d/1689.mdnew file mode 100644index 000000000..c1a6a7114--- /dev/null+++ b/changelog.d/1689.md@@ -0,0 +1,3 @@+### Added++- Add the gdd-0.3 population identity foundation: immutable records, a validated ledger, identity-aware scale, canonical state and synthetic fixture initialization. Production population, Food and command/replay integration remain held; legacy and gdd-0.1 behavior and shipped content are unchanged.diff --git a/docs/population-ledger.md b/docs/population-ledger.mdnew file mode 100644index 000000000..43f9fc83a--- /dev/null+++ b/docs/population-ledger.md@@ -0,0 +1,13 @@+# Population identity foundation — #1689 steps 1–2++This is a fixture-only data/helper contract under exact `gdd-0.3` identity (R-POP-001/002/003), not a playable campaign. No production era, shipped content, catalogue or save envelope changes. The existing synthetic Attention/Arms harnesses still exercise their pre-ledger aggregate model; that does not activate population identity. A state with an initialized ledger is rejected by Simulation.Step, Preview and DelegatedTo and at direct aggregate population/resource producer boundaries before any mutation (PopulationLedger.RefuseAggregate). The guarded sites include Cities, PopulationSystem, Pools, starting forces, training, qualification/demobilisation, military/combat/prisoners, event mutation, the economy and objectives (the readers of GameState.TotalPopulation, which reads the ledger once it is initialized) and the turn resolver. Direct integration into Cities, PopulationSystem, Training, Combat, Prisoners, Pools and other systems remains held.++`PopulationLedger.CreateFixture` is internal (test assembly friend access), constructs a fresh GameState without Simulation.NewGame, validates explicit frozen location/target/captor/qualification bindings and builds inventory in source-key/ordinal order. It never converts census headcounts, historical formations, cohorts or events into people. Fixture rows are visibly synthetic, supplied in test code; no new files are loaded or hashed as content. Each reception tick is one whole reception turn, capped by the Agreed catalogue `reception.turns`; course limits are explicit synthetic target data, not production defaults.++The public read surface returns immutable records and a read-only snapshot list. Mutations require an initialized gdd-0.3 ledger. Get/count, move, explicit assignment release/change, atomic transition, replacement of history/progress/equipment, registered arrival and combat loss form the contract for later issues. Replacement cannot insert a new identity. Transition and move preserve reception, both experience tracks, profession/tier, qualification and issued-equipment facts. Capture must retain a bound home and captor and clear local assignment/location; return callers must supply a valid status/location/assignment. The helper chooses no destination, formation, exchange timing, prices or refunds.++Validation builds a candidate map first, including teacher resolution and unique issued-item ownership across both equipment categories. A referenced teacher cannot disappear or leave teaching while pupils still refer to it; future integrated operations must release/reassign references atomically before that loss/transition. No resources, RNG or cause log are involved. Explicit arrival provenance remains consumed after death. `int.MaxValue` is the allocator exhaustion sentinel; allocation refuses before changing anything. Reconcile checks the exact source/loss/living id relation. Fixture-only `nextPopulationId` allows boundary coverage without allocating billions of records.++GameState.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.diff --git a/docs/rules/mvp.md b/docs/rules/mvp.mdindex 13416c640..a174a8a54 100644--- a/docs/rules/mvp.md+++ b/docs/rules/mvp.md@@ -88,13 +88,13 @@ R-SAVE-004: A schema 2 save of the GDD game with a player attack (`order <unit>Each GDD turn resolves in the order of the approved plan's section 2.3 (decision D-A6): production, then housing and Social cohesion, then arrivals.-R-CITY-001: `AssignWorkers(city, role, n)` sets how many of the city's people work in `role` (only `job` exists: a craftsman fills an ordinary job slot, R-CRAFT-002). It is refused, with the state unchanged and the Attention refunded, when the city or role is unknown, `n` is negative, or `n` is above the city's jobs or its civilians and craftsmen. An accepted order turns the city's job default off (R-CITY-009). The legacy loop refuses it before charging Attention.+R-CITY-001: Under legacy/gdd-0.1, `AssignWorkers(city, role, n)` sets how many of the city's people work in `role` (only `job` exists: a craftsman fills an ordinary job slot, R-CRAFT-002). It is refused, with the state unchanged and the Attention refunded, when the city or role is unknown, `n` is negative, or `n` is above the city's jobs or its civilians and craftsmen. An accepted order turns the city's job default off (R-CITY-009). The legacy loop refuses it before charging Attention. The gdd-0.3 population foundation uses one typed assignment per ledger id (R-POP-002); initialized ledger fixtures refuse this aggregate command path, pending producer integration.R-CITY-002: Each turn every city's employed units add `employed * income_per_job_per_year * the turn's share of a year` to the Treasury (an employed craftsman earns more, R-CRAFT-002).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-008: `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.+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. 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-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).@@ -489,3 +489,14 @@ R-ALT-010: An event of `kind: reconvergence` has a historical option and may carR-ALT-011: A shareable build refuses while any consequence card, or any event with variants, has no `reviewed_by` (a person's sign-off), alongside the sensitivity gate (Q-ALT-9). `Timeline.Entries` lists each resolved event, in window order, with the player's option beside the record's, and `Timeline.Origin` names the road a consequence card follows.R-ALT-012: The historical run (the reference player's orders from 15 May 1948 to 15 January 1952) raises no consequence card and diverges nowhere.+++## 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).++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-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.diff --git a/sim/Statecraft.Sim.Tests/NoAttentionTests.cs b/sim/Statecraft.Sim.Tests/NoAttentionTests.csindex fc607b3c8..7d38e3f25 100644--- a/sim/Statecraft.Sim.Tests/NoAttentionTests.cs+++ b/sim/Statecraft.Sim.Tests/NoAttentionTests.cs@@ -19,7 +19,7 @@ public class NoAttentionTestsforeach (var r in c.EraRules.Values.Append(c.Rules)) { r.AttentionCost.Clear(); r.AttentionPerTurn=double.NaN; r.RungAttentionStep=double.NaN; }}static string WithoutLegacyAccounting(string canonical) =>- Regex.Replace(canonical.Replace("ruleset=gdd-0.3;", ""), @"\natt=[^\n]*", "");+ Regex.Replace(Regex.Replace(canonical, @"\npopulation-ledger\{(?:\n [^\n]*)*", "").Replace("ruleset=gdd-0.3;", ""), @"\natt=[^\n]*", "");static bool Unavailable(string kind) => kind is "map_action" or "set_mobilization" or "security_order";static (Content c,GameState s,Command valid,Command invalid) Case(string kind,bool modern){diff --git a/sim/Statecraft.Sim.Tests/NoShotArmsTests.cs b/sim/Statecraft.Sim.Tests/NoShotArmsTests.csindex 994cdf6a8..5b808a0e5 100644--- a/sim/Statecraft.Sim.Tests/NoShotArmsTests.cs+++ b/sim/Statecraft.Sim.Tests/NoShotArmsTests.cs@@ -204,7 +204,7 @@ public class NoShotArmsTestsvar normalized = y.State.Clone();normalized.Arms = x.State.Arms;- static string Core(string text) => Regex.Replace(text.Replace("ruleset=gdd-0.3;", ""), @"\natt=[^\n]*", "");+ static string Core(string text) => Regex.Replace(Regex.Replace(text, @"\npopulation-ledger\{(?:\n [^\n]*)*", "").Replace("ruleset=gdd-0.3;", ""), @"\natt=[^\n]*", "");Assert.Equal(Core(x.State.Describe()), Core(normalized.Describe()));Assert.Equal(x.Why.Select(w => w.Message), y.Why.Select(w => w.Message));}diff --git a/sim/Statecraft.Sim.Tests/PopulationLedgerBoundaryTests.cs b/sim/Statecraft.Sim.Tests/PopulationLedgerBoundaryTests.csnew file mode 100644index 000000000..37b1f322c--- /dev/null+++ b/sim/Statecraft.Sim.Tests/PopulationLedgerBoundaryTests.cs@@ -0,0 +1,126 @@+using Statecraft.Sim;++// R-POP-001/002: the fixture ledger must not feed the old scale, Food refill or population mutators.+public class PopulationLedgerBoundaryTests+{+ [Theory]+ [InlineData("population.init")] [InlineData("population.apply")]+ [InlineData("pools.init")] [InlineData("pools.consume")] [InlineData("pools.harvest")]+ [InlineData("pools.buy")] [InlineData("pools.term")]+ [InlineData("cities.init")] [InlineData("cities.assign")] [InlineData("cities.produce")]+ [InlineData("cities.house")] [InlineData("cities.condition")] [InlineData("cities.arrive")] [InlineData("cities.upkeep")]+ [InlineData("starting.init")] [InlineData("starting.arrive")]+ [InlineData("training.start")] [InlineData("training.cancel")] [InlineData("training.progress")] [InlineData("training.reinforce")]+ [InlineData("military.serve")] [InlineData("military.upkeep")]+ [InlineData("qualification.return")] [InlineData("qualification.craftsmen")] [InlineData("qualification.pioneers")] [InlineData("qualification.unit")]+ [InlineData("demobilization.give")]+ [InlineData("combat.resolve")] [InlineData("combat.outcomes")]+ [InlineData("prisoners.upkeep")] [InlineData("prisoners.return")] [InlineData("prisoners.take")]+ [InlineData("events.trigger")] [InlineData("events.choose")] [InlineData("events.delegate")] [InlineData("turn.resolve")]+ [InlineData("economy.flows")] [InlineData("economy.apply")] [InlineData("objectives.complete")]+ public void DirectAggregateCallsRefuseBeforeAnyStateResourceOrCauseMutation(string call)+ {+ var c = PopulationLedgerTests.Content();+ var s = PopulationLedger.CreateFixture(c, PopulationLedgerTests.Bindings(), new[] {+ new PopulationInventoryRow("fixture", 0, PopulationLedgerTests.Person()) });+ s.Population["fixture"] = 2000; s.Treasury = 23; s.Debt = 2; s.Food = 7; s.FoodNeed = 123; s.Arms = 5; s.RngState = 99;+ var why = new List<Cause> { new Cause("fixture", "keep", 1, "keep") };+ var before = s.Describe(); var hash = s.Hash(); var cause = why.Single(); var rules = new MvpRules();+ void Invoke()+ {+ switch (call)+ {+ 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.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;+ case "pools.term": Pools.FoodTerm(c,s); break;+ case "cities.init": Cities.Init(c,s); break;+ case "cities.assign": Cities.Assign(c,s,"missing","work",1,why); break;+ case "cities.produce": Cities.Produce(c,s,rules,.1,why); break;+ case "cities.house": Cities.House(c,s,rules,why); break;+ case "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.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;+ case "training.progress": Training.Progress(c,s,why); break;+ case "training.reinforce": Training.Reinforce(c,s,0,"missing",1,why); break;+ case "military.serve": Military.Serve(s,rules,why); break;+ case "military.upkeep": Military.PayUpkeep(c,s,rules,why); break;+ case "qualification.return": Qualification.ReturnCraftsmen(c,s,"missing",1,why); break;+ case "qualification.craftsmen": Qualification.ReassignCraftsmen(c,s,"missing",1,why); break;+ case "qualification.pioneers": Qualification.ReassignPioneers(c,s,"missing","missing",1,why); break;+ case "qualification.unit": Qualification.Return(c,s,0,why); break;+ case "demobilization.give": Demobilization.Give(c,s,0,null,why); break;+ case "combat.resolve": Combat.Resolve(c,s,why); break;+ case "combat.outcomes": Combat.Outcomes(c,s,0); break;+ case "prisoners.upkeep": Prisoners.Upkeep(c,s,rules,why); break;+ case "prisoners.return": Prisoners.Return(c,s,"missing",why); break;+ case "prisoners.take": Prisoners.Take(s,new Unit(1,"missing",0,0,side:"missing",strength:1),new Unit(2,"missing",0,0,side:Movement.PlayerSide)); break;+ case "events.trigger": EventSystem.Trigger(c,s,why); break;+ case "events.choose": EventSystem.Choose(c,s,"missing","missing",why); break;+ case "events.delegate": EventSystem.Delegate(c,s,why); break;+ case "turn.resolve": TurnResolver.Resolve(c,s,s.Date.AddMonths(1),.1,why); break;+ case "economy.flows": EconomySystem.Flows(c,s,.1); break;+ case "economy.apply": EconomySystem.Apply(c,s,.1,why); break;+ case "objectives.complete": Objectives.Complete(c,s,rules,s.Date.AddMonths(1),why); break;+ default: throw new Exception("Unknown boundary fixture");+ }+ }+ Assert.Contains("integration is held", Assert.Throws<NotSupportedException>(Invoke).Message);+ Assert.Equal(before,s.Describe()); Assert.Equal(hash,s.Hash()); Assert.Same(cause,Assert.Single(why));+ }++ // 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)+ {+ var bad = new string((char)codeUnit, 1);+ if (framed) bad = "x" + bad + "z";+ var p = PopulationLedgerTests.Person();+ var s = PopulationLedger.CreateFixture(PopulationLedgerTests.Content(),PopulationLedgerTests.Bindings(),+ new[] { new PopulationInventoryRow("fixture",0,p) });+ var before = s.Describe();+ void Refuse(Action a) { Assert.ThrowsAny<ArgumentException>(a); Assert.Equal(before,s.Describe()); }+ Refuse(()=>new PopulationLocation(bad)); Refuse(()=>new PopulationLocation("north",facilityOrPort:bad));+ Refuse(()=>new PopulationTarget(bad,PopulationAssignmentKind.Work,"north"));+ Refuse(()=>new PopulationTarget("work",PopulationAssignmentKind.Work,bad));+ Refuse(()=>new PopulationAssignment(PopulationAssignmentKind.Work,bad));+ Refuse(()=>new PopulationEquipment(toolsId:bad)); Refuse(()=>new PopulationEquipment(militaryId:bad));+ Refuse(()=>new PopulationUnit(0,p.Status,1,p.Location,p.Assignment,p.Profession,p.Tier,7,bad,9,p.Equipment));+ Refuse(()=>new PopulationUnit(0,p.Status,1,p.Location,p.Assignment,p.Profession,p.Tier,7,"basic",9,p.Equipment,bad,p.Location));+ Refuse(()=>new PopulationBindings(new[]{p.Location!},Array.Empty<PopulationTarget>(),new[]{bad},Array.Empty<string>()));+ Refuse(()=>new PopulationBindings(new[]{p.Location!},Array.Empty<PopulationTarget>(),Array.Empty<string>(),new[]{bad}));+ Refuse(()=>new PopulationInventoryRow(bad,0,p));+ var newcomer = new PopulationUnit(0,p.Status,1,p.Location,p.Assignment,p.Profession,p.Tier,7,"basic",9,PopulationEquipment.None);+ Refuse(()=>s.PopulationLedger.RegisterArrival(bad,0,newcomer));+ Refuse(()=>s.PopulationLedger.RegisterCombatLoss(0,bad));+ }+ [Fact]+ public void SupplementaryUnicodeReferencesRemainLosslessAndDistinct()+ {+ var p = PopulationLedgerTests.Person();+ GameState S(string source) => PopulationLedger.CreateFixture(PopulationLedgerTests.Content(),PopulationLedgerTests.Bindings(),+ new[]{new PopulationInventoryRow(source,0,p)});+ var a=S("ship\U0001F6A2"); var b=S("ship\U0001F6A3");+ Assert.NotEqual(a.Hash(),b.Hash()); Assert.Equal(a.Hash(),a.Clone().Hash());+ a.PopulationLedger.RegisterCombatLoss(0,"loss\U0001F6A2"); a.PopulationLedger.Reconcile();+ }+ // R-POP-001/002: reception.turns is6, not the3 basic-credit catalogue value.+ [Fact]+ public void RealAgreedReceptionRequirementAcceptsFourAndSixAndRefusesSeven()+ {+ var real=ContentLoader.Load(RealContentTests.ContentRoot()); var c=PopulationLedgerTests.Content();+ c.Gdd03Balance=real.Gdd03Balance;+ Assert.Equal(6,c.RequirePopulationInteger("reception.turns"));+ var s=PopulationLedger.CreateFixture(c,PopulationLedgerTests.Bindings(),new[]{new PopulationInventoryRow("fixture",0,PopulationLedgerTests.Person())});+ foreach(var ticks in new[]{4,6}) { s.PopulationLedger.Replace(s.PopulationLedger.Get(0).WithReception(ticks)); s.PopulationLedger.Reconcile(); }+ var before=s.Describe(); Assert.Throws<ArgumentException>(()=>s.PopulationLedger.Replace(s.PopulationLedger.Get(0).WithReception(7)));+ Assert.Equal(before,s.Describe());+ }+}diff --git a/sim/Statecraft.Sim.Tests/PopulationLedgerTests.cs b/sim/Statecraft.Sim.Tests/PopulationLedgerTests.csnew file mode 100644index 000000000..7707e6dca--- /dev/null+++ b/sim/Statecraft.Sim.Tests/PopulationLedgerTests.cs@@ -0,0 +1,224 @@+using Statecraft.Sim;+using System.Globalization;++/// <summary>#1689 foundation only: synthetic inventory; no playable campaign or replay claim.</summary>+public class PopulationLedgerTests+{+ internal static Content Content(string ruleset = SaveGame.Gdd03Ruleset) => new Content {+ Eras = new List<Era> { new Era { Systems = new EraSystems { Loop = EraSystems.Gdd, Ruleset = ruleset } } },+ Gdd03Balance = new Gdd03BalanceCatalogue { Ruleset = SaveGame.Gdd03Ruleset, Values = new() {+ ["population.people_per_unit"] = new Gdd03DesignValue { Basis = "Agreed", Values = new() { 10000 }, Note = "pinned catalogue" },+ ["reception.turns"] = new Gdd03DesignValue { Basis = "Agreed", Values = new() { 6 }, Note = "pinned reception.turns from the Agreed catalogue" }+ } }+ };+ internal static PopulationBindings Bindings(bool reverse = false) => new PopulationBindings(+ reverse ? new[] { new PopulationLocation("south", 1, 0, "port"), new PopulationLocation("north", 0, 0, "camp") }+ : new[] { new PopulationLocation("north", 0, 0, "camp"), new PopulationLocation("south", 1, 0, "port") },+ new[] { new PopulationTarget("field", PopulationAssignmentKind.Work, "north"),+ new PopulationTarget("course", PopulationAssignmentKind.Course, "north", 3),+ new PopulationTarget("teacher", PopulationAssignmentKind.Teaching, "north"),+ new PopulationTarget("service", PopulationAssignmentKind.ActiveService, "north"),+ new PopulationTarget("travel", PopulationAssignmentKind.Travel, "south"),+ new PopulationTarget("reception", PopulationAssignmentKind.Reception, "north") },+ new[] { "captor" }, new[] { "basic", "trained" });+ internal static PopulationUnit Person(int id = 0) => new PopulationUnit(id, PopulationStatus.FreeCivilian,+ 1, new PopulationLocation("north", 0, 0, "camp"), PopulationAssignment.Unassigned,+ CivilianProfession.Farmer, CivilianTier.Trained, 7, "basic", 9,+ new PopulationEquipment("tools", true, "arms", true));+ internal static GameState State(params PopulationInventoryRow[] rows) =>+ PopulationLedger.CreateFixture(Content(), Bindings(), rows);+ static PopulationInventoryRow Row(string key = "start", int ordinal = 0, PopulationUnit? person = null) =>+ new PopulationInventoryRow(key, ordinal, person ?? Person());++ // R-POP-001, R-POP-002: ids change only on registered creation/loss; transitions preserve histories.+ [Fact] public void LifecycleKeepsIdentityAndHistoryAndReconcilesExactIds()+ {+ var s = State(Row()); var l = s.PopulationLedger;+ var p = l.Get(0); var home = p.Location!;+ foreach (var status in new[] { PopulationStatus.Refugee, PopulationStatus.CivilianInTransit,+ PopulationStatus.Trainee, PopulationStatus.ActiveSoldier, PopulationStatus.Captured, PopulationStatus.FreeCivilian })+ {+ var assignment = status switch {+ PopulationStatus.CivilianInTransit => new PopulationAssignment(PopulationAssignmentKind.Travel, "travel"),+ PopulationStatus.Trainee => new PopulationAssignment(PopulationAssignmentKind.Course, "course", 1),+ PopulationStatus.ActiveSoldier => new PopulationAssignment(PopulationAssignmentKind.ActiveService, "service"),+ _ => PopulationAssignment.Unassigned };+ var location = status == PopulationStatus.Captured ? null : status == PopulationStatus.CivilianInTransit+ ? new PopulationLocation("south", 1, 0, "port") : home;+ l.Transition(0, status, location, assignment, status == PopulationStatus.Captured ? "captor" : null, home);+ l.Reconcile(); Assert.Equal(new[] { 0 }, l.Units.Select(x => x.Id));+ Assert.Equal(l.Units.Count, Enum.GetValues<PopulationStatus>().Sum(l.Count));+ var now = l.Get(0);+ Assert.Equal(p.Profession, now.Profession); Assert.Equal(p.Tier, now.Tier);+ Assert.Equal(p.WorkXp, now.WorkXp); Assert.Equal(p.Qualification, now.Qualification);+ Assert.Equal(p.CombatXp, now.CombatXp); Assert.Equal(p.ReceptionTicks, now.ReceptionTicks);+ Assert.Same(p.Equipment, now.Equipment);+ }+ Assert.Equal(1, l.Count(PopulationStatus.FreeCivilian, "north"));+ l.RegisterCombatLoss(0, "fixture-loss"); Assert.Empty(l.Units);+ l.RegisterArrival("ship", 0, Person()); Assert.Equal(1, l.Get(1).Id);+ Assert.Equal(2, l.NextPopulationId); Assert.Single(l.Units); l.Reconcile();+ Assert.Equal(10000, s.TotalPopulation);+ }++ // R-POP-001, R-POP-002: refusal must leave the entire state unchanged, including allocator/provenance.+ [Fact] public void InvalidOperationsAreAtomicAndIdsNeverRecycle()+ {+ var s = State(Row()); var l = s.PopulationLedger;+ void Refuses(Action action) { var before = s.Describe(); Assert.ThrowsAny<ArgumentException>(action); Assert.Equal(before, s.Describe()); }+ Refuses(() => l.Move(99, new PopulationLocation("north", 0, 0, "camp")));+ Refuses(() => l.Move(0, new PopulationLocation("south", 0, 0, "camp")));+ Refuses(() => l.Transition(0, PopulationStatus.ActiveSoldier, l.Get(0).Location, PopulationAssignment.Unassigned));+ Refuses(() => l.Transition(0, PopulationStatus.FreeCivilian, l.Get(0).Location,+ new PopulationAssignment(PopulationAssignmentKind.Work, "missing")));+ Refuses(() => l.RegisterArrival("start", 0, Person()));+ Refuses(() => l.RegisterArrival("ship", 0, Person())); // duplicate issued equipment+ Refuses(() => l.RegisterCombatLoss(99, "loss"));+ Refuses(() => l.Replace(l.Get(0).WithReception(7)));+ Refuses(() => l.Replace(new PopulationUnit(0, PopulationStatus.FreeCivilian, 0, l.Get(0).Location,+ PopulationAssignment.Unassigned, CivilianProfession.None, CivilianTier.Expert, 0, "", 0, PopulationEquipment.None)));+ l.ChangeAssignment(0, new PopulationAssignment(PopulationAssignmentKind.Work, "field"));+ Refuses(() => l.ChangeAssignment(0, new PopulationAssignment(PopulationAssignmentKind.Work, "field")));+ var exhausted = PopulationLedger.CreateFixture(Content(), Bindings(), Array.Empty<PopulationInventoryRow>(), int.MaxValue);+ var hash = exhausted.Hash(); Assert.Throws<OverflowException>(() => exhausted.PopulationLedger.RegisterArrival("ship", 0, Person()));+ Assert.Equal(hash, exhausted.Hash());+ }++ // R-POP-003: canonical source ordering, clone isolation, exact culture-independent field serialization.+ [Fact] public void FixtureOrderCloneAndCultureDoNotChangeCanonicalState()+ {+ var emptyEquipment = new PopulationUnit(0, PopulationStatus.Refugee, 0,+ new PopulationLocation("north", 0, 0, "camp"), PopulationAssignment.Unassigned,+ CivilianProfession.None, CivilianTier.None, 0, "", 0, PopulationEquipment.None);+ var a = State(Row("z", 0, emptyEquipment), Row("a"));+ var b = PopulationLedger.CreateFixture(Content(), Bindings(true), new[] { Row("a"), Row("z", 0, emptyEquipment) });+ Assert.Equal(a.Hash(), b.Hash()); Assert.Equal(CivilianProfession.Farmer, a.PopulationLedger.Get(0).Profession);+ var before = a.Hash(); var clone = a.Clone();+ clone.PopulationLedger.RegisterCombatLoss(0, "loss"); Assert.Equal(before, a.Hash()); Assert.NotEqual(before, clone.Hash());+ var culture = CultureInfo.CurrentCulture;+ try { foreach (var name in new[] { "de-DE", "ar-SA", "" }) { CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo(name); Assert.Equal(before, a.Hash()); } }+ finally { CultureInfo.CurrentCulture = culture; }+ var withHistory = State(Row()); withHistory.PopulationLedger.RegisterCombatLoss(0, "loss");+ Assert.NotEqual(State().Hash(), withHistory.Hash());+ }++ // R-POP-003: mutate every field independently, including every nested payload.+ [Fact] public void EveryRecordFieldReachesHash()+ {+ var p = Person();+ var variants = new[] {+ new PopulationUnit(0, PopulationStatus.Refugee, 1, p.Location, p.Assignment, p.Profession, p.Tier, 7, "basic", 9, p.Equipment),+ p.WithReception(2),+ new PopulationUnit(0, p.Status, 1, new PopulationLocation("south", 1, 0, "port"), p.Assignment, p.Profession, p.Tier, 7, "basic", 9, p.Equipment),+ new PopulationUnit(0, p.Status, 1, p.Location, p.Assignment, CivilianProfession.Pioneer, p.Tier, 7, "basic", 9, p.Equipment),+ new PopulationUnit(0, p.Status, 1, p.Location, p.Assignment, p.Profession, CivilianTier.Veteran, 7, "basic", 9, p.Equipment),+ new PopulationUnit(0, p.Status, 1, p.Location, p.Assignment, p.Profession, p.Tier, 8, "basic", 9, p.Equipment),+ new PopulationUnit(0, p.Status, 1, p.Location, p.Assignment, p.Profession, p.Tier, 7, "trained", 9, p.Equipment),+ new PopulationUnit(0, p.Status, 1, p.Location, p.Assignment, p.Profession, p.Tier, 7, "basic", 10, p.Equipment),+ new PopulationUnit(0, p.Status, 1, p.Location, new PopulationAssignment(PopulationAssignmentKind.Work,"field"), p.Profession, p.Tier, 7, "basic", 9, p.Equipment)+ };+ var original = State(Row()).Hash();+ foreach (var v in variants) Assert.NotEqual(original, State(Row(person: v)).Hash());+ foreach (var equipment in new[] { new PopulationEquipment("other",true,"arms",true), new PopulationEquipment("tools",false,"arms",true),+ new PopulationEquipment("tools",true,"other",true), new PopulationEquipment("tools",true,"arms",false) })+ {+ var v = new PopulationUnit(0,p.Status,1,p.Location,p.Assignment,p.Profession,p.Tier,7,"basic",9,equipment);+ Assert.NotEqual(original,State(Row(person:v)).Hash());+ }+ var a = State(Row()); var b = a.Clone();+ a.PopulationLedger.Transition(0,PopulationStatus.Captured,null,PopulationAssignment.Unassigned,"captor",p.Location);+ b.PopulationLedger.Transition(0,PopulationStatus.Captured,null,PopulationAssignment.Unassigned,"captor",new PopulationLocation("south",1,0,"port"));+ Assert.NotEqual(a.Hash(),b.Hash());+ }++ // R-POP-001, R-POP-003, R-LOOP-002, R-CITY-001, R-CITY-008: old identities neither gain state nor accept helpers.+ [Theory] [InlineData("legacy")] [InlineData("gdd-0.1")]+ public void OldIdentitiesKeepCanonicalTextAndSaveBytes(string identity)+ {+ var s = new GameState(Content(identity)); var before = s.Describe();+ Assert.False(s.UsesPopulationLedger); Assert.DoesNotContain("population-ledger", before);+ Assert.Throws<InvalidOperationException>(()=>s.PopulationLedger.RegisterArrival("ship",0,Person()));+ Assert.Equal(before,s.Describe()); Assert.Equal(before,s.Clone().Describe());+ var save = new SaveGame(new string('a',64),1,Mode.Historical,identity,new string('b',64));+ Assert.Equal($"statecraft-save 3\ncontent {new string('a',64)}\nseed 1\nmode Historical\nruleset {identity}\nend {new string('b',64)}\n",save.Write());+ }++ // R-POP-001, R-LOOP-005: no numeric fallback from the old common scale or Deferred start.army.+ [Fact] public void ScaleIsIdentityAwareAndInvalidCatalogueValuesAreRefused()+ {+ var c=Content(); Assert.True(c.UsesPopulationLedger); Assert.Equal(10000,c.PopulationPeoplePerUnit);+ foreach (var value in new[] { 0m, -1m, 1.5m, (decimal)int.MaxValue+1 }) {+ c.Gdd03Balance!.Values["population.people_per_unit"].Values[0]=value;+ Assert.Throws<ContentException>(()=> { _ = c.PopulationPeoplePerUnit; });+ }+ c=Content(); c.Gdd03Balance!.Values["population.people_per_unit"].Basis="Deferred";+ Assert.Throws<ContentException>(()=> { _ = c.PopulationPeoplePerUnit; });+ c.Gdd03Balance.Values.Remove("population.people_per_unit"); Assert.Throws<ContentException>(()=> { _ = c.PopulationPeoplePerUnit; });+ foreach(var identity in new[]{SaveGame.LegacyRuleset,SaveGame.GddRuleset}) {+ var old=Content(identity); old.Rules.Mvp=new MvpRules { PeoplePerUnit=1000 };+ old.Gdd03Balance=null; Assert.Equal(1000,old.PopulationPeoplePerUnit);+ }+ }++ // R-POP-002/003: course references and every payload field are validated and canonical.+ [Fact] public void CoursePayloadReferencesAndProvenanceAreCanonicalAndAtomic()+ {+ PopulationUnit Teacher() => new PopulationUnit(0, PopulationStatus.FreeCivilian, 1, Person().Location,+ new PopulationAssignment(PopulationAssignmentKind.Teaching,"course"), CivilianProfession.Pioneer,+ CivilianTier.Trained, 4,"basic",2,PopulationEquipment.None);+ PopulationUnit Pupil(int progress, int? teacher) => new PopulationUnit(0,PopulationStatus.Trainee,1,Person().Location,+ new PopulationAssignment(PopulationAssignmentKind.Course,"course",progress,teacher),CivilianProfession.None,+ CivilianTier.None,0,"",0,PopulationEquipment.None);+ GameState Course(int progress, int? teacher) => State(Row("a",0,Teacher()),Row("a",1,Teacher()),Row("z",0,Pupil(progress,teacher)));+ var a=Course(0,null); var b=Course(1,null); var c=Course(0,0); var d=Course(0,1);+ Assert.Equal(4,new HashSet<string>{a.Hash(),b.Hash(),c.Hash(),d.Hash()}.Count);+ var before=c.Describe();+ Assert.Throws<ArgumentException>(()=>c.PopulationLedger.RegisterCombatLoss(0,"loss"));+ Assert.Equal(before,c.Describe());+ Assert.Throws<ArgumentException>(()=>Course(4,null)); Assert.Throws<ArgumentException>(()=>Course(0,99));+ Assert.Throws<ArgumentException>(()=>Course(0,2));+ Assert.Throws<ArgumentException>(()=>State(Row("a"),Row("a")));+ Assert.Throws<ArgumentException>(()=>PopulationLedger.CreateFixture(Content(),new PopulationBindings(+ new[]{new PopulationLocation("north",0,0),new PopulationLocation("south",0,0)},+ Array.Empty<PopulationTarget>(),Array.Empty<string>(),Array.Empty<string>()),Array.Empty<PopulationInventoryRow>()));+ Assert.NotEqual(State(Row("start")).Hash(),State(Row("start|\n",1)).Hash());+ var lost=State(Row());lost.PopulationLedger.RegisterCombatLoss(0,"loss");var hash=lost.Hash();+ Assert.Throws<ArgumentException>(()=>lost.PopulationLedger.RegisterArrival("start",0,Person()));+ Assert.Equal(hash,lost.Hash());+ Assert.NotEqual(State().Hash(),PopulationLedger.CreateFixture(Content(),Bindings(),Array.Empty<PopulationInventoryRow>(),1).Hash());+ Assert.Contains("population-ledger",new GameState(Content()).Describe());+ }++ // R-POP-003: each nullable/reference component has an independent canonical representation.+ [Fact] public void LocationCaptorAndTargetTokensCannotAlias()+ {+ var p=Person();+ PopulationUnit Placed(PopulationLocation location) => new PopulationUnit(0,p.Status,1,location,p.Assignment,p.Profession,p.Tier,7,"basic",9,p.Equipment);+ var locations=new[]{new PopulationLocation("north"),new PopulationLocation("north",0,0),+ new PopulationLocation("north",1,0),new PopulationLocation("north",0,1),new PopulationLocation("north",0,0,"camp"),+ new PopulationLocation("north",0,0,"port|\n")};+ var bindings=new PopulationBindings(locations,new[]{new PopulationTarget("field",PopulationAssignmentKind.Work,"north"),+ new PopulationTarget("field|\n",PopulationAssignmentKind.Work,"north")},new[]{"captor","captor|\n"},new[]{"basic"});+ GameState S(PopulationUnit unit) => PopulationLedger.CreateFixture(Content(),bindings,new[]{Row(person:unit)});+ Assert.Equal(locations.Length,locations.Select(l=>S(Placed(l)).Hash()).Distinct().Count());+ var a=S(p);var b=a.Clone();+ a.PopulationLedger.Transition(0,PopulationStatus.Captured,null,PopulationAssignment.Unassigned,"captor",p.Location);+ b.PopulationLedger.Transition(0,PopulationStatus.Captured,null,PopulationAssignment.Unassigned,"captor|\n",p.Location);+ Assert.NotEqual(a.Hash(),b.Hash());+ a=S(p);b=a.Clone();a.PopulationLedger.ChangeAssignment(0,new PopulationAssignment(PopulationAssignmentKind.Work,"field"));+ b.PopulationLedger.ChangeAssignment(0,new PopulationAssignment(PopulationAssignmentKind.Work,"field|\n"));+ Assert.NotEqual(a.Hash(),b.Hash());+ Assert.Throws<ArgumentException>(()=>S(new PopulationUnit(0,p.Status,1,p.Location,p.Assignment,p.Profession,p.Tier,-1,"basic",9,p.Equipment)));+ Assert.Throws<ArgumentException>(()=>S(new PopulationUnit(0,p.Status,1,p.Location,p.Assignment,p.Profession,p.Tier,7,"unknown",9,p.Equipment)));+ }++ // R-POP-002: fixture-only initialization must never enter old turn/command producers.+ [Fact] public void FixturesRefuseAggregateSimulationEntryPoints()+ {+ var s=State(Row());var c=Content();var hash=s.Hash();+ Assert.Throws<NotSupportedException>(()=>Simulation.Step(c,s,Array.Empty<Command>()));+ Assert.Throws<NotSupportedException>(()=>Simulation.Preview(c,s,Array.Empty<Command>()));+ Assert.Throws<NotSupportedException>(()=>Simulation.DelegatedTo(c,s,Array.Empty<Command>(),"missing"));+ Assert.Equal(hash,s.Hash());+ }+}diff --git a/sim/Statecraft.Sim/Cities.cs b/sim/Statecraft.Sim/Cities.csindex ea3fb57b5..e7e81a296 100644--- a/sim/Statecraft.Sim/Cities.cs+++ b/sim/Statecraft.Sim/Cities.cs@@ -50,6 +50,7 @@ namespace Statecraft.Sim/// <summary>Fills the state's cities from cities.yaml, with no refugees yet and the start housing condition (R-HOUSE-001). Does nothing in the legacy loop.</summary>public static void Init(Content c, GameState s){+ PopulationLedger.RefuseAggregate(s);if (!c.IsGdd) return;var r = c.RulesAt(s.Date).Mvp!;foreach (var x in c.Cities) s.Cities[x.Id] = new City(x.Id, x.HousingCapacity, x.JobSlots, x.Civilians, x.Employed, 0, 0, r.HousingStartCondition!.Value);@@ -62,6 +63,7 @@ namespace Statecraft.Sim/// the job slots or above the civilians and craftsmen. Step has already refused it in the legacy loop.</summary>public static string? Assign(Content c, GameState s, string city, string role, int count, List<Cause> why){+ PopulationLedger.RefuseAggregate(s);if (!s.Cities.TryGetValue(city, out var x)) return "There is no such city";// Craftsmen fill ordinary job slots (Q-CRAFT-2, R-CRAFT-002), so "job" stays the only role.if (role != "job") return "There is no such role";@@ -79,6 +81,7 @@ namespace Statecraft.Sim/// year. Craftsmen take the jobs first, and each employed craftsman earns craftsman_income_multiple times that.</summary>public static void Produce(Content c, GameState s, MvpRules r, double yearFraction, List<Cause> why){+ PopulationLedger.RefuseAggregate(s);foreach (var x in s.Cities.Values){if (x.Employed == 0) continue;@@ -93,6 +96,7 @@ namespace Statecraft.Sim/// projects and camp sites count. The six rates are explicit content design values; all are 0 in the MVP.</summary>public static double AnnualUpkeep(Content c, GameState s, MvpRules r){+ PopulationLedger.RefuseAggregate(s);var total = s.Cities.Count * r.CityUpkeepPerYear!.Value;foreach (var p in s.CityProjects.Values){@@ -120,6 +124,7 @@ namespace Statecraft.Sim/// default is on fills its free job slots from its people without a job, at no Attention cost.</summary>public static void House(Content c, GameState s, MvpRules r, List<Cause> why){+ PopulationLedger.RefuseAggregate(s);// R-MIN-001, R-MIN-002 (D-H3; Q-MIN-1, Q-MIN-2): the Immigration minister's multiplier scales how many of the// city's refugees are housed this turn; the count is floored (whole groups only) and the rest wait as// refugees. At a neutral multiplier every refugee is housed, as R-CITY-004 says.@@ -192,6 +197,7 @@ namespace Statecraft.Sim/// counts (R-HOUSE-001: the condition is per city).</summary>public static void UpdateCondition(Content c, GameState s, MvpRules r, List<Cause> why){+ PopulationLedger.RefuseAggregate(s);foreach (var x in s.Cities.Values.ToList()){var over = Overflow(s, x);@@ -221,6 +227,7 @@ namespace Statecraft.Sim/// count from the game's start, and the cities are the part of it placed in towns (R-CITY-008, Q-ARRV-2).</summary>public static void Arrive(Content c, GameState s, MvpRules r, DateTime next, List<Cause> why){+ PopulationLedger.RefuseAggregate(s);var units = ArrivedUnits(c, s.Date, next, r.PeoplePerUnit);if (units == 0) return;var before = UnitsBy(c, s.Date, r.PeoplePerUnit);diff --git a/sim/Statecraft.Sim/Combat.cs b/sim/Statecraft.Sim/Combat.csindex fddbc71fd..c93d51c9f 100644--- a/sim/Statecraft.Sim/Combat.cs+++ b/sim/Statecraft.Sim/Combat.cs@@ -164,6 +164,7 @@ namespace Statecraft.Sim/// mvp.people_per_unit, as the engagement's report counts them) and whether the defenders retreat.</summary>public static IReadOnlyList<(int Faces, int Of, int AttackersLose, int DefendersLose, bool Retreat)> Outcomes(Content c, GameState s, int row){+ PopulationLedger.RefuseAggregate(s);var mvp = c.RulesAt(s.Date).Mvp!;var t = mvp.CombatTable[row];var bands = new List<(int Faces, int Of, int AttackersLose, int DefendersLose, bool Retreat)>();@@ -205,6 +206,7 @@ namespace Statecraft.Sim/// Afterwards every attack whose hex is now empty ends.</summary>public static void Resolve(Content c, GameState s, List<Cause> why){+ PopulationLedger.RefuseAggregate(s);var mvp = c.RulesAt(s.Date).Mvp!;var done = new HashSet<int>();foreach (var id in s.Units.Keys.ToList()) // Units is a SortedList: ascending iddiff --git a/sim/Statecraft.Sim/Content.cs b/sim/Statecraft.Sim/Content.csindex c35eed2c5..372f3763d 100644--- a/sim/Statecraft.Sim/Content.cs+++ b/sim/Statecraft.Sim/Content.cs@@ -1255,6 +1255,23 @@ namespace Statecraft.Sim/// <summary>Identity predicate: legacy and gdd-0.1 have Attention, gdd-0.3 omits it. The sim reads it to leave/// Attention out of gdd-0.3 (R-LOOP-001, R-GOV-002, #1688).</summary>public bool UsesAttention => Ruleset != SaveGame.Gdd03Ruleset;+ /// <summary>Exact population capability, independent of loop and Attention (R-POP-001).</summary>+ public bool UsesPopulationLedger => Ruleset == SaveGame.Gdd03Ruleset;+ /// <summary>The new identity reads its own catalogue; old callers retain the common rules value.</summary>+ public int PopulationPeoplePerUnit => UsesPopulationLedger+ ? RequirePopulationInteger("population.people_per_unit")+ : (Rules.Mvp ?? throw new InvalidOperationException("Population scale needs mvp rules.")).PeoplePerUnit;+ internal int RequirePopulationInteger(string key)+ {+ if (!UsesPopulationLedger) throw new InvalidOperationException("Population catalogue access requires gdd-0.3.");+ if (Gdd03Balance == null || Gdd03Balance.Values == null || Gdd03Balance.Ruleset != SaveGame.Gdd03Ruleset+ || !Gdd03Balance.Values.TryGetValue(key, out var row) || row == null || row.Basis != "Agreed"+ || row.Values == null || row.Values.Count != 1 || row.Parts == null || row.Parts.Count != 0+ || !string.IsNullOrEmpty(row.Expression) || row.Values[0] <= 0 || row.Values[0] > int.MaxValue+ || decimal.Truncate(row.Values[0]) != row.Values[0])+ throw new ContentException(Gdd03BalanceCatalogue.FileName, "values." + key, "requires one positive Agreed integer; no Deferred or old-rules fallback");+ return (int)row.Values[0];+ }/// <summary>The day play ends, a boundary the last turn reaches (Simulation.Step): rules.yaml mvp.end in the GDD loop/// (R-LOOP-004), otherwise the last era's end.</summary>public DateTime End => IsGdd && Rules.Mvp?.End is DateTime e ? e : Eras[Eras.Count - 1].To;diff --git a/sim/Statecraft.Sim/ContentLoader.cs b/sim/Statecraft.Sim/ContentLoader.csindex 6fcc74f6b..024ee462e 100644--- a/sim/Statecraft.Sim/ContentLoader.cs+++ b/sim/Statecraft.Sim/ContentLoader.cs@@ -373,6 +373,8 @@ namespace Statecraft.SimValidate(c, settlementIds);if (c.Ruleset == SaveGame.Gdd03Ruleset && c.Gdd03Balance == null)throw new ContentException(Gdd03BalanceCatalogue.FileName, "(file)", "required for the gdd-0.3 ruleset");+ // R-POP-001: validate the identity-specific scale without altering old content reads/hash inputs.+ if (c.UsesPopulationLedger) _ = c.PopulationPeoplePerUnit;ApplyMapOverrides(readFile, c, settlementIds); // after the map's own checks, before the GDD records that read itif (c.IsGdd){diff --git a/sim/Statecraft.Sim/Demobilization.cs b/sim/Statecraft.Sim/Demobilization.csindex 5e2660c5c..72c660f80 100644--- a/sim/Statecraft.Sim/Demobilization.cs+++ b/sim/Statecraft.Sim/Demobilization.cs@@ -60,6 +60,7 @@ namespace Statecraft.Siminternal static string? Give(Content c, GameState s, int unitId,IReadOnlyDictionary<int, (int Q, int R)>? attacked, List<Cause> why){+ PopulationLedger.RefuseAggregate(s);var refused = Check(c, s, unitId, attacked);if (refused != null) return refused;var u = s.Units[unitId];diff --git a/sim/Statecraft.Sim/EconomySystem.cs b/sim/Statecraft.Sim/EconomySystem.csindex da7fa616c..c2f7e7cae 100644--- a/sim/Statecraft.Sim/EconomySystem.cs+++ b/sim/Statecraft.Sim/EconomySystem.cs@@ -25,6 +25,7 @@ namespace Statecraft.Simpublic static TreasuryFlows Flows(Content c, GameState s, double yearFraction){+ PopulationLedger.RefuseAggregate(s);var r = c.RulesAt(s.Date); var pop = s.TotalPopulation;return new TreasuryFlows(r.TaxPerCapitaPerYear * pop * yearFraction, r.SpendingPerCapitaPerYear * pop * yearFraction,MobilizationCost(c, s.Date, s.Mobilization, yearFraction));@@ -60,6 +61,7 @@ namespace Statecraft.Simpublic static void Apply(Content c, GameState s, double yearFraction, List<Cause> why){+ PopulationLedger.RefuseAggregate(s);var r = c.RulesAt(s.Date); var pop = s.TotalPopulation;var flows = Flows(c, s, yearFraction);var revenue = flows.Tax; var spending = flows.Spending; var mobilization = flows.Mobilization;diff --git a/sim/Statecraft.Sim/EventSystem.cs b/sim/Statecraft.Sim/EventSystem.csindex 155cce300..e1a8ff49d 100644--- a/sim/Statecraft.Sim/EventSystem.cs+++ b/sim/Statecraft.Sim/EventSystem.cs@@ -22,6 +22,7 @@ namespace Statecraft.Sim/// (<see cref="FillDate"/>).</summary>public static void Trigger(Content c, GameState s, List<Cause> why, DateTime? turnStart = null){+ PopulationLedger.RefuseAggregate(s);var start = turnStart ?? s.Date;var eligible = c.Events.Where(e => !s.FiredEvents.Contains(e.Id) && e.From <= s.Date && (e.To == null || start < e.To.Value))@@ -63,6 +64,7 @@ namespace Statecraft.Sim/// <summary>Returns null on success, or the reason the choice was rejected.</summary>public static string? Choose(Content c, GameState s, string eventId, string optionId, List<Cause> why){+ PopulationLedger.RefuseAggregate(s);if (!s.PendingEvents.Contains(eventId)) return "That event is not waiting for a decision";var option = Get(c, eventId).Options.FirstOrDefault(o => o.Id == optionId);if (option == null) return "That event has no such option";@@ -306,6 +308,7 @@ namespace Statecraft.Sim/// decision he was left to make, competence which decision he makes; anchors and objective cards stay whole.</summary>public static void Delegate(Content c, GameState s, List<Cause> why){+ PopulationLedger.RefuseAggregate(s);var rng = new Rng(s.RngState);var mvp = c.IsGdd ? c.RulesAt(s.Date).Mvp : null; // the legacy loop has no floor, so its goldens holdforeach (var id in s.PendingEvents.ToList())diff --git a/sim/Statecraft.Sim/GameState.cs b/sim/Statecraft.Sim/GameState.csindex 55774935f..44b727614 100644--- a/sim/Statecraft.Sim/GameState.cs+++ b/sim/Statecraft.Sim/GameState.cs@@ -29,8 +29,14 @@ namespace Statecraft.Sim/// <summary>Immutable replay identity. Old manually constructed states retain their historical hash layout.</summary>public string Ruleset { get; } = SaveGame.LegacyRuleset;readonly bool usesAttention = true;+ public bool UsesPopulationLedger => Ruleset == SaveGame.Gdd03Ruleset;+ public PopulationLedger PopulationLedger { get; private set; } = new PopulationLedger(false);public GameState() { }- internal GameState(Content c) { Ruleset = c.Ruleset; usesAttention = c.UsesAttention; }+ internal GameState(Content c)+ {+ Ruleset = c.Ruleset; usesAttention = c.UsesAttention;+ PopulationLedger = new PopulationLedger(UsesPopulationLedger);+ }public DateTime Date;public ulong RngState;public Mode Mode;@@ -116,7 +122,8 @@ namespace Statecraft.Sim/// not people (Q-CAP-2 (b)), with no destination on the board (Q-DEP-3 (a)).</summary>public int DisplacedByPlayer;- public double TotalPopulation => Population.Values.Sum();+ public double TotalPopulation => PopulationLedger.IsInitialized+ ? PopulationLedger.TotalPeople : Population.Values.Sum();public GameState Clone(){@@ -128,6 +135,7 @@ namespace Statecraft.Simc.ActiveSituations = new SortedSet<string>(ActiveSituations, StringComparer.Ordinal);c.Budget = new Dictionary<string, double>(Budget);c.Population = new Dictionary<string, double>(Population);+ c.PopulationLedger = PopulationLedger.Clone();c.FiredEvents = new SortedSet<string>(FiredEvents, StringComparer.Ordinal);c.PendingEvents = new List<string>(PendingEvents);c.ChosenOptions = new Dictionary<string, string>(ChosenOptions);@@ -261,6 +269,7 @@ namespace Statecraft.Simif (PrisonersReturned.Count > 0) Section("powret", '{', '}', Counts(PrisonersReturned));if (SoldiersHeld.Count > 0) Section("ownheld", '{', '}', Counts(SoldiersHeld));if (DisplacedByPlayer != 0) { Sep(); Nl(); sb.Append("displaced=").Append(DisplacedByPlayer.ToString(CultureInfo.InvariantCulture)); } // R-CTRL-019: only after a Deport+ if (UsesPopulationLedger) Section("population-ledger", '{', '}', PopulationLedger.Canonical());return sb.ToString();}}diff --git a/sim/Statecraft.Sim/Military.cs b/sim/Statecraft.Sim/Military.csindex 191efaf0a..5ec64c769 100644--- a/sim/Statecraft.Sim/Military.cs+++ b/sim/Statecraft.Sim/Military.cs@@ -10,6 +10,7 @@ namespace Statecraft.Sim/// never counts as service. Promotion preserves the formation and its standing order; combat adds no service.</summary>public static void Serve(GameState s, MvpRules r, List<Cause> why){+ PopulationLedger.RefuseAggregate(s);foreach (var u in s.Units.Values.ToList()){if (u.Type != "recruit" || u.Side != "israel") continue;@@ -25,6 +26,7 @@ namespace Statecraft.Sim/// Treasury borrows a shortfall (R-MONEY-003); upkeep never consumes Arms (Q-UNIT-3).</summary>public static void PayUpkeep(Content c, GameState s, MvpRules r, List<Cause> why){+ PopulationLedger.RefuseAggregate(s);var count = s.Units.Values.Count(u => u.Side == "israel" && c.UnitTypes.Any(t => t.Id == u.Type && t.Side == "israel"));var cost = count * r.MilitaryUpkeepPerTurn!.Value;if (cost == 0) return;diff --git a/sim/Statecraft.Sim/Objectives.cs b/sim/Statecraft.Sim/Objectives.csindex a946d534e..c5ffc77a0 100644--- a/sim/Statecraft.Sim/Objectives.cs+++ b/sim/Statecraft.Sim/Objectives.cs@@ -42,6 +42,7 @@ namespace Statecraft.Sim/// the date the turn starts from (docs/determinism.md, "Rules per era").</summary>public static void Complete(Content c, GameState s, MvpRules r, DateTime next, List<Cause> why){+ PopulationLedger.RefuseAggregate(s);foreach (var o in c.Objectives) // in objectives.yaml's order (the loader; R-OBJ-007)if (Holds(c, s, o)) Record(c, s, r, o.Id, next, why);}diff --git a/sim/Statecraft.Sim/Pools.cs b/sim/Statecraft.Sim/Pools.csindex 825a31632..52c785be0 100644--- a/sim/Statecraft.Sim/Pools.cs+++ b/sim/Statecraft.Sim/Pools.cs@@ -27,6 +27,7 @@ namespace Statecraft.Sim/// <summary>R-FOOD-001: the stock starts at cover_months of the start's need, so food_supply starts at its level.</summary>public static void Init(Content c, GameState s){+ PopulationLedger.RefuseAggregate(s);if (!c.IsGdd) return;var r = c.RulesAt(s.Date).Mvp!;s.FoodNeed = Need(s, r);@@ -40,6 +41,7 @@ namespace Statecraft.Sim/// stock that would pass a whole number's range. Step has already refused it in the legacy loop.</summary>public static string? BuyArms(Content c, GameState s, int count, List<Cause> why){+ PopulationLedger.RefuseAggregate(s);if (count < 1) return "Buy at least 1 Arms";if ((long)s.Arms + count > int.MaxValue) return "That is more Arms than the stock can hold";var cost = count * c.RulesAt(s.Date).Mvp!.ArmsPrice!.Value;@@ -57,6 +59,7 @@ namespace Statecraft.Sim/// nation eats in step 7, so in a turn with imports the import only tops the stock up by less.</summary>public static void Harvest(Content c, GameState s, MvpRules r, List<Cause> why){+ PopulationLedger.RefuseAggregate(s);var yield = r.FieldFoodPerTurn!.Value; // the loader requires it in the GDD loopif (yield == 0) return;foreach (var f in c.Sites.Where(x => x.Kinds.Contains(Projects.FieldKind)).OrderBy(x => x.Id, StringComparer.Ordinal))@@ -72,6 +75,7 @@ namespace Statecraft.Sim/// currency is exhausted (the fx_crisis situation at the turn's start), when no Food is imported.</summary>public static void Consume(Content c, GameState s, MvpRules r, List<Cause> why){+ PopulationLedger.RefuseAggregate(s);var need = Need(s, r);var eaten = Math.Min(need, s.Food);s.Food -= eaten;@@ -93,6 +97,7 @@ namespace Statecraft.Sim/// share lowers it further; food_supply's clamp to 0..1 bounds it. 0 in the legacy loop and with no need.</summary>public static double FoodTerm(Content c, GameState s){+ PopulationLedger.RefuseAggregate(s);if (!c.IsGdd || s.FoodNeed == 0) return 0.0;var r = c.RulesAt(s.Date).Mvp!;var full = (long)r.CoverMonths!.Value * s.FoodNeed;diff --git a/sim/Statecraft.Sim/PopulationLedger.cs b/sim/Statecraft.Sim/PopulationLedger.csnew file mode 100644index 000000000..b83c900cf--- /dev/null+++ b/sim/Statecraft.Sim/PopulationLedger.cs@@ -0,0 +1,281 @@+using System;+using System.Collections.Generic;+using System.Collections.ObjectModel;+using System.Linq;++namespace Statecraft.Sim+{+ public sealed class PopulationTarget+ {+ public string Id { get; }+ public PopulationAssignmentKind Kind { get; }+ public string Region { get; }+ public int? MaxProgressTicks { get; }+ public PopulationTarget(string id, PopulationAssignmentKind kind, string region, int? maxProgressTicks = null)+ {+ PopulationText.Assignment(kind);+ if (string.IsNullOrWhiteSpace(id) || string.IsNullOrWhiteSpace(region) || kind == PopulationAssignmentKind.Unassigned+ || maxProgressTicks < 0 || (kind == PopulationAssignmentKind.Course) != maxProgressTicks.HasValue)+ throw new ArgumentException("Targets need explicit kind/region; courses need an explicit progress limit.");+ PopulationText.ValidateText(id); PopulationText.ValidateText(region);+ Id = id; Kind = kind; Region = region; MaxProgressTicks = maxProgressTicks;+ }+ internal string Canonical() => PopulationText.Fields(Id, PopulationText.Assignment(Kind), Region, MaxProgressTicks);+ }++ /// <summary>Frozen explicit reference inventory. No guesses about regional hex ownership, facilities or qualifications.+ /// Foundation fixtures supply these bindings; production authoring remains held.</summary>+ public sealed class PopulationBindings+ {+ readonly PopulationLocation[] locations;+ readonly SortedDictionary<string, PopulationTarget> targets;+ readonly SortedSet<string> captors, qualifications;+ public PopulationBindings(IEnumerable<PopulationLocation> locations, IEnumerable<PopulationTarget> targets,+ IEnumerable<string> captors, IEnumerable<string> qualifications)+ {+ this.locations = locations.OrderBy(x => x.Canonical(), StringComparer.Ordinal).ToArray();+ if (this.locations.Select(x => x.Canonical()).Distinct(StringComparer.Ordinal).Count() != this.locations.Length)+ throw new ArgumentException("Duplicate location binding.");+ // A hex or facility cannot silently refer to two different regions.+ if (this.locations.Where(x => x.Q != null).GroupBy(x => PopulationText.Fields(x.Q, x.R))+ .Any(g => g.Select(x => x.Region).Distinct(StringComparer.Ordinal).Count() != 1)+ || this.locations.Where(x => x.FacilityOrPort != null).GroupBy(x => x.FacilityOrPort, StringComparer.Ordinal)+ .Any(g => g.Select(x => x.Canonical()).Distinct(StringComparer.Ordinal).Count() != 1))+ throw new ArgumentException("Inconsistent region/hex/facility bindings.");+ this.targets = new SortedDictionary<string, PopulationTarget>(StringComparer.Ordinal);+ foreach (var t in targets)+ {+ if (!this.locations.Any(l => l.Region == t.Region)) throw new ArgumentException("Unknown target region.");+ this.targets.Add(t.Id, t);+ }+ this.captors = Names(captors); this.qualifications = Names(qualifications);+ }+ static SortedSet<string> Names(IEnumerable<string> values)+ {+ var result = new SortedSet<string>(StringComparer.Ordinal);+ foreach (var value in values)+ {+ PopulationText.ValidateText(value);+ if (string.IsNullOrWhiteSpace(value) || !result.Add(value)) throw new ArgumentException("Duplicate or empty reference.");+ }+ return result;+ }+ internal void ValidateLocation(PopulationLocation location)+ {+ if (!locations.Any(x => x.Canonical() == location.Canonical())) throw new ArgumentException("Unknown or inconsistent location.");+ }+ internal PopulationTarget Target(PopulationAssignment assignment)+ {+ if (assignment.Target == null || !targets.TryGetValue(assignment.Target, out var t)+ || (t.Kind != assignment.Kind && !(t.Kind == PopulationAssignmentKind.Course && assignment.Kind == PopulationAssignmentKind.Teaching)))+ throw new ArgumentException("Unknown or incompatible assignment target.");+ return t;+ }+ internal bool HasCaptor(string captor) => captors.Contains(captor);+ internal bool HasQualification(string qualification) => qualification == "" || qualifications.Contains(qualification);+ internal IEnumerable<string> Canonical()+ {+ foreach (var l in locations) yield return PopulationText.Fields("location", l.Canonical());+ foreach (var t in targets.Values) yield return PopulationText.Fields("target", t.Canonical());+ foreach (var c in captors) yield return PopulationText.Fields("captor", c);+ foreach (var q in qualifications) yield return PopulationText.Fields("qualification", q);+ }+ }++ /// <summary>Visibly synthetic fixture input. Template ids are ignored; source key plus within-row ordinal determines order.</summary>+ internal sealed class PopulationInventoryRow+ {+ internal string Source { get; }+ internal int Ordinal { get; }+ internal PopulationUnit Template { get; }+ internal PopulationInventoryRow(string source, int ordinal, PopulationUnit template)+ {+ if (string.IsNullOrWhiteSpace(source) || ordinal < 0) throw new ArgumentException("Explicit source and nonnegative ordinal required.");+ PopulationText.ValidateText(source);+ Source = source; Ordinal = ordinal; Template = template ?? throw new ArgumentNullException(nameof(template));+ }+ }++ /// <summary>R-POP-001/002/003. Sole own-person authority for initialized gdd-0.3 fixtures.+ /// Mutations validate a candidate map before committing. No resources, causes or RNG are touched here.</summary>+ public sealed class PopulationLedger+ {+ readonly bool enabled;+ SortedDictionary<int, PopulationUnit> units = new SortedDictionary<int, PopulationUnit>();+ SortedDictionary<string, int> sources = new SortedDictionary<string, int>(StringComparer.Ordinal);+ SortedDictionary<int, string> losses = new SortedDictionary<int, string>();+ PopulationBindings? bindings;+ int receptionLimit;+ int peoplePerUnit;+ public bool IsInitialized { get; private set; }+ public int NextPopulationId { get; private set; }+ public double TotalPeople => (double)units.Count * peoplePerUnit;+ /// <summary>Reconcile exact ids, not just totals that could hide substitution. No mutation.</summary>+ public void Reconcile()+ {+ RequireInitialized();+ var created = new HashSet<int>(sources.Values);+ if (created.Count != sources.Count || losses.Keys.Any(id => !created.Contains(id))+ || !new HashSet<int>(created.Except(losses.Keys)).SetEquals(units.Keys)+ || created.Any(id => id < 0 || id >= NextPopulationId))+ throw new InvalidOperationException("Population id conservation failed.");+ Validate(units);+ }+ // A snapshot wrapper prevents casts back to the writable container; records are immutable.+ public IReadOnlyList<PopulationUnit> Units => new ReadOnlyCollection<PopulationUnit>(units.Values.ToList());+ internal PopulationLedger(bool enabled) { this.enabled = enabled; }+ internal PopulationLedger Clone()+ {+ var c = (PopulationLedger)MemberwiseClone();+ c.units = new SortedDictionary<int, PopulationUnit>(units);+ c.sources = new SortedDictionary<string, int>(sources, StringComparer.Ordinal);+ c.losses = new SortedDictionary<int, string>(losses);+ return c;+ }+ // R-POP-002: refuse before old producers/consumers can mutate resources, causes or a second population.+ internal static void RefuseAggregate(GameState state)+ {+ if (state.PopulationLedger.IsInitialized)+ throw new NotSupportedException("Population-ledger fixtures cannot run aggregate systems; gdd-0.3 integration is held.");+ }+ void RequireInitialized()+ {+ if (!enabled || !IsInitialized) throw new InvalidOperationException("Population ledger mutations require an initialized gdd-0.3 fixture.");+ }+ public PopulationUnit Get(int id) => units.TryGetValue(id, out var p) ? p : throw new ArgumentException("Unknown population id.", nameof(id));+ public int Count(PopulationStatus status) => Count(status, null);+ public int Count(PopulationStatus status, string? region)+ {+ PopulationText.Status(status);+ // Captives have no invented location; retained home region is their regional accounting context.+ return units.Values.Count(p => p.Status == status && (region == null || (p.Location ?? p.Home)?.Region == region));+ }+ public void Move(int id, PopulationLocation location)+ {+ RequireInitialized(); var p = Get(id);+ Replace(p.WithPlacement(p.Status, location, p.Assignment, p.Captor, p.Home));+ }+ /// <summary>A second nonempty assignment must first be released explicitly. Transition is the atomic status/location path.</summary>+ public void ChangeAssignment(int id, PopulationAssignment assignment)+ {+ RequireInitialized(); var p = Get(id);+ if (p.Assignment.Kind != PopulationAssignmentKind.Unassigned && assignment.Kind != PopulationAssignmentKind.Unassigned)+ throw new ArgumentException("Release the current assignment first.");+ Replace(p.WithPlacement(p.Status, p.Location, assignment, p.Captor, p.Home));+ }+ public void Transition(int id, PopulationStatus status, PopulationLocation? location, PopulationAssignment assignment,+ string? captor = null, PopulationLocation? home = null)+ {+ RequireInitialized(); var p = Get(id);+ Replace(p.WithPlacement(status, location, assignment, captor, home ?? p.Home));+ }+ /// <summary>Explicit history/progress/equipment update contract. No implicit payments, refunds or XP are awarded.</summary>+ public void Replace(PopulationUnit replacement)+ {+ RequireInitialized(); Get(replacement.Id);+ var candidate = new SortedDictionary<int, PopulationUnit>(units) { [replacement.Id] = replacement };+ Validate(candidate); units = candidate;+ }+ /// <summary>A manifest item can arrive only once, including after its population id is lost.</summary>+ public int RegisterArrival(string source, int ordinal, PopulationUnit template)+ {+ RequireInitialized();+ if (string.IsNullOrWhiteSpace(source) || ordinal < 0) throw new ArgumentException("Explicit source and nonnegative ordinal required.");+ PopulationText.ValidateText(source);+ var key = PopulationText.Fields(source, ordinal);+ if (sources.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 next = checked(NextPopulationId + 1);+ var id = NextPopulationId;+ var candidate = new SortedDictionary<int, PopulationUnit>(units) { [id] = template.WithId(id) };+ Validate(candidate);+ units = candidate; sources.Add(key, id); NextPopulationId = next;+ return id;+ }+ public void RegisterCombatLoss(int id, string source)+ {+ RequireInitialized(); Get(id);+ if (string.IsNullOrWhiteSpace(source)) throw new ArgumentException("Explicit combat-loss provenance required.");+ PopulationText.ValidateText(source);+ var candidate = new SortedDictionary<int, PopulationUnit>(units); candidate.Remove(id);+ Validate(candidate); units = candidate; losses.Add(id, source);+ }+ void Validate(SortedDictionary<int, PopulationUnit> candidate)+ {+ var issued = new HashSet<string>(StringComparer.Ordinal);+ foreach (var p in candidate.Values)+ {+ if (p.ReceptionTicks > receptionLimit || !bindings!.HasQualification(p.Qualification))+ throw new ArgumentException("Invalid reception progress or qualification.");+ var tierValid = p.Profession switch {+ CivilianProfession.None => p.Tier == CivilianTier.None && p.WorkXp == 0,+ CivilianProfession.Farmer or CivilianProfession.Pioneer => p.Tier == CivilianTier.Novice || p.Tier == CivilianTier.Trained || p.Tier == CivilianTier.Veteran,+ CivilianProfession.Craftsman => p.Tier == CivilianTier.Apprentice || p.Tier == CivilianTier.Expert,+ _ => false };+ if (!tierValid) throw new ArgumentException("Tier does not belong to the civilian profession.");+ if (p.Home != null) bindings.ValidateLocation(p.Home);+ if (p.Status == PopulationStatus.Captured)+ {+ if (p.Location != null || p.Home == null || p.Captor == null || !bindings.HasCaptor(p.Captor)+ || p.Assignment.Kind != PopulationAssignmentKind.Unassigned)+ throw new ArgumentException("Captives need captor/home context and no local assignment/location.");+ }+ else+ {+ if (p.Location == null || p.Captor != null) throw new ArgumentException("Noncaptives need a location and no captor.");+ bindings.ValidateLocation(p.Location);+ }+ var kind = p.Assignment.Kind;+ var compatible = p.Status switch {+ PopulationStatus.Refugee => kind == PopulationAssignmentKind.Unassigned || kind == PopulationAssignmentKind.Reception,+ PopulationStatus.FreeCivilian => kind == PopulationAssignmentKind.Unassigned || kind == PopulationAssignmentKind.Work || kind == PopulationAssignmentKind.Teaching || kind == PopulationAssignmentKind.Reception,+ PopulationStatus.CivilianInTransit => kind == PopulationAssignmentKind.Travel,+ PopulationStatus.Trainee => kind == PopulationAssignmentKind.Course,+ PopulationStatus.ActiveSoldier => kind == PopulationAssignmentKind.ActiveService,+ PopulationStatus.Captured => kind == PopulationAssignmentKind.Unassigned,+ _ => false };+ if (!compatible) throw new ArgumentException("Status and assignment are incompatible.");+ if (kind != PopulationAssignmentKind.Unassigned)+ {+ var target = bindings.Target(p.Assignment);+ if (target.Region != p.Location!.Region || (kind == PopulationAssignmentKind.Course && p.Assignment.ProgressTicks > target.MaxProgressTicks))+ throw new ArgumentException("Assignment region/progress is inconsistent.");+ if (p.Assignment.TeacherId is int teacherId && (teacherId == p.Id || !candidate.TryGetValue(teacherId, out var teacher)+ || teacher.Assignment.Kind != PopulationAssignmentKind.Teaching || teacher.Assignment.Target != p.Assignment.Target))+ throw new ArgumentException("Course teacher reference must resolve to a teacher of the same course.");+ }+ foreach (var item in new[] { p.Equipment.ToolsId, p.Equipment.MilitaryId })+ if (item != null && !issued.Add(item)) throw new ArgumentException("Issued equipment cannot have two owners.");+ }+ }+ /// <summary>No production caller or content file opts into initialization. Does not invoke old population producers.</summary>+ internal static GameState CreateFixture(Content c, PopulationBindings bindings, IEnumerable<PopulationInventoryRow> rows, int nextPopulationId = 0)+ {+ 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;+ l.bindings = bindings ?? throw new ArgumentNullException(nameof(bindings));+ l.peoplePerUnit = c.PopulationPeoplePerUnit;+ l.receptionLimit = c.RequirePopulationInteger("reception.turns");+ l.NextPopulationId = nextPopulationId;+ // Build all records before validating references: teachers may occur after their pupils in authored order.+ foreach (var row in rows.OrderBy(x => x.Source, StringComparer.Ordinal).ThenBy(x => x.Ordinal))+ {+ var next = checked(l.NextPopulationId + 1);+ l.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;+ }+ internal IEnumerable<string> Canonical()+ {+ yield return PopulationText.Fields("initialized", IsInitialized, "next", NextPopulationId,+ "people-per-unit", peoplePerUnit, "reception-limit", receptionLimit);+ 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);+ foreach (var loss in losses) yield return PopulationText.Fields("loss", loss.Key, loss.Value);+ }+ }+}diff --git a/sim/Statecraft.Sim/PopulationSystem.cs b/sim/Statecraft.Sim/PopulationSystem.csindex 6feed4d27..50d2a15bf 100644--- a/sim/Statecraft.Sim/PopulationSystem.cs+++ b/sim/Statecraft.Sim/PopulationSystem.cs@@ -7,7 +7,11 @@ namespace Statecraft.Sim/// <summary>Jewish population by origin group. Historical mode takes arrivals from the sourced aliyah series.</summary>public static class PopulationSystem{- public static void Init(Content c, GameState s) => s.Population = new Dictionary<string, double>(c.Rules.InitialPopulation);+ public static void Init(Content c, GameState s)+ {+ PopulationLedger.RefuseAggregate(s);+ s.Population = new Dictionary<string, double>(c.Rules.InitialPopulation);+ }/// <summary>Arrivals in [from, to). Each series period is inclusive of both dates and spread evenly by day.</summary>public static Dictionary<string, double> Arrivals(Content c, DateTime from, DateTime to)@@ -29,6 +33,7 @@ namespace Statecraft.Simpublic static void Apply(Content c, GameState s, DateTime to, double yearFraction, List<Cause> why){+ PopulationLedger.RefuseAggregate(s);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))diff --git a/sim/Statecraft.Sim/PopulationUnit.cs b/sim/Statecraft.Sim/PopulationUnit.csnew file mode 100644index 000000000..7af21571a--- /dev/null+++ b/sim/Statecraft.Sim/PopulationUnit.cs@@ -0,0 +1,155 @@+using System;+using System.Globalization;+using System.Linq;++namespace Statecraft.Sim+{+ // R-POP-002: enum ordinals are never serialized. Tokens below are an explicit wire contract.+ public enum PopulationStatus { Refugee, FreeCivilian, CivilianInTransit, Trainee, ActiveSoldier, Captured }+ public enum PopulationAssignmentKind { Unassigned, Work, Travel, Reception, Course, Teaching, ActiveService }+ public enum CivilianProfession { None, Farmer, Pioneer, Craftsman }+ public enum CivilianTier { None, Novice, Trained, Veteran, Apprentice, Expert }++ /// <summary>An exact authored binding, not a region inferred from a hex or a captive's invented prison.</summary>+ public sealed class PopulationLocation+ {+ public string Region { get; }+ public int? Q { get; }+ public int? R { get; }+ public string? FacilityOrPort { get; }+ public PopulationLocation(string region, int? q = null, int? r = null, string? facilityOrPort = null)+ {+ if (string.IsNullOrWhiteSpace(region) || q.HasValue != r.HasValue || (facilityOrPort != null && string.IsNullOrWhiteSpace(facilityOrPort)))+ throw new ArgumentException("A region, a complete optional hex and a nonempty optional facility/port are required.");+ PopulationText.ValidateText(region); PopulationText.ValidateText(facilityOrPort);+ Region = region; Q = q; R = r; FacilityOrPort = facilityOrPort;+ }+ internal string Canonical() => PopulationText.Fields(Region, Q, R, FacilityOrPort);+ }++ public sealed class PopulationAssignment+ {+ public static PopulationAssignment Unassigned { get; } = new PopulationAssignment(PopulationAssignmentKind.Unassigned);+ public PopulationAssignmentKind Kind { get; }+ public string? Target { get; }+ public int ProgressTicks { get; }+ public int? TeacherId { get; }+ public PopulationAssignment(PopulationAssignmentKind kind, string? target = null, int progressTicks = 0, int? teacherId = null)+ {+ PopulationText.Assignment(kind); // Reject unknown enum values even before ledger validation.+ if ((kind == PopulationAssignmentKind.Unassigned) != (target == null) || target == ""+ || progressTicks < 0 || teacherId < 0+ || (kind != PopulationAssignmentKind.Course && (progressTicks != 0 || teacherId != null)))+ throw new ArgumentException("Only a course carries progress/teacher; assigned work needs one target.");+ PopulationText.ValidateText(target);+ Kind = kind; Target = target; ProgressTicks = progressTicks; TeacherId = teacherId;+ }+ internal string Canonical() => PopulationText.Fields(PopulationText.Assignment(Kind), Target, ProgressTicks, TeacherId);+ }++ /// <summary>Issued items are distinct from spare Arms. Payment facts are retained independently of current ownership.+ /// This contract makes no refund, replacement or captive-equipment policy.</summary>+ public sealed class PopulationEquipment+ {+ public static PopulationEquipment None { get; } = new PopulationEquipment();+ public string? ToolsId { get; }+ public bool ToolsPaid { get; }+ public string? MilitaryId { get; }+ public bool MilitaryPaid { get; }+ public PopulationEquipment(string? toolsId = null, bool toolsPaid = false, string? militaryId = null, bool militaryPaid = false)+ {+ if ((toolsId != null && string.IsNullOrWhiteSpace(toolsId)) || (militaryId != null && string.IsNullOrWhiteSpace(militaryId))+ || (toolsId != null && toolsId == militaryId))+ throw new ArgumentException("Issued items need distinct nonempty ids.");+ PopulationText.ValidateText(toolsId); PopulationText.ValidateText(militaryId);+ ToolsId = toolsId; ToolsPaid = toolsPaid; MilitaryId = militaryId; MilitaryPaid = militaryPaid;+ }+ internal string Canonical() => PopulationText.Fields(ToolsId, ToolsPaid, MilitaryId, MilitaryPaid);+ }++ /// <summary>Immutable own-population record. Each record represents one population unit, not a named person.+ /// Cross-record/binding validation occurs atomically at the ledger boundary.</summary>+ public sealed class PopulationUnit+ {+ public int Id { get; }+ public PopulationStatus Status { get; }+ public int ReceptionTicks { get; }+ public PopulationLocation? Location { get; }+ public PopulationAssignment Assignment { get; }+ public CivilianProfession Profession { get; }+ public CivilianTier Tier { get; }+ public int WorkXp { get; }+ public string Qualification { get; }+ public int CombatXp { get; }+ public PopulationEquipment Equipment { get; }+ public string? Captor { get; }+ public PopulationLocation? Home { get; }+ public PopulationUnit(int id, PopulationStatus status, int receptionTicks, PopulationLocation? location,+ PopulationAssignment assignment, CivilianProfession profession, CivilianTier tier, int workXp,+ string qualification, int combatXp, PopulationEquipment equipment, string? captor = null, PopulationLocation? home = null)+ {+ PopulationText.Status(status); PopulationText.Profession(profession); PopulationText.Tier(tier);+ if (id < 0 || receptionTicks < 0 || workXp < 0 || combatXp < 0 || qualification == null)+ throw new ArgumentException("Identity, progress and XP must be nonnegative; qualification must be explicit.");+ PopulationText.ValidateText(qualification); PopulationText.ValidateText(captor);+ Id = id; Status = status; ReceptionTicks = receptionTicks; Location = location;+ Assignment = assignment ?? throw new ArgumentNullException(nameof(assignment));+ Profession = profession; Tier = tier; WorkXp = workXp; Qualification = qualification; CombatXp = combatXp;+ Equipment = equipment ?? throw new ArgumentNullException(nameof(equipment)); Captor = captor; Home = home;+ }+ internal PopulationUnit WithId(int id) => new PopulationUnit(id, Status, ReceptionTicks, Location, Assignment,+ Profession, Tier, WorkXp, Qualification, CombatXp, Equipment, Captor, Home);+ public PopulationUnit WithReception(int ticks) => new PopulationUnit(Id, Status, ticks, Location, Assignment,+ Profession, Tier, WorkXp, Qualification, CombatXp, Equipment, Captor, Home);+ internal PopulationUnit WithPlacement(PopulationStatus status, PopulationLocation? location, PopulationAssignment assignment,+ string? captor, PopulationLocation? home) => new PopulationUnit(Id, status, ReceptionTicks, location, assignment,+ Profession, Tier, WorkXp, Qualification, CombatXp, Equipment, captor, home);+ internal string Canonical() => PopulationText.Fields(Id, PopulationText.Status(Status), ReceptionTicks,+ Location?.Canonical(), Assignment.Canonical(), PopulationText.Profession(Profession), PopulationText.Tier(Tier),+ WorkXp, Qualification, CombatXp, Equipment.Canonical(), Captor, Home?.Canonical());+ }++ internal static class PopulationText+ {+ // Length prefixes distinguish delimiters/null; well-formed UTF-16 ensures UTF-8 hash encoding is lossless.+ internal static void ValidateText(string? value)+ {+ if (value == null) return;+ for (int i = 0; i < value.Length; i++)+ {+ if (char.IsHighSurrogate(value[i]))+ {+ if (++i >= value.Length || !char.IsLowSurrogate(value[i]))+ throw new ArgumentException("Population references require well-formed UTF-16.", nameof(value));+ }+ else if (char.IsLowSurrogate(value[i]))+ throw new ArgumentException("Population references require well-formed UTF-16.", nameof(value));+ }+ }+ internal static string Fields(params object?[] fields) => string.Join("|", fields.Select(Field));+ static string Field(object? field)+ {+ if (field == null) return "-";+ var value = field is bool b ? (b ? "true" : "false") : Convert.ToString(field, CultureInfo.InvariantCulture)!;+ ValidateText(value);+ return value.Length.ToString(CultureInfo.InvariantCulture) + ":" + value;+ }+ internal static string Status(PopulationStatus x) => x switch {+ PopulationStatus.Refugee => "refugee", PopulationStatus.FreeCivilian => "free_civilian",+ PopulationStatus.CivilianInTransit => "civilian_in_transit", PopulationStatus.Trainee => "trainee",+ PopulationStatus.ActiveSoldier => "active_soldier", PopulationStatus.Captured => "captured",+ _ => throw new ArgumentException("Unknown population status.") };+ internal static string Assignment(PopulationAssignmentKind x) => x switch {+ PopulationAssignmentKind.Unassigned => "unassigned", PopulationAssignmentKind.Work => "work",+ PopulationAssignmentKind.Travel => "travel", PopulationAssignmentKind.Reception => "reception",+ PopulationAssignmentKind.Course => "course", PopulationAssignmentKind.Teaching => "teaching",+ PopulationAssignmentKind.ActiveService => "active_service", _ => throw new ArgumentException("Unknown assignment.") };+ internal static string Profession(CivilianProfession x) => x switch {+ CivilianProfession.None => "none", CivilianProfession.Farmer => "farmer", CivilianProfession.Pioneer => "pioneer",+ CivilianProfession.Craftsman => "craftsman", _ => throw new ArgumentException("Unknown profession.") };+ internal static string Tier(CivilianTier x) => x switch {+ CivilianTier.None => "none", CivilianTier.Novice => "novice", CivilianTier.Trained => "trained",+ CivilianTier.Veteran => "veteran", CivilianTier.Apprentice => "apprentice", CivilianTier.Expert => "expert",+ _ => throw new ArgumentException("Unknown civilian tier.") };+ }+}diff --git a/sim/Statecraft.Sim/Prisoners.cs b/sim/Statecraft.Sim/Prisoners.csindex 4299871e0..b040ec60a 100644--- a/sim/Statecraft.Sim/Prisoners.cs+++ b/sim/Statecraft.Sim/Prisoners.cs@@ -34,6 +34,7 @@ namespace Statecraft.Sim/// Combat's surrender, the one way a unit is captured.</summary>internal static string Take(GameState s, Unit u, Unit captor){+ PopulationLedger.RefuseAggregate(s);if (u.Side == Movement.PlayerSide){Add(s.SoldiersHeld, captor.Side, u.Strength);@@ -56,6 +57,7 @@ namespace Statecraft.Sim/// player's soldiers held, borrowing what it lacks (Q-POW-4; R-MONEY-003).</summary>public static void Upkeep(Content c, GameState s, MvpRules r, List<Cause> why){+ PopulationLedger.RefuseAggregate(s);var need = (long)s.PrisonersHeld.Values.Sum() * r.FoodPerPrisonerUnit!.Value;if (need > 0){@@ -80,6 +82,7 @@ namespace Statecraft.Sim/// score (Q-POW-4).</summary>internal static void Return(Content c, GameState s, string front, List<Cause> why){+ PopulationLedger.RefuseAggregate(s);// Only GDD combat creates prisoners and the card waits for them, so this runs only in the GDD loop, which has Mvp.var points = c.RulesAt(s.Date).Mvp!.PointsPerPrisonerUnitReturned!.Value;var ppu = c.RulesAt(s.Date).Mvp!.PeoplePerUnit;diff --git a/sim/Statecraft.Sim/Qualification.cs b/sim/Statecraft.Sim/Qualification.csindex a48f1e987..4a22860fa 100644--- a/sim/Statecraft.Sim/Qualification.cs+++ b/sim/Statecraft.Sim/Qualification.cs@@ -72,6 +72,7 @@ namespace Statecraft.Sim/// untouched, for an unknown city, a count below 1 or more than the city's craftsmen.</summary>public static string? ReturnCraftsmen(Content c, GameState s, string city, int count, List<Cause> why){+ PopulationLedger.RefuseAggregate(s);if (!s.Cities.TryGetValue(city, out var x)) return "There is no such city";if (count < 1) return "Return at least one group";var name = PlayerText.Settlement(c, city);@@ -87,6 +88,7 @@ namespace Statecraft.Sim/// the civilians without work (<see cref="Training.Idle"/>).</summary>public static string? ReassignCraftsmen(Content c, GameState s, string city, int count, List<Cause> why){+ PopulationLedger.RefuseAggregate(s);if (!s.Cities.TryGetValue(city, out var x)) return "There is no such city";if (count < 1) return "Reassign at least one group";var name = PlayerText.Settlement(c, city);@@ -112,6 +114,7 @@ namespace Statecraft.Siminternal static string? Return(Content c, GameState s, int unitId, List<Cause> why){+ PopulationLedger.RefuseAggregate(s);var refused = CheckReturn(s, unitId);if (refused != null) return refused;var u = s.Units[unitId];@@ -131,6 +134,7 @@ namespace Statecraft.Sim/// than its civilians without work.</summary>public static string? ReassignPioneers(Content c, GameState s, string city, string track, int count, List<Cause> why){+ PopulationLedger.RefuseAggregate(s);if (!s.Cities.TryGetValue(city, out var x)) return "There is no such city";var veteran = track == Projects.VeteranType;if (!veteran && track != "halutz") return "There is no such qualification";diff --git a/sim/Statecraft.Sim/Simulation.cs b/sim/Statecraft.Sim/Simulation.csindex 598caa186..029e8a65c 100644--- a/sim/Statecraft.Sim/Simulation.cs+++ b/sim/Statecraft.Sim/Simulation.cs@@ -34,6 +34,8 @@ namespace Statecraft.Simif (state == null) throw new ArgumentNullException(nameof(state));if (commands == null) throw new ArgumentNullException(nameof(commands));if (commands.Any(x => x == null)) throw new ArgumentException("Commands cannot contain null.", nameof(commands));+ // R-POP-002: fixture ledger producers/consumers are not integrated with the aggregate loop.+ PopulationLedger.RefuseAggregate(state);CommandText.Validate(commands);var s = state.Clone();@@ -99,6 +101,8 @@ namespace Statecraft.Simif (state == null) throw new ArgumentNullException(nameof(state));if (commands == null) throw new ArgumentNullException(nameof(commands));if (commands.Any(x => x == null)) throw new ArgumentException("Commands cannot contain null.", nameof(commands));+ // R-POP-002: fixture ledger producers/consumers are not integrated with the aggregate loop.+ PopulationLedger.RefuseAggregate(state);CommandText.Validate(commands);var s = state.Clone();if (s.GameOver == null) RunOrders(c, s, commands, new Dictionary<int, int>(), new Dictionary<int, (int Q, int R)>(), new List<Cause>(), new List<Rejection>());@@ -113,6 +117,8 @@ namespace Statecraft.Simif (state == null) throw new ArgumentNullException(nameof(state));if (commands == null) throw new ArgumentNullException(nameof(commands));if (commands.Any(x => x == null)) throw new ArgumentException("Commands cannot contain null.", nameof(commands));+ // R-POP-002: fixture ledger producers/consumers are not integrated with the aggregate loop.+ PopulationLedger.RefuseAggregate(state);CommandText.Validate(commands);var s = state.Clone();var why = new List<Cause>(); var rejected = new List<Rejection>(); var spent = new Dictionary<int, int>();diff --git a/sim/Statecraft.Sim/StartingForces.cs b/sim/Statecraft.Sim/StartingForces.csindex 414dcf360..ebd1f361c 100644--- a/sim/Statecraft.Sim/StartingForces.cs+++ b/sim/Statecraft.Sim/StartingForces.cs@@ -129,6 +129,7 @@ namespace Statecraft.Sim/// (R-UNIT-009).</summary>public static void Init(Content c, GameState s){+ PopulationLedger.RefuseAggregate(s);foreach (var f in c.StartingForces){var id = s.NextId++;@@ -142,6 +143,7 @@ namespace Statecraft.Sim/// limit and what else stands on the hex.</summary>public static void Arrive(Content c, GameState s, DateTime next){+ PopulationLedger.RefuseAggregate(s);for (int i = 0; i < c.StartingForces.Count; i++){var f = c.StartingForces[i];diff --git a/sim/Statecraft.Sim/Training.cs b/sim/Statecraft.Sim/Training.csindex 5c5910c15..cf9705547 100644--- a/sim/Statecraft.Sim/Training.cs+++ b/sim/Statecraft.Sim/Training.cs@@ -88,6 +88,7 @@ namespace Statecraft.Sim/// its strength and the replacements already training for it.</summary>public static string? Reinforce(Content c, GameState s, int unit, string city, int count, List<Cause> why){+ PopulationLedger.RefuseAggregate(s);if (!s.Units.TryGetValue(unit, out var u)) return "There is no such unit";if (u.Side == "") return "Only a military unit takes that order";if (u.Side != Movement.PlayerSide) return "That unit is not yours";@@ -111,6 +112,7 @@ namespace Statecraft.Simstatic string? Start(Content c, GameState s, string city, string track, int count, List<Cause> why, int? unit){+ PopulationLedger.RefuseAggregate(s);if (!s.Cities.TryGetValue(city, out var x)) return "There is no such city";var type = c.UnitTypes.FirstOrDefault(t => t.Id == track && t.Facility != "");if (type == null) return "There is no such training";@@ -154,6 +156,7 @@ namespace Statecraft.Sim/// the legacy loop.</summary>public static string? Cancel(Content c, GameState s, int cohort, List<Cause> why){+ PopulationLedger.RefuseAggregate(s);if (!s.Cohorts.TryGetValue(cohort, out var k)) return "There is no such training group";var x = s.Cities[k.City];s.Cities[k.City] = x.WithCounts(x.Civilians + k.Count, x.Employed, x.Refugees);@@ -175,6 +178,7 @@ namespace Statecraft.Sim/// of its type with its count as strength (R-UNIT-003, R-UNIT-008), craftsmen join the city's count, and halutzim become one unit per group at its hex.</summary>public static void Progress(Content c, GameState s, List<Cause> why){+ PopulationLedger.RefuseAggregate(s);foreach (var k in s.Cohorts.Values.ToList()){// R-TRAIN-004 (owner, 23 October 2026, "Default"): replacements whose unit is gone (destroyed, captured, sentdiff --git a/sim/Statecraft.Sim/TurnResolver.cs b/sim/Statecraft.Sim/TurnResolver.csindex 26bf943a5..891f1786f 100644--- a/sim/Statecraft.Sim/TurnResolver.cs+++ b/sim/Statecraft.Sim/TurnResolver.cs@@ -13,6 +13,7 @@ namespace Statecraft.Sim/// of a year long).</summary>public static void Resolve(Content c, GameState s, DateTime next, double yearFraction, List<Cause> why){+ PopulationLedger.RefuseAggregate(s);if (!c.IsGdd) return;var r = c.RulesAt(s.Date).Mvp!; // the loader requires it in the GDD loopEnemyAI.Order(c, s, why, next); // 1. enemy orders, in ascending unit id (R-ENEMY-001)