A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Sim: gdd-0.3 housing fixtures count overflow after arrivals (Fixes #2517) (#2629)
Beric47126233f81
diff --git a/changelog.d/2517-housing-overflow-after-arrivals.md b/changelog.d/2517-housing-overflow-after-arrivals.mdnew file mode 100644index 000000000..9643e4e4f--- /dev/null+++ b/changelog.d/2517-housing-overflow-after-arrivals.md@@ -0,0 +1,5 @@+### Fixed+- Under the gdd-0.3 rules only, the detached housing test fixtures now count housing overflow from the housed residents+ after the step's arrivals, as the owner ruled (27M-15), not from the residents before them (Fixes #2517). The synthetic+ month context drops its unused pre-arrival resident list. The live housing step already counted after arrivals, so+ the game is unchanged.diff --git a/docs/rules/mvp.md b/docs/rules/mvp.mdindex 9ed7aa23f..bf6550f9a 100644--- a/docs/rules/mvp.md+++ b/docs/rules/mvp.md@@ -136,11 +136,11 @@ For R-HOUSE-001, the preceding legacy/gdd-0.1 wording remains unchanged. The inaR-HOUSE-002: A city's overflow is `max(0, housed - housing_capacity)`, one capacity point housing one population unit (D-D1, Q-HOUSE-1, owner, 15 October 2026). On the housing step, after R-CITY-004 and before Social cohesion (D-A6), a city with overflow loses `overflow_condition_loss * overflow / housed` of its condition, never below 0; a city without overflow keeps its condition. `overflow_condition_loss` is 0.15, a design value. The loader requires both values, from 0 to 1. Overflow reaches Social cohesion through R-HOUSE-004 (a lower condition lowers the base of the national `housing` indicator) and the existing `homes_lift_morale` link (k 0.15) from `housing` into `morale`, which is Social cohesion (R-NAT-001); there is no direct overflow term (Q-HOUSE-1, decided by the owner 15 October 2026, plan:165 of `docs/superpowers/plans/2026-10-15-gdd-phase-3.md`: cohesion follows through the existing `housing` to `morale` link, "so it needs no number of its own"; the cohesion half was built after #728, merged as #857, owner 17 October 2026).-For R-HOUSE-002, inactive gdd-0.3 synthetic arithmetic prices the surcharge as `SurchargeResidents * max(0, money_threshold - ConditionBefore) * money_slope`, then subtracts overflow and unpaid-upkeep losses and clamps condition. Overflow loss is `(overflow_deterioration / 100) * max(0, PreArrivalResidents - Capacity) / PreArrivalResidents`; unpaid loss is `(max_deterioration / 100) * (UpkeepDue - UpkeepPaid) / UpkeepDue`. Zero pre-arrival residents or zero upkeep due gives zero for the respective loss. The returned cohesion contribution is `max_cohesion_loss * (CohesionResidents / OwnPopulation) * max(0, (cohesion_threshold - ConditionAfter) / cohesion_threshold)`, zero with no own population. It is displayed points, not an indicator write or a national summation (`sim/Statecraft.Sim/Gdd03HousingFormula.cs:65-85@7ec122145`; worked-number, distinct-count, post-deterioration and zero-denominator fixtures in `sim/Statecraft.Sim.Tests/Gdd03HousingFormulaTests.cs:16-75@7ec122145`). Source: `docs/gdd/cities.md:29-35@605277dfa511dc512562ececeb273b8393b21d35`; #1703 says, "Price the surcharge from pre-deterioration condition, then deteriorate once, then apply cohesion once." Under `gdd-0.3` this arithmetic is now live, per city, as R-HOUSE-005 (#1703); under `gdd-0.1` and legacy the preceding active rule (0.15) is unchanged. Repairs are R-HOUSE-006 under `gdd-0.3` (#1700); monthly snapshot timing (#1716) remains pending.+For R-HOUSE-002, inactive gdd-0.3 synthetic arithmetic prices the surcharge as `SurchargeResidents * max(0, money_threshold - ConditionBefore) * money_slope`, then subtracts overflow and unpaid-upkeep losses and clamps condition. Overflow loss is `(overflow_deterioration / 100) * max(0, Residents - Capacity) / Residents`, with `Residents` the housed residents after the step's arrivals become civilians (27M-15, owner-approved 1 November 2026: "After that step's arrivals become civilians (R-CITY-004)."; #2517); unpaid loss is `(max_deterioration / 100) * (UpkeepDue - UpkeepPaid) / UpkeepDue`. Zero residents or zero upkeep due gives zero for the respective loss. The returned cohesion contribution is `max_cohesion_loss * (CohesionResidents / OwnPopulation) * max(0, (cohesion_threshold - ConditionAfter) / cohesion_threshold)`, zero with no own population. It is displayed points, not an indicator write or a national summation (`sim/Statecraft.Sim/Gdd03HousingFormula.cs:66-88@25938871c`; the after-arrivals, worked-number, distinct-count, post-deterioration and zero-denominator fixtures in `sim/Statecraft.Sim.Tests/Gdd03HousingFormulaTests.cs:77-86,112-172@25938871c`). Source: `docs/gdd/cities.md:29-35@605277dfa511dc512562ececeb273b8393b21d35`; #1703 says, "Price the surcharge from pre-deterioration condition, then deteriorate once, then apply cohesion once." Under `gdd-0.3` this arithmetic is now live, per city, as R-HOUSE-005 (#1703); under `gdd-0.1` and legacy the preceding active rule (0.15) is unchanged. Repairs are R-HOUSE-006 under `gdd-0.3` (#1700); monthly snapshot timing (#1716) remains pending.R-HOUSE-003: The people who take a city's housing (`housed`) are its civilians, its craftsmen, its recruits and its groups in training, a halutz group included until it becomes a movable unit. Halutz units do not (Q-HOUSE-5, owner, 15 October 2026). Refugees wait for housing and are not in it.-For R-HOUSE-003, the inactive gdd-0.3 helper takes independently supplied surcharge, pre-arrival and cohesion resident counts plus own population; it selects no residents and substitutes none of those counts for another (`sim/Statecraft.Sim/Gdd03HousingFormula.cs:68-85@7ec122145`, `:107-125`; `sim/Statecraft.Sim.Tests/Gdd03HousingFormulaTests.cs:39-47@7ec122145`). Negative counts, capacity or upkeep, overpayment, cohesion residents above total own population, and condition outside 0..1 are refused. A zero-population cohesion input therefore requires zero cohesion residents (`docs/gdd/cities.md:27,31@605277dfa511dc512562ececeb273b8393b21d35`). Source: `docs/gdd/cities.md:25@605277dfa511dc512562ececeb273b8393b21d35`, "A civilian resident without dedicated reception, teacher or military-training housing uses ordinary housing."; `docs/gdd/loop-switch.md:33` at that revision says, "use pre-arrival residents for overcrowding deterioration". Those are producer requirements, not resident-selection behavior implemented here. Live status selection (#1689), regions/approved housing locations (#1691; #1690 closed on 2 November 2026, its post-MVP regional pools moved to #2233) and which residents to count (#1668) remain pending under the #1703 status comment, which says, "Regional housing settlement is not yet implemented". The preceding legacy/gdd-0.1 resident set remains unchanged. Under `gdd-0.3` (#1703) a city's Israeli formations are not housed: `housed` is its civilians, craftsmen, recruits and groups in training, so the formations whose home it is no longer count toward its overflow, R-HOUSE-004's weights or R-OBJ-004 (27M-18, owner-approved 1 November 2026: "Housed = civilians, craftsmen, recruits and groups in training. Refugees and pioneer units are not housed."; confirmed by the owner, 3 November 2026: "Yes, formations not housed (Recommended)"). `gdd-0.1` keeps counting them (Q-HOUSE-5; `Cities.Housed`).+For R-HOUSE-003, the inactive gdd-0.3 helper takes independently supplied surcharge, overflow and cohesion resident counts plus own population, the overflow count taken after the step's arrivals (27M-15); it selects no residents and substitutes none of those counts for another (`sim/Statecraft.Sim/Gdd03HousingFormula.cs:66-88@25938871c`, `:130-150`; `sim/Statecraft.Sim.Tests/Gdd03HousingFormulaTests.cs:77-86,135-144@25938871c`). Negative counts, capacity or upkeep, overpayment, cohesion residents above total own population, and condition outside 0..1 are refused. A zero-population cohesion input therefore requires zero cohesion residents (`docs/gdd/cities.md:27,31@605277dfa511dc512562ececeb273b8393b21d35`). Source: `docs/gdd/cities.md:25@605277dfa511dc512562ececeb273b8393b21d35`, "A civilian resident without dedicated reception, teacher or military-training housing uses ordinary housing."; `docs/gdd/loop-switch.md:33` at that revision said, "use pre-arrival residents for overcrowding deterioration", which 27M-15 superseded: housing effects count residents after the step's arrivals become civilians (owner-approved 1 November 2026; owner, 2 November 2026: "After housing arrivals (Recommended)"), so `Gdd03SyntheticMonthContext` no longer carries a pre-arrival resident list (#2517). Those are producer requirements, not resident-selection behavior implemented here. Live status selection (#1689), regions/approved housing locations (#1691; #1690 closed on 2 November 2026, its post-MVP regional pools moved to #2233) and which residents to count (#1668) remain pending under the #1703 status comment, which says, "Regional housing settlement is not yet implemented". The preceding legacy/gdd-0.1 resident set remains unchanged. Under `gdd-0.3` (#1703) a city's Israeli formations are not housed: `housed` is its civilians, craftsmen, recruits and groups in training, so the formations whose home it is no longer count toward its overflow, R-HOUSE-004's weights or R-OBJ-004 (27M-18, owner-approved 1 November 2026: "Housed = civilians, craftsmen, recruits and groups in training. Refugees and pioneer units are not housed."; confirmed by the owner, 3 November 2026: "Yes, formations not housed (Recommended)"). `gdd-0.1` keeps counting them (Q-HOUSE-5; `Cities.Housed`).R-HOUSE-004: In the GDD loop the base of the national `housing` indicator is the people-weighted mean of the cities' housing condition, each city weighed by its housed people (R-HOUSE-003): `sum(condition * housed) / sum(housed)`. Policy effects, map actions and events still act on top, as on any indicator. Decided (owner, 17 Oct 2026, option (a) of Q-PR3-A, relayed on [#855 at 06:33Z](https://github.com/eyalgolan/statecraft-israel/pull/855#issuecomment-6230731177)): the national housing base is the people-weighted mean of city condition, with policy, map actions and events still applied on top. When no city houses anybody the mean is undefined, and the base is `model.yaml`'s. Capacity reaches the level through overflow and condition (R-HOUSE-002).diff --git a/sim/Statecraft.Sim.Tests/Gdd03CraftCourseFixtureTests.cs b/sim/Statecraft.Sim.Tests/Gdd03CraftCourseFixtureTests.csindex 5f40d1179..25d41e14b 100644--- a/sim/Statecraft.Sim.Tests/Gdd03CraftCourseFixtureTests.cs+++ b/sim/Statecraft.Sim.Tests/Gdd03CraftCourseFixtureTests.cs@@ -62,7 +62,7 @@ public class Gdd03CraftCourseFixtureTestsstatic Gdd03SyntheticMonthContext Month(GameState s, int ordinal, bool coursesAvailable = true)=> Gdd03SyntheticMonthContext.CreateSynthetic(SaveGame.Gdd03Ruleset, ordinal, s.PopulationLedger.Units,Facilities.Select(f => new Gdd03SyntheticFacilitySnapshot(f, coursesAvailable || !f.Contains("craft", StringComparison.Ordinal), 1)),- Array.Empty<int>(), Array.Empty<Gdd03SyntheticHousingSnapshot>(), Array.Empty<Gdd03SyntheticPendingEntry>());+ Array.Empty<Gdd03SyntheticHousingSnapshot>(), Array.Empty<Gdd03SyntheticPendingEntry>());const string GraduationMonth = Gdd03TrainingCentreFixture.GraduationMonthReason;const string CourseAtOpening = Gdd03CraftCourseFixture.CourseAtOpeningReason;diff --git a/sim/Statecraft.Sim.Tests/Gdd03CraftWorkFixtureTests.cs b/sim/Statecraft.Sim.Tests/Gdd03CraftWorkFixtureTests.csindex 729679e3c..964a4ad35 100644--- a/sim/Statecraft.Sim.Tests/Gdd03CraftWorkFixtureTests.cs+++ b/sim/Statecraft.Sim.Tests/Gdd03CraftWorkFixtureTests.cs@@ -43,7 +43,7 @@ public class Gdd03CraftWorkFixtureTestsstatic Gdd03SyntheticMonthContext Month(GameState s, int ordinal) => Gdd03SyntheticMonthContext.CreateSynthetic(SaveGame.Gdd03Ruleset, ordinal, s.PopulationLedger.Units,new[] { Industry, Workshop, Builder, Field, Course, "teacher" }.Select(f => new Gdd03SyntheticFacilitySnapshot(f, true, 9)),- Array.Empty<int>(), Array.Empty<Gdd03SyntheticHousingSnapshot>(), Array.Empty<Gdd03SyntheticPendingEntry>());+ Array.Empty<Gdd03SyntheticHousingSnapshot>(), Array.Empty<Gdd03SyntheticPendingEntry>());// R-CRAFT-002: an apprentice at 35 Industry or workshop months reaches 36 and turns expert. That month's output is// quoted at the snapshot's apprentice tier (2x); the next month's snapshot holds an expert (3x). Id, assignment,diff --git a/sim/Statecraft.Sim.Tests/Gdd03FieldFixtureTests.cs b/sim/Statecraft.Sim.Tests/Gdd03FieldFixtureTests.csindex efd3b9d00..bf8d2da6c 100644--- a/sim/Statecraft.Sim.Tests/Gdd03FieldFixtureTests.cs+++ b/sim/Statecraft.Sim.Tests/Gdd03FieldFixtureTests.cs@@ -36,7 +36,7 @@ public class Gdd03FieldFixtureTestsstatic Gdd03SyntheticMonthContext MonthAt(Content c, GameState s, int ordinal, params string[] notHeldAtFreeze) =>Gdd03SyntheticMonthContext.CreateSynthetic(SaveGame.Gdd03Ruleset, ordinal, s.PopulationLedger.Units,Gdd03FieldFixture.Fields(c).Select(f => new Gdd03SyntheticFacilitySnapshot(f.Id, !notHeldAtFreeze.Contains(f.Id), 1)),- Array.Empty<int>(), Array.Empty<Gdd03SyntheticHousingSnapshot>(), Array.Empty<Gdd03SyntheticPendingEntry>());+ Array.Empty<Gdd03SyntheticHousingSnapshot>(), Array.Empty<Gdd03SyntheticPendingEntry>());static HashSet<string> AllHeld(Content c) => Gdd03FieldFixture.Fields(c).Select(f => f.Id).ToHashSet(StringComparer.Ordinal);static void Refused(GameState s, Action a, string? message = null){@@ -239,7 +239,7 @@ public class Gdd03FieldFixtureTestsGdd03SyntheticMonthContext.CreateSynthetic(SaveGame.Gdd03Ruleset, 0, s.PopulationLedger.Units,Gdd03FieldFixture.Fields(c).Select(f => new Gdd03SyntheticFacilitySnapshot(f.Id, !notHeldAtFreeze.Contains(f.Id), 1)).Concat(new[] { new Gdd03SyntheticFacilitySnapshot(industry, true, 1), new Gdd03SyntheticFacilitySnapshot(Course, true, 3) }),- Array.Empty<int>(), Array.Empty<Gdd03SyntheticHousingSnapshot>(), Array.Empty<Gdd03SyntheticPendingEntry>());+ Array.Empty<Gdd03SyntheticHousingSnapshot>(), Array.Empty<Gdd03SyntheticPendingEntry>());// R-VET-001, R-VET-002 (#2468): one worked, still-held field month gives its farmer exactly one work XP. A field lost// after the freeze, one not held at the freeze, a farmer moved to another field after the freeze (the wrong target), an@@ -384,7 +384,7 @@ public class Gdd03FieldFixtureTestsAssert.Throws<InvalidOperationException>(() => new Gdd03FieldFixture(c, s, Array.Empty<Gdd03FixtureSlot>()));Assert.Throws<InvalidOperationException>(() => Gdd03FieldFixture.ResolveWorkXp(c, s,Gdd03SyntheticMonthContext.CreateSynthetic(SaveGame.Gdd03Ruleset, 0, Array.Empty<PopulationUnit>(),- Array.Empty<Gdd03SyntheticFacilitySnapshot>(), Array.Empty<int>(), Array.Empty<Gdd03SyntheticHousingSnapshot>(),+ Array.Empty<Gdd03SyntheticFacilitySnapshot>(), Array.Empty<Gdd03SyntheticHousingSnapshot>(),Array.Empty<Gdd03SyntheticPendingEntry>()), new HashSet<string>()));Assert.Equal(before, s.Describe());}diff --git a/sim/Statecraft.Sim.Tests/Gdd03HousingFormulaTests.cs b/sim/Statecraft.Sim.Tests/Gdd03HousingFormulaTests.csindex add96b9fd..bc6b4b6c6 100644--- a/sim/Statecraft.Sim.Tests/Gdd03HousingFormulaTests.cs+++ b/sim/Statecraft.Sim.Tests/Gdd03HousingFormulaTests.cs@@ -7,10 +7,10 @@ public class Gdd03HousingFormulaTestsstatic Gdd03HousingFormula Formula() => Gdd03HousingFormula.FromCatalogue(ContentLoader.Load(RealContentTests.ContentRoot()).Gdd03Balance ?? throw new InvalidOperationException("GDD 0.3 catalogue required"));- static Gdd03HousingInput Input(int surcharge = 10, int beforeArrival = 10,+ static Gdd03HousingInput Input(int surcharge = 10, int residents = 10,int cohesion = 10, int population = 20, decimal capacity = 5m,decimal condition = 0.40m, decimal due = 4m, decimal paid = 2m) =>- new Gdd03HousingInput(surcharge, beforeArrival, cohesion, population,+ new Gdd03HousingInput(surcharge, residents, cohesion, population,capacity, condition, due, paid);// Each fixture changes one coefficient before the existing reader validates/snapshots it.@@ -68,12 +68,23 @@ public class Gdd03HousingFormulaTestsconst decimal overflowPp = 12.5m;var f = FormulaWithSyntheticScalar("housing.overflow_deterioration", overflowPp);var expectedLoss = (overflowPp / 100m) * Math.Max(0m, 20m - 8m) / 20m;- var r = f.Evaluate(Input(beforeArrival: 20, capacity: 8m,+ var r = f.Evaluate(Input(residents: 20, capacity: 8m,condition: 0.40m, due: 4m, paid: 4m));Assert.Equal(expectedLoss, r.OverflowConditionLoss);Assert.Equal(0.40m - expectedLoss, r.ConditionAfter);}+ [Fact] public void AnArrivalThisStepCountsTowardOverflow()+ {+ // R-HOUSE-005, 27M-15 (#2517): R is counted after the step's arrivals become civilians. 10 housed people at+ // capacity 10 overflow by nothing; 2 arrivals this step make R 12, and those 2 overflow.+ var f = Formula();+ Assert.Equal(0m, f.Evaluate(new Gdd03HousingInput(10, residents: 10, 10, 20, 10m, 0.40m, 0m, 0m)).OverflowConditionLoss);+ var r = f.Evaluate(new Gdd03HousingInput(12, residents: 12, 12, 20, 10m, 0.40m, 0m, 0m));+ Assert.Equal((5m / 100m) * 2m / 12m, r.OverflowConditionLoss); // overflow_deterioration 5 pp (owner, 2 November 2026)+ Assert.Equal(0.40m - (5m / 100m) * 2m / 12m, r.ConditionAfter);+ }+[Fact] public void SyntheticUnpaidRateComesFromSuppliedCatalogue(){// R-HOUSE-002: catches unpaidPp replaced by the shipped literal 10m.@@ -124,7 +135,7 @@ public class Gdd03HousingFormulaTests[Fact] public void ExplicitBoundaryCountsAreNeverSubstitutedForEachOther(){// R-HOUSE-002, R-HOUSE-003: does not select residents or settle timing.- var r = Formula().Evaluate(Input(surcharge: 10, beforeArrival: 20,+ var r = Formula().Evaluate(Input(surcharge: 10, residents: 20,cohesion: 5, population: 20, capacity: 15m, condition: 0.125m, due: 0m, paid: 0m));Assert.Equal(0.375m, r.SurchargeMoney); // 10 x 0.375 x money_slope 0.1 (#1703; was 3.75 at slope 1)Assert.Equal(0.0125m, r.OverflowConditionLoss);@@ -140,7 +151,7 @@ public class Gdd03HousingFormulaTestsAssert.Equal(0.235m, r.ConditionAfter);Assert.Equal(0.12m, r.CohesionLossPoints);var a = f.Evaluate(Input(condition: 0.125m, capacity: 10m, due: 0m, paid: 0m));- var b = f.Evaluate(Input(surcharge: 5, beforeArrival: 5, cohesion: 5,+ var b = f.Evaluate(Input(surcharge: 5, residents: 5, cohesion: 5,condition: 0m, capacity: 5m, due: 0m, paid: 0m));Assert.Equal(1m, a.CohesionLossPoints + b.CohesionLossPoints);}@@ -148,7 +159,7 @@ public class Gdd03HousingFormulaTests[Fact] public void ZeroDenominatorsAndFullPaymentHaveNoLoss(){// R-HOUSE-002- var r = Formula().Evaluate(Input(surcharge: 0, beforeArrival: 0, cohesion: 0,+ var r = Formula().Evaluate(Input(surcharge: 0, residents: 0, cohesion: 0,population: 0, capacity: 0m, condition: 0m, due: 0m, paid: 0m));Assert.Equal(0m, r.OverflowConditionLoss);Assert.Equal(0m, r.UnpaidConditionLoss);@@ -156,7 +167,7 @@ public class Gdd03HousingFormulaTestsAssert.Equal(0m, r.SurchargeMoney);Assert.Equal(0m, Formula().Evaluate(Input(due: 4m, paid: 4m)).UnpaidConditionLoss);Assert.Equal(0.075m, Formula().Evaluate(Input(due: 4m, paid: 1m)).UnpaidConditionLoss);- Assert.Equal(0m, Formula().Evaluate(Input(beforeArrival: 0, cohesion: 0, population: 0,+ Assert.Equal(0m, Formula().Evaluate(Input(residents: 0, cohesion: 0, population: 0,condition: 0m)).CohesionLossPoints);}@@ -184,7 +195,7 @@ public class Gdd03HousingFormulaTests[Fact] public void InvalidExplicitInputsAreRejectedWithoutState(){var f = Formula();- foreach (var input in new[] { Input(surcharge: -1), Input(beforeArrival: -1),+ foreach (var input in new[] { Input(surcharge: -1), Input(residents: -1),Input(cohesion: -1), Input(population: -1), Input(capacity: -1m),Input(condition: -0.01m), Input(condition: 1.01m), Input(due: -1m),Input(paid: -1m), Input(paid: 5m), Input(due: 0m, paid: 1m) })diff --git a/sim/Statecraft.Sim.Tests/Gdd03SyntheticMonthContextTests.cs b/sim/Statecraft.Sim.Tests/Gdd03SyntheticMonthContextTests.csindex 4f51fd291..00b6aceff 100644--- a/sim/Statecraft.Sim.Tests/Gdd03SyntheticMonthContextTests.cs+++ b/sim/Statecraft.Sim.Tests/Gdd03SyntheticMonthContextTests.cs@@ -16,11 +16,11 @@ public class Gdd03SyntheticMonthContextTestsstatic Gdd03SyntheticMonthContext Context(IEnumerable<PopulationUnit>? people = null,IEnumerable<Gdd03SyntheticFacilitySnapshot>? facilities = null,- IEnumerable<int>? residents = null, IEnumerable<Gdd03SyntheticPendingEntry>? entries = null,+ IEnumerable<Gdd03SyntheticPendingEntry>? entries = null,string identity = SaveGame.Gdd03Ruleset, int month = 0) =>Gdd03SyntheticMonthContext.CreateSynthetic(identity, month,people ?? Array.Empty<PopulationUnit>(), facilities ?? Array.Empty<Gdd03SyntheticFacilitySnapshot>(),- residents ?? Array.Empty<int>(), Array.Empty<Gdd03SyntheticHousingSnapshot>(),+ Array.Empty<Gdd03SyntheticHousingSnapshot>(),entries ?? Array.Empty<Gdd03SyntheticPendingEntry>());// RED-FIRST 1: R-LOOP-001/002. No old-identity contract and no implicit identity fallback.@@ -33,17 +33,15 @@ public class Gdd03SyntheticMonthContextTestsAssert.Throws<ArgumentException>(() => Context(identity: identity));// RED-FIRST 2: R-LOOP-001/002; GDD loop-switch:17,24-28.- [Fact] public void RejectsDuplicatePeopleAndUnresolvedAssignmentsOrResidents()+ [Fact] public void RejectsDuplicatePeopleAndUnresolvedAssignments(){var p = Person(7, PopulationAssignmentKind.Work, "synthetic-work");Assert.Throws<ArgumentException>(() => Context(new[] { p, p }, new[] { Facility() }));Assert.Throws<ArgumentException>(() => Context(new[] { p }));- Assert.Throws<ArgumentException>(() => Context(residents: new[] { 7 }));- Assert.Throws<ArgumentException>(() => Context(new[] { p }, new[] { Facility() }, new[] { 7, 7 }));Assert.Throws<ArgumentException>(() => Context(facilities: new[] { Facility(), Facility() }));Assert.Throws<ArgumentNullException>(() => Gdd03SyntheticMonthContext.CreateSynthetic(SaveGame.Gdd03Ruleset, 0, null!, Array.Empty<Gdd03SyntheticFacilitySnapshot>(),- Array.Empty<int>(), Array.Empty<Gdd03SyntheticHousingSnapshot>(), Array.Empty<Gdd03SyntheticPendingEntry>()));+ Array.Empty<Gdd03SyntheticHousingSnapshot>(), Array.Empty<Gdd03SyntheticPendingEntry>()));Assert.Throws<ArgumentException>(() => Context(new PopulationUnit[] { null! }));Assert.Throws<ArgumentException>(() => Context(month: -1));Assert.Throws<ArgumentException>(() => new Gdd03SyntheticFacilitySnapshot(" ", true, 2));@@ -56,11 +54,12 @@ public class Gdd03SyntheticMonthContextTestsnew Gdd03SyntheticPendingEntry("synthetic-key", "synthetic-other-unit", -3m) }));}- // Synthetic boundary only: these statuses may be opening records but cannot be pre-arrival residents.+ // Synthetic boundary only: these statuses may be opening records but are eligible for nothing. The context holds no+ // residents: housing effects count them after the step's arrivals (27M-15, #2517).[Theory][InlineData(PopulationStatus.Captured)][InlineData(PopulationStatus.CivilianInTransit)]- public void CaptiveOrTransitOpeningPeopleCannotBePreArrivalResidents(PopulationStatus status)+ public void CaptiveOrTransitOpeningPeopleAreEligibleForNothing(PopulationStatus status){var assignment = status == PopulationStatus.CivilianInTransit? new PopulationAssignment(PopulationAssignmentKind.Travel, "synthetic-route")@@ -69,9 +68,7 @@ public class Gdd03SyntheticMonthContextTestsCivilianProfession.None, CivilianTier.None, 0, "", 0, PopulationEquipment.None);var control = Context(new[] { person });Assert.Equal(new[] { 4 }, control.OpeningPeople.Select(p => p.Id));- Assert.Empty(control.PreArrivalResidentIds);Assert.Empty(control.WorkEligibleIds);- Assert.Throws<ArgumentException>(() => Context(new[] { person }, residents: new[] { 4 }));}// RED-FIRST: GDD loop-switch:17,24. Structural references do not replace owner validation.@@ -85,14 +82,13 @@ public class Gdd03SyntheticMonthContextTestsCivilianProfession.None, CivilianTier.None, 0, "", 0, PopulationEquipment.None);Assert.Throws<ArgumentException>(() => Context(new[] { invalid }, new[] { Facility() }));Assert.Throws<ArgumentException>(() => Context(new[] { Pupil(99) }, new[] { Facility("synthetic-course") }));- Assert.Throws<ArgumentException>(() => Context(new[] { Person(1, PopulationAssignmentKind.Unassigned) }, residents: new[] { -1 }));var teacher = Person(2, PopulationAssignmentKind.Teaching, "synthetic-course");var valid = Context(new[] { teacher, Pupil(2) }, new[] { Facility("synthetic-course") });Assert.Equal(new[] { 7 }, valid.CourseEligibleIds);Assert.Empty(valid.WorkEligibleIds);Assert.Throws<ArgumentException>(() => Gdd03SyntheticMonthContext.CreateSynthetic(SaveGame.Gdd03Ruleset, 0, Array.Empty<PopulationUnit>(), Array.Empty<Gdd03SyntheticFacilitySnapshot>(),- Array.Empty<int>(), new[] { new Gdd03SyntheticHousingSnapshot("synthetic-house", 0m),+ new[] { new Gdd03SyntheticHousingSnapshot("synthetic-house", 0m),new Gdd03SyntheticHousingSnapshot("synthetic-house", 1m) }, Array.Empty<Gdd03SyntheticPendingEntry>()));var zero = new Gdd03SyntheticFacilitySnapshot("synthetic-work", true, 0);Assert.Empty(Context(new[] { Person(1, PopulationAssignmentKind.Work, zero.Id) }, new[] { zero }).WorkEligibleIds);@@ -108,13 +104,12 @@ public class Gdd03SyntheticMonthContextTestsPerson(8, PopulationAssignmentKind.Work, "synthetic-closed") };var facilities = new List<Gdd03SyntheticFacilitySnapshot> {Facility(), Facility("synthetic-course"), Facility("synthetic-reception"), Facility("synthetic-closed", false) };- var context = Context(people, facilities, new[] { 9 });+ var context = Context(people, facilities);people.Clear(); facilities.Clear();Assert.Equal(new[] { 3, 5, 8, 9 }, context.OpeningPeople.Select(p => p.Id));Assert.Equal(new[] { 9 }, context.WorkEligibleIds);Assert.Equal(new[] { 3 }, context.CourseEligibleIds);Assert.Equal(new[] { 5 }, context.ReceptionEligibleIds);- Assert.Equal(new[] { 9 }, context.PreArrivalResidentIds);Assert.Throws<NotSupportedException>(() => ((IList<int>)context.WorkEligibleIds).Add(11));Assert.Throws<NotSupportedException>(() => ((IList<PopulationUnit>)context.OpeningPeople).Clear());Assert.Equal(PopulationAssignmentKind.Course, context.OpeningPeople[0].Assignment.Kind);@@ -138,22 +133,19 @@ public class Gdd03SyntheticMonthContextTestsvar keys = new[] { "synthetic-é", "synthetic-i", "synthetic-I", "synthetic_!", "synthetic-!" };var expectedKeys = new[] { "synthetic-!", "synthetic-I", "synthetic-i", "synthetic-é", "synthetic_!" };var facilities = keys.Select(id => Facility(id)).ToList();- var residents = new List<int> { 20, 2 };var housing = keys.Select(id => new Gdd03SyntheticHousingSnapshot(id, id == "synthetic-é" ? 0.4m : 0.7m)).ToList();var pending = keys.Select(id => new Gdd03SyntheticPendingEntry(id, "synthetic-unit", id == "synthetic-é" ? -1.25m : 2m)).ToList();Gdd03SyntheticMonthContext Make(bool reverse) => Gdd03SyntheticMonthContext.CreateSynthetic(SaveGame.Gdd03Ruleset, 4, reverse ? people.Reverse() : people,reverse ? facilities.AsEnumerable().Reverse() : facilities,- reverse ? residents.AsEnumerable().Reverse() : residents,reverse ? housing.AsEnumerable().Reverse() : housing,reverse ? pending.AsEnumerable().Reverse() : pending);var a = Make(false); var b = Make(true);people[0] = Person(99, PopulationAssignmentKind.Unassigned);- facilities.Clear(); residents.Clear(); housing.Clear(); pending.Clear();+ facilities.Clear(); housing.Clear(); pending.Clear();foreach (var context in new[] { a, b }){Assert.Equal(new[] { 2, 20 }, context.OpeningPeople.Select(p => p.Id));- Assert.Equal(new[] { 2, 20 }, context.PreArrivalResidentIds);Assert.Equal(expectedKeys, context.Facilities.Select(f => f.Id));Assert.Equal(expectedKeys, context.Housing.Select(h => h.Id));Assert.Equal(expectedKeys, context.PendingEntries.Select(e => e.Key));@@ -181,7 +173,6 @@ public class Gdd03SyntheticMonthContextTestsAssert.Throws<NotSupportedException>(() => ((IList<Gdd03SyntheticFacilitySnapshot>)context.Facilities).Clear());Assert.Throws<NotSupportedException>(() => ((IList<Gdd03SyntheticHousingSnapshot>)context.Housing).Clear());Assert.Throws<NotSupportedException>(() => ((IList<Gdd03SyntheticPendingEntry>)context.PendingEntries).Clear());- Assert.Throws<NotSupportedException>(() => ((IList<int>)context.PreArrivalResidentIds).Clear());Assert.Throws<NotSupportedException>(() => ((IList<int>)context.WorkEligibleIds).Clear());Assert.Throws<NotSupportedException>(() => ((IList<int>)context.CourseEligibleIds).Clear());Assert.Throws<NotSupportedException>(() => ((IList<int>)context.ReceptionEligibleIds).Clear());diff --git a/sim/Statecraft.Sim.Tests/Gdd03TrainingCentreFixtureTests.cs b/sim/Statecraft.Sim.Tests/Gdd03TrainingCentreFixtureTests.csindex 0ae121dd9..037e6f0cf 100644--- a/sim/Statecraft.Sim.Tests/Gdd03TrainingCentreFixtureTests.cs+++ b/sim/Statecraft.Sim.Tests/Gdd03TrainingCentreFixtureTests.cs@@ -65,7 +65,7 @@ public class Gdd03TrainingCentreFixtureTestsstatic Gdd03SyntheticMonthContext Month(GameState s, int ordinal, bool centresAvailable = true)=> Gdd03SyntheticMonthContext.CreateSynthetic(SaveGame.Gdd03Ruleset, ordinal, s.PopulationLedger.Units,Facilities.Select(f => new Gdd03SyntheticFacilitySnapshot(f, centresAvailable || !f.Contains("centre", StringComparison.Ordinal), 1)),- Array.Empty<int>(), Array.Empty<Gdd03SyntheticHousingSnapshot>(), Array.Empty<Gdd03SyntheticPendingEntry>());+ Array.Empty<Gdd03SyntheticHousingSnapshot>(), Array.Empty<Gdd03SyntheticPendingEntry>());static (int teacher, int trainee) Pair(CivilianProfession p) => p == CivilianProfession.Farmer ? (0, 1) : (2, 3);// A ruled #1668 Q42 or Q43 refusal is a plain ArgumentException with its reason; only unbuilt cases say "Deferred:".@@ -469,7 +469,7 @@ public class Gdd03TrainingCentreFixtureTestsvar c = Catalogue(); var s = State(c); var f = new Gdd03TrainingCentreFixture(c, s, Centres());var noPlace = Gdd03SyntheticMonthContext.CreateSynthetic(SaveGame.Gdd03Ruleset, 0, s.PopulationLedger.Units,Facilities.Select(id => new Gdd03SyntheticFacilitySnapshot(id, true, id == CentreA ? 0 : 1)),- Array.Empty<int>(), Array.Empty<Gdd03SyntheticHousingSnapshot>(), Array.Empty<Gdd03SyntheticPendingEntry>());+ Array.Empty<Gdd03SyntheticHousingSnapshot>(), Array.Empty<Gdd03SyntheticPendingEntry>());f.Start(1, 0, CentreA, Month(s, 0));Unchanged(s, () => f.Advance(1, noPlace), typeof(NotSupportedException), MonthFreezeDeferred);Assert.Equal(0, s.PopulationLedger.Get(1).Assignment.ProgressTicks);@@ -965,7 +965,7 @@ public class Gdd03TrainingCentreFixtureTestsvar without = Gdd03SyntheticMonthContext.CreateSynthetic(SaveGame.Gdd03Ruleset, 1,l.Units.Where(p => p.Id != trainee && p.Id != teacher),Facilities.Select(x => new Gdd03SyntheticFacilitySnapshot(x, true, 1)),- Array.Empty<int>(), Array.Empty<Gdd03SyntheticHousingSnapshot>(), Array.Empty<Gdd03SyntheticPendingEntry>());+ Array.Empty<Gdd03SyntheticHousingSnapshot>(), Array.Empty<Gdd03SyntheticPendingEntry>());new Gdd03TrainingCentreFixture(c, s, Centres(operating: false)).Advance(trainee, without);CancelledByTheLoss(s, before, teacherBefore, 100, 7);}diff --git a/sim/Statecraft.Sim.Tests/PoolsTests.cs b/sim/Statecraft.Sim.Tests/PoolsTests.csindex e56a12a91..eba53fe07 100644--- a/sim/Statecraft.Sim.Tests/PoolsTests.cs+++ b/sim/Statecraft.Sim.Tests/PoolsTests.cs@@ -548,7 +548,7 @@ public class PoolsTests/// <summary>The month's frozen opening snapshot of the ledger, taken when the month's context is created.</summary>static Gdd03SyntheticMonthContext Month(GameState s) => Gdd03SyntheticMonthContext.CreateSynthetic(SaveGame.Gdd03Ruleset, 0,s.PopulationLedger.Units, new[] { "course", "field", "reception", "teacher" }.Select(f => new Gdd03SyntheticFacilitySnapshot(f, true, 1)),- Array.Empty<int>(), Array.Empty<Gdd03SyntheticHousingSnapshot>(), Array.Empty<Gdd03SyntheticPendingEntry>());+ Array.Empty<Gdd03SyntheticHousingSnapshot>(), Array.Empty<Gdd03SyntheticPendingEntry>());// R-FOOD-001 (one unit is one population unit's food for a month) and R-FOOD-002 under gdd-0.3: every living own ledger// id eats one ration whatever its assignment, the stock stops at 0, and the import refills to cover_months of that need.diff --git a/sim/Statecraft.Sim/Gdd03HousingFormula.cs b/sim/Statecraft.Sim/Gdd03HousingFormula.csindex 64a637ce2..80f714576 100644--- a/sim/Statecraft.Sim/Gdd03HousingFormula.cs+++ b/sim/Statecraft.Sim/Gdd03HousingFormula.cs@@ -66,17 +66,17 @@ namespace Statecraft.Siminternal Gdd03HousingResult Evaluate(Gdd03HousingInput input){if (input == null) throw new ArgumentNullException(nameof(input));- if (input.SurchargeResidents < 0 || input.PreArrivalResidents < 0+ if (input.SurchargeResidents < 0 || input.Residents < 0|| input.CohesionResidents < 0 || input.OwnPopulation < 0|| input.CohesionResidents > input.OwnPopulation || input.Capacity < 0m|| input.UpkeepDue < 0m || input.UpkeepPaid < 0m || input.UpkeepPaid > input.UpkeepDue)throw new ArgumentOutOfRangeException(nameof(input), "counts/capacity/upkeep must be nonnegative; regional residents cannot exceed own population; paid cannot exceed due");ValidateCondition(input.ConditionBefore);- // GDD cities.md:29,33,35; loop-switch.md:29,33 at 605277df.- // Counts are independently supplied; this helper makes no timing/status decision.+ // GDD cities.md:29,33,35 at 605277df. Overflow counts the housed residents after the step's arrivals become+ // civilians (27M-15, owner, 1 November 2026). Counts are independently supplied; this helper selects no one.var surcharge = input.SurchargeResidents * Math.Max(0m, moneyThreshold - input.ConditionBefore) * moneySlope;- var overflow = input.PreArrivalResidents == 0 ? 0m :- (overflowPp / 100m) * Math.Max(0m, input.PreArrivalResidents - input.Capacity) / input.PreArrivalResidents;+ var overflow = input.Residents == 0 ? 0m :+ (overflowPp / 100m) * Math.Max(0m, input.Residents - input.Capacity) / input.Residents;var unpaid = input.UpkeepDue == 0m ? 0m :(unpaidPp / 100m) * ((input.UpkeepDue - input.UpkeepPaid) / input.UpkeepDue);var after = Clamp(input.ConditionBefore - overflow - unpaid);@@ -131,7 +131,8 @@ namespace Statecraft.Siminternal sealed class Gdd03HousingInput{internal int SurchargeResidents { get; }- internal int PreArrivalResidents { get; }+ /// <summary>The housed residents after the step's arrivals become civilians (R-HOUSE-005, 27M-15).</summary>+ internal int Residents { get; }internal int CohesionResidents { get; }internal int OwnPopulation { get; }internal decimal Capacity { get; }@@ -139,10 +140,10 @@ namespace Statecraft.Siminternal decimal UpkeepDue { get; }internal decimal UpkeepPaid { get; }- internal Gdd03HousingInput(int surchargeResidents, int preArrivalResidents, int cohesionResidents,+ internal Gdd03HousingInput(int surchargeResidents, int residents, int cohesionResidents,int ownPopulation, decimal capacity, decimal conditionBefore, decimal upkeepDue, decimal upkeepPaid){- SurchargeResidents = surchargeResidents; PreArrivalResidents = preArrivalResidents;+ SurchargeResidents = surchargeResidents; Residents = residents;CohesionResidents = cohesionResidents; OwnPopulation = ownPopulation; Capacity = capacity;ConditionBefore = conditionBefore; UpkeepDue = upkeepDue; UpkeepPaid = upkeepPaid;}diff --git a/sim/Statecraft.Sim/Gdd03SyntheticMonthContext.cs b/sim/Statecraft.Sim/Gdd03SyntheticMonthContext.csindex d95ea0e59..02b1194e2 100644--- a/sim/Statecraft.Sim/Gdd03SyntheticMonthContext.cs+++ b/sim/Statecraft.Sim/Gdd03SyntheticMonthContext.cs@@ -6,7 +6,8 @@ using System.Linq;namespace Statecraft.Sim{/// <summary>Synthetic #1716 contract, test fixtures only. Not a live-state adapter.- /// GDD 605277df docs/gdd/loop-switch.md:17-39.+ /// GDD 605277df docs/gdd/loop-switch.md:17-39, except its pre-arrival residents: housing effects count residents after+ /// the step's arrivals (27M-15, owner, 1 November 2026), which an opening snapshot cannot hold, so it holds none./// Frozen eligibility is only an upper bound: future consumers must recheck survival,/// location, control and facility availability immediately before using an entry./// This object neither executes phases nor authorizes work, settlement or persistence.</summary>@@ -14,7 +15,6 @@ namespace Statecraft.Sim{internal int MonthOrdinal { get; }internal IReadOnlyList<PopulationUnit> OpeningPeople { get; }- internal IReadOnlyList<int> PreArrivalResidentIds { get; }internal IReadOnlyList<int> WorkEligibleIds { get; }internal IReadOnlyList<int> CourseEligibleIds { get; }internal IReadOnlyList<int> ReceptionEligibleIds { get; }@@ -22,12 +22,12 @@ namespace Statecraft.Siminternal IReadOnlyList<Gdd03SyntheticHousingSnapshot> Housing { get; }internal IReadOnlyList<Gdd03SyntheticPendingEntry> PendingEntries { get; }- private Gdd03SyntheticMonthContext(int monthOrdinal, PopulationUnit[] people, int[] residents,+ private Gdd03SyntheticMonthContext(int monthOrdinal, PopulationUnit[] people,Gdd03SyntheticFacilitySnapshot[] facilities, Gdd03SyntheticHousingSnapshot[] housing,Gdd03SyntheticPendingEntry[] pending){MonthOrdinal = monthOrdinal;- OpeningPeople = Freeze(people); PreArrivalResidentIds = Freeze(residents);+ OpeningPeople = Freeze(people);Facilities = Freeze(facilities); Housing = Freeze(housing); PendingEntries = Freeze(pending);var available = new HashSet<string>(facilities.Where(f => f.AvailableAtMonthFreeze && f.OpeningCapacity > 0).Select(f => f.Id), StringComparer.Ordinal);@@ -46,7 +46,6 @@ namespace Statecraft.Siminternal static Gdd03SyntheticMonthContext CreateSynthetic(string ruleset, int monthOrdinal,IEnumerable<PopulationUnit> openingPeople,IEnumerable<Gdd03SyntheticFacilitySnapshot> facilities,- IEnumerable<int> preArrivalResidentIds,IEnumerable<Gdd03SyntheticHousingSnapshot> housing,IEnumerable<Gdd03SyntheticPendingEntry> pendingEntries){@@ -56,16 +55,9 @@ namespace Statecraft.Simvar capacity = Materialize(facilities);var conditions = Materialize(housing);var pending = Materialize(pendingEntries);- if (preArrivalResidentIds == null) throw new ArgumentNullException(nameof(preArrivalResidentIds));- var residents = preArrivalResidentIds.OrderBy(id => id).ToArray();- if (people.Select(p => p.Id).Distinct().Count() != people.Length- || residents.Distinct().Count() != residents.Length)- throw new ArgumentException("Population and resident ids must be unique.");+ if (people.Select(p => p.Id).Distinct().Count() != people.Length)+ throw new ArgumentException("Population ids must be unique.");var peopleById = people.ToDictionary(p => p.Id);- if (residents.Any(id => !peopleById.ContainsKey(id)- || peopleById[id].Status == PopulationStatus.Captured- || peopleById[id].Status == PopulationStatus.CivilianInTransit))- throw new ArgumentException("Pre-arrival residents must reference present non-captive, non-transit people.");Unique(capacity.Select(f => f.Id)); Unique(conditions.Select(h => h.Id)); Unique(pending.Select(e => e.Key));var targets = new HashSet<string>(capacity.Select(f => f.Id), StringComparer.Ordinal);foreach (var person in people)@@ -87,7 +79,7 @@ namespace Statecraft.Sim|| t.Assignment.Target != person.Assignment.Target))throw new ArgumentException("Course teacher must reference an opening teacher at the same target.");}- return new Gdd03SyntheticMonthContext(monthOrdinal, people.OrderBy(p => p.Id).ToArray(), residents,+ return new Gdd03SyntheticMonthContext(monthOrdinal, people.OrderBy(p => p.Id).ToArray(),capacity.OrderBy(f => f.Id, StringComparer.Ordinal).ToArray(),conditions.OrderBy(h => h.Id, StringComparer.Ordinal).ToArray(),pending.OrderBy(e => e.Key, StringComparer.Ordinal).ToArray());