Skip to content

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): combat runs on a Historical ledger game: losses are records lost, and surrender captures them (#1706, #1725 PR 7) (#2985)

Eyal Golan0cb141006053
diff --git a/changelog.d/1725-pr7-combat.md b/changelog.d/1725-pr7-combat.md
new file mode 100644
index 000000000..d0a63fc65
--- /dev/null
+++ b/changelog.d/1725-pr7-combat.md
@@ -0,0 +1,6 @@
+- GDD 0.3 starting population (Refs #1725, Refs #1706): battles now run on the inactive dark start's Historical ledger.
+ Each unit of strength one of the player's formations loses removes one of its soldier records as a death, the lowest
+ id first, noted with the battle's date and hex; a trained formation is covered too. The battle itself, its draw and
+ its report are the aggregate start's, and a surrender's losses are written before its soldiers are captured. A
+ surrender's report counts the soldiers actually captured, and a formation's records beyond its strength go home as
+ Send home sends them, with Send home's report lines. No new-game wiring, so there is no change in the game.
diff --git a/docs/rules/mvp.md b/docs/rules/mvp.md
index 5a070cb6a..001b15dcc 100644
--- a/docs/rules/mvp.md
+++ b/docs/rules/mvp.md
@@ -340,10 +340,12 @@ R-COMBAT-003: The face gives the population units each side loses and whether th
R-COMBAT-004: Each of the player's units pays `mvp.arms_per_attack` (real value 1; artillery pays its `arms_per_fire` instead, R-COMBAT-007) from the Arms stock when the attack is given; an attack the stock cannot pay for is refused. Enemy units pay nothing (Q-ENEMY-4: no supply). This price rule remains for `gdd-0.1`; under `gdd-0.3`, player attacks and artillery fire neither read nor spend these shot prices (#1706; owner ruling, 25 October 2026, on #1668). Arms stock, purchases, equipment, replacements and training refunds remain governed by their existing rules.
-R-COMBAT-005: Combat changes only combatant units, the Arms and, through a surrender, the counts of prisoners and of the player's soldiers held (R-POW-001, R-POW-005), and, under `gdd-0.3`, the quiet-turn count of each front in the engagement (R-WAR-005). No city, locality, resident, building, job or other resource, and no score, changes because of a combat outcome (Q-CIV-2; impact plan §4.3: kills and enemy losses never score). Halutzim are never attackers or targets. Lost strength comes back only through replacements (R-TRAIN-004), which are training, not a combat outcome. Under `gdd-0.3`, attacks and artillery fire leave the Arms stock unchanged; the other combat effects in this rule remain.
+R-COMBAT-005: Combat changes only combatant units, the Arms and, through a surrender, the counts of prisoners and of the player's soldiers held (R-POW-001, R-POW-005), and, under `gdd-0.3`, the quiet-turn count of each front in the engagement (R-WAR-005). No city, locality, resident, building, job or other resource, and no score, changes because of a combat outcome (Q-CIV-2; impact plan §4.3: kills and enemy losses never score). Halutzim are never attackers or targets. Lost strength comes back only through replacements (R-TRAIN-004), which are training, not a combat outcome. Under `gdd-0.3`, attacks and artillery fire leave the Arms stock unchanged; the other combat effects in this rule remain. One exception, on a game with an initialized Historical ledger only: when a surrendering own formation has more serving records than its strength, the leftover records go home as R-POW-005 sets out (owner, 9 November 2026: "Sent home (Recommended)"), so they become residents, free civilians of the nearest city, and their issued items go back to the Arms stock.
R-COMBAT-006: Each engagement's Why line names the hex, the units on each side and the ratio, and states "the attackers lost N people and the defenders lost M people", the strength each side lost times `people_per_unit`, in the same words whichever side attacks (Q-CIV-4; impact plan §4.2). A destroyed unit gets "Unit N was destroyed", a retreat the hex it went to, a surrender the people it surrendered with. No running count of losses is kept; the war's Israeli total is PR 13's.
+On a game with an initialized Historical ledger (the dark start, R-POP-004; #1706, #1725 PR 7; owner, 8 November 2026, #1725: https://github.com/eyalgolan/statecraft-israel/issues/1725#issuecomment-6726365722), `Combat.Resolve` and `Combat.Outcomes` run, and every engagement, step 2's and the player's instant attack alike, is fought as above on the units' strength, with the same draw, units and Why lines as the aggregate game, but for an own surrender's (below). Each population unit an own formation loses (R-COMBAT-003) also removes one of its serving soldier records, the active soldiers on its target (a starting force's `units_1948/<row>`, a trained formation's `formation/<unit id>` from R-TRAIN-003; "Yes, after #2964 (Recommended)"), from the ledger as a combat loss (R-POP-001): the lowest id first ("Lowest id first (Recommended)"), with the provenance `combat/<turn date yyyy-MM-dd>/<q>,<r>` of the engaged hex ("Date + battle hex (Recommended)"). Every loss is a death and there is no wounded status ("No, losses are deaths (Recommended)"). Combat experience stays on the formation (R-UNIT-011): no record's combat XP changes ("No, formation only (Recommended)"). A retreat moves the unit only: its records keep their formation's region-only location ("No, keep region (Recommended)"). A formation whose strength differs from its serving records still fights on its strength, and a record is removed only while one is left ("Go ahead on strength"). Enemy formations are not own population and their losses touch no record; a lost record's issued military item leaves with it, with no refund (R-COMBAT-005). An own surrender's losses are written before `Prisoners.Take` sees its records, so for a formation whose records matched its strength R-POW-005 finds the records left numbering its strength ("Prisoners #1710 first (Recommended)"); a formation whose records do not match is captured too, at most its strength of the records left, with no refusal (owner, 9 November 2026: "Go ahead on strength (Recommended)"; R-POW-005), and the records left beyond its strength go home as R-POW-005 sets out (owner, 9 November 2026: "Sent home (Recommended)"), with Send home's own Why lines after the surrender line ("Yes, reuse Send home's (Recommended)"). An own surrender's Why line states the people it surrendered with as the records captured times `people_per_unit`, not its strength times `people_per_unit` (owner, 9 November 2026: "Records captured (Recommended)"): the same key, `surrendered_held`, and the same one argument, a count of people; without a ledger it is the strength, as before. The losses draw nothing. A synthetic or Open ledger is still refused (R-POP-002). `LedgerCombatTests` pins this.
+
Phase 5 PR 9, part 1 (#748): artillery's combat role and the armoured car. Q-ARTY-1 and Q-ARTY-2 are the plan's recommendations (owner, 15 October 2026, #375: "Take all recommendations"). The numbers in `unit_types.yaml` are agent defaults proposed on #748 and accepted by the owner as design values on 21 October 2026, together with three of R-COMBAT-007's mechanics that the Q-ARTY-1 text does not settle: the attackers' losses sparing the guns, the hold refused as "never holds ground", and the 200% counting on defence too (owner, 21 October 2026, #748, https://github.com/eyalgolan/statecraft-israel/issues/748#issuecomment-6317339304). How either type is acquired (R-UNIT-008) is part 2, on top of Phase 5 PR 3's training.
R-COMBAT-007: Artillery (a type of class `artillery`, which needs a `range` and an `arms_per_fire`; real values 2 and 2) attacks alone from range. Its `UnitOrder(unit, attack, q, r)` names an enemy hex at a hex distance of 1 to its `range`; a farther hex is refused with "That hex is beyond the unit's range". The player's artillery attacks at once like any unit, pays its type's `arms_per_fire` in place of `mvp.arms_per_attack`, and its losses spare it, so it loses nothing. Enemy artillery still joins an engagement in step 2 after the other attackers of its side and only when at least one of them joins; otherwise it holds its fire, with a line, pays nothing and keeps its order. Its strength counts at its `combat_percent` (real value 200). Artillery that is attacked defends and takes losses like any unit. It never holds ground: a hold order for it is refused with "Artillery does not hold ground" (fortify is allowed). As in any attack, residents are never a target (Q-CIV-2, R-COMBAT-005). Under `gdd-0.3`, artillery still fires alone at once from the existing range and keeps the same outcomes, but has no Arms affordability check or deduction; `arms_per_fire` is not required or read in that identity. Range and combat factors retain their existing validation. The remaining combat redesign is held.
@@ -404,7 +406,7 @@ R-POW-003: Prisoners are never labour, Money, Arms, housing occupants, jobs or a
R-POW-004: An event with `prisoners: <front>` (egypt, jordan, lebanon or syria) is that front's exchange card. It fires only while the front holds prisoners either way, a stored 0 holding nobody (the Jordan card also returns the Iraqi prisoners: the Jordan agreement took over the Iraqi sector, Art. VI, Q-OBJ-1; the ALA and the local forces belong to no front, so no card returns theirs). It has exactly one option and resolves without an RNG draw, like an objective's card. Resolving it moves its sides' prisoners from `PrisonersHeld` to `PrisonersReturned` and adds `mvp.points_per_prisoner_unit_returned` (real value 10) to the score for each population unit returned (Q-POW-2). Nothing scores at the capture (impact plan §4.3 item 3). It holds unchanged under gdd-0.3, played with a synthetic exchange card: a returned unit scores 10 (owner, 1 November 2026, O7: "10 per unit, main (Recommended)"; `PrisonersGdd03Tests.AReturnedUnitScoresTenPoints`); the card fires once, so prisoners taken after it has resolved stay held to the end of the game with no points (27M-19; `PrisonersGdd03Tests.PrisonersTakenAfterTheCardStayHeldWithNoPoints`); and a loaded save pays no return twice (`PrisonersGdd03Tests.ASaveAndReloadCannotPayTwice`).
-R-POW-005: A surrendered unit of the player's is added to `GameState.SoldiersHeld` under the side of the engagement's lowest-id attacker. In step 7, after the prisoners eat, the Treasury pays `mvp.held_soldier_cost_per_turn` (real value IL 0.005m) for each population unit held, borrowing what it lacks (R-MONEY-003; Q-POW-4). They come home when that side's front's exchange card resolves, with no score effect. On the dark start's Historical ledger (#1710, #1725 PR 7) the surrender also makes the formation's serving soldier records Captured, in one validated ledger commit after every check. Their captor is that same side: every enemy side with military units (a `unit_types.yaml` side other than `israel` and `""`) is bound as a captor when the Historical ledger is initialized (owner, 8 November 2026: "Winning side, set at start (Recommended)"). Their Home is the formation's region, region only ("Formation's region (Recommended)"). Each keeps its id, history and issued military item, unchanged while held; what happens to the item on return is #2473's (docs/GDD.md Q10; "Stays on record (Recommended)"). `GameState.SoldiersHeld` keeps its count beside the records, and per captor side it must equal the Captured records with that captor: Take and Upkeep check this before any write ("Keep count + check (Recommended)"). The held soldiers keep this Money cost ("Yes, as today (Recommended)"; docs/gdd/military-combat.md calls the exemption non-operative). A surrender whose serving records do not number its strength, to a side that is not a bound captor, or of a unit that is not a `units_1948.yaml` formation (a trained formation, whose records come with #2964), is refused: Take throws before it writes anything. Called from combat, the throw comes after the engagement's draw and losses and after any earlier engagement of the same command or turn; on a direct call to `Combat.Strike` or `Combat.Resolve` those writes stay on the state object given. In the game that object is `Simulation.Step`'s clone (`sim/Statecraft.Sim/Simulation.cs:51`; combat's callers are `Simulation.cs:268` and `TurnResolver.cs:20`), so the whole command's or turn's result is discarded and the caller's state is unchanged. Today Step refuses an initialized ledger (`Simulation.cs:48`) and `Combat.Resolve` refuses one at its entry, so only a direct `Combat.Strike` reaches the refusal in combat (`LedgerPrisonersTests.ARefusedCaptureInCombatThrowsAndAPriorCloneIsUnchanged`). `Prisoners.Return` still refuses any initialized ledger, a Historical one included (`LedgerPrisonersTests.ReturnStillRefusesAHistoricalLedger`): it removes the `SoldiersHeld` count but moves no Captured record, so the change that lifts that refusal (#2473) must move the Captured records back in the same commit. Hand-off to #1706: in combat the defenders' losses lower the surrendering unit's strength before `Prisoners.Take` sees its records, and no ledger loss is written for them, so before `Combat.Resolve` runs on a ledger, #1706 must write those losses to the ledger first or Take refuses the surrender.
+R-POW-005: A surrendered unit of the player's is added to `GameState.SoldiersHeld` under the side of the engagement's lowest-id attacker. In step 7, after the prisoners eat, the Treasury pays `mvp.held_soldier_cost_per_turn` (real value IL 0.005m) for each population unit held, borrowing what it lacks (R-MONEY-003; Q-POW-4). They come home when that side's front's exchange card resolves, with no score effect. On the dark start's Historical ledger (#1710, #1725 PR 7) the surrender also makes the formation's serving soldier records Captured, in one validated ledger commit after every check. Their captor is that same side: every enemy side with military units (a `unit_types.yaml` side other than `israel` and `""`) is bound as a captor when the Historical ledger is initialized (owner, 8 November 2026: "Winning side, set at start (Recommended)"). Their Home is the formation's region, region only ("Formation's region (Recommended)"). Each keeps its id, history and issued military item, unchanged while held; what happens to the item on return is #2473's (docs/GDD.md Q10; "Stays on record (Recommended)"). `GameState.SoldiersHeld` keeps its count beside the records, and per captor side it must equal the Captured records with that captor: Take and Upkeep check this before any write ("Keep count + check (Recommended)"). The held soldiers keep this Money cost ("Yes, as today (Recommended)"; docs/gdd/military-combat.md calls the exemption non-operative). The records captured are the active soldiers on the formation's target, found as battles find them (`Training.FormationTarget`: an opening formation's `units_1948/<row>`, a trained formation's `formation/<unit id>` from R-TRAIN-003), so a trained formation's soldiers become captives too (owner, 9 November 2026: "Yes, in #1706 (Recommended)"). A formation whose serving records do not number its strength is not refused, and the turn goes on (owner, 9 November 2026: "Go ahead on strength (Recommended)"): with more records than its strength, its strength of them are captured, the lowest ids first (as "Lowest id first (Recommended)" and docs/GDD.md's ascending population ids), and the rest leave service as soldiers sent home do (owner, 9 November 2026: "Sent home (Recommended)"): R-UNIT-005's ledger outcome, by Send home's own code (`Demobilization.RecordsHome`, written in the capture's one ledger commit, `PopulationLedger.Capture`, then `Demobilization.ReturnArms`), with "Nearest city, unemployed (Recommended)", "Settled in (Recommended)", "Keep both (Recommended)", "Back to Arms stock (Recommended)" and "No, records only (Recommended)". Each becomes a free civilian without an assignment, located in the nearest city to the formation's hex by R-UNIT-005's rule (its region plus the city), with reception ticks `reception.turns`, its qualification and combat XP kept, and its issued military item back in the Arms stock once; after the surrender line come Send home's own Why lines, in Send home's order (owner, 9 November 2026: "Yes, reuse Send home's (Recommended)"): its people line (key `sent_home`, "Unit N is sent home: its P people are civilians in <city> now", P the leftover records times `people_per_unit`), then, only when Arms go back, its Arms line ("Yes, one Why line (Recommended)", key `sent_home_arms_returned`). No aggregate city field is written. Every check comes before the first write: the captives and the leftovers change in one validated ledger commit, so a leftover location the ledger does not bind, like an unbound captor, refuses the surrender with nothing written; the Arms go back after that commit. With fewer records than its strength, all of them are captured. On a ledger game `SoldiersHeld` grows by the number of records captured, not by the unit's strength, so the check above still holds; without a ledger it grows by the strength, as before. For a formation whose records do not match its strength, the count held, and with it the Money cost per population unit held, therefore follows the records captured. A surrender to a side that is not a bound captor, or made while the held count already disagrees with the Captured records, is refused: Take throws before it writes anything. Called from combat, the throw comes after the engagement's draw and losses and after any earlier engagement of the same command or turn; on a direct call to `Combat.Strike` or `Combat.Resolve` those writes stay on the state object given. In the game that object is `Simulation.Step`'s clone (`sim/Statecraft.Sim/Simulation.cs:51`; combat's callers are `Simulation.cs:268` and `TurnResolver.cs:20`), so the whole command's or turn's result is discarded and the caller's state is unchanged. Today Step refuses an initialized ledger (`Simulation.cs:48`), so only a direct `Combat.Strike` or `Combat.Resolve` reaches the refusal in combat (`LedgerPrisonersTests.ARefusedCaptureInCombatThrowsAndAPriorCloneIsUnchanged`). `Prisoners.Return` still refuses any initialized ledger, a Historical one included (`LedgerPrisonersTests.ReturnStillRefusesAHistoricalLedger`): it removes the `SoldiersHeld` count but moves no Captured record, so the change that lifts that refusal (#2473) must move the Captured records back in the same commit. Since #1706 the engagement's losses have already removed the surrendering formation's lost records as combat losses (R-COMBAT-006's ledger paragraph).
Under gdd-0.3 (#1710), the prisoners in these pins come from a real surrender (R-POW-001). `PrisonersGdd03Tests.PrisonersEatAndAFoodShortfallCostsCohesion` pins R-POW-002, `PrisonersGdd03Tests.PrisonersAreNeverAResource` pins R-POW-003, and `PrisonersGdd03Tests.OwnSoldiersAreCapturedCostMoneyAndComeHome` pins R-POW-005. The real per-front exchange cards wait on #751, so the return and homecoming pins use the synthetic card until those cards land. On the dark start, `LedgerPrisonersTests` pins R-POW-001, R-POW-002 and R-POW-005 against the aggregate start with the same counts.
diff --git a/sim/Statecraft.Sim.Tests/LedgerCombatTests.cs b/sim/Statecraft.Sim.Tests/LedgerCombatTests.cs
new file mode 100644
index 000000000..2f518009c
--- /dev/null
+++ b/sim/Statecraft.Sim.Tests/LedgerCombatTests.cs
@@ -0,0 +1,544 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using Statecraft.Sim;
+
+/// <summary>#1706, #1725 PR 7: Combat.Resolve and Combat.Outcomes on a game with an initialized Historical ledger, the dark
+/// start. Each population unit an own formation loses in an engagement removes one of its serving soldier records from the
+/// ledger as a combat loss (R-COMBAT-003, R-POP-001), the player's instant attack and step 2's alike; the units, the draw
+/// and the Why lines are the aggregate game's. Owner rulings, 8 November 2026 (#1725): "Lowest id first (Recommended)",
+/// "No, losses are deaths (Recommended)", "No, formation only (Recommended)", "Go ahead on strength", "Date + battle hex
+/// (Recommended)", "Prisoners #1710 first (Recommended)", "No, keep region (Recommended)" and "Yes, after #2964
+/// (Recommended)". Owner rulings, 9 November 2026: "Go ahead on strength (Recommended)", "Yes, in #1706 (Recommended)",
+/// "Sent home (Recommended)" and "Records captured (Recommended)" for a surrender (R-POW-005); on a ledger game the
+/// surrender Why line states the records captured, and a formation's leftover records add Send home's Arms line.</summary>
+public class LedgerCombatTests
+{
+ static Content Gdd03() => HistoricalPopulationTests.Real(true);
+
+ static GameState Dark(Content c) => Simulation.NewGame(c, 1, Mode.Historical, darkStart: true);
+
+ static GameState Aggregate(Content c) => Simulation.NewGame(c, 1, Mode.Historical);
+
+ // "Yes, after #2964 (Recommended)": a formation's soldiers are the active-soldier records on its target (#2964's link).
+ static List<PopulationUnit> Serving(Content c, GameState s, int unit) => s.PopulationLedger.Units
+ .Where(p => p.Status == PopulationStatus.ActiveSoldier && p.Assignment.Target == Training.FormationTarget(c, unit))
+ .OrderBy(p => p.Id).ToList();
+
+ // "Date + battle hex (Recommended)": combat/<turn date>/<q>,<r> of the engaged hex.
+ static string Source(GameState s, int q, int r) =>
+ string.Format(CultureInfo.InvariantCulture, "combat/{0:yyyy-MM-dd}/{1},{2}", s.Date, q, r);
+
+ static string LossLine(int id, string source) => PopulationText.Fields("loss", id, source);
+
+ static List<string> LossLines(GameState s) =>
+ s.PopulationLedger.Canonical().Where(l => l.StartsWith("4:loss|", StringComparison.Ordinal)).ToList();
+
+ // The own opening formations, strongest first (lowest id on a tie).
+ static List<Unit> Own(Content c, GameState s) => s.Units.Values
+ .Where(u => u.Side == Movement.PlayerSide && u.Id < c.StartingForces.Count && u.Strength > 0)
+ .OrderByDescending(u => u.Strength).ThenBy(u => u.Id).ToList();
+
+ static Unit Enemy(GameState s, int nth = 0) => s.Units.Values.Where(u => Prisoners.FrontOf.ContainsKey(u.Side))
+ .OrderBy(u => u.Id).Skip(nth).First();
+
+ static List<(int Q, int R)> Ring(Content c, GameState s, Unit u) => Movement.Neighbours
+ .Select(d => (Q: u.Q + d.Q, R: u.R + d.R)).Where(h => c.HexAt(h.Q, h.R) is MapHex hex && hex.Land).ToList();
+
+ static void Place(GameState s, Unit u, int q, int r, int? strength = null, string order = "", string target = "") =>
+ s.Units[u.Id] = new Unit(u.Id, u.Type, q, r, u.Service, u.Side, strength ?? u.Strength, order, target, u.HomeCity, u.Full, u.CombatXp);
+
+ // Step 2 on its own: no attack order is left standing, then one enemy unit, set next to own unit
+ // <paramref name="defender"/> on a free land hex, attacks it with <paramref name="strength"/>.
+ static void Besiege(Content c, GameState s, int defender, int strength)
+ {
+ foreach (var u in s.Units.Values.ToList()) if (u.Order == Combat.Attack) Place(s, u, u.Q, u.R);
+ var d = s.Units[defender];
+ var free = Ring(c, s, d).First(h => !s.Units.Values.Any(x => x.Q == h.Q && x.R == h.R));
+ Place(s, Enemy(s), free.Q, free.R, strength, Combat.Attack, FormattableString.Invariant($"{d.Q},{d.R}"));
+ }
+
+ static string Units(GameState s) => string.Join(";", s.Units.Values.Select(x => x.Canonical()));
+
+ // No attack order is left standing; one enemy unit goes on each land hex around own unit <paramref name="unit"/> and every
+ // other unit leaves that ring, so it has no hex to retreat to. The lowest-id one attacks it with
+ // <paramref name="strength"/>, the rest have strength 1. Returns the attacker's side, the captor of a surrender.
+ static string Surround(Content c, GameState g, int unit, int strength)
+ {
+ foreach (var u in g.Units.Values.ToList()) if (u.Order == Combat.Attack) Place(g, u, u.Q, u.R);
+ var at = g.Units[unit];
+ var ring = Ring(c, g, at);
+ var enemies = g.Units.Values.Where(u => u.Side != Movement.PlayerSide && u.Side != "").OrderBy(u => u.Id).Take(ring.Count).ToList();
+ Assert.Equal(ring.Count, enemies.Count);
+ foreach (var x in g.Units.Values.ToList())
+ if (x.Id != unit && !enemies.Any(e => e.Id == x.Id) && ring.Contains((x.Q, x.R))) g.Units.Remove(x.Id);
+ for (int i = 0; i < ring.Count; i++)
+ Place(g, enemies[i], ring[i].Q, ring[i].R, i == 0 ? strength : 1, i == 0 ? Combat.Attack : "", i == 0 ? FormattableString.Invariant($"{at.Q},{at.R}") : "");
+ return enemies[0].Side;
+ }
+
+ // The first seed for which the aggregate twin, set up by <paramref name="setUp"/> and fought by
+ // <paramref name="fight"/>, passes <paramref name="wanted"/>.
+ static ulong Seed(Content c, Action<GameState> setUp, Action<GameState, List<Cause>> fight, Func<GameState, GameState, List<Cause>, bool> wanted)
+ {
+ for (ulong seed = 1; seed < 2000; seed++)
+ {
+ var g = Aggregate(c); setUp(g); var before = g.Clone(); g.RngState = seed; before.RngState = seed;
+ var why = new List<Cause>();
+ fight(g, why);
+ if (wanted(before, g, why)) return seed;
+ }
+ throw new Xunit.Sdk.XunitException("no seed gave the wanted engagement");
+ }
+
+ static int Lost(GameState before, GameState after, int unit) =>
+ before.Units[unit].Strength - (after.Units.TryGetValue(unit, out var u) ? u.Strength : 0);
+
+ // R-COMBAT-002, R-COMBAT-003, R-POP-001: an enemy attack in step 2 on an own opening formation. Each population unit it
+ // loses removes one of its serving records as a combat loss, the lowest id first ("Lowest id first (Recommended)"), with
+ // the provenance combat/<date>/<q>,<r> of the engaged hex ("Date + battle hex (Recommended)"); every loss is a death and
+ // nothing else is written ("No, losses are deaths (Recommended)"). The units, the draw and the Why lines are the aggregate
+ // twin's, and every other record is unchanged, the survivors' combat XP included ("No, formation only (Recommended)").
+ [Theory, InlineData("en-US"), InlineData("he-IL")]
+ public void AnEnemyAttackRemovesTheLowestIdServingRecordsAsCombatLosses(string culture)
+ {
+ Gdd03CombatCatalogueTests.InCulture(culture, () =>
+ {
+ var c = Gdd03();
+ var d = Own(c, Dark(c))[0];
+ Assert.True(d.Strength >= 2);
+ void SetUp(GameState g) => Besiege(c, g, d.Id, 3 * d.Strength);
+ var seed = Seed(c, SetUp, (g, why) => Combat.Resolve(c, g, why),
+ (b, g, _) => Lost(b, g, d.Id) >= 2 && g.Units.ContainsKey(d.Id));
+ var s = Dark(c); SetUp(s); s.RngState = seed;
+ var twin = Aggregate(c); SetUp(twin); twin.RngState = seed;
+ var serving = Serving(c, s, d.Id);
+ Assert.Equal(d.Strength, serving.Count);
+ var count = s.PopulationLedger.Units.Count;
+ var why = new List<Cause>(); var twinWhy = new List<Cause>();
+
+ Combat.Resolve(c, s, why);
+ Combat.Resolve(c, twin, twinWhy);
+
+ Assert.Equal(Units(twin), Units(s));
+ Assert.Equal(twin.RngState, s.RngState);
+ Assert.Equal(twinWhy.Select(x => x.Message), why.Select(x => x.Message));
+ var lost = d.Strength - s.Units[d.Id].Strength;
+ Assert.True(lost >= 2);
+ var gone = serving.Take(lost).Select(p => p.Id).ToList();
+ Assert.Equal(serving.Skip(lost).Select(p => p.Id), Serving(c, s, d.Id).Select(p => p.Id));
+ Assert.Equal(s.Units[d.Id].Strength, Serving(c, s, d.Id).Count);
+ Assert.Equal(gone.Select(id => LossLine(id, Source(s, d.Q, d.R))), LossLines(s));
+ Assert.Equal(count - lost, s.PopulationLedger.Units.Count);
+ Assert.All(gone, id => Assert.DoesNotContain(s.PopulationLedger.Units, p => p.Id == id));
+ var kept = Dark(c).PopulationLedger.Units.Where(p => !gone.Contains(p.Id)).Select(p => p.Canonical());
+ Assert.Equal(kept, s.PopulationLedger.Units.Select(p => p.Canonical()));
+ s.PopulationLedger.Reconcile();
+ });
+ }
+
+ // R-COMBAT-003, "No, keep region (Recommended)": a defender that loses and retreats moves on the map only; its remaining
+ // records keep their formation's region-only location.
+ [Fact]
+ public void ARetreatMovesTheUnitAndNoRecord()
+ {
+ var c = Gdd03();
+ var d = Own(c, Dark(c))[0];
+ void SetUp(GameState g) => Besiege(c, g, d.Id, 3 * d.Strength);
+ var seed = Seed(c, SetUp, (g, why) => Combat.Resolve(c, g, why),
+ (b, g, _) => g.Units.TryGetValue(d.Id, out var u) && (u.Q, u.R) != (d.Q, d.R) && Lost(b, g, d.Id) >= 1);
+ var s = Dark(c); SetUp(s); s.RngState = seed;
+ var before = Serving(c, s, d.Id);
+ Combat.Resolve(c, s, new List<Cause>());
+ var u = s.Units[d.Id];
+ Assert.NotEqual((d.Q, d.R), (u.Q, u.R));
+ var after = Serving(c, s, d.Id);
+ Assert.Equal(u.Strength, after.Count);
+ Assert.Equal(before.Skip(before.Count - after.Count).Select(p => p.Canonical()), after.Select(p => p.Canonical()));
+ s.PopulationLedger.Reconcile();
+ }
+
+ // R-COMBAT-001, R-COMBAT-005: the player's instant attack (Combat.Strike) fights through the same engagement: the own
+ // attacker's losses remove its lowest-id serving records with the attacked hex in the provenance; the enemy defenders'
+ // losses touch no record (R-POP-004: enemy formations are not own population), and the units match the aggregate twin.
+ [Fact]
+ public void ThePlayersStrikeLosesTheAttackersRecordsAndEnemyLossesTouchNone()
+ {
+ var c = Gdd03();
+ var a = Own(c, Dark(c))[0];
+ (int Q, int R) hex = default;
+ void SetUp(GameState g)
+ {
+ foreach (var u in g.Units.Values.ToList()) if (u.Order == Combat.Attack) Place(g, u, u.Q, u.R);
+ var at = g.Units[a.Id];
+ hex = Ring(c, g, at).First(h => !g.Units.Values.Any(x => x.Q == h.Q && x.R == h.R));
+ Place(g, Enemy(g), hex.Q, hex.R, 2 * a.Strength);
+ }
+ string? Strike(GameState g, List<Cause> why) => Combat.Strike(c, g, a.Id, hex.Q, hex.R, new Dictionary<int, int>(),
+ new Dictionary<int, AttackRecord>(), why);
+ var seed = Seed(c, SetUp, (g, why) => Assert.Null(Strike(g, why)), (b, g, _) => Lost(b, g, a.Id) >= 1);
+ var s = Dark(c); SetUp(s); s.RngState = seed;
+ var twin = Aggregate(c); SetUp(twin); twin.RngState = seed;
+ var serving = Serving(c, s, a.Id);
+ Assert.Null(Strike(s, new List<Cause>()));
+ Assert.Null(Strike(twin, new List<Cause>()));
+ Assert.Equal(Units(twin), Units(s));
+ var lost = a.Strength - (s.Units.TryGetValue(a.Id, out var after) ? after.Strength : 0);
+ Assert.True(lost >= 1);
+ Assert.Equal(serving.Take(lost).Select(p => LossLine(p.Id, Source(s, hex.Q, hex.R))), LossLines(s));
+ s.PopulationLedger.Reconcile();
+ }
+
+ // "Yes, after #2964 (Recommended)", R-COMBAT-003: a formation trained during the game (#2964: its records serve
+ // formation/<unit id>) is covered too. A strength-1 trained formation destroyed in step 2 leaves the map and its one
+ // record leaves the ledger as a combat loss.
+ [Fact]
+ public void ADestroyedTrainedFormationLeavesNoServingRecord()
+ {
+ var c = Gdd03();
+ int unit = -1;
+ void Train(GameState g)
+ {
+ g.Arms = 200; g.Treasury = 100; g.Debt = 0;
+ Assert.Null(Training.Start(c, g, "tel_aviv", "recruit", 1, new List<Cause>()));
+ unit = g.NextId;
+ for (int i = 0; i < c.UnitTypes.First(t => t.Id == "recruit").TrainingTurns; i++) Training.Progress(c, g, new List<Cause>());
+ }
+ var probe = Dark(c); Train(probe);
+ Assert.True(unit >= c.StartingForces.Count);
+ Assert.Equal(1, probe.Units[unit].Strength);
+ // Alone on its hex (losses fall on the strongest unit there first), on a free land hex beside the last enemy unit.
+ void SetUp(GameState g)
+ {
+ Train(g);
+ var e = g.Units.Values.Where(u => Prisoners.FrontOf.ContainsKey(u.Side)).OrderBy(u => u.Id).Last();
+ var free = Ring(c, g, e).First(h => !g.Units.Values.Any(x => x.Q == h.Q && x.R == h.R));
+ Place(g, g.Units[unit], free.Q, free.R);
+ Besiege(c, g, unit, 6);
+ }
+ var s = Dark(c); SetUp(s);
+ // The draw is found on the dark game itself here: the aggregate start trains no records, so its twin is not one.
+ ulong seed = 1;
+ for (; seed < 2000; seed++)
+ {
+ var t = s.Clone(); t.RngState = seed;
+ Combat.Resolve(c, t, new List<Cause>());
+ if (!t.Units.ContainsKey(unit)) break;
+ }
+ Assert.True(seed < 2000, "no seed destroyed the formation");
+ s.RngState = seed;
+ var u = s.Units[unit];
+ var record = Assert.Single(Serving(c, s, unit));
+ var why = new List<Cause>();
+ Combat.Resolve(c, s, why);
+ Assert.False(s.Units.ContainsKey(unit));
+ Assert.Contains(why, x => x.Key == WhyKeys.Destroyed);
+ Assert.Empty(Serving(c, s, unit));
+ Assert.Equal(new[] { LossLine(record.Id, Source(s, u.Q, u.R)) }, LossLines(s));
+ s.PopulationLedger.Reconcile();
+ }
+
+ // "Go ahead on strength": a formation whose strength differs from its serving records still fights on its strength,
+ // with the aggregate twin's units and draw, and loses records only while any remain: here one record is left for a
+ // loss of at least two.
+ [Fact]
+ public void AMismatchedFormationFightsOnItsStrengthAndLosesOnlyTheRecordsLeft()
+ {
+ var c = Gdd03();
+ var d = Own(c, Dark(c))[0];
+ void SetUp(GameState g) => Besiege(c, g, d.Id, 3 * d.Strength);
+ var seed = Seed(c, SetUp, (g, why) => Combat.Resolve(c, g, why), (b, g, _) => Lost(b, g, d.Id) >= 2);
+ var s = Dark(c); SetUp(s); s.RngState = seed;
+ var twin = Aggregate(c); SetUp(twin); twin.RngState = seed;
+ var serving = Serving(c, s, d.Id);
+ foreach (var p in serving.Skip(1)) s.PopulationLedger.RegisterCombatLoss(p.Id, "fixture");
+ var last = Assert.Single(Serving(c, s, d.Id));
+ var prior = LossLines(s);
+
+ Combat.Resolve(c, s, new List<Cause>());
+ Combat.Resolve(c, twin, new List<Cause>());
+
+ Assert.Equal(Units(twin), Units(s));
+ Assert.Equal(twin.RngState, s.RngState);
+ Assert.Empty(Serving(c, s, d.Id));
+ Assert.Equal(prior.Append(LossLine(last.Id, Source(s, d.Q, d.R))).OrderBy(x => x, StringComparer.Ordinal),
+ LossLines(s).OrderBy(x => x, StringComparer.Ordinal));
+ s.PopulationLedger.Reconcile();
+ }
+
+ // "Prisoners #1710 first (Recommended)", R-COMBAT-003, R-POW-005: an own formation with nowhere to retreat surrenders on a
+ // ledger game. Its losses are written first, as combat losses on its lowest ids, so Prisoners.Take finds its records
+ // numbering its strength; the rest become Captured under the attacker's side, and SoldiersHeld matches them.
+ [Fact]
+ public void AnOwnSurrenderLosesItsLowestRecordsThenTheRestAreCaptured()
+ {
+ var c = Gdd03();
+ var d = Own(c, Dark(c))[0];
+ string side = "";
+ void SetUp(GameState g) => side = Surround(c, g, d.Id, 3 * d.Strength);
+ var seed = Seed(c, SetUp, (g, why) => Combat.Resolve(c, g, why),
+ (b, g, why) => Lost(b, g, d.Id) >= 1 && why.Any(x => x.Key == WhyKeys.SurrenderedHeld));
+ var s = Dark(c); SetUp(s); s.RngState = seed;
+ var twin = Aggregate(c); SetUp(twin); twin.RngState = seed;
+ var serving = Serving(c, s, d.Id);
+
+ Combat.Resolve(c, s, new List<Cause>());
+ Combat.Resolve(c, twin, new List<Cause>());
+
+ Assert.False(s.Units.ContainsKey(d.Id));
+ Assert.Equal(Units(twin), Units(s));
+ var held = twin.SoldiersHeld[side];
+ var lost = d.Strength - held;
+ Assert.True(lost >= 1);
+ Assert.Equal(held, s.SoldiersHeld[side]);
+ Assert.Equal(serving.Take(lost).Select(p => LossLine(p.Id, Source(s, d.Q, d.R))), LossLines(s));
+ foreach (var p in serving.Skip(lost))
+ Assert.Equal((PopulationStatus.Captured, side), (s.PopulationLedger.Get(p.Id).Status, s.PopulationLedger.Get(p.Id).Captor));
+ Prisoners.RequireHeldMatchesRecords(s);
+ s.PopulationLedger.Reconcile();
+ }
+
+ // "Go ahead on strength (Recommended)" (owner, 9 November 2026), R-POW-005: an own formation with fewer serving records
+ // than its strength surrenders in step 2 with no refusal. The units and the draw are the aggregate twin's; every record
+ // left after its losses is Captured, SoldiersHeld grows by those records (one fewer than the twin's count, for the one
+ // record taken out first), and the count still matches the records, so the next Upkeep goes on. "Records captured
+ // (Recommended)" (owner, 9 November 2026): the surrender Why line states the records captured, in people (captured x
+ // people_per_unit), not the strength; the aggregate twin's line still states its strength in people.
+ [Fact]
+ public void AFormationWithFewerRecordsThanStrengthSurrendersAndAllItsRecordsAreCaptured()
+ {
+ var c = Gdd03();
+ var d = Own(c, Dark(c))[0];
+ string side = "";
+ void SetUp(GameState g) => side = Surround(c, g, d.Id, 3 * d.Strength);
+ var seed = Seed(c, SetUp, (g, why) => Combat.Resolve(c, g, why),
+ (b, g, why) => why.Any(x => x.Key == WhyKeys.SurrenderedHeld) && g.SoldiersHeld.Values.Sum() >= 2);
+ var s = Dark(c); SetUp(s); s.RngState = seed;
+ var twin = Aggregate(c); SetUp(twin); twin.RngState = seed;
+ s.PopulationLedger.RegisterCombatLoss(Serving(c, s, d.Id).Last().Id, "fixture");
+ var serving = Serving(c, s, d.Id);
+ Assert.Equal(d.Strength - 1, serving.Count);
+ var why = new List<Cause>(); var twinWhy = new List<Cause>();
+
+ Combat.Resolve(c, s, why);
+ Combat.Resolve(c, twin, twinWhy);
+
+ Assert.False(s.Units.ContainsKey(d.Id));
+ Assert.Equal(Units(twin), Units(s));
+ Assert.Equal(twin.RngState, s.RngState);
+ var ppu = c.RulesAt(s.Date).Mvp!.PeoplePerUnit;
+ var captured = s.SoldiersHeld[side];
+ var line = Assert.Single(why, x => x.Key == WhyKeys.SurrenderedHeld);
+ Assert.Equal(new[] { (captured * ppu).ToString(CultureInfo.InvariantCulture) }, line.Args);
+ Assert.Equal(FormattableString.Invariant($"Unit {d.Id} surrendered with {captured * ppu:N0} people: it had no hex to retreat to. They are held by the enemy"), line.Message);
+ var twinLine = Assert.Single(twinWhy, x => x.Key == WhyKeys.SurrenderedHeld); // the aggregate game: its strength, unchanged
+ Assert.Equal(new[] { (twin.SoldiersHeld[side] * ppu).ToString(CultureInfo.InvariantCulture) }, twinLine.Args);
+ Assert.Equal(FormattableString.Invariant($"Unit {d.Id} surrendered with {twin.SoldiersHeld[side] * ppu:N0} people: it had no hex to retreat to. They are held by the enemy"), twinLine.Message);
+ // No leftover record, so none goes home: Take gives no home city, and combat writes neither Send home line.
+ Assert.DoesNotContain(why, x => x.Key == CauseKeys.SentHomeArmsReturned || x.Key == WhyKeys.SentHome);
+ var lost = d.Strength - twin.SoldiersHeld[side];
+ Assert.Empty(Serving(c, s, d.Id));
+ foreach (var p in serving.Skip(lost))
+ Assert.Equal((PopulationStatus.Captured, side), (s.PopulationLedger.Get(p.Id).Status, s.PopulationLedger.Get(p.Id).Captor));
+ Assert.Equal(serving.Count - lost, s.SoldiersHeld[side]);
+ Assert.Equal(twin.SoldiersHeld[side] - 1, s.SoldiersHeld[side]);
+ Prisoners.RequireHeldMatchesRecords(s);
+ Prisoners.Upkeep(c, s, c.RulesAt(s.Date).Mvp!, new List<Cause>());
+ s.PopulationLedger.Reconcile();
+ }
+
+ // "Go ahead on strength (Recommended)": an own formation with more serving records than its strength surrenders in step
+ // 2. Its losses take its lowest records first; of the rest exactly its strength are Captured, the lowest ids first.
+ // SoldiersHeld is the aggregate twin's. "Sent home (Recommended)" (owner, 9 November 2026): the leftover records leave
+ // service as Send home's do (R-UNIT-005): settled-in free civilians without an assignment in the nearest city to the
+ // formation's hex, the issued items back in the Arms stock. "Yes, reuse Send home's (Recommended)" (owner, 9 November
+ // 2026): after the surrender line comes Send home's own people line (key sent_home, its wording) for the leftover
+ // people, then, only when Arms go back, Send home's Arms line, in Send home's order. With <paramref name="armed"/>
+ // false the leftovers hold no military item: the people still go home with their line, and no Arms line is written
+ // and the stock is unchanged. The aggregate twin writes neither line and its stock is unchanged.
+ [Theory, InlineData(true), InlineData(false)]
+ public void AFormationWithMoreRecordsThanStrengthSurrendersItsLowestRecordsAndSendsTheRestHome(bool armed)
+ {
+ var c = Gdd03();
+ var d = Own(c, Dark(c))[0];
+ string side = "";
+ void SetUp(GameState g)
+ {
+ side = Surround(c, g, d.Id, 3 * d.Strength);
+ var u = g.Units[d.Id]; Place(g, u, u.Q, u.R, u.Strength - 2);
+ }
+ var seed = Seed(c, SetUp, (g, why) => Combat.Resolve(c, g, why),
+ (b, g, why) => why.Any(x => x.Key == WhyKeys.SurrenderedHeld) && g.SoldiersHeld.Values.Sum() >= 1);
+ var s = Dark(c); SetUp(s); s.RngState = seed;
+ var twin = Aggregate(c); SetUp(twin); twin.RngState = seed;
+ if (!armed) // the two highest records are the leftovers whatever the losses: take their military items off first
+ s.PopulationLedger.Commit(Serving(c, s, d.Id).Skip(Serving(c, s, d.Id).Count - 2).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(), Array.Empty<PopulationTarget>());
+ var serving = Serving(c, s, d.Id);
+ Assert.Equal(s.Units[d.Id].Strength + 2, serving.Count);
+ var at = s.Units[d.Id];
+ var city = Demobilization.Nearest(c, at.Q, at.R);
+ var region = c.PlayerRegions.AtLocation(city)!.Id;
+ var arms = s.Arms; var twinArms = twin.Arms;
+ var why = new List<Cause>(); var twinWhy = new List<Cause>();
+
+ Combat.Resolve(c, s, why);
+ Combat.Resolve(c, twin, twinWhy);
+
+ Assert.Equal(Units(twin), Units(s));
+ var held = twin.SoldiersHeld[side];
+ var lost = d.Strength - 2 - held;
+ Assert.Equal(held, s.SoldiersHeld[side]);
+ Assert.Equal(serving.Take(lost).Select(p => LossLine(p.Id, Source(s, d.Q, d.R))), LossLines(s));
+ foreach (var p in serving.Skip(lost).Take(held))
+ Assert.Equal((PopulationStatus.Captured, side), (s.PopulationLedger.Get(p.Id).Status, s.PopulationLedger.Get(p.Id).Captor));
+ Assert.Empty(Serving(c, s, d.Id));
+ var leftover = serving.Skip(lost + held).ToList();
+ Assert.Equal(new[] { serving[serving.Count - 2].Id, serving[serving.Count - 1].Id }, leftover.Select(p => p.Id));
+ var received = c.RequirePopulationInteger("reception.turns");
+ foreach (var was in leftover)
+ {
+ var p = s.PopulationLedger.Get(was.Id);
+ Assert.Equal((PopulationStatus.FreeCivilian, PopulationAssignmentKind.Unassigned), (p.Status, p.Assignment.Kind));
+ Assert.Equal((region, city), (p.Location!.Region, p.Location.City));
+ Assert.Equal(received, p.ReceptionTicks);
+ Assert.Null(p.Equipment.MilitaryId);
+ Assert.Equal((was.Qualification, was.CombatXp), (p.Qualification, p.CombatXp));
+ }
+ var items = leftover.Count(p => p.Equipment.MilitaryId != null);
+ Assert.Equal(armed ? 2 : 0, items);
+ Assert.Equal(arms + items, s.Arms);
+ Assert.Equal(twinArms, twin.Arms);
+ var ppu = c.RulesAt(s.Date).Mvp!.PeoplePerUnit;
+ var surrender = Assert.Single(why, x => x.Key == WhyKeys.SurrenderedHeld);
+ Assert.Equal(new[] { (held * ppu).ToString(CultureInfo.InvariantCulture) }, surrender.Args);
+ var home = Assert.Single(why, x => x.Key == WhyKeys.SentHome); // Send home's own line, for the 2 leftover records
+ Assert.Equal(why.IndexOf(surrender) + 1, why.IndexOf(home));
+ Assert.Equal(("map", d.Id.ToString(CultureInfo.InvariantCulture), 2.0,
+ FormattableString.Invariant($"Unit {d.Id} is sent home: its {2 * ppu:N0} people are civilians in {PlayerText.Settlement(c, city)} now")),
+ (home.System, home.Target, home.Delta, home.Message));
+ Assert.Equal(new[] { (2 * ppu).ToString(CultureInfo.InvariantCulture), city }, home.Args);
+ Assert.Equal(new[] { d.Id }, home.Units.Select(x => x.Id));
+ if (armed)
+ {
+ var back = Assert.Single(why, x => x.Key == CauseKeys.SentHomeArmsReturned);
+ Assert.Equal(why.IndexOf(home) + 1, why.IndexOf(back));
+ Assert.Equal(("city", "arms", (double)items, FormattableString.Invariant($"{PlayerText.Settlement(c, city)}: unit {d.Id} returned {items} Arms")),
+ (back.System, back.Target, back.Delta, back.Message));
+ Assert.Equal(new[] { city, d.Id.ToString(CultureInfo.InvariantCulture) }, back.Args);
+ }
+ else Assert.DoesNotContain(why, x => x.Key == CauseKeys.SentHomeArmsReturned);
+ Assert.DoesNotContain(twinWhy, x => x.Key == CauseKeys.SentHomeArmsReturned || x.Key == WhyKeys.SentHome);
+ Prisoners.RequireHeldMatchesRecords(s);
+ s.PopulationLedger.Reconcile();
+ }
+
+ // "Yes, in #1706 (Recommended)" (owner, 9 November 2026): a trained formation (#2964's formation/<unit id> target)
+ // surrenders in step 2 and its records left after its losses become Captured under the attacker's side, found as its
+ // losses are (Training.FormationTarget); SoldiersHeld matches them.
+ [Fact]
+ public void ATrainedFormationSurrendersAndItsRecordsAreCaptured()
+ {
+ var c = Gdd03();
+ int unit = -1;
+ string side = "";
+ void SetUp(GameState g)
+ {
+ g.Arms = 200; g.Treasury = 100; g.Debt = 0;
+ // Three groups: every face that makes the defender retreat also costs it at least one unit (combat_table).
+ Assert.Null(Training.Start(c, g, "tel_aviv", "recruit", 3, new List<Cause>()));
+ unit = g.NextId;
+ for (int i = 0; i < c.UnitTypes.First(t => t.Id == "recruit").TrainingTurns; i++) Training.Progress(c, g, new List<Cause>());
+ // Alone on the strongest opening formation's hex (whose ring the enemy units can fill: the other units there
+ // change places with it), then surrounded.
+ var trained = g.Units[unit]; var at = g.Units[Own(c, g)[0].Id];
+ foreach (var x in g.Units.Values.Where(x => x.Q == at.Q && x.R == at.R).ToList()) Place(g, x, trained.Q, trained.R);
+ Place(g, trained, at.Q, at.R);
+ side = Surround(c, g, unit, 9);
+ }
+ var s = Dark(c); SetUp(s);
+ Assert.True(unit >= c.StartingForces.Count);
+ // The draw is found on the dark game itself: the aggregate start trains no records, so its twin is not one.
+ ulong seed = 1;
+ for (; seed < 2000; seed++)
+ {
+ var t = s.Clone(); t.RngState = seed; var w = new List<Cause>();
+ Combat.Resolve(c, t, w);
+ if (w.Any(x => x.Key == WhyKeys.SurrenderedHeld && x.Units.Any(u => u.Id == unit))) break;
+ }
+ Assert.True(seed < 2000, "no seed made the trained formation surrender");
+ s.RngState = seed;
+ var serving = Serving(c, s, unit);
+ Assert.Equal(s.Units[unit].Strength, serving.Count);
+ Assert.All(serving, p => Assert.Equal(Training.FormationPrefix + unit.ToString(CultureInfo.InvariantCulture), p.Assignment.Target));
+ var why = new List<Cause>();
+ Combat.Resolve(c, s, why);
+ Assert.False(s.Units.ContainsKey(unit));
+ Assert.Empty(Serving(c, s, unit));
+ var held = s.SoldiersHeld[side];
+ Assert.True(held >= 1);
+ foreach (var p in serving.Skip(serving.Count - held))
+ Assert.Equal((PopulationStatus.Captured, side), (s.PopulationLedger.Get(p.Id).Status, s.PopulationLedger.Get(p.Id).Captor));
+ Prisoners.RequireHeldMatchesRecords(s);
+ s.PopulationLedger.Reconcile();
+ }
+
+ // Q-UI-1, #2553: Combat.Outcomes runs on a ledger game and gives the aggregate twin's bands for every row, for a unit and
+ // hex too, so the card's bands are what Fight takes (the formation's strength).
+ [Fact]
+ public void OutcomesOnALedgerGameAreTheAggregateGames()
+ {
+ var c = Gdd03();
+ var a = Own(c, Dark(c))[0];
+ var s = Dark(c); var twin = Aggregate(c);
+ var e = Enemy(s);
+ var hex = Ring(c, s, s.Units[a.Id]).First(h => !s.Units.Values.Any(x => x.Q == h.Q && x.R == h.R));
+ Place(s, e, hex.Q, hex.R); Place(twin, twin.Units[e.Id], hex.Q, hex.R);
+ var before = s.Hash();
+ for (int row = 0; row < c.RulesAt(s.Date).Mvp!.CombatTable.Count; row++)
+ {
+ Assert.Equal(Combat.Outcomes(c, twin, row), Combat.Outcomes(c, s, row));
+ Assert.Equal(Combat.Outcomes(c, twin, row, a.Id, hex.Q, hex.R), Combat.Outcomes(c, s, row, a.Id, hex.Q, hex.R));
+ }
+ Assert.Equal(before, s.Hash());
+ }
+
+ // R-POP-002: only a ledger initialized with mode Historical is let through; an Open or synthetic one is still refused by
+ // Resolve and Outcomes before any write.
+ [Theory]
+ [InlineData(true, false)] [InlineData(false, false)] [InlineData(true, true)] [InlineData(false, true)]
+ public void AnOpenOrSyntheticLedgerIsStillRefused(bool open, bool outcomes)
+ {
+ 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 before = s.Describe(); var hash = s.Hash(); var why = new List<Cause>();
+ Action call = outcomes ? () => Combat.Outcomes(c, s, 0) : () => Combat.Resolve(c, s, why);
+ Assert.Contains("integration is held", Assert.Throws<NotSupportedException>(call).Message);
+ Assert.Equal(before, s.Describe()); Assert.Equal(hash, s.Hash()); Assert.Empty(why);
+ }
+
+ // Determinism: the ledger losses draw nothing; two dark games fought from the same seed end with the same hash and
+ // ledger text, and the losses change the hash.
+ [Fact]
+ public void TheSameEngagementGivesTheSameHashAndLedger()
+ {
+ var c = Gdd03();
+ var d = Own(c, Dark(c))[0];
+ void SetUp(GameState g) => Besiege(c, g, d.Id, 3 * d.Strength);
+ var seed = Seed(c, SetUp, (g, why) => Combat.Resolve(c, g, why), (b, g, _) => Lost(b, g, d.Id) >= 1);
+ string Run(out string start)
+ {
+ var s = Dark(c); SetUp(s); s.RngState = seed; start = s.Hash();
+ Combat.Resolve(c, s, new List<Cause>());
+ return s.Hash() + "\n" + string.Join("\n", s.PopulationLedger.Canonical());
+ }
+ var a = Run(out var startA); var b = Run(out var startB);
+ Assert.Equal(startA, startB);
+ Assert.Equal(a, b);
+ Assert.NotEqual(startA, a.Split('\n')[0]);
+ }
+}
diff --git a/sim/Statecraft.Sim.Tests/LedgerPrisonersTests.cs b/sim/Statecraft.Sim.Tests/LedgerPrisonersTests.cs
index ac365a54a..07afb70f9 100644
--- a/sim/Statecraft.Sim.Tests/LedgerPrisonersTests.cs
+++ b/sim/Statecraft.Sim.Tests/LedgerPrisonersTests.cs
@@ -9,14 +9,15 @@ using Statecraft.Sim;
/// Captured records with that captor. The prisoners eat and the held soldiers cost Money as today (R-POW-002, R-POW-005).
/// Owner rulings, 8 November 2026 (#1725): "Yes, as today (Recommended)", "Winning side, set at start (Recommended)",
/// "Formation's region (Recommended)", "Stays on record (Recommended)", "Keep count + check (Recommended)", "No, keep
-/// count (Recommended)" and "Prisoners #1710 first (Recommended)".</summary>
+/// count (Recommended)" and "Prisoners #1710 first (Recommended)". Owner rulings, 9 November 2026: "Go ahead on strength (Recommended)",
+/// "Yes, in #1706 (Recommended)" and "Sent home (Recommended)".</summary>
public class LedgerPrisonersTests
{
static Content Gdd03() => HistoricalPopulationTests.Real(true);
static GameState Dark(Content c) => Simulation.NewGame(c, 1, Mode.Historical, darkStart: true);
- static string Take(Content c, GameState s, Unit u, Unit captor) => Prisoners.Take(c, s, u, captor);
+ static string Take(Content c, GameState s, Unit u, Unit captor) => Prisoners.Take(c, s, u, captor).Text;
// The own opening formations on the board, lowest id first: unit id i is c.StartingForces[i] (StartingForces.Init).
static List<Unit> Own(Content c, GameState s) => s.Units.Values
@@ -161,12 +162,12 @@ public class LedgerPrisonersTests
dark.PopulationLedger.Reconcile();
}
- // R-POP-002 "refused before mutation": each refusal leaves the state, the ledger and the hash unchanged. A formation whose
- // serving records do not match its strength; a trained formation (not an opening one: its records are #2964's
- // formation/<id> target, not on main); a captor side the ledger does not bind; and a count that already disagrees with
- // the Captured records ("Keep count + check (Recommended)").
+ // R-POP-002 "refused before mutation": each refusal leaves the state, the ledger and the hash unchanged. A captor side
+ // the ledger does not bind, and a count that already disagrees with the Captured records ("Keep count + check
+ // (Recommended)"). The owner's rulings of 9 November 2026, "Go ahead on strength (Recommended)" and "Yes, in #1706
+ // (Recommended)", took out the refusals of a strength its records do not number and of a trained formation: those
+ // cases are captured now (the tests below).
[Theory]
- [InlineData("mismatch", "serves it with")] [InlineData("trained", "no ledger records to capture")]
[InlineData("unbound", "is not a bound captor")] [InlineData("count", "captured records with that captor")]
public void ARefusedCaptureLeavesStateLedgerAndHashUnchanged(string why, string reason)
{
@@ -175,8 +176,6 @@ public class LedgerPrisonersTests
var u = Own(c, s)[0]; var captor = Enemy(s, "egypt");
switch (why)
{
- case "mismatch": s.PopulationLedger.RegisterCombatLoss(Serving(c, s, u)[0].Id, "fixture"); break;
- case "trained": u = new Unit(s.NextId, "recruit", u.Q, u.R, side: Movement.PlayerSide, strength: 1); s.Units.Add(u.Id, u); s.NextId++; break;
case "unbound": captor = new Unit(captor.Id, captor.Type, captor.Q, captor.R, side: "local", strength: captor.Strength); break;
case "count": s.SoldiersHeld["egypt"] = 1; break;
}
@@ -188,6 +187,146 @@ public class LedgerPrisonersTests
Assert.Equal(units, s.Units.Values.Select(x => x.Canonical()));
}
+ // "Go ahead on strength (Recommended)" (owner, 9 November 2026): a formation with fewer serving records than its strength
+ // surrenders; every record it has is captured, and SoldiersHeld grows by the records captured, not the strength, so the
+ // count still equals the Captured records ("Keep count + check (Recommended)") and the next Take and Upkeep go on.
+ [Fact]
+ public void AFormationWithFewerRecordsThanStrengthHasAllItsRecordsCaptured()
+ {
+ var c = Gdd03();
+ var s = Dark(c);
+ var u = Own(c, s)[0]; var captor = Enemy(s, "egypt");
+ var serving = Serving(c, s, u);
+ Assert.True(serving.Count >= 3);
+ foreach (var p in serving.Skip(serving.Count - 2)) s.PopulationLedger.RegisterCombatLoss(p.Id, "fixture");
+ var left = Serving(c, s, u);
+ Assert.Equal(u.Strength - 2, left.Count);
+ var taken = Prisoners.Take(c, s, u, captor); // no leftover: no home city, no Arms back
+ Assert.Equal(("They are held by the enemy", left.Count, 0, (string?)null), (taken.Text, taken.Held, taken.ArmsBack, taken.Home));
+ Assert.Empty(Serving(c, s, u));
+ foreach (var p in left)
+ Assert.Equal((PopulationStatus.Captured, "egypt"), (s.PopulationLedger.Get(p.Id).Status, s.PopulationLedger.Get(p.Id).Captor));
+ Assert.Equal(left.Count, s.SoldiersHeld["egypt"]);
+ AssertHeldMatchesRecords(s);
+ Take(c, s, Own(c, s)[1], captor);
+ Prisoners.Upkeep(c, s, c.RulesAt(s.Date).Mvp!, new List<Cause>());
+ AssertHeldMatchesRecords(s);
+ s.PopulationLedger.Reconcile();
+ }
+
+ // "Go ahead on strength (Recommended)": a formation with more serving records than its strength surrenders exactly its
+ // strength of them, the lowest ids first (as "Lowest id first (Recommended)" and docs/GDD.md's ascending population
+ // ids). SoldiersHeld grows by the strength, as in the aggregate game. "Sent home (Recommended)" (owner, 9 November
+ // 2026): the leftover records leave service as Send home's do (R-UNIT-005: "Nearest city, unemployed (Recommended)",
+ // "Settled in (Recommended)", "Keep both (Recommended)", "Back to Arms stock (Recommended)"): free civilians without an
+ // assignment in the nearest city to the formation's hex, reception ticks reception.turns, qualification and combat XP
+ // kept, the issued item back in the Arms stock once. No record is made or lost.
+ [Fact]
+ public void AFormationWithMoreRecordsThanStrengthHasItsLowestRecordsCapturedAndTheRestSentHome()
+ {
+ var c = Gdd03();
+ var s = Dark(c);
+ var o = Own(c, s)[0]; var captor = Enemy(s, "egypt");
+ var u = new Unit(o.Id, o.Type, o.Q, o.R, o.Service, o.Side, o.Strength - 2, o.Order, o.OrderTarget, o.HomeCity, o.Full, o.CombatXp);
+ s.Units[u.Id] = u;
+ var serving = Serving(c, s, u);
+ Assert.Equal(u.Strength + 2, serving.Count);
+ var leftover = serving.Skip(u.Strength).ToList();
+ Assert.Equal(new[] { serving[u.Strength].Id, serving[u.Strength + 1].Id }, leftover.Select(p => p.Id));
+ Assert.All(leftover, p => Assert.NotNull(p.Equipment.MilitaryId));
+ var city = Demobilization.Nearest(c, u.Q, u.R);
+ var region = c.PlayerRegions.AtLocation(city)!.Id;
+ var received = c.RequirePopulationInteger("reception.turns");
+ var arms = s.Arms; var next = s.PopulationLedger.NextPopulationId; var count = s.PopulationLedger.Units.Count;
+ var cities = string.Join(";", s.Cities.Values.Select(x => x.Canonical()));
+ var taken = Prisoners.Take(c, s, u, captor);
+ Assert.Equal((u.Strength, leftover.Count, city), (taken.Held, taken.ArmsBack, taken.Home));
+ foreach (var p in serving.Take(u.Strength))
+ Assert.Equal((PopulationStatus.Captured, "egypt"), (s.PopulationLedger.Get(p.Id).Status, s.PopulationLedger.Get(p.Id).Captor));
+ Assert.Empty(Serving(c, s, u));
+ var home = s.PopulationLedger.Units.Where(p => p.Status == PopulationStatus.FreeCivilian && serving.Any(w => w.Id == p.Id))
+ .Select(p => p.Id).OrderBy(x => x).ToList();
+ Assert.Equal(leftover.Select(p => p.Id), home);
+ foreach (var was in leftover)
+ {
+ var p = s.PopulationLedger.Get(was.Id);
+ Assert.Equal(PopulationAssignmentKind.Unassigned, p.Assignment.Kind);
+ Assert.Equal((region, city), (p.Location!.Region, p.Location.City));
+ Assert.Equal(received, p.ReceptionTicks);
+ Assert.Null(p.Captor);
+ Assert.Null(p.Equipment.MilitaryId);
+ Assert.Equal((was.Qualification, was.CombatXp, was.Profession, was.Tier, was.WorkXp, was.Equipment.ToolsId),
+ (p.Qualification, p.CombatXp, p.Profession, p.Tier, p.WorkXp, p.Equipment.ToolsId));
+ }
+ Assert.Equal(arms + leftover.Count, s.Arms);
+ Assert.Equal((next, count), (s.PopulationLedger.NextPopulationId, s.PopulationLedger.Units.Count));
+ Assert.Equal(cities, string.Join(";", s.Cities.Values.Select(x => x.Canonical()))); // "No, records only (Recommended)"
+ Assert.Equal(u.Strength, s.SoldiersHeld["egypt"]);
+ AssertHeldMatchesRecords(s);
+ s.PopulationLedger.Reconcile();
+ }
+
+ // R-POW-005, R-POP-002 "refused before mutation": every check, the leftovers' home location binding included, comes
+ // before the first write, so the capture and the leftovers' homecoming are one validated ledger commit. Here the
+ // nearest city to the formation is a region member the ledger does not bind as a location (a content change made
+ // after the start, the only way to reach it), so the leftovers' location is refused and nothing is written: no
+ // record captured, no count, no Arms, the same hash.
+ [Fact]
+ public void ALeftoverWhoseHomeIsNotABoundLocationRefusesBeforeAnyWrite()
+ {
+ var c = Gdd03();
+ var s = Dark(c);
+ var o = Own(c, s)[0]; var captor = Enemy(s, "egypt");
+ var u = new Unit(o.Id, o.Type, o.Q, o.R, o.Service, o.Side, o.Strength - 2, o.Order, o.OrderTarget, o.HomeCity, o.Full, o.CombatXp);
+ s.Units[u.Id] = u;
+ var unbound = c.PlayerRegions.Regions.Values.SelectMany(r => r.MemberLocations.Where(m => c.Cities.All(x => x.Id != m)
+ && r.FieldHosts.All(h => h.Host != m))).OrderBy(x => x, StringComparer.Ordinal).First();
+ c.Cities.Insert(0, new CityStart { Id = unbound });
+ c.SettlementHexes.Insert(0, new SettlementHex { Id = unbound, Q = u.Q, R = u.R });
+ Assert.Equal(unbound, Demobilization.Nearest(c, u.Q, u.R));
+ var hash = s.Hash(); var ledger = s.PopulationLedger.Canonical().ToList(); var arms = s.Arms;
+ var held = s.SoldiersHeld.ToList();
+ var refused = Assert.Throws<ArgumentException>(() => Prisoners.Take(c, s, u, captor));
+ Assert.Equal("Unknown or inconsistent location.", refused.Message); // the leftover's home, not some other refusal
+ Assert.Equal(ledger, s.PopulationLedger.Canonical());
+ Assert.Equal((hash, arms), (s.Hash(), s.Arms));
+ Assert.Equal(held, s.SoldiersHeld.ToList());
+ AssertHeldMatchesRecords(s);
+ }
+
+ // "Yes, in #1706 (Recommended)" (owner, 9 November 2026): a trained formation's soldiers are found as battles find them,
+ // on Training.FormationTarget (formation/<unit id>, #2964), and become Captured; a player unit with no records on its
+ // target captures none and adds nothing to SoldiersHeld ("Go ahead on strength (Recommended)").
+ [Fact]
+ public void ATrainedFormationsRecordsAreCaptured()
+ {
+ var c = Gdd03();
+ var s = Dark(c);
+ s.Arms = 200; s.Treasury = 100; s.Debt = 0;
+ Assert.Null(Training.Start(c, s, "tel_aviv", "recruit", 1, new List<Cause>()));
+ 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.True(unit >= c.StartingForces.Count);
+ var u = s.Units[unit];
+ var target = Training.FormationTarget(c, unit);
+ var serving = s.PopulationLedger.Units.Where(p => p.Status == PopulationStatus.ActiveSoldier && p.Assignment.Target == target)
+ .OrderBy(p => p.Id).ToList();
+ Assert.Equal(u.Strength, serving.Count);
+ Assert.Equal("They are held by the enemy", Take(c, s, u, Enemy(s, "jordan")));
+ foreach (var p in serving)
+ Assert.Equal((PopulationStatus.Captured, "jordan"), (s.PopulationLedger.Get(p.Id).Status, s.PopulationLedger.Get(p.Id).Captor));
+ Assert.Equal(u.Strength, s.SoldiersHeld["jordan"]);
+ AssertHeldMatchesRecords(s);
+
+ var none = new Unit(s.NextId, "recruit", u.Q, u.R, side: Movement.PlayerSide, strength: 1); s.Units.Add(none.Id, none); s.NextId++;
+ var ledger = s.PopulationLedger.Canonical().ToList();
+ Take(c, s, none, Enemy(s, "jordan"));
+ Assert.Equal(ledger, s.PopulationLedger.Canonical());
+ Assert.Equal(u.Strength, s.SoldiersHeld["jordan"]);
+ AssertHeldMatchesRecords(s);
+ s.PopulationLedger.Reconcile();
+ }
+
// "Keep count + check (Recommended)": Upkeep refuses a count that disagrees with the records, with nothing paid or eaten.
[Fact]
public void UpkeepRefusesACountThatDisagreesWithTheRecords()
@@ -218,9 +357,9 @@ public class LedgerPrisonersTests
Assert.Equal(before, s.Describe()); Assert.Equal(hash, s.Hash()); Assert.Empty(why);
}
- // Where Take's refusal can be reached from combat, and what it leaves. Combat.Resolve (step 2, called by TurnResolver) refuses
- // any initialized ledger at its entry, before any engagement, so on this branch only the player's instant
- // attack, Combat.Strike (its one caller is Step, through Simulation.RunOrders), can reach Prisoners.Take on a dark start. Here an
+ // Where Take's refusal can be reached from combat, and what it leaves. Since #1706 both Combat.Resolve (step 2,
+ // TurnResolver.cs:20) and the player's instant attack, Combat.Strike (its one caller is Step, Simulation.cs:268), fight
+ // on a dark start and can reach Prisoners.Take (LedgerCombatTests covers Resolve's surrender). Here an
// enemy unit boxed in by own units surrenders to a Strike while SoldiersHeld disagrees with the Captured records, so Take
// throws InvalidOperationException before it writes anything. The throw comes after the Strike's own writes (the
// attacker's order and the engagement's draw and losses), and those stay on the state object a direct call is given. In
@@ -233,10 +372,6 @@ public class LedgerPrisonersTests
{
var c = Gdd03();
var s = Dark(c);
- var resolve = s.Clone();
- Assert.Contains("integration is held",
- Assert.Throws<NotSupportedException>(() => Combat.Resolve(c, resolve, new List<Cause>())).Message);
- Assert.Equal(s.Hash(), resolve.Hash());
// The weakest enemy unit (lowest id on a tie), attacked by the strongest own formation (lowest id on a tie).
var e = s.Units.Values.Where(u => Prisoners.FrontOf.ContainsKey(u.Side) && u.Strength > 0)
diff --git a/sim/Statecraft.Sim/Combat.cs b/sim/Statecraft.Sim/Combat.cs
index 43350a325..fe49baa36 100644
--- a/sim/Statecraft.Sim/Combat.cs
+++ b/sim/Statecraft.Sim/Combat.cs
@@ -206,7 +206,7 @@ namespace Statecraft.Sim
/// strength, and no retreat when the defenders are all lost; faces equal after that share a band.</summary>
public static IReadOnlyList<(int Faces, int Of, int AttackersLose, int DefendersLose, bool Retreat)> Outcomes(Content c, GameState s, int row, int? unitId = null, int? q = null, int? r = null)
{
- PopulationLedger.RefuseAggregate(s);
+ PopulationLedger.RefuseUnlessHistorical(s); // #1725 PR 7 (#1706): on a Historical ledger it reads the units' strength, as Fight does
var mvp = c.RulesAt(s.Date).Mvp!;
var t = mvp.CombatTable[row];
var attacker = unitId is int id && s.Units.TryGetValue(id, out var u) ? u : null;
@@ -264,7 +264,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);
+ PopulationLedger.RefuseUnlessHistorical(s); // #1725 PR 7 (#1706): on a Historical ledger each own loss is a record (Fight)
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 id
@@ -359,9 +359,10 @@ namespace Statecraft.Sim
var target = Hex(q, r);
var ppu = mvp.PeoplePerUnit;
var removed = new List<Unit>();
+ var source = FormattableString.Invariant($"combat/{s.Date:yyyy-MM-dd}/{target}"); // "Date + battle hex (Recommended)"
// R-COMBAT-007: the guns fire from behind the line, so the attackers' losses fall on the others only.
- var attackersLost = Take(s, attackers.Where(x => !Guns(c, x)).Select(x => x.Id).ToList(), row.AttackerLoss[face], removed);
- var defendersLost = Take(s, defenders.Select(x => x.Id).ToList(), row.DefenderLoss[face], removed);
+ var attackersLost = Take(c, s, attackers.Where(x => !Guns(c, x)).Select(x => x.Id).ToList(), row.AttackerLoss[face], removed, source);
+ var defendersLost = Take(c, s, defenders.Select(x => x.Id).ToList(), row.DefenderLoss[face], removed, source);
var named = attackers.OrderBy(x => x.Id).Concat(defenders.OrderBy(x => x.Id)).Select(x => new UnitRef(x)).ToList();
why.Add(new Cause("map", target, 0, FormattableString.Invariant(
$"The attack on hex {target} ({Ids(attackers)} against {Ids(defenders)}, strength ratio {ratio}%): the attackers lost {attackersLost * ppu:N0} people and the defenders lost {defendersLost * ppu:N0} people"),
@@ -385,26 +386,39 @@ namespace Statecraft.Sim
}
else
{
- // The only way a unit is captured (impact plan section 4.3 item 1; R-POW-001). Its captor is the engagement's
- // lowest-id attacker (not attackers[0]: the guns are listed last, R-COMBAT-007), whose side holds the
- // player's soldiers (R-POW-005). Take runs before the unit is removed (#1710). On a Historical ledger game
- // it may refuse, before it writes anything: InvalidOperationException for a held count that disagrees with
- // the Captured records, a unit that is not a units_1948 formation or a strength its records do not number,
- // and ArgumentException from PopulationLedger.Capture for an unbound captor or a record that is not an
- // active soldier (a synthetic or Open ledger is NotSupportedException). This engagement's draw and losses,
- // and any earlier write to s (an earlier engagement, or the Strike's own), stay on s. In the game s is
- // always a clone: Strike's caller (Simulation.RunOrders) and Resolve's (TurnResolver) run inside
- // Simulation.Step on its clone (Preview and DelegatedTo clone too), so the whole command's or turn's result
- // is discarded and the caller's state is unchanged. Today Step refuses a ledger game before it clones, and
- // Resolve refuses one at its entry.
- // Hand-off to #1706: the defenders' combat losses above have already lowered u.Strength, and no ledger
- // loss is written for them, so Take sees records that still number the strength before the losses and
- // refuses. When #1706 runs Resolve on a ledger, it must write those losses to the ledger before this call.
- var held = Prisoners.Take(c, s, u, attackers.OrderBy(x => x.Id).First());
+ // The only way a unit is captured (impact plan section 4.3 item 1; R-POW-001). Its captor is the
+ // engagement's lowest-id attacker (not attackers[0]: the guns are listed last, R-COMBAT-007), whose
+ // side holds the player's soldiers (R-POW-005). Take runs before the unit is removed (#1710). On a
+ // Historical ledger game it may refuse, before it writes anything: InvalidOperationException for a held
+ // count that disagrees with the Captured records, and ArgumentException from PopulationLedger.Capture
+ // for an unbound captor or a record that is not an active soldier (a synthetic or Open ledger is
+ // NotSupportedException). A trained formation and a strength its records do not number are not refused
+ // (owner, 9 November 2026: "Yes, in #1706 (Recommended)" and "Go ahead on strength (Recommended)"):
+ // Take captures the records on the formation's target, at most its strength of them, the lowest ids
+ // first, and SoldiersHeld grows by that number. A formation's leftover records, beyond its strength,
+ // leave service as Send home's do (owner, 9 November 2026: "Sent home (Recommended)"; R-UNIT-005,
+ // Demobilization.RecordsHome), in the capture's own ledger commit. After the surrender line come Send
+ // home's own lines, in its order: the people sent home ("Yes, reuse Send home's (Recommended)"), then,
+ // only when Arms go back, the Arms line. On a ledger the surrender line states the records captured in
+ // people, not the strength (owner, 9 November 2026: "Records captured (Recommended)"); Take's Held is
+ // the strength without one, so the aggregate line is unchanged. This engagement's draw and losses, and
+ // any earlier write to s (an earlier engagement, or the Strike's own), stay on s. In the game s is
+ // always a clone: Strike's caller (Simulation.cs:268) and Resolve's (TurnResolver.cs:20) run inside
+ // Simulation.Step on its clone (Simulation.cs:51; Preview and DelegatedTo clone too), so the whole
+ // command's or turn's result is discarded and the caller's state is unchanged. Today Step refuses a
+ // ledger game (Simulation.cs:48). On a Historical ledger the losses above already removed this
+ // formation's lost records (LoseRecord, #1706: "Prisoners #1710 first (Recommended)"), so for a
+ // formation whose records matched its strength Take finds the records left numbering its strength.
+ var taken = Prisoners.Take(c, s, u, attackers.OrderBy(x => x.Id).First());
s.Units.Remove(u.Id);
why.Add(UnitLines.Line(u.Side == Movement.PlayerSide ? WhyKeys.SurrenderedHeld : WhyKeys.SurrenderedPrisoners, // Prisoners.Take's two cases
- FormattableString.Invariant($"Unit {u.Id} surrendered with {u.Strength * ppu:N0} people: it had no hex to retreat to. {held}"),
- new[] { u }, (u.Strength * ppu).ToString(CultureInfo.InvariantCulture)));
+ FormattableString.Invariant($"Unit {u.Id} surrendered with {taken.Held * ppu:N0} people: it had no hex to retreat to. {taken.Text}"),
+ new[] { u }, (taken.Held * ppu).ToString(CultureInfo.InvariantCulture)));
+ if (taken.Home != null) // leftover records went home: Send home's two lines, in its order ("Yes, reuse Send home's (Recommended)")
+ {
+ why.Add(Demobilization.SentHomeLine(c, s, u, taken.Sent, taken.Home));
+ if (taken.ArmsBack > 0) why.Add(Demobilization.ArmsReturnedLine(c, taken.Home, u.Id, taken.ArmsBack));
+ }
}
}
}
@@ -414,8 +428,9 @@ namespace Statecraft.Sim
/// <summary>Takes up to <paramref name="loss"/> population units from <paramref name="ids"/>, one at a time from the
/// strongest unit left (a tie on the lower id; the list is in id order), removing each that reaches 0 (its id is never
- /// reused: NextId is not touched) and adding it to <paramref name="removed"/>. Returns the units taken.</summary>
- static int Take(GameState s, List<int> ids, int loss, List<Unit> removed)
+ /// reused: NextId is not touched) and adding it to <paramref name="removed"/>. Each one an own formation loses on a
+ /// Historical ledger also removes one of its serving records (<see cref="LoseRecord"/>). Returns the units taken.</summary>
+ static int Take(Content c, GameState s, List<int> ids, int loss, List<Unit> removed, string source)
{
int taken = 0;
for (; taken < loss; taken++)
@@ -424,12 +439,30 @@ namespace Statecraft.Sim
foreach (var id in ids)
if (s.Units.TryGetValue(id, out var x) && (top == null || x.Strength > top.Strength)) top = x;
if (top == null) break;
+ LoseRecord(c, s, top, source);
if (top.Strength <= 1) { s.Units.Remove(top.Id); removed.Add(top); }
else s.Units[top.Id] = Lose(top);
}
return taken;
}
+ /// <summary>R-COMBAT-003 and R-POP-001 on a Historical ledger (#1706, #1725 PR 7; owner, 8 November 2026, #1725): the
+ /// own formation <paramref name="u"/> loses one population unit, so one of its serving soldier records (the active
+ /// soldiers on its target, <see cref="Training.FormationTarget"/>: "Yes, after #2964 (Recommended)") leaves the ledger
+ /// as a combat loss, with <paramref name="source"/>, combat/date/hex, as its provenance ("Date + battle hex
+ /// (Recommended)"). "Lowest id first (Recommended)": the lowest id goes. "No, losses are deaths (Recommended)": nothing
+ /// else is written. "Go ahead on strength": the engagement is fought on the unit's strength, and a record goes only
+ /// while one is left. Enemy formations are not own population (R-POP-004) and lose none; any other game has no
+ /// Historical ledger and writes none. Draws nothing.</summary>
+ static void LoseRecord(Content c, GameState s, Unit u, string source)
+ {
+ if (!s.PopulationLedger.IsHistorical || u.Side != Movement.PlayerSide) return;
+ var target = Training.FormationTarget(c, u.Id);
+ var lowest = s.PopulationLedger.Units.Where(p => p.Status == PopulationStatus.ActiveSoldier
+ && string.Equals(p.Assignment.Target, target, StringComparison.Ordinal)).OrderBy(p => p.Id).FirstOrDefault();
+ if (lowest != null) s.PopulationLedger.RegisterCombatLoss(lowest.Id, source);
+ }
+
/// <summary>What <see cref="Take"/> returns for <paramref name="loss"/> on units of <paramref name="pool"/> summed
/// strength: it takes one population unit a time until the loss is met or no unit is left, so the smaller of the two.
/// Outcomes reads it so the card's bands are Fight's (#2553).</summary>
diff --git a/sim/Statecraft.Sim/Demobilization.cs b/sim/Statecraft.Sim/Demobilization.cs
index de1d26e2f..dfcdd6288 100644
--- a/sim/Statecraft.Sim/Demobilization.cs
+++ b/sim/Statecraft.Sim/Demobilization.cs
@@ -82,16 +82,32 @@ namespace Statecraft.Sim
s.Cities[city] = x.WithCounts(x.Civilians + u.Strength, x.Employed, x.Refugees);
}
s.Units.Remove(unitId);
- 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 }));
+ why.Add(SentHomeLine(c, s, u, u.Strength, 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) }));
+ why.Add(ArmsReturnedLine(c, city, unitId, back));
return null;
}
+ /// <summary>R-UNIT-005's Why line, in people (Q-CIV-4): <paramref name="count"/> population units of unit
+ /// <paramref name="u"/> are civilians in <paramref name="city"/> now. Send home writes it for the unit's strength and,
+ /// for a surrendering formation's leftover records (owner, 9 November 2026: "Yes, reuse Send home's (Recommended)"),
+ /// Combat's surrender for the leftovers, both before the Arms line.</summary>
+ internal static Cause SentHomeLine(Content c, GameState s, Unit u, int count, string city)
+ {
+ var ppu = c.RulesAt(s.Date).Mvp!.PeoplePerUnit;
+ return new Cause("map", u.Id.ToString(CultureInfo.InvariantCulture), count, FormattableString.Invariant(
+ $"Unit {u.Id} is sent home: its {count * ppu:N0} people are civilians in {PlayerText.Settlement(c, city)} now"),
+ key: WhyKeys.SentHome, units: new[] { new UnitRef(u) },
+ args: new[] { (count * ppu).ToString(CultureInfo.InvariantCulture), city });
+ }
+
+ /// <summary>"Yes, one Why line (Recommended)" (owner, 8 November 2026): the line naming the <paramref name="back"/> Arms
+ /// that unit <paramref name="unitId"/>'s records returned to the stock in <paramref name="city"/>. Written by Send home
+ /// and, for a surrendering formation's leftover records (owner, 9 November 2026: "Sent home (Recommended)"), by
+ /// Combat's surrender.</summary>
+ internal static Cause ArmsReturnedLine(Content c, string city, int unitId, int back) =>
+ 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) });
+
/// <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
@@ -102,7 +118,10 @@ namespace Statecraft.Sim
/// 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>
+ /// writes one Why line naming the <paramref name="back"/> Arms returned. Null when done, else the reason. The records'
+ /// change is <see cref="RecordsHome"/> then <see cref="CommitHome"/>; a surrender's leftover records share
+ /// <see cref="RecordsHome"/> and <see cref="ReturnArms"/>, written in the capture's one ledger commit
+ /// (<see cref="PopulationLedger.Capture"/>).</summary>
static string? LedgerSendHome(Content c, GameState s, Unit u, string city, out int back)
{
back = 0;
@@ -111,23 +130,54 @@ namespace Statecraft.Sim
&& 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 civilians = RecordsHome(c, serving, city, out var items);
+ back = CommitHome(s, civilians, items);
+ return null;
+ }
+
+ /// <summary>R-UNIT-005 on a Historical ledger, the records leaving service (owner, 8 November 2026): each of
+ /// <paramref name="serving"/> as a free civilian without an assignment located in <paramref name="city"/> (its region
+ /// plus the city; "Nearest city, unemployed (Recommended)"), reception ticks reception.turns ("Settled in
+ /// (Recommended)"), qualification and combat XP kept ("Keep both (Recommended)"), its issued military item taken off
+ /// and counted in <paramref name="items"/> ("Back to Arms stock (Recommended)"). Writes nothing: a missing region or
+ /// reception.turns throws here, before the caller's first write; the ledger's own location check comes in the commit
+ /// that writes them. Send home's ledger path and, for "Sent home (Recommended)" (owner, 9 November 2026), a
+ /// surrendering formation's leftover records (Prisoners.CaptureRecords, in the capture's own commit) use it.</summary>
+ internal static List<PopulationUnit> RecordsHome(Content c, IEnumerable<PopulationUnit> serving, string city, out int items)
+ {
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 issued = 0;
var civilians = serving.Select(p =>
{
var e = p.Equipment;
- if (e.MilitaryId != null) items++;
+ if (e.MilitaryId != null) issued++;
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();
+ items = issued;
+ return civilians;
+ }
+
+ /// <summary>Writes <see cref="RecordsHome"/>'s records in one validated commit ("No, records only (Recommended)": no
+ /// aggregate city field), then returns their <paramref name="items"/> issued items to the Arms stock once ("Back to
+ /// Arms stock (Recommended)") and gives the Arms added.</summary>
+ internal static int CommitHome(GameState s, IReadOnlyCollection<PopulationUnit> civilians, int items)
+ {
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
+ return ReturnArms(s, items);
+ }
+
+ /// <summary>"Back to Arms stock (Recommended)": <paramref name="items"/> issued items go back to the stock once, after
+ /// the records' commit; gives the Arms added.</summary>
+ internal static int ReturnArms(GameState s, int items)
+ {
+ var 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;
+ return back;
}
/// <summary>The nearest of the cities by hex distance to its settlement hex; a tie takes the city's id in ordinal
diff --git a/sim/Statecraft.Sim/PopulationLedger.cs b/sim/Statecraft.Sim/PopulationLedger.cs
index fd5b33934..f46c4ff2c 100644
--- a/sim/Statecraft.Sim/PopulationLedger.cs
+++ b/sim/Statecraft.Sim/PopulationLedger.cs
@@ -228,7 +228,7 @@ namespace Statecraft.Sim
/// Home the place it served in (the formation's region; owner, 8 November 2026: "Formation's region (Recommended)"),
/// and keeps its id, history and issued item (owner: "Stays on record (Recommended)"). Every record is checked and the
/// candidate validated before any is committed, so a refusal changes nothing. Nobody is lost: no loss is written.</summary>
- internal void Capture(IReadOnlyList<int> ids, string captor)
+ internal void Capture(IReadOnlyList<int> ids, string captor, IReadOnlyCollection<PopulationUnit>? alsoReplace = null)
{
RequireInitialized();
if (captor == null || !bindings!.HasCaptor(captor))
@@ -242,6 +242,15 @@ namespace Statecraft.Sim
throw new ArgumentException("Only an active soldier can surrender, once (R-POW-005).");
candidate[id] = p.WithPlacement(PopulationStatus.Captured, null, PopulationAssignment.Unassigned, captor, p.Location);
}
+ // R-POW-005 (owner, 9 November 2026: "Sent home (Recommended)"): a surrendering formation's leftover records,
+ // replaced in the same candidate as Commit replaces records, so the capture and their homecoming are validated
+ // together and written all or nothing.
+ foreach (var r in alsoReplace ?? Array.Empty<PopulationUnit>())
+ {
+ Get(r.Id);
+ if (!seen.Add(r.Id)) throw new ArgumentException("A record is replaced at most once in a commit.");
+ candidate[r.Id] = r;
+ }
Validate(candidate); units = candidate;
}
/// <summary>A manifest item can arrive only once, including after its population id is lost.</summary>
diff --git a/sim/Statecraft.Sim/Prisoners.cs b/sim/Statecraft.Sim/Prisoners.cs
index aa43cf196..609653e1d 100644
--- a/sim/Statecraft.Sim/Prisoners.cs
+++ b/sim/Statecraft.Sim/Prisoners.cs
@@ -33,41 +33,67 @@ namespace Statecraft.Sim
/// people become prisoners under its own side; the player's soldiers are counted under the captor's side. Called only by
/// Combat's surrender, the one way a unit is captured. With an initialized Historical ledger (the dark start, #1710,
/// #1725 PR 7) the player's surrendering formation's serving soldier records also become Captured under the captor's
- /// side (<see cref="CaptureRecords"/>), checked in full before anything is written; enemy prisoners stay a count per
- /// side (owner, 8 November 2026: "No, keep count (Recommended)"). A synthetic or Open ledger is still refused. A refusal
- /// throws before Take writes anything; what the throw leaves in combat is set out at Combat.Fight's call.</summary>
- internal static string Take(Content c, GameState s, Unit u, Unit captor)
+ /// side (<see cref="CaptureRecords"/>), and SoldiersHeld grows by the records captured, so the count per captor stays
+ /// the Captured records with that captor (owner, 8 November 2026: "Keep count + check (Recommended)"). Without a
+ /// ledger it grows by the unit's strength, as before. Enemy prisoners stay a count per side (owner, 8 November 2026:
+ /// "No, keep count (Recommended)"). A synthetic or Open ledger, an unbound captor and a held count that already
+ /// disagrees with the records are refused; a refusal throws before Take writes anything, and what the throw leaves in
+ /// combat is set out at Combat.Fight's call. Returns the Why line's last sentence; Held, the population units taken
+ /// (the records captured on a ledger, owner, 9 November 2026: "Records captured (Recommended)"; else the unit's
+ /// strength), which the surrender Why line states in people; and, when a formation's leftover records went home
+ /// ("Sent home (Recommended)"), their city (Home), their number (Sent) and the Arms they returned to the stock
+ /// (ArmsBack), else null, 0 and 0.</summary>
+ internal static (string Text, int Held, int ArmsBack, string? Home, int Sent) Take(Content c, GameState s, Unit u, Unit captor)
{
PopulationLedger.RefuseUnlessHistorical(s);
if (s.PopulationLedger.IsInitialized) RequireHeldMatchesRecords(s);
if (u.Side == Movement.PlayerSide)
{
- if (s.PopulationLedger.IsInitialized) CaptureRecords(c, s, u, captor.Side);
- Add(s.SoldiersHeld, captor.Side, u.Strength);
- return "They are held by the enemy";
+ int back = 0, sent = 0; string? home = null;
+ var held = s.PopulationLedger.IsInitialized ? CaptureRecords(c, s, u, captor.Side, out back, out home, out sent) : u.Strength;
+ Add(s.SoldiersHeld, captor.Side, held);
+ return ("They are held by the enemy", held, back, home, sent);
}
Add(s.PrisonersHeld, u.Side, u.Strength);
- return "They are held as prisoners";
+ return ("They are held as prisoners", u.Strength, 0, null, 0);
}
- /// <summary>R-POW-005, R-POP-002 on the dark start: the opening formation <paramref name="u"/>'s serving soldier records
- /// (active soldiers on its units_1948 target; unit id i is c.StartingForces[i], StartingForces.Init) become Captured
- /// under <paramref name="side"/>, in one validated ledger commit. Refused before any write when the unit is not a
- /// units_1948 formation (a trained formation's soldiers serve a target this ledger does not have yet) or when its
- /// records do not number its strength (R-POP-004).</summary>
- static void CaptureRecords(Content c, GameState s, Unit u, string side)
+ /// <summary>R-POW-005, R-POP-002 on the dark start: the serving soldier records of the player's formation
+ /// <paramref name="u"/> become Captured under <paramref name="side"/>, in one validated ledger commit, and the number
+ /// captured is returned. They are the active soldiers on its ActiveService target, found as battles find them
+ /// (<see cref="Training.FormationTarget"/>: an opening formation's units_1948 target, a trained one's formation/&lt;id&gt;;
+ /// owner, 9 November 2026: "Yes, in #1706 (Recommended)"). A strength its records do not number is not refused (owner,
+ /// 9 November 2026: "Go ahead on strength (Recommended)"): with more records than its strength, its strength of them
+ /// are captured, the lowest ids first; with fewer, all of them are. The leftover records leave service as soldiers sent
+ /// home do (owner, 9 November 2026: "Sent home (Recommended)"; R-UNIT-005): Demobilization's
+ /// <see cref="Demobilization.RecordsHome"/>, Send home's own ledger code, written in the capture's one ledger commit,
+ /// make them settled-in free civilians without an assignment in the nearest city to the formation's hex
+ /// (<see cref="Demobilization.Nearest"/>) and return their issued items to the Arms stock (<see
+ /// cref="Demobilization.ReturnArms"/>); <paramref name="back"/> is the Arms added, <paramref name="home"/> that city and
+ /// <paramref name="sent"/> their number (0, null and 0 with no leftover). The captives and the leftovers change in
+ /// one validated ledger commit (PopulationLedger.Capture with the leftovers as replacements), so every check comes
+ /// before any write: a missing region or reception.turns in RecordsHome, then an unbound captor, a record that is not
+ /// an active soldier, or a leftover location the ledger does not bind, all refused with nothing written. The Arms go
+ /// back after that commit.</summary>
+ static int CaptureRecords(Content c, GameState s, Unit u, string side, out int back, out string? home, out int sent)
{
- if (u.Id < 0 || u.Id >= c.StartingForces.Count || c.StartingForces[u.Id].Side != Movement.PlayerSide)
- throw new InvalidOperationException(FormattableString.Invariant(
- $"Unit {u.Id} is not a formation of units_1948.yaml, so its soldiers have no ledger records to capture (R-POP-002)."));
- var key = HistoricalPopulation.FormationPrefix + c.StartingForces[u.Id].Row;
- var ids = s.PopulationLedger.Units.Where(p => p.Status == PopulationStatus.ActiveSoldier
+ var key = Training.FormationTarget(c, u.Id);
+ var serving = s.PopulationLedger.Units.Where(p => p.Status == PopulationStatus.ActiveSoldier
&& p.Assignment.Kind == PopulationAssignmentKind.ActiveService && p.Assignment.Target == key)
- .Select(p => p.Id).OrderBy(x => x).ToList();
- if (ids.Count != u.Strength)
- throw new InvalidOperationException(FormattableString.Invariant(
- $"Unit {u.Id} has strength {u.Strength} but the population ledger serves it with {ids.Count} (R-POP-004)."));
- s.PopulationLedger.Capture(ids, side);
+ .OrderBy(p => p.Id).ToList();
+ var take = Math.Max(0, u.Strength);
+ var ids = serving.Take(take).Select(p => p.Id).ToList();
+ var leftover = serving.Skip(take).ToList();
+ back = 0; home = null; sent = 0;
+ List<PopulationUnit>? civilians = null; var items = 0;
+ if (leftover.Count > 0)
+ {
+ home = Demobilization.Nearest(c, u.Q, u.R);
+ civilians = Demobilization.RecordsHome(c, leftover, home, out items);
+ }
+ s.PopulationLedger.Capture(ids, side, civilians);
+ if (civilians != null) { sent = civilians.Count; back = Demobilization.ReturnArms(s, items); }
+ return ids.Count;
}
/// <summary>The owner's ruling of 8 November 2026, "Keep count + check (Recommended)": on an initialized ledger,