A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
feat(sim): Send home runs on a Historical ledger game (#1699 part 2, #1725 PR 7) (#2975)
Eyal Golan9d49866b3e3a
diff --git a/changelog.d/1725-pr7-send-home.md b/changelog.d/1725-pr7-send-home.mdnew file mode 100644index 000000000..9f17c15bc--- /dev/null+++ b/changelog.d/1725-pr7-send-home.md@@ -0,0 +1,5 @@+- GDD 0.3 starting population (Refs #1699, Refs #1725): on the inactive dark start's Historical ledger, Send home now+ moves people records: every soldier serving the formation becomes a settled-in civilian without a job in the nearest+ city, keeping their military training and combat experience, and their issued Arms go back to the stock once, with one Why line naming the Arms returned. A+ formation whose strength differs from its soldiers on record is refused with a reason. No new-game wiring, so there is+ no change in the game.diff --git a/docs/rules/mvp.md b/docs/rules/mvp.mdindex 4ded41e4c..9b159fb3d 100644--- a/docs/rules/mvp.md+++ b/docs/rules/mvp.md@@ -268,7 +268,7 @@ R-UNIT-003: A finished recruit cohort becomes exactly one Israeli infantry formaR-UNIT-004: Each Israeli recruit formation already in play before step 4 gains one service turn; a cohort graduating in step 4 starts serving on the next turn. At `veteran_soldier_service` it becomes `veteran_soldier`, keeping id, hex, service, side, strength and standing order, with a Why cause. Veterans stop accumulating service. Combat gives no extra service, and Phase 5 adds no return to civilian life (Q-UNIT-2, Q-UNIT-6; owner, 15 October 2026). The owner-accepted initial threshold is 6 turns, a labelled design value under Q-GEN-1, not a historical period (19 October 2026, https://github.com/eyalgolan/statecraft-israel/pull/1130#issuecomment-6269103829). The loader requires it to be at least 1 and requires the Israeli veteran infantry type when recruits exist. Under exact `gdd-0.3` service is a statistic only and never promotes: a recruit still gains its service turn, and veterancy comes from combat experience, R-UNIT-011 (owner, 1 November 2026, Q16: "Under gdd-0.3, yes: veterancy comes from combat experience. gdd-0.1 keeps R-UNIT-004."). Service also runs on a game with an initialized Historical ledger (the dark start, R-POP-002; #1725 PR 7): a recruit formation gains its service turn as in the aggregate game and, under `gdd-0.3`, never promotes. Service stays on the formation only, so no ledger record or ledger hash changes, and service checks no formation strength against the ledger's soldiers; a synthetic or Open ledger is still refused (maintainer calls by coordinator eyalgolan-30, 8 November 2026, not owner rulings).-R-UNIT-005: `UnitOrder(unit, send_home)` (the unit card's "Send home", #1309) is the player's order and the only way home: no automatic demobilisation happens (owner, 22 October 2026, #1309: https://github.com/eyalgolan/statecraft-israel/issues/1309#issuecomment-6334162964). It is refused, the state unchanged, with the orders' own reasons for an unknown unit, a unit with no side or an enemy unit (R-ORDER-001's wording) and "That order names no hex" when a hex is given, and with "The armistice with <front> is not signed" while the armistice on the unit's front is unsigned. A unit's front is the front of the enemy side it attacked this turn or borders; ties take the nearest enemy unit, then the lowest unit id (owner, 22 October 2026, #1309: https://github.com/eyalgolan/statecraft-israel/issues/1309#issuecomment-6340226644). A side that belongs to no front (the ALA and the local forces, Q-OBJ-1; R-POW-004's map) names none (accepted per maintainer comment, 22 October 2026, #1309: https://github.com/eyalgolan/statecraft-israel/issues/1309#issuecomment-6341877062: the ALA and the local forces belong to no front, having no armistice of their own), and a unit attacking and bordering no front-bearing enemy may be sent home once any armistice is signed, refused with "No armistice is signed" until then (accepted per maintainer comment 6341877062 on #1309: "no enemy units in play" means attacking and bordering no enemy that has a front). Taken, the order waits for End turn and can be withdrawn until then, as Send home is not an instant order (R-TURN-004); when it runs, it acts at once: the unit leaves the map and its strength, in population units, joins the nearest of the twelve cities as civilians without a job (owner, 22 October 2026, #1309: https://github.com/eyalgolan/statecraft-israel/issues/1309#issuecomment-6334162964: "nearest ... as unemployed civilians"), counting in the city's jobs and housing from the same turn; nearest by hex distance to the city's settlement hex, ties by the city's id (agent default - the ruling sets no tie break). The Why line states the count in people (Q-CIV-4): "Unit N is sent home: its P people are civilians in <city> now". A veteran keeps nothing (none suggested, #1309).+R-UNIT-005: `UnitOrder(unit, send_home)` (the unit card's "Send home", #1309) is the player's order and the only way home: no automatic demobilisation happens (owner, 22 October 2026, #1309: https://github.com/eyalgolan/statecraft-israel/issues/1309#issuecomment-6334162964). It is refused, the state unchanged, with the orders' own reasons for an unknown unit, a unit with no side or an enemy unit (R-ORDER-001's wording) and "That order names no hex" when a hex is given, and with "The armistice with <front> is not signed" while the armistice on the unit's front is unsigned. A unit's front is the front of the enemy side it attacked this turn or borders; ties take the nearest enemy unit, then the lowest unit id (owner, 22 October 2026, #1309: https://github.com/eyalgolan/statecraft-israel/issues/1309#issuecomment-6340226644). A side that belongs to no front (the ALA and the local forces, Q-OBJ-1; R-POW-004's map) names none (accepted per maintainer comment, 22 October 2026, #1309: https://github.com/eyalgolan/statecraft-israel/issues/1309#issuecomment-6341877062: the ALA and the local forces belong to no front, having no armistice of their own), and a unit attacking and bordering no front-bearing enemy may be sent home once any armistice is signed, refused with "No armistice is signed" until then (accepted per maintainer comment 6341877062 on #1309: "no enemy units in play" means attacking and bordering no enemy that has a front). Taken, the order waits for End turn and can be withdrawn until then, as Send home is not an instant order (R-TURN-004); when it runs, it acts at once: the unit leaves the map and its strength, in population units, joins the nearest of the twelve cities as civilians without a job (owner, 22 October 2026, #1309: https://github.com/eyalgolan/statecraft-israel/issues/1309#issuecomment-6334162964: "nearest ... as unemployed civilians"), counting in the city's jobs and housing from the same turn; nearest by hex distance to the city's settlement hex, ties by the city's id (agent default - the ruling sets no tie break). The Why line states the count in people (Q-CIV-4): "Unit N is sent home: its P people are civilians in <city> now". A veteran keeps nothing (none suggested, #1309). On a game with an initialized Historical ledger (#1699, #1725 PR 7; owner, 8 November 2026, #1725: https://github.com/eyalgolan/statecraft-israel/issues/1725#issuecomment-6726421643 and https://github.com/eyalgolan/statecraft-israel/issues/1725#issuecomment-6727007834) the formation's soldiers are person records; a synthetic or Open ledger is still refused (R-POP-002). The refusals above come first. "Every soldier in it (Recommended)": every active-soldier record serving the formation's target (`units_1948/<row>` for a starting force, `formation/<unit id>` after graduation, R-TRAIN-003) leaves service. "Refuse with a reason (Recommended)": when the formation's strength differs from those records, the order is refused with `Unit N has S soldiers on record but strength T`, the state unchanged. "Nearest city, unemployed (Recommended)": each record becomes a free civilian without an assignment, located in the nearest city by the rule above (its region plus the city), so that city houses it from the same turn. "Settled in (Recommended)": its reception ticks are `reception.turns`. "Keep both (Recommended)": it keeps its military qualification and combat XP. "Back to Arms stock (Recommended)": its issued military item leaves the record and goes back to the Arms stock once, so spare plus issued Arms is unchanged. The opening formations' items were issued apart from the stock (R-POP-004), so sending an opening formation home adds Arms the stock never paid for; this effect was known and accepted with the ruling. "No, records only (Recommended)": no aggregate city field is written, so the city's jobs share (R-CITY-005), which still reads those fields, does not count them. The Why line is the aggregate game's. "Yes, one Why line (Recommended)" (owner, 8 November 2026, relayed by the coordinator for #1725 PR 7): when Arms go back to the stock, one more Why line, after it, names them as training's Cancel does (R-TRAIN-002): "<city>: unit N returned K Arms", its delta the Arms added (key `sent_home_arms_returned`); none is written when no item goes back, and the aggregate game writes none. Every check comes before the first write; the records change in one validated commit, then the unit leaves and the stock rises. The Arms change is Send home's, not the ledger's.R-UNIT-006: A new Historical game places one military unit per row of `map/units_1948.yaml` that is not `hidden`, has `service: army` (the squadron and the ships stay presentation-only tokens, Q-UNIT-5), has a `strength` whose `as_of` is the start day, and has an anchor window [from, to) covering the start. The unit stands on the hex that holds the first such anchor's coordinates, by the map's projection and cube rounding (`tools/hexgrid.py`, Unity's `HexPicker`), precomputed by `tools/unit_anchor_hexes.py` into `map/unit_anchor_hexes.yaml`, which the sim reads (no projection maths in the sim, docs/determinism.md); the token may stand one hex away (`UnitPlacer`), which is presentation. Every IDF brigade is a `veteran_soldier`; an Arab force takes its side's one military type, a labelled design value of class infantry with 3 movement points. Its strength is the row's people in population units, the nearest unit with a half up and never below 1 (`people_per_unit` 1,000: Golani's 4,095 is 4, Kiryati's 2,504 is 3). The units take ids 0 upward in the file's order, before any other unit (owner, 20 October 2026, #743: "all five defaults"). The file is in the content hash (Q-START-1), and so is the hex file. The loader refuses a starting row whose `strength.value` is not a whole number of at least 1 (#2815, option 1, the issue's Recommended option, confirmed on the issue on 6 November 2026), whose anchor is off the map or not on land or has no row in the hex file, a hex row for an anchor the unit file does not have, or whose side has no single military type, naming the file and the row. A shareable build refuses while any row a unit starts from is not `fact-checked` (Q-START-3): `Statecraft.Cli --release-gate`, `Build -shareable` and `tools/package_release.py` name them.@@ -605,7 +605,7 @@ These contracts cover #1689 steps 1–2 and the Historical start inventory (R-POR-POP-001: Only exact `gdd-0.3` enables the population-ledger capability, independently of the broad GDD loop and Attention (R-LOOP-002/005). An immutable own-population record has a dedicated nonnegative ordinal id. Synthetic fixture inventory is ordered by source key (ordinal string comparison), then within-source ordinal. Registered arrivals allocate monotonically; only explicit combat losses remove living ids. Sources remain registered after loss, and ids are never reused. Reconciliation checks the exact created-minus-lost id set against the living ledger, not just equal totals. Status/region counts include every matching record once. The gdd-0.3 scale of a synthetic or Open fixture reads one positive Agreed integer from `population.people_per_unit` in its catalogue (currently 10,000, Open mode's scale under D2); a Historical fixture reads `rules.yaml`'s `people_per_unit` for the start day (1,000), as R-UNIT-006 does (owner, 1 November 2026, D2: "Approve all six (Recommended)", "The Historical MVP keeps main's start: census cities at 1,000 people a unit (`R-CITY-007`)"; R-POP-004); rows with a `census/`, `units_1948/` or `field/` source key are the Historical start's and are refused in any other fixture. Old identities retain the common rules scale. Missing, fractional, nonpositive, overflowing or Deferred values have no fallback, in either source.-R-POP-002: A ledger record has exactly one typed status and assignment, validated location, home and captor references, whole reception-turn ticks capped by the catalogue requirement, civilian profession-specific tier and actual-work XP, separate military qualification/combat XP, and distinct issued civilian/military equipment and paid facts. Unknown references, unresolved teacher ids, incompatible statuses/assignments, inconsistent region/hex/facility bindings, invalid progress/tiers and duplicate issued-item ownership are refused before mutation. Moves and atomic status/location/assignment transitions retain identity/history. Capture retains home context without inventing a prison hex or refunding equipment. Ledger changes never touch resources, causes, RNG or Attention. Initialization is internal and fixture-only; initialized ledger fixtures refuse aggregate Simulation commands and turns. The dark start (#1725 PR 5) is the internal, fixture-only `Simulation.NewGame` overload that initializes the Historical ledger (R-POP-004) in place before `Pools.Init`: `Pools.Init` then reads the ledger's need, one ration for each living own population id (R-FOOD-001, #2470), after the ledger reconciles, and `StartingForces.Init` places the forces once each own starting formation's strength is its ledger soldiers, refusing otherwise. Both read only a ledger initialized with mode Historical, the dark start's; a synthetic or Open ledger is refused by both, as by the other aggregate systems, with the state unchanged. An aggregate system whose own rule says it runs on that Historical ledger (#1725 PR 7: civilian upkeep, R-MONEY-002, the first, and food_supply's stock term, R-FOOD-003; training, R-TRAIN-001 to R-TRAIN-004; military upkeep, R-UNIT-010; arms workshops, R-ARMS-005 and R-ARMS-006) also reads only that ledger; a synthetic or Open ledger is still refused by it. Prisoners.Take and Prisoners.Upkeep are such systems (#1710, R-POW-001, R-POW-002, R-POW-005): a capture turns the surrendered formation's serving records into captives with their captor and home, all or nothing, and records no loss. `EventSystem.Trigger` still refuses a ledger, so a dark start fires no opening event; the public `NewGame` is unchanged. The step-7 Food settlement given a month's synthetic context is another exception to that refusal: it reads its need from that month's frozen snapshot (R-FOOD-002, #2470). The live month snapshot (`Gdd03SyntheticMonthContext.CreateLive`, #1725 PR 7; owner, 8 November 2026, "One snapshot per turn (Recommended)") reads only a ledger initialized with mode Historical and changes no record; a synthetic or Open ledger and an aggregate game are refused (R-FOOD-002). Old identities refuse ledger mutation. Prices, progression awards, return destinations, tool lock-in and captive-equipment outcomes remain with their owning issues. A craftsman's tier is novice, apprentice or expert (R-CRAFT-003); a farmer's or pioneer's is novice, trained or veteran.+R-POP-002: A ledger record has exactly one typed status and assignment, validated location, home and captor references, whole reception-turn ticks capped by the catalogue requirement, civilian profession-specific tier and actual-work XP, separate military qualification/combat XP, and distinct issued civilian/military equipment and paid facts. Unknown references, unresolved teacher ids, incompatible statuses/assignments, inconsistent region/hex/facility bindings, invalid progress/tiers and duplicate issued-item ownership are refused before mutation. Moves and atomic status/location/assignment transitions retain identity/history. Capture retains home context without inventing a prison hex or refunding equipment. Ledger changes never touch resources, causes, RNG or Attention. Initialization is internal and fixture-only; initialized ledger fixtures refuse aggregate Simulation commands and turns. The dark start (#1725 PR 5) is the internal, fixture-only `Simulation.NewGame` overload that initializes the Historical ledger (R-POP-004) in place before `Pools.Init`: `Pools.Init` then reads the ledger's need, one ration for each living own population id (R-FOOD-001, #2470), after the ledger reconciles, and `StartingForces.Init` places the forces once each own starting formation's strength is its ledger soldiers, refusing otherwise. Both read only a ledger initialized with mode Historical, the dark start's; a synthetic or Open ledger is refused by both, as by the other aggregate systems, with the state unchanged. An aggregate system whose own rule says it runs on that Historical ledger (#1725 PR 7: civilian upkeep, R-MONEY-002, the first, and food_supply's stock term, R-FOOD-003; training, R-TRAIN-001 to R-TRAIN-004; military upkeep, R-UNIT-010; arms workshops, R-ARMS-005 and R-ARMS-006; Send home, R-UNIT-005) also reads only that ledger; a synthetic or Open ledger is still refused by it. Prisoners.Take and Prisoners.Upkeep are such systems (#1710, R-POW-001, R-POW-002, R-POW-005): a capture turns the surrendered formation's serving records into captives with their captor and home, all or nothing, and records no loss. `EventSystem.Trigger` still refuses a ledger, so a dark start fires no opening event; the public `NewGame` is unchanged. The step-7 Food settlement given a month's synthetic context is another exception to that refusal: it reads its need from that month's frozen snapshot (R-FOOD-002, #2470). The live month snapshot (`Gdd03SyntheticMonthContext.CreateLive`, #1725 PR 7; owner, 8 November 2026, "One snapshot per turn (Recommended)") reads only a ledger initialized with mode Historical and changes no record; a synthetic or Open ledger and an aggregate game are refused (R-FOOD-002). Old identities refuse ledger mutation. Prices, progression awards, return destinations, tool lock-in and captive-equipment outcomes remain with their owning issues. A craftsman's tier is novice, apprentice or expert (R-CRAFT-003); a farmer's or pioneer's is novice, trained or veteran.R-POP-003: Clone copies all ledger containers; immutable records and frozen bindings may be shared. The canonical writer emits a gdd-0.3-only section ordered by numeric population id, with fixed field order, stable machine tokens, invariant integer formatting and length-prefixed reference strings. It covers every record/assignment/equipment/reference field, binding, creation/loss provenance and allocator even after the last combat loss. Legacy/gdd-0.1 emit no ledger section or allocator marker. A location's optional city (a `regions.yaml` member location of its region that is a census city of `cities.yaml` or one of that region's field hosts, where R-POP-004 houses own people: a settlement hosts only F19 and F20, owner, 7 November 2026, #1689: "These two only (Recommended)"; any other, including a locality, a `sites.yaml` id or a map location, is refused when a fixture is created, naming the city and the region, R-POP-002) is written after its other fields as `|city=` with a length-prefixed id, only when set, as R-UNIT-002's `|home=` is, so a location without a city keeps its canonical text and hash. R-SAVE-001/002 still govern identity mismatch refusal and replay: no ledger snapshot or new command syntax is added in this foundation, and fixture injection is not replay evidence. Existing unpublished schema-4 draft hashes change; no migration promise is made.diff --git a/sim/Statecraft.Sim.Tests/LedgerSendHomeTests.cs b/sim/Statecraft.Sim.Tests/LedgerSendHomeTests.csnew file mode 100644index 000000000..1e8b8c252--- /dev/null+++ b/sim/Statecraft.Sim.Tests/LedgerSendHomeTests.cs@@ -0,0 +1,307 @@+using Statecraft.Sim;++/// <summary>#1699 part 2, #1725 PR 7: Send home (R-UNIT-005, Demobilization.Give) runs on a game with an initialized+/// Historical ledger, the dark start (R-POP-002). The owner's rulings, 8 November 2026 (#1725 issuecomment-6726421643 and+/// issuecomment-6727007834):+/// - "Every soldier in it (Recommended)": every soldier record serving the formation's target leaves service.+/// - "Refuse with a reason (Recommended)": a formation whose strength differs from its serving records is refused with a+/// plain reason, and nothing changes.+/// - "Nearest city, unemployed (Recommended)": the records become free civilians without an assignment in the nearest of the+/// twelve cities (R-UNIT-005's nearest-city rule), so that city houses them from the same turn.+/// - "Back to Arms stock (Recommended)": each record's issued military item is cleared and returned to the stock once.+/// - "Settled in (Recommended)": the records' reception ticks are reception.turns.+/// - "Keep both (Recommended)": the military qualification and combat XP stay on the record.+/// - "No, records only (Recommended)": no aggregate city field is written.+/// The owner's ruling, 8 November 2026, "Yes, one Why line (Recommended)": Send home writes one Why line naming the Arms+/// returned to the stock, as training's Cancel does (R-TRAIN-002).+/// The tests call Demobilization.Give directly: Simulation.Step and TurnResolver.Resolve still refuse a ledger game.</summary>+public class LedgerSendHomeTests+{+ static Content Gdd03() => HistoricalPopulationTests.Real(true);++ // Every armistice signed, so any of the player's units may go home (R-UNIT-005's Check passes).+ static GameState Signed(GameState s)+ {+ foreach (var f in Prisoners.Fronts) s.ChosenOptions["armistice_" + f] = "sign";+ return s;+ }++ static GameState Dark(Content c) => Signed(Simulation.NewGame(c, 1, Mode.Historical, darkStart: true));++ static GameState Aggregate(Content c) => Signed(Simulation.NewGame(c, 1, Mode.Historical));++ // The first of the player's opening formations (unit id i is c.StartingForces[i], StartingForces.Init).+ static int Opening(Content c, GameState s) => s.Units.Values+ .Where(u => u.Side == Movement.PlayerSide && u.Id < c.StartingForces.Count).Min(u => u.Id);++ static string Target(Content c, int unit) => HistoricalPopulation.FormationPrefix + c.StartingForces[unit].Row;++ static List<PopulationUnit> Serving(GameState s, string target) => s.PopulationLedger.Units+ .Where(p => p.Status == PopulationStatus.ActiveSoldier && p.Assignment.Target == target).OrderBy(p => p.Id).ToList();++ static int Issued(GameState s) => s.PopulationLedger.Units.Count(p => p.Equipment.MilitaryId != null);++ static string Cities(GameState s) => string.Join(";", s.Cities.Values.Select(x => x.Canonical()));++ static IEnumerable<(string, string, double, string, string)> Lines(IEnumerable<Cause> why) =>+ why.Select(x => (x.System, x.Target, x.Delta, x.Message, x.Key));++ // "Every soldier in it", "Nearest city, unemployed", "Settled in", "Keep both": each serving record keeps its id,+ // qualification, combat XP, profession, tier and work XP, and becomes a settled-in free civilian without an assignment in+ // the nearest city (region plus city). The unit leaves the map, no id is made or lost, and the first Why line is the+ // aggregate game's.+ [Fact]+ public void SendHomeTurnsTheFormationsSoldiersIntoSettledCiviliansOfTheNearestCity()+ {+ var c = Gdd03();+ var s = Dark(c); var twin = Aggregate(c);+ var unit = Opening(c, s); var u = s.Units[unit];+ var serving = Serving(s, Target(c, unit));+ Assert.Equal(u.Strength, serving.Count);+ Assert.NotEmpty(serving);+ var city = Demobilization.Nearest(c, u.Q, u.R);+ var region = c.PlayerRegions.AtLocation(city)!.Id;+ var next = s.PopulationLedger.NextPopulationId; var count = s.PopulationLedger.Units.Count;+ var housed = Statecraft.Sim.Cities.Housed(s, s.Cities[city]);+ var why = new List<Cause>(); var twinWhy = new List<Cause>();++ Assert.Null(Demobilization.Give(c, s, unit, null, why));+ Assert.Null(Demobilization.Give(c, twin, unit, null, twinWhy));++ Assert.False(s.Units.ContainsKey(unit));+ Assert.Equal(Lines(twinWhy), Lines(why.Take(twinWhy.Count)));+ Assert.Equal((next, count), (s.PopulationLedger.NextPopulationId, s.PopulationLedger.Units.Count));+ Assert.Empty(Serving(s, Target(c, unit)));+ var received = c.RequirePopulationInteger("reception.turns");+ foreach (var was in serving)+ {+ var p = s.PopulationLedger.Get(was.Id);+ Assert.Equal(PopulationStatus.FreeCivilian, p.Status);+ Assert.Equal(PopulationAssignmentKind.Unassigned, p.Assignment.Kind);+ Assert.Equal((region, city), (p.Location!.Region, p.Location.City));+ Assert.Equal(received, p.ReceptionTicks);+ Assert.Equal((was.Qualification, was.CombatXp), (p.Qualification, p.CombatXp));+ Assert.NotEqual("", p.Qualification);+ Assert.Equal((was.Profession, was.Tier, was.WorkXp, was.Equipment.ToolsId), (p.Profession, p.Tier, p.WorkXp, p.Equipment.ToolsId));+ }+ Assert.Equal(housed + serving.Count, Statecraft.Sim.Cities.Housed(s, s.Cities[city]));+ s.PopulationLedger.Reconcile();+ }++ // "Back to Arms stock": each record's issued military item leaves the record and the stock rises by those items, once.+ // Spare plus issued stays the same. (Known effect: the opening items were issued apart from the stock, so this adds+ // Arms the stock never paid for.) The aggregate game returns none.+ [Fact]+ public void SendHomeReturnsEachIssuedItemToTheStockOnce()+ {+ var c = Gdd03();+ var s = Dark(c); var twin = Aggregate(c);+ var unit = Opening(c, s);+ var serving = Serving(s, Target(c, unit));+ var items = serving.Count(p => p.Equipment.MilitaryId != null);+ Assert.Equal(serving.Count, items);+ var arms = s.Arms; var issued = Issued(s); var twinArms = twin.Arms;+ var city = Demobilization.Nearest(c, s.Units[unit].Q, s.Units[unit].R);+ var why = new List<Cause>(); var twinWhy = new List<Cause>();++ Assert.Null(Demobilization.Give(c, s, unit, null, why));+ Assert.Null(Demobilization.Give(c, twin, unit, null, twinWhy));++ Assert.Equal(arms + items, s.Arms);+ Assert.Equal(issued - items, Issued(s));+ Assert.Equal(arms + issued, s.Arms + Issued(s));+ Assert.All(serving, was => Assert.Null(s.PopulationLedger.Get(was.Id).Equipment.MilitaryId));+ Assert.All(serving, was => Assert.False(s.PopulationLedger.Get(was.Id).Equipment.MilitaryPaid));+ Assert.Equal(twinArms, twin.Arms);++ // "Yes, one Why line (Recommended)": one line, after the aggregate game's, names the Arms returned to the stock,+ // its delta the Arms added, as Cancel's training_arms_returned line does. The aggregate game writes none.+ Assert.Equal(twinWhy.Count + 1, why.Count);+ var line = why.Last();+ Assert.Equal(("city", "arms", (double)items, FormattableString.Invariant($"{PlayerText.Settlement(c, city)}: unit {unit} returned {items} Arms"), "sent_home_arms_returned"),+ (line.System, line.Target, line.Delta, line.Message, line.Key));+ Assert.Equal(new[] { city, unit.ToString(System.Globalization.CultureInfo.InvariantCulture) }, line.Args);+ Assert.Single(why, x => x.Key == "sent_home_arms_returned");+ Assert.DoesNotContain(twinWhy, x => x.Key == "sent_home_arms_returned");+ }++ // "Yes, one Why line": a formation whose records hold no issued military item returns no Arms, so no Arms line is+ // written and the Why lines are the aggregate game's.+ [Fact]+ public void SendHomeWithNoIssuedItemWritesNoArmsLine()+ {+ var c = Gdd03();+ var s = Dark(c); var twin = Aggregate(c);+ var unit = Opening(c, s);+ var bare = Serving(s, Target(c, unit)).Select(p => new PopulationUnit(p.Id, p.Status, p.ReceptionTicks, p.Location,+ p.Assignment, p.Profession, p.Tier, p.WorkXp, p.Qualification, p.CombatXp,+ new PopulationEquipment(p.Equipment.ToolsId, p.Equipment.ToolsPaid), p.Captor, p.Home)).ToList();+ s.PopulationLedger.Commit(bare, Array.Empty<PopulationTarget>());+ var arms = s.Arms;+ var why = new List<Cause>(); var twinWhy = new List<Cause>();++ Assert.Null(Demobilization.Give(c, s, unit, null, why));+ Assert.Null(Demobilization.Give(c, twin, unit, null, twinWhy));++ Assert.Equal(arms, s.Arms);+ Assert.Equal(Lines(twinWhy), Lines(why));+ Assert.DoesNotContain(why, x => x.Key == "sent_home_arms_returned");+ }++ // A trained formation (#2964, R-TRAIN-003, "New unit at graduation (Rec.)"): a recruit cohort trained to graduation on+ // the dark start serves formation/<unit id>, not units_1948/<row>. Sending it home turns each of its records into a+ // settled-in free civilian of the nearest city, keeping its qualification and combat XP; each record's training item+ // (training/<cohort>/<id>) goes back to the stock once, with the one "Yes, one Why line (Recommended)" line; the unit+ // leaves the map.+ [Fact]+ public void SendHomeOfATrainedFormationSettlesItsRecordsAndReturnsTheirItems()+ {+ var c = Gdd03();+ var s = Dark(c);+ s.Arms = 200; s.Treasury = 100; s.Debt = 0;+ const string telAviv = "tel_aviv";+ Assert.Null(Training.Start(c, s, telAviv, "recruit", 2, new List<Cause>()));+ var cohort = Assert.Single(s.Cohorts).Key;+ var unit = s.NextId;+ for (int i = 0; i < c.UnitTypes.First(t => t.Id == "recruit").TrainingTurns; i++) Training.Progress(c, s, new List<Cause>());+ Assert.Empty(s.Cohorts);+ var u = s.Units[unit];+ Assert.True(unit >= c.StartingForces.Count);+ var target = "formation/" + unit;+ Assert.Equal(target, Training.FormationTarget(c, unit));+ // Combat XP the records earned in service, so "Keep both" is seen on a value other than the default.+ s.PopulationLedger.Commit(Serving(s, target).Select(p => new PopulationUnit(p.Id, p.Status, p.ReceptionTicks, p.Location,+ p.Assignment, p.Profession, p.Tier, p.WorkXp, p.Qualification, p.CombatXp + 3, p.Equipment, p.Captor, p.Home)).ToList(),+ Array.Empty<PopulationTarget>());+ var serving = Serving(s, target);+ Assert.Equal(2, serving.Count);+ Assert.Equal(u.Strength, serving.Count);+ Assert.All(serving, p => Assert.Equal(("training/" + cohort + "/" + p.Id, "infantry"), (p.Equipment.MilitaryId, p.Qualification)));+ var city = Demobilization.Nearest(c, u.Q, u.R);+ var region = c.PlayerRegions.AtLocation(city)!.Id;+ var arms = s.Arms; var issued = Issued(s);+ var next = s.PopulationLedger.NextPopulationId; var count = s.PopulationLedger.Units.Count;+ var housed = Statecraft.Sim.Cities.Housed(s, s.Cities[city]);+ var cities = Cities(s);+ var why = new List<Cause>();++ Assert.Null(Demobilization.Give(c, s, unit, null, why));++ Assert.False(s.Units.ContainsKey(unit));+ Assert.Empty(Serving(s, target));+ Assert.Equal((next, count), (s.PopulationLedger.NextPopulationId, s.PopulationLedger.Units.Count));+ var received = c.RequirePopulationInteger("reception.turns");+ foreach (var was in serving)+ {+ var p = s.PopulationLedger.Get(was.Id);+ Assert.Equal((PopulationStatus.FreeCivilian, PopulationAssignmentKind.Unassigned, received),+ (p.Status, p.Assignment.Kind, p.ReceptionTicks));+ Assert.Equal((region, city), (p.Location!.Region, p.Location.City));+ Assert.Equal((was.Qualification, was.CombatXp), (p.Qualification, p.CombatXp));+ Assert.Equal(("infantry", true), (p.Qualification, p.CombatXp > 0));+ Assert.Equal((was.Profession, was.Tier, was.WorkXp, was.Equipment.ToolsId), (p.Profession, p.Tier, p.WorkXp, p.Equipment.ToolsId));+ Assert.Equal(((string?)null, false), (p.Equipment.MilitaryId, p.Equipment.MilitaryPaid));+ }+ Assert.Equal(housed + serving.Count, Statecraft.Sim.Cities.Housed(s, s.Cities[city]));+ Assert.Equal(cities, Cities(s));+ Assert.Equal(arms + serving.Count, s.Arms);+ Assert.Equal(issued - serving.Count, Issued(s));+ Assert.Equal(2, why.Count);+ Assert.Equal(WhyKeys.SentHome, why[0].Key);+ var line = Assert.Single(why, x => x.Key == "sent_home_arms_returned");+ Assert.Equal(("city", "arms", (double)serving.Count, FormattableString.Invariant($"{PlayerText.Settlement(c, city)}: unit {unit} returned {serving.Count} Arms")),+ (line.System, line.Target, line.Delta, line.Message));+ Assert.Equal(new[] { city, unit.ToString(System.Globalization.CultureInfo.InvariantCulture) }, line.Args);+ s.PopulationLedger.Reconcile();+ }++ // "No, records only": the aggregate city fields are not written on a ledger game (the aggregate game adds the strength).+ [Fact]+ public void SendHomeWritesNoAggregateCityField()+ {+ var c = Gdd03();+ var s = Dark(c);+ var unit = Opening(c, s);+ var cities = Cities(s);+ Assert.Null(Demobilization.Give(c, s, unit, null, new List<Cause>()));+ Assert.Equal(cities, Cities(s));+ }++ // "Refuse with a reason": a formation whose strength differs from its serving records is refused with a plain reason,+ // not an exception, and the state, ledger and hash are unchanged.+ [Fact]+ public void AStrengthMismatchIsRefusedWithAReasonAndChangesNothing()+ {+ var c = Gdd03();+ var s = Dark(c);+ var unit = Opening(c, s); var u = s.Units[unit];+ var serving = Serving(s, Target(c, unit));+ s.PopulationLedger.RegisterCombatLoss(serving[0].Id, "test/mismatch");+ var before = s.Describe(); var hash = s.Hash(); var ledger = s.PopulationLedger.Canonical().ToList();+ var why = new List<Cause>();++ Assert.Equal(string.Format(System.Globalization.CultureInfo.InvariantCulture, Training.LedgerRefusedStrength,+ unit, serving.Count - 1, u.Strength), Demobilization.Give(c, s, unit, null, why));++ Assert.Equal(before, s.Describe()); Assert.Equal(hash, s.Hash());+ Assert.Equal(ledger, s.PopulationLedger.Canonical().ToList());+ Assert.True(s.Units.ContainsKey(unit));+ Assert.Empty(why);+ }++ // R-UNIT-005's own refusals are unchanged on the ledger: with no armistice signed, the reason is main's and nothing+ // changes.+ [Fact]+ public void NoArmisticeIsRefusedWithMainsReasonOnTheLedger()+ {+ var c = Gdd03();+ var s = Simulation.NewGame(c, 1, Mode.Historical, darkStart: true);+ var twin = Simulation.NewGame(c, 1, Mode.Historical);+ var unit = Opening(c, s);+ var before = s.Describe(); var hash = s.Hash(); var why = new List<Cause>();+ var reason = Demobilization.Give(c, s, unit, null, why);+ Assert.NotNull(reason);+ Assert.Equal(Demobilization.Give(c, twin, unit, null, new List<Cause>()), reason);+ Assert.Equal(before, s.Describe()); Assert.Equal(hash, s.Hash()); Assert.Empty(why);+ }++ // Each of the twelve cities is a bound ledger location, so the nearest city can always hold the records.+ [Fact]+ public void EveryCityIsABoundLedgerLocation()+ {+ var c = Gdd03();+ var s = Dark(c);+ var cities = s.PopulationLedger.Units.Where(p => p.Location?.City != null).Select(p => p.Location!.City!).ToHashSet();+ Assert.All(c.Cities, x => Assert.Contains(x.Id, cities));+ }++ // R-POP-002: an Open or synthetic ledger is still refused, with the state unchanged.+ [Theory]+ [InlineData(true)] [InlineData(false)]+ public void AnOpenOrSyntheticLedgerIsStillRefused(bool open)+ {+ var c = PopulationLedgerTests.Content();+ var s = PopulationLedger.CreateFixture(c, PopulationLedgerTests.Bindings(),+ new[] { new PopulationInventoryRow("fixture", 0, PopulationLedgerTests.Person()) }, mode: open ? Mode.Open : null);+ Assert.Equal((true, false), (s.PopulationLedger.IsInitialized, s.PopulationLedger.IsHistorical));+ var why = new List<Cause>();+ var before = s.Describe(); var hash = s.Hash();+ Assert.Contains("integration is held",+ Assert.Throws<NotSupportedException>(() => Demobilization.Give(c, s, 0, null, why)).Message);+ Assert.Equal(before, s.Describe()); Assert.Equal(hash, s.Hash()); Assert.Empty(why);+ }++ // R-POP-003: the same order on the same seed gives the same ledger and state hash, and a clone's run matches.+ [Fact]+ public void SendHomeIsDeterministic()+ {+ var c = Gdd03();+ var a = Dark(c); var b = Dark(c); var clone = a.Clone();+ var unit = Opening(c, a);+ Assert.Null(Demobilization.Give(c, a, unit, null, new List<Cause>()));+ Assert.Null(Demobilization.Give(c, b, unit, null, new List<Cause>()));+ Assert.Null(Demobilization.Give(c, clone, unit, null, new List<Cause>()));+ Assert.Equal(a.PopulationLedger.Canonical(), b.PopulationLedger.Canonical());+ Assert.Equal(a.Hash(), b.Hash()); Assert.Equal(a.Hash(), clone.Hash());+ }+}diff --git a/sim/Statecraft.Sim.Tests/RemainingCauseKeysTests.cs b/sim/Statecraft.Sim.Tests/RemainingCauseKeysTests.csindex aed46d8c2..5e073fc06 100644--- a/sim/Statecraft.Sim.Tests/RemainingCauseKeysTests.cs+++ b/sim/Statecraft.Sim.Tests/RemainingCauseKeysTests.cs@@ -116,7 +116,7 @@ public class RemainingCauseKeysTestssites++;}}- Assert.Equal(129, sites); // 129 with R-ENEMY-007's truce-break line (a late operation inside an accepted truce, #2543); 128 with R-ENEMY-007's lapse cost (Q8, the event-amount Security line of a lapsed operation, #2543); 127 with R-ENEMY-007's keyed postponed/lapsed operation producer (#2543); 126 with #2558: EconomySystem.MoneyLine, the event Debt line worded for the Money row; 125 with #1711's CityHeld (R-CITY-010); 124 with #2534's enemy attack-order line (Combat.Give marks the order's own cause); 123 with #2471's gdd-0.3 field Food line (R-FIELD-002); 122 with #2527's FoodImported and the conversion's fx_reserves line; 120 with #2457's event Debt line (R-EFX-009); 119 with #1700 slice B's ProjectBuilderFreed; 118 with #1700's builders (R-CITY-011: two ProjectBuilder lines, ProjectWaiting, the build order's job-default line); 114 with #1703's gdd-0.3 housing surcharge and housing cohesion lines; 112 with the arms workshops' five (R-ARMS-005 with its job-default line, R-ARMS-006; #1701); 107 with R-MONEY-004's DollarsConverted (#813); 106 since #2212: EconomySystem.OtherMoney's line (105 since #2199: PayOrBorrow's Paid line)+ Assert.Equal(130, sites); // 130 with R-UNIT-005's ledger Send home Arms line (owner, 8 November 2026, "Yes, one Why line (Recommended)", #1725 PR 7); 129 with R-ENEMY-007's truce-break line (a late operation inside an accepted truce, #2543); 128 with R-ENEMY-007's lapse cost (Q8, the event-amount Security line of a lapsed operation, #2543); 127 with R-ENEMY-007's keyed postponed/lapsed operation producer (#2543); 126 with #2558: EconomySystem.MoneyLine, the event Debt line worded for the Money row; 125 with #1711's CityHeld (R-CITY-010); 124 with #2534's enemy attack-order line (Combat.Give marks the order's own cause); 123 with #2471's gdd-0.3 field Food line (R-FIELD-002); 122 with #2527's FoodImported and the conversion's fx_reserves line; 120 with #2457's event Debt line (R-EFX-009); 119 with #1700 slice B's ProjectBuilderFreed; 118 with #1700's builders (R-CITY-011: two ProjectBuilder lines, ProjectWaiting, the build order's job-default line); 114 with #1703's gdd-0.3 housing surcharge and housing cohesion lines; 112 with the arms workshops' five (R-ARMS-005 with its job-default line, R-ARMS-006; #1701); 107 with R-MONEY-004's DollarsConverted (#813); 106 since #2212: EconomySystem.OtherMoney's line (105 since #2199: PayOrBorrow's Paid line)}[Fact]diff --git a/sim/Statecraft.Sim/Cause.cs b/sim/Statecraft.Sim/Cause.csindex 35535ead6..d0bfe0eba 100644--- a/sim/Statecraft.Sim/Cause.cs+++ b/sim/Statecraft.Sim/Cause.cs@@ -185,6 +185,8 @@ namespace Statecraft.Simpublic const string TrainingCancelled = "training_cancelled";/// <summary>Args: k.City; Training.CourseId(type).</summary>public const string TrainingArmsReturned = "training_arms_returned";+ /// <summary>Args: city; CauseKeys.Number(u.Id). R-UNIT-005 on a Historical ledger game only (#1725 PR 7).</summary>+ public const string SentHomeArmsReturned = "sent_home_arms_returned";/// <summary>Args: CauseKeys.Number(aim).</summary>public const string ReplacementsStopped = "replacements_stopped";/// <summary>Args: CauseKeys.Number(k.Count); Training.CourseId(type); CauseKeys.Number(target.Id).</summary>@@ -282,7 +284,7 @@ namespace Statecraft.SimEventNew, EventChosen, EventDelegated, EventDelegatedPartial, OperationPostponed, OperationLapsed, OperationLapsedSigned, OperationLapsedUnitLost, OperationWaitsForArmistice, EventAmount, EventStock, EventGrant, EventCity,EventUnlock, EventPolicy, EventSetRung, EventRejoin, MilitaryUpkeep, HousingSurcharge, HousingCohesion,ObjectiveCompleted, PrisonersReturned, SoldiersReturned,- WorkersAssigned, WagesPaid, ImmigrantsHoused, HousingShortage, ImmigrantsWaiting, RecruitsVeteran, CorridorStarted, CorridorCancelled, CorridorCompleted, PioneersVeteran, MapBorrowed, MapBuilt, LandWorkStarted, SiteStarted, SiteCancelled, SiteCompleted, ProjectStarted, ProjectCancelled, ProjectCompleted, ProjectBuilder, ProjectBuilderFreed, ProjectWaiting, ArmsBought, WorkshopWorkers, WorkshopArms, WorkshopPaused, DollarsConverted, DollarsConvertedFx, FoodHarvest, FieldFood, FoodShortage, FoodWithoutImports, FoodImported, PrisonerFood, PrisonerFoodShortage, CraftsmenReturned, CraftsmenReassigned, PioneerReturned, PioneersReassigned, TrainingStarted, TrainingArms, TrainingCancelled, TrainingArmsReturned, ReplacementsStopped, ReplacementsJoined, MilitaryTrained, PioneersTrained, CraftsmenTrained, Appointed, Reshuffle, AppointmentsEnded, ApprovalStability, CoalitionCollapsed, LegislatureConvened, GovernmentTookOffice, CoalitionChanged, EraEnded, AdvisoryPolicyRejected, PolicyRejected, PolicySet, AdvisoryBudgetRejected, BudgetRejected, PlaceCaptured, EnemyRegained, PlaceAnnexed, PlaceWithdrawn, PlaceDeported, DeportEffect, DeportCost, OccupationStarted, PendingBecameRaid, OccupationLostUnit, OccupationCountdown, DepopulationSupport, CityHeld,+ WorkersAssigned, WagesPaid, ImmigrantsHoused, HousingShortage, ImmigrantsWaiting, RecruitsVeteran, CorridorStarted, CorridorCancelled, CorridorCompleted, PioneersVeteran, MapBorrowed, MapBuilt, LandWorkStarted, SiteStarted, SiteCancelled, SiteCompleted, ProjectStarted, ProjectCancelled, ProjectCompleted, ProjectBuilder, ProjectBuilderFreed, ProjectWaiting, ArmsBought, WorkshopWorkers, WorkshopArms, WorkshopPaused, DollarsConverted, DollarsConvertedFx, FoodHarvest, FieldFood, FoodShortage, FoodWithoutImports, FoodImported, PrisonerFood, PrisonerFoodShortage, CraftsmenReturned, CraftsmenReassigned, PioneerReturned, PioneersReassigned, TrainingStarted, TrainingArms, TrainingCancelled, TrainingArmsReturned, SentHomeArmsReturned, ReplacementsStopped, ReplacementsJoined, MilitaryTrained, PioneersTrained, CraftsmenTrained, Appointed, Reshuffle, AppointmentsEnded, ApprovalStability, CoalitionCollapsed, LegislatureConvened, GovernmentTookOffice, CoalitionChanged, EraEnded, AdvisoryPolicyRejected, PolicyRejected, PolicySet, AdvisoryBudgetRejected, BudgetRejected, PlaceCaptured, EnemyRegained, PlaceAnnexed, PlaceWithdrawn, PlaceDeported, DeportEffect, DeportCost, OccupationStarted, PendingBecameRaid, OccupationLostUnit, OccupationCountdown, DepopulationSupport, CityHeld,};/// <summary>A number as an Arg: invariant and round-trip, so the UI rounds exactly the value Message rounded.</summary>diff --git a/sim/Statecraft.Sim/Demobilization.cs b/sim/Statecraft.Sim/Demobilization.csindex 28a646789..de1d26e2f 100644--- a/sim/Statecraft.Sim/Demobilization.cs+++ b/sim/Statecraft.Sim/Demobilization.cs@@ -60,23 +60,73 @@ namespace Statecraft.Sim/// <summary>R-UNIT-005: sends the unit home at once, like CancelTraining returns a cohort (R-TRAIN-002): the unit/// leaves the map and its strength joins the nearest city's civilians, employed count untouched, so the people count/// in the city's jobs and housing rules from the same turn. Refused, state untouched, with <see cref="Check"/>'s- /// reason.</summary>+ /// reason. On a Historical ledger game (#1725 PR 7) the formation's soldiers are records instead: see+ /// <see cref="LedgerSendHome"/>.</summary>internal static string? Give(Content c, GameState s, int unitId,IReadOnlyDictionary<int, AttackRecord>? attacked, List<Cause> why){- PopulationLedger.RefuseAggregate(s);+ PopulationLedger.RefuseUnlessHistorical(s); // #1725 PR 7: on a Historical ledger the soldiers sent home are recordsvar refused = Check(c, s, unitId, attacked);if (refused != null) return refused;var u = s.Units[unitId];var city = Nearest(c, u.Q, u.R);+ var back = 0;+ if (s.PopulationLedger.IsHistorical)+ {+ refused = LedgerSendHome(c, s, u, city, out back);+ if (refused != null) return refused;+ }+ else+ {+ var x = s.Cities[city];+ s.Cities[city] = x.WithCounts(x.Civilians + u.Strength, x.Employed, x.Refugees);+ }s.Units.Remove(unitId);- var x = s.Cities[city];- s.Cities[city] = x.WithCounts(x.Civilians + u.Strength, x.Employed, x.Refugees);var ppu = c.RulesAt(s.Date).Mvp!.PeoplePerUnit;why.Add(new Cause("map", unitId.ToString(CultureInfo.InvariantCulture), u.Strength, FormattableString.Invariant($"Unit {unitId} is sent home: its {u.Strength * ppu:N0} people are civilians in {PlayerText.Settlement(c, city)} now"),key: WhyKeys.SentHome, units: new[] { new UnitRef(u) },args: new[] { (u.Strength * ppu).ToString(CultureInfo.InvariantCulture), city }));+ if (back > 0) // the ledger path only (owner, 8 November 2026: "Yes, one Why line (Recommended)"), as Training's Cancel writes it+ why.Add(new Cause("city", "arms", back, FormattableString.Invariant($"{PlayerText.Settlement(c, city)}: unit {unitId} returned {back} Arms"), key: CauseKeys.SentHomeArmsReturned, args: new[] { city, CauseKeys.Number(unitId) }));+ return null;+ }++ /// <summary>R-UNIT-005 on a Historical ledger game (#1699, #1725 PR 7; owner, 8 November 2026, #1725+ /// issuecomment-6726421643 and issuecomment-6727007834). "Every soldier in it (Recommended)": every active-soldier record+ /// serving the formation's target (<see cref="Training.FormationTarget"/>) leaves service. "Refuse with a reason+ /// (Recommended)": when the formation's strength differs from those records, the order is refused with a plain reason+ /// and nothing changes. "Nearest city, unemployed (Recommended)": each record becomes a free civilian without an+ /// assignment located in <paramref name="city"/> (its region plus the city), so the city houses it from the same turn.+ /// "Settled in (Recommended)": its reception ticks are reception.turns. "Keep both (Recommended)": its military+ /// qualification and combat XP stay. "Back to Arms stock (Recommended)": its issued military item leaves the record and+ /// goes back to the stock once. "No, records only (Recommended)": no aggregate city field is written. The records are+ /// written in one validated commit; the caller removes the unit after it and, for "Yes, one Why line (Recommended)",+ /// writes one Why line naming the <paramref name="back"/> Arms returned. Null when done, else the reason.</summary>+ static string? LedgerSendHome(Content c, GameState s, Unit u, string city, out int back)+ {+ back = 0;+ var target = Training.FormationTarget(c, u.Id);+ var serving = s.PopulationLedger.Units.Where(p => p.Status == PopulationStatus.ActiveSoldier+ && string.Equals(p.Assignment.Target, target, StringComparison.Ordinal)).ToList();+ if (serving.Count != u.Strength)+ return string.Format(CultureInfo.InvariantCulture, Training.LedgerRefusedStrength, u.Id, serving.Count, u.Strength);+ var region = c.PlayerRegions.AtLocation(city)?.Id+ ?? throw new InvalidOperationException("No region in regions.yaml for " + city + " (R-POP-004).");+ var location = new PopulationLocation(region, city: city);+ var received = c.RequirePopulationInteger("reception.turns");+ var items = 0;+ var civilians = serving.Select(p =>+ {+ var e = p.Equipment;+ if (e.MilitaryId != null) items++;+ return new PopulationUnit(p.Id, PopulationStatus.FreeCivilian, received, location, PopulationAssignment.Unassigned,+ p.Profession, p.Tier, p.WorkXp, p.Qualification, p.CombatXp, new PopulationEquipment(e.ToolsId, e.ToolsPaid),+ p.Captor, p.Home);+ }).ToList();+ s.PopulationLedger.Commit(civilians, Array.Empty<PopulationTarget>());+ back = (int)Math.Min(items, (long)int.MaxValue - s.Arms); // the stock stops at int.MaxValue, as Training's cancel leaves it+ s.Arms += back;return null;}diff --git a/sim/Statecraft.Sim/Training.cs b/sim/Statecraft.Sim/Training.csindex 0dd0d9007..533963488 100644--- a/sim/Statecraft.Sim/Training.cs+++ b/sim/Statecraft.Sim/Training.cs@@ -371,7 +371,7 @@ namespace Statecraft.Sim/// <summary>The ActiveService target of map unit <paramref name="unit"/>: a starting force's own (unit id i is/// <c>c.StartingForces[i]</c>, StartingForces.Init; R-POP-004), else the one bound at its graduation.</summary>- static string FormationTarget(Content c, int unit) => unit >= 0 && unit < c.StartingForces.Count+ internal static string FormationTarget(Content c, int unit) => unit >= 0 && unit < c.StartingForces.Count? HistoricalPopulation.FormationPrefix + c.StartingForces[unit].Row: FormationPrefix + unit.ToString(CultureInfo.InvariantCulture);diff --git a/unity/Assets/Tests/EditMode/CauseTextTests.cs b/unity/Assets/Tests/EditMode/CauseTextTests.csindex 0768d0f33..64872a599 100644--- a/unity/Assets/Tests/EditMode/CauseTextTests.cs+++ b/unity/Assets/Tests/EditMode/CauseTextTests.cs@@ -645,7 +645,7 @@ public class CauseTextTestsCauseKeys.EventRejoin, CauseKeys.EventSetRung, CauseKeys.EventStock, CauseKeys.EventUnlock,CauseKeys.MilitaryUpkeep, CauseKeys.HousingSurcharge, CauseKeys.HousingCohesion,CauseKeys.ObjectiveCompleted, CauseKeys.PrisonersReturned, CauseKeys.SoldiersReturned,- CauseKeys.FieldFood }), rows.Select(x => x.Key).Distinct(), "all remaining keys"); // FieldFood (#2471): only the gdd-0.3 field fixture makes it, no turn yet, so no wording yet+ CauseKeys.FieldFood, CauseKeys.SentHomeArmsReturned }), rows.Select(x => x.Key).Distinct(), "all remaining keys"); // FieldFood (#2471): only the gdd-0.3 field fixture makes it, no turn yet, so no wording yet; SentHomeArmsReturned (#1725 PR 7): only a Historical ledger game's Send home makes it, no turn yet, so no wording yetvar appointed = rows.Single(x => x.Key == CauseKeys.Appointed);StringAssert.Contains("התפקיד שנשמר", CauseText.Line(appointed, c, NoRows, he, names), "historical title, not current title");}