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): link halutz map units to their pioneer records on a Historical ledger game (#1725 PR 7) (#2987)
Eyal Golan010fbaf55faa
diff --git a/changelog.d/1725-pr7-halutz-link.md b/changelog.d/1725-pr7-halutz-link.mdnew file mode 100644index 000000000..9845cf541--- /dev/null+++ b/changelog.d/1725-pr7-halutz-link.md@@ -0,0 +1,7 @@+- GDD 0.3 starting population (Refs #1725): on the inactive dark start's Historical ledger, each halutz map unit from the+ Hakhshara now lists the people record it stands for, and a veteran pioneer keeps that list. Return moves exactly that+ record to the nearest city as a settled-in civilian without a job, and Reassign takes the city's free pioneer records,+ lowest id first for the most service, back to the region. The pioneer's service is still kept on the city's counts, not+ on the person. A training order that takes a returned pioneer lowers the city's qualified pioneers by one, so a+ later reassignment still finds its people. A pioneer unit with no people record (one an event grants) makes one new+ settled-in pioneer when it returns, a beginner from a halutz unit and a veteran from a veteran unit. No new-game wiring, so there is no change in the game.diff --git a/docs/rules/mvp.md b/docs/rules/mvp.mdindex 72882f024..2fdafc1d7 100644--- a/docs/rules/mvp.md+++ b/docs/rules/mvp.md@@ -176,7 +176,7 @@ R-TRAIN-001: `Train(city, track, n)` takes `n` of the city's civilians without aR-TRAIN-002: `CancelTraining(cohort)` returns the cohort's people to its city as civilians without a job and refunds none of the Money paid (D-A3); a recruit cohort's Arms go back to the pool (R-ARMS-003). A cohort that does not exist, or has finished, is refused with the state unchanged. Replacements (R-TRAIN-004) cancel the same way. On a Historical ledger game (R-TRAIN-001) the cohort's member records are free civilians without a job again, in place, with their reception, and only the items this course issued leave them; those items and the cohort's pooled Arms go back to the stock, as many as the aggregate cohort's Arms.-R-TRAIN-003: Each turn, in ascending id, every cohort has one turn less to go. A cohort that reaches 0 ends: a recruit cohort becomes one military unit with its count as strength (R-UNIT-003), and so does a gun or armoured car cohort, of its own type (R-UNIT-008), craftsmen join the city's count (R-CRAFT-001), and halutzim become one movable unit per group. Units appear at the city's settlement hex, taking the next ids in turn. New recruit completions never fill `City.Recruits`; its old canonical field is retained, and saves still replay their command log. Cohorts are written into the state hash only when there are some. A cohort aimed at a unit ends as R-TRAIN-004 says instead. Reassignment of a qualified civilian is a second way into the role, with no cohort (R-QUAL-004, R-QUAL-005). On a Historical ledger game (R-TRAIN-001) each turn of a cohort counts one course tick on each of its records, and every record change and new target of the step is validated as one candidate before any write. Owner, 8 November 2026, "New unit at graduation (Rec.)" (#1725 issuecomment-6724941867): a new formation target is bound at graduation, one new formation per cohort (R-UNIT-003). A finished recruit or crew cohort's records are active soldiers serving the new target `formation/<unit id>` in the city's region, with the type's class as their qualification and their item kept; like an opening soldier each has the region-only location of its formation's region (owner, 8 November 2026, Q2: "Formation region (Recommended)"). "Free pioneer, not housed (Rec.)" (#1725 issuecomment-6724941867): a halutz graduate is a free civilian, Pioneer, Novice and unassigned, in the city's region with no city, so the city no longer houses it; a record that is a pioneer already keeps its tier and work XP (owner, 8 November 2026, Q1: "Keeps tier and XP (Recommended)"). The map units are made as above.+R-TRAIN-003: Each turn, in ascending id, every cohort has one turn less to go. A cohort that reaches 0 ends: a recruit cohort becomes one military unit with its count as strength (R-UNIT-003), and so does a gun or armoured car cohort, of its own type (R-UNIT-008), craftsmen join the city's count (R-CRAFT-001), and halutzim become one movable unit per group. Units appear at the city's settlement hex, taking the next ids in turn. New recruit completions never fill `City.Recruits`; its old canonical field is retained, and saves still replay their command log. Cohorts are written into the state hash only when there are some. A cohort aimed at a unit ends as R-TRAIN-004 says instead. Reassignment of a qualified civilian is a second way into the role, with no cohort (R-QUAL-004, R-QUAL-005). On a Historical ledger game (R-TRAIN-001) each turn of a cohort counts one course tick on each of its records, and every record change and new target of the step is validated as one candidate before any write. Owner, 8 November 2026, "New unit at graduation (Rec.)" (#1725 issuecomment-6724941867): a new formation target is bound at graduation, one new formation per cohort (R-UNIT-003). A finished recruit or crew cohort's records are active soldiers serving the new target `formation/<unit id>` in the city's region, with the type's class as their qualification and their item kept; like an opening soldier each has the region-only location of its formation's region (owner, 8 November 2026, Q2: "Formation region (Recommended)"). "Free pioneer, not housed (Rec.)" (#1725 issuecomment-6724941867): a halutz graduate is a free civilian, Pioneer, Novice and unassigned, in the city's region with no city, so the city no longer houses it; a record that is a pioneer already keeps its tier and work XP (owner, 8 November 2026, Q1: "Keeps tier and XP (Recommended)"). The map units are made as above. On a Historical ledger game each halutz map unit keeps the ids of the pioneer records that form it (owner, 9 November 2026: "Add the link first (Recommended)"): `Unit.Records`, one per group, the cohort's records in ascending id for its units in id order. "List on the unit (Recommended)": the list is sorted and written into the state hash as `|records=` only when set, like a cohort's members, so only a ledger game with a trained pioneer unit hashes differently; the records stay free, unassigned pioneers. "Yes, keep the link (Recommended)": a veteran pioneer made by promotion (R-VET-001) keeps the list, as every other change of a unit does.R-TRAIN-004: `Reinforce(unit, city, n)` (#1510; owner, 23 October 2026: "Replacements cost Arms", https://github.com/eyalgolan/statecraft-israel/issues/1510#issuecomment-6372356139, and "Default (Recommended)") refills a damaged formation of the player's with trained replacements. The unit must be a military unit of the player's side standing on `city`'s settlement hex. Its course is the trained type of the unit's side and class (a type with a `facility`): the recruit's basic training for a recruit or a veteran soldier, the guns' and the armoured cars' own for artillery and armoured cars (R-UNIT-008); a type no course trains (any enemy type) takes none. The cohort then follows R-TRAIN-001: the city's facility, `n` of its civilians without a job, `n * training_cost` with borrowing (R-MONEY-003), and the Arms of R-ARMS-003 for that course; it carries the unit's id, written into the state hash (`|unit=<id>`) only when set. The cap is the strength the unit had before its first loss, `Unit.Full`: combat stores it on a player's unit at its first loss (R-COMBAT-003) and clears it when replacements bring the unit back to it, and it is written into the state hash (`|full=<n>`) only when set, so a unit that has lost nobody, and every enemy unit, hashes as before. The order is refused, the state and Attention unchanged, for an unknown unit ("There is no such unit"), a unit with no side or an enemy unit (R-ORDER-001's wording), an unknown city, a unit off the city's hex ("Unit N is not in <city>"), a type no course trains ("Unit N cannot take replacements"), a unit with nothing to refill ("Unit N has no losses to replace") and `n` past the cap less the unit's strength and the replacements already training for it ("Unit N can take K more groups"), then for R-TRAIN-001's and R-ARMS-003's reasons. A queued `Reinforce` takes its city's civilians as a queued `Train` does (R-CITY-001). In step 4, before a turn is counted, replacements whose unit has left the state (destroyed, captured, sent home) or stands off the city's hex are cancelled as R-TRAIN-002 cancels a cohort: people and Arms back, the Money spent, with a Why line. A cohort that finishes adds its count to the unit's strength and makes no unit and takes no id; the unit keeps its type, service, order and home (a veteran stays a veteran, R-UNIT-004). The people join the unit's home city's housing (R-HOUSE-003). `attention_cost.reinforce` is 1, Train's cost, a design value (owner, 24 October 2026: "1, like Train (Recommended)", https://github.com/eyalgolan/statecraft-israel/issues/1510#issuecomment-6375591436). The save line is `reinforce <unit> <city> <n>` and the scenario form `{ kind: reinforce, unit, city, count }`. On a Historical ledger game (R-TRAIN-001) the owner's ruling of 8 November 2026, "Full minus strength (Rec.)" (#1725 issuecomment-6724941867): the room is `Unit.Full` minus strength minus training, and a formation whose strength differs from its serving records is refused, the refusal "Unit <id> has <n> soldiers on record but strength <s>". A starting formation's records serve `units_1948/<row>` (unit id i is `c.StartingForces[i]`), a trained one's `formation/<unit id>`. Finished replacements serve the unit's own target, as active soldiers with the course's class as their qualification.@@ -220,13 +220,13 @@ R-QUAL-001: Each city keeps its qualified civilians (`City.Qualified`): qualifieR-QUAL-002: `ReturnCraftsmen(city, n)` turns `n` of the city's craftsmen into civilians and qualified craftsmen, at once and with no Money. Employed is unchanged. It is refused, with the state unchanged and the Attention refunded, when the city is unknown, `n` is below 1 or `n` is above the city's craftsmen. On a game with an initialized Historical ledger (the dark start, R-POP-002; #1725) the order is refused, after the unknown city and the count below 1, with "Craftsmen are not on the population ledger yet (#2476)", the state unchanged and nothing thrown, until #2476 makes craftsmen exist there: the Historical start has none, and the craftsman course is refused until then (R-TRAIN-001) (owner, 9 November 2026: "Refuse for now (Recommended)"). A synthetic or Open ledger is still refused (R-POP-002). This internal English text gets its Hebrew with the UI wiring PR.-R-QUAL-003: `UnitOrder(unit, return_civilian)` (the unit card's "Return", an order with no hex) takes an idle halutz or veteran pioneer unit off the map, at once and with no Money. It joins the nearest city (hex distance to the settlement hex, ties by ordinal city id, R-UNIT-005's rule) as one civilian and one qualified halutz group with the unit's service, or one qualified veteran pioneer. A halutz's partial service toward veteran is kept (owner ruling 3). It is refused, state unchanged, for an unknown unit, a unit that is not a halutz or veteran ("Only a pioneer unit takes that order") and a unit at work on a site or corridor segment ("That unit is at work; stop the work first").+R-QUAL-003: `UnitOrder(unit, return_civilian)` (the unit card's "Return", an order with no hex) takes an idle halutz or veteran pioneer unit off the map, at once and with no Money. It joins the nearest city (hex distance to the settlement hex, ties by ordinal city id, R-UNIT-005's rule) as one civilian and one qualified halutz group with the unit's service, or one qualified veteran pioneer. A halutz's partial service toward veteran is kept (owner ruling 3). It is refused, state unchanged, for an unknown unit, a unit that is not a halutz or veteran ("Only a pioneer unit takes that order") and a unit at work on a site or corridor segment ("That unit is at work; stop the work first"). On a Historical ledger game (#1725 PR 7; owner, 9 November 2026: "Add the link first (Recommended)") exactly the unit's record returns. "Nearest city, settled (Recommended)": it becomes a free civilian without an assignment in the nearest city (its region plus the city), with reception ticks equal to `reception.turns`, as Send home does (R-UNIT-005), and keeps its profession, tier, work XP and items, except that a veteran pioneer unit's record becomes a Veteran pioneer (R-QUAL-005). "City counts, as today (Recommended)": the unit's service, or the veteran, goes into the city's `City.Qualified` as above, and no new field is added to the record; the civilian count is the records', so no other city field is written. A pioneer unit with no linked records (one an event grants) makes new ones (owner, 9 November 2026: "Make new records"): "One per unit (Recommended)", one new person record, registered under its "Own heading (Recommended)", `returned_pioneer_unit/<city>` with ordinals from 0, apart from the census, the natural increase and the arrivals, so "Yes, new people (Recommended)": it counts as a new person in the ledger's totals, as an arrival does. "Beginner; veteran stays (Recommended)": a halutz gives a Novice pioneer with 0 work XP and a veteran pioneer a Veteran pioneer. It lands as the other returned pioneers do, free, unassigned and settled in, in the nearest city, with no qualification, combat XP or item, and the service goes to `City.Qualified` as for any return.R-QUAL-004: `ReassignCraftsmen(city, n)` turns `n` of the city's qualified craftsmen, who have no job, into craftsmen again, at once, with no Money and no training. It is refused, state unchanged, when the city is unknown, `n` is below 1, `n` is above its qualified craftsmen or `n` is above its civilians without work (R-TRAIN-001's Idle; owner, 24 October 2026: "Accept all as built", https://github.com/eyalgolan/statecraft-israel/issues/1511#issuecomment-6375597377: the check counts all the city's idle civilians). Queued, it counts in full against the city's civilians without work as a queued `Train` does (R-TRAIN-001), so the orders are accepted in any order, and it counts against `Cities.MaxWorkers` (R-CITY-001) for the turn it is queued: its craftsmen stay in the city, but if the job order runs first they are already in work. On a game with an initialized Historical ledger it is refused as R-QUAL-002 sets, with the same reason (owner, 9 November 2026: "Refuse for now (Recommended)").-R-QUAL-005: `ReassignPioneers(city, track, n)` (`track` is `halutz` or `veteran_halutz`) turns `n` of the city's qualified halutz groups or veteran pioneers, who have no job, into `n` units at the city's settlement hex, as R-TRAIN-003 places them, taking the next ids in turn: a halutz keeps its service and a veteran comes back a veteran with `veteran_halutz_service`, and the halutz groups with the most service come back first (owner, 24 October 2026: "Accept all as built", https://github.com/eyalgolan/statecraft-israel/issues/1511#issuecomment-6375597377). Refusals as R-QUAL-004's, and "There is no such qualification" for another track. Queued, it counts against the city's civilians without work as a queued `Train` does (R-TRAIN-001) and against `Cities.MaxWorkers` (R-CITY-001), since its groups leave the city as units.+R-QUAL-005: `ReassignPioneers(city, track, n)` (`track` is `halutz` or `veteran_halutz`) turns `n` of the city's qualified halutz groups or veteran pioneers, who have no job, into `n` units at the city's settlement hex, as R-TRAIN-003 places them, taking the next ids in turn: a halutz keeps its service and a veteran comes back a veteran with `veteran_halutz_service`, and the halutz groups with the most service come back first (owner, 24 October 2026: "Accept all as built", https://github.com/eyalgolan/statecraft-israel/issues/1511#issuecomment-6375597377). Refusals as R-QUAL-004's, and "There is no such qualification" for another track. Queued, it counts against the city's civilians without work as a queued `Train` does (R-TRAIN-001) and against `Cities.MaxWorkers` (R-CITY-001), since its groups leave the city as units. On a Historical ledger game (#1725 PR 7; owner, 9 November 2026: "Free pioneers by service (Recommended)") the groups are the city's free, unassigned pioneer records in ascending id, paired with the qualified groups most service first, so the group with the most service is the lowest id; each record goes back to region-only with no city, as at graduation (R-TRAIN-003), and its new unit is linked to it. A returned veteran's record counts for the `veteran_halutz` track ("Yes, keep the link (Recommended)"), and following that ruling there is no split between the tracks, only a preference: each track takes its own tier's records first (Veteran-tier ones for `veteran_halutz`, the others for `halutz`), then the other tier's when it has too few, so no qualified group is left without a record it can use; a linked veteran pioneer unit's record returns as a Veteran pioneer (R-QUAL-003), as a new record from one does. The training centre's census veteran pioneer teacher, the last `census/haifa` record (#1689), is set apart only while untouched, never linked to a map unit since the start: it then comes after every other record, of either tier (owner, 7 November 2026: "Takeable, but last (Recommended)"), and a Train order does not count it as holding a qualified group (R-QUAL-006). Once a unit is linked to it, the ledger records that (`teacher-linked`, in the state hash only once set) and it is a pioneer like any other. The order is refused, state unchanged, when the city has fewer free, unassigned pioneer records than `n`, as when a qualified pioneer holds a job (an arms workshop's worker, R-ARMS-005), the ledger's form of "civilians without work"; only `City.Qualified` is written.-R-QUAL-006: A Train order (R-TRAIN-001) takes the city's unqualified civilians first. A qualified civilian it has to take loses its qualification, in the order craftsmen, halutz groups with the least service, veterans (owner, 24 October 2026: "Accept all as built", https://github.com/eyalgolan/statecraft-israel/issues/1511#issuecomment-6375597377).+R-QUAL-006: A Train order (R-TRAIN-001) takes the city's unqualified civilians first. A qualified civilian it has to take loses its qualification, in the order craftsmen, halutz groups with the least service, veterans (owner, 24 October 2026: "Accept all as built", https://github.com/eyalgolan/statecraft-israel/issues/1511#issuecomment-6375597377). On a Historical ledger game (#1725 PR 7; owner, 9 November 2026: "Yes, lower it (Recommended)") a Train order that takes a returned pioneer record lowers the city's qualified pioneers (`City.Qualified`) by one, halutz groups with the least service first, then veterans, so the qualified pioneers never outnumber the city's free civilian pioneer records; as on the aggregate path, only what the remaining records cannot hold is lost ("Only as needed (Recommended)").R-QUAL-007: Attention is that of the matching existing order (owner ruling 1): `return_craftsmen` and `reassign_craftsmen` cost what `assign_workers` does (0.5), and `reassign_pioneers` and the `return_civilian` unit order cost what a unit order does (0), all design values in `rules.yaml`. The qualified counts are written into the state hash only when not 0 (`,qcraftsmen=N,qhalutz=S:S,qveterans=N` after the other city fields), so a game without them hashes as before. The saves write `retcraft CITY N`, `regcraft CITY N`, `regpioneer CITY TRACK N` and `order UNIT return_civilian`; scenarios use `return_craftsmen`, `reassign_craftsmen`, `reassign_pioneers` and `unit_order` with `order: return_civilian`.diff --git a/sim/Statecraft.Sim.Tests/Gdd03CombatXpTests.cs b/sim/Statecraft.Sim.Tests/Gdd03CombatXpTests.csindex 546a6af43..86e5dac64 100644--- a/sim/Statecraft.Sim.Tests/Gdd03CombatXpTests.cs+++ b/sim/Statecraft.Sim.Tests/Gdd03CombatXpTests.cs@@ -230,7 +230,9 @@ public class Gdd03CombatXpTestselse if (source[end] == ')' && --depth == 0) break;}var call = source.Substring(m.Index, end - m.Index + 1);- if (Path.GetFileName(file) == "Combat.cs" && call.EndsWith("u.Full, xp)")) { awards++; continue; }+ // #1725 PR 7 (owner, 9 November 2026, "Yes, keep the link (Recommended)"): every copy also passes the unit's records.+ Assert.True(call.EndsWith(m.Groups[1].Value + ".Records)"), Path.GetFileName(file) + " drops Records: " + call);+ if (Path.GetFileName(file) == "Combat.cs" && call.EndsWith("u.Full, xp, u.Records)")) { awards++; continue; }Assert.True(call.Contains(m.Groups[1].Value + ".CombatXp"), Path.GetFileName(file) + " drops CombatXp: " + call);copies++;}diff --git a/sim/Statecraft.Sim.Tests/LedgerHalutzLinkTests.cs b/sim/Statecraft.Sim.Tests/LedgerHalutzLinkTests.csnew file mode 100644index 000000000..3dda26398--- /dev/null+++ b/sim/Statecraft.Sim.Tests/LedgerHalutzLinkTests.cs@@ -0,0 +1,574 @@+using Statecraft.Sim;++/// <summary>#1725 PR 7: the halutz map unit's link to its pioneer records, and the pioneer's return (R-QUAL-003) and+/// reassignment (R-QUAL-005) on a game with an initialized Historical ledger, the dark start (R-POP-002). The owner's+/// rulings, 9 November 2026:+/// - "Add the link first (Recommended)": the halutz course records which pioneer records form each map unit, and Return+/// and ReassignPioneers use exactly those records.+/// - "List on the unit (Recommended)": the map unit keeps a sorted list of its records' ids, hashed only when set, like a+/// cohort's members; the records stay free, unassigned pioneers.+/// - "City counts, as today (Recommended)": a returned pioneer's service stays in City.Qualified, as on the aggregate game.+/// - "Nearest city, settled (Recommended)": a returned record goes to the nearest city, unemployed, reception ticks =+/// reception.turns, as Send home does.+/// - "Free pioneers by service (Recommended)": Reassign takes the city's free, unassigned pioneer records, most service+/// first then lowest id, and they go back to region-only with no city, as at graduation.+/// - "Yes, keep the link (Recommended)": a veteran pioneer unit made by promotion keeps the link, and a returned veteran+/// record counts for the veteran track.+/// The tests call Training and Qualification directly: Simulation.Step still refuses a ledger game (R-POP-002).</summary>+public class LedgerHalutzLinkTests+{+ const string TelAviv = "tel_aviv";++ static Content Gdd03() => HistoricalPopulationTests.Real(true);++ static GameState Dark(Content c)+ {+ var s = Simulation.NewGame(c, 1, Mode.Historical, darkStart: true);+ s.Arms = 200; s.Treasury = 100; s.Debt = 0;+ return s;+ }++ static GameState Aggregate(Content c)+ {+ var s = Simulation.NewGame(c, 1, Mode.Historical);+ s.Arms = 200; s.Treasury = 100; s.Debt = 0;+ return s;+ }++ static string Region(Content c, string city) => c.PlayerRegions.AtLocation(city)!.Id;++ static IEnumerable<(string, string, double, string, string)> Lines(IEnumerable<Cause> why) => why.Select(x => (x.System, x.Target, x.Delta, x.Message, x.Key));++ // The training order's pick ("Unskilled first, keep (Rec.)"): free civilians without an assignment in the city,+ // Profession None first, then ascending id.+ static List<int> Idle(GameState s, string city, int n) => s.PopulationLedger.Units+ .Where(p => p.Status == PopulationStatus.FreeCivilian && p.Assignment.Kind == PopulationAssignmentKind.Unassigned && p.Location?.City == city)+ .OrderBy(p => p.Profession == CivilianProfession.None ? 0 : 1).ThenBy(p => p.Id).Take(n).Select(p => p.Id).ToList();++ // "Free pioneers by service (Recommended)": the city's free, unassigned pioneer records, ascending id.+ static List<int> FreePioneers(GameState s, string city) => s.PopulationLedger.Units+ .Where(p => p.Status == PopulationStatus.FreeCivilian && p.Assignment.Kind == PopulationAssignmentKind.Unassigned+ && p.Profession == CivilianProfession.Pioneer && p.Location?.City == city)+ .Select(p => p.Id).OrderBy(x => x).ToList();++ /// <summary>Trains <paramref name="n"/> halutz groups in Tel Aviv to graduation. Returns the records picked (ascending+ /// id on the ledger, empty on the aggregate game) and the new map units, ascending id.</summary>+ static (List<int> Records, List<int> Units) Graduate(Content c, GameState s, int n, List<Cause> why)+ {+ var picked = s.PopulationLedger.IsInitialized ? Idle(s, TelAviv, n).OrderBy(x => x).ToList() : new List<int>();+ var before = s.Units.Keys.ToHashSet();+ Assert.Null(Training.Start(c, s, TelAviv, "halutz", n, why));+ var turns = c.UnitTypes.First(t => t.Id == "halutz").TrainingTurns;+ for (int t = 0; t < turns; t++) Training.Progress(c, s, why);+ return (picked, s.Units.Keys.Where(k => !before.Contains(k)).OrderBy(k => k).ToList());+ }++ // A tuple compares an array by reference, so record lists are compared as text.+ static string Ids(params int[] ids) => string.Join(",", ids);+ static string Ids(IReadOnlyList<int> ids) => string.Join(",", ids);++ static void SetService(GameState s, int id, int service, string? type = null)+ {+ var u = s.Units[id];+ s.Units[id] = new Unit(u.Id, type ?? u.Type, u.Q, u.R, service, u.Side, u.Strength, u.Order, u.OrderTarget, u.HomeCity, u.Full, u.CombatXp, u.Records);+ }++ static Dictionary<int, string> Others(GameState s, ICollection<int> except) => s.PopulationLedger.Units+ .Where(p => !except.Contains(p.Id)).ToDictionary(p => p.Id, p => string.Join("|", p.Assignment.Canonical(), p.Location?.Canonical(), p.Status, p.ReceptionTicks, p.Profession, p.Tier, p.WorkXp));++ // "Add the link first" and "List on the unit": the cohort's records, ascending, form its map units in id order, one+ // record per group; the records stay free, unassigned pioneers ("Free pioneer, not housed (Rec.)"). The unit's list is+ // in the state hash only when set, so the aggregate game's units hash as before.+ [Fact]+ public void AGraduateHalutzUnitIsLinkedToItsRecord()+ {+ var c = Gdd03();+ var s = Dark(c); var twin = Aggregate(c);+ var (records, units) = Graduate(c, s, 2, new List<Cause>());+ var (_, twinUnits) = Graduate(c, twin, 2, new List<Cause>());+ Assert.Equal(2, units.Count);+ Assert.Equal(twinUnits, units);+ for (int i = 0; i < units.Count; i++)+ {+ var u = s.Units[units[i]];+ Assert.Equal(new[] { records[i] }, u.Records);+ Assert.Equal(twin.Units[units[i]].Canonical() + "|records=" + records[i], u.Canonical());+ var p = s.PopulationLedger.Get(records[i]);+ Assert.Equal((PopulationStatus.FreeCivilian, PopulationAssignmentKind.Unassigned, CivilianProfession.Pioneer, (string?)null),+ (p.Status, p.Assignment.Kind, p.Profession, p.Location!.City));+ }+ Assert.All(twinUnits, id => Assert.Null(twin.Units[id].Records));+ Assert.DoesNotContain("records=", string.Join(";", twin.Units.Values.Select(x => x.Canonical())));+ s.PopulationLedger.Reconcile();+ }++ // R-QUAL-003 on the ledger. "Nearest city, settled": exactly the unit's record becomes a free civilian without a job in+ // the nearest city (its region plus the city), reception ticks = reception.turns, its profession, tier and work XP kept.+ // "City counts, as today": the unit's service goes into the city's qualified halutz groups, as the aggregate game does;+ // the civilian count is the records'. No other record changes, and the Why line is the aggregate game's.+ [Fact]+ public void ReturnOnTheLedgerMovesExactlyTheUnitsRecord()+ {+ var c = Gdd03();+ var s = Dark(c); var twin = Aggregate(c);+ var (records, units) = Graduate(c, s, 2, new List<Cause>());+ Graduate(c, twin, 2, new List<Cause>());+ SetService(s, units[0], 3); SetService(twin, units[0], 3);+ var before = s.PopulationLedger.Get(records[0]);+ var others = Others(s, new[] { records[0] });+ var civilians = s.Cities[TelAviv].Civilians;+ var why = new List<Cause>(); var twinWhy = new List<Cause>();++ Assert.Null(Qualification.Return(c, s, units[0], why));+ Assert.Null(Qualification.Return(c, twin, units[0], twinWhy));++ Assert.False(s.Units.ContainsKey(units[0]));+ Assert.Equal(Lines(twinWhy), Lines(why));+ var p = s.PopulationLedger.Get(records[0]);+ Assert.Equal((PopulationStatus.FreeCivilian, PopulationAssignmentKind.Unassigned, c.RequirePopulationInteger("reception.turns")),+ (p.Status, p.Assignment.Kind, p.ReceptionTicks));+ Assert.Equal((Region(c, TelAviv), (string?)TelAviv), (p.Location!.Region, p.Location.City));+ Assert.Equal((before.Profession, before.Tier, before.WorkXp, before.Qualification, before.CombatXp),+ (p.Profession, p.Tier, p.WorkXp, p.Qualification, p.CombatXp));+ Assert.Equal(others, Others(s, new[] { records[0] }));+ Assert.Equal(new[] { 3 }, s.Cities[TelAviv].Qualified.Halutzim);+ Assert.Equal(twin.Cities[TelAviv].Qualified.Canonical(), s.Cities[TelAviv].Qualified.Canonical());+ Assert.Equal(civilians, s.Cities[TelAviv].Civilians);+ s.PopulationLedger.Reconcile();+ }++ // R-QUAL-005 on the ledger. "Free pioneers by service": the city's free, unassigned pioneer records in ascending id are+ // paired with its qualified halutz groups, most service first; each new unit is linked to its record, which goes back+ // to region-only with no city, as at graduation. Asking for more than the qualified groups is refused, state unchanged.+ [Fact]+ public void ReassignPioneersOnTheLedgerUsesExactlyThoseRecords()+ {+ var c = Gdd03();+ var s = Dark(c);+ var (records, units) = Graduate(c, s, 2, new List<Cause>());+ SetService(s, units[0], 1); SetService(s, units[1], 3);+ var why = new List<Cause>();+ Assert.Null(Qualification.Return(c, s, units[0], why));+ Assert.Null(Qualification.Return(c, s, units[1], why));+ var free = FreePioneers(s, TelAviv);+ Assert.True(records.All(free.Contains));+ var civilians = s.Cities[TelAviv].Civilians;++ var first = s.NextId;+ Assert.Null(Qualification.ReassignPioneers(c, s, TelAviv, "halutz", 1, why));+ var u = s.Units[first];+ Assert.Equal(("halutz", 3, Ids(free[0])), (u.Type, u.Service, Ids(u.Records!)));+ var hex = c.SettlementHexes.First(h => h.Id == TelAviv);+ Assert.Equal((hex.Q, hex.R), (u.Q, u.R));+ var p = s.PopulationLedger.Get(free[0]);+ Assert.Equal((PopulationStatus.FreeCivilian, PopulationAssignmentKind.Unassigned, CivilianProfession.Pioneer, Region(c, TelAviv), (string?)null),+ (p.Status, p.Assignment.Kind, p.Profession, p.Location!.Region, p.Location.City));+ Assert.Equal(new[] { 1 }, s.Cities[TelAviv].Qualified.Halutzim);+ Assert.Equal(civilians, s.Cities[TelAviv].Civilians);++ var others = Others(s, new[] { free[1] });+ var second = s.NextId;+ Assert.Null(Qualification.ReassignPioneers(c, s, TelAviv, "halutz", 1, why));+ Assert.Equal((1, Ids(free[1])), (s.Units[second].Service, Ids(s.Units[second].Records!)));+ Assert.Equal(others, Others(s, new[] { free[1] }));+ Assert.Empty(s.Cities[TelAviv].Qualified.Halutzim);++ var hash = s.Hash();+ Assert.Equal("Tel Aviv has 0 qualified halutzim", Qualification.ReassignPioneers(c, s, TelAviv, "halutz", 1, why));+ Assert.Equal(hash, s.Hash());+ s.PopulationLedger.Reconcile();+ }++ // R-QUAL-006 on the ledger (owner, 9 November 2026, "Yes, lower it (Recommended)"): a Train order that takes a returned+ // pioneer record lowers the city's qualified pioneer count by one, halutz groups with the least service first, so the+ // count and the city's pioneer records stay equal and a later Reassign finds its records.+ [Fact]+ public void ATrainOrderThatTakesAReturnedPioneerLowersTheQualifiedCount()+ {+ var c = Gdd03();+ var s = Dark(c);+ var (records, units) = Graduate(c, s, 2, new List<Cause>());+ SetService(s, units[0], 1); SetService(s, units[1], 3);+ var why = new List<Cause>();+ Assert.Null(Qualification.Return(c, s, units[0], why));+ Assert.Null(Qualification.Return(c, s, units[1], why));+ var free = FreePioneers(s, TelAviv);+ Assert.Equal(2, free.Count);+ var unskilled = s.PopulationLedger.Units.Count(p => p.Status == PopulationStatus.FreeCivilian && p.Assignment.Kind == PopulationAssignmentKind.Unassigned+ && p.Location?.City == TelAviv && p.Profession == CivilianProfession.None);++ // Only unqualified civilians taken: the count stays.+ Assert.Null(Training.Start(c, s, TelAviv, "halutz", unskilled, why));+ Assert.Equal(new[] { 1, 3 }, s.Cities[TelAviv].Qualified.Halutzim);++ // One more takes the lowest-id pioneer record: the group with the least service loses its qualification.+ Assert.Null(Training.Start(c, s, TelAviv, "halutz", 1, why));+ Assert.Equal(PopulationStatus.Trainee, s.PopulationLedger.Get(free[0]).Status);+ Assert.Equal(new[] { 3 }, s.Cities[TelAviv].Qualified.Halutzim);+ Assert.Equal(FreePioneers(s, TelAviv).Count, s.Cities[TelAviv].Qualified.Halutzim.Count + s.Cities[TelAviv].Qualified.Veterans);++ var id = s.NextId;+ Assert.Null(Qualification.ReassignPioneers(c, s, TelAviv, "halutz", 1, why));+ Assert.Equal((3, Ids(free[1])), (s.Units[id].Service, Ids(s.Units[id].Records!)));+ s.PopulationLedger.Reconcile();+ }++ // A pioneer unit with no linked records (one an event grants) at Tel Aviv's settlement hex, not at work.+ static int Unlinked(Content c, GameState s, string type, int service, string city = TelAviv)+ {+ var hex = c.SettlementHexes.First(h => h.Id == city);+ var id = s.NextId++;+ s.Units.Add(id, new Unit(id, type, hex.Q, hex.R, service));+ return id;+ }++ // Owner, 9 November 2026, "Make new records" with "One per unit (Recommended)", "Own heading (Recommended)",+ // "Beginner; veteran stays (Recommended)" and "Yes, new people (Recommended)": a returned pioneer unit with no records+ // makes one new person record, booked under its own source heading (returned_pioneer_unit/<city>, ordinals from 0),+ // landing as other returned pioneers do ("Nearest city, settled (Recommended)"): free, unassigned, settled in, in the+ // nearest city. A halutz gives a Novice pioneer with 0 work XP, a veteran pioneer a Veteran pioneer; the service goes+ // to City.Qualified as for any return, and the ledger has one more person.+ [Fact]+ public void AnUnlinkedPioneerUnitReturnedOnTheLedgerMakesOneNewRecord()+ {+ var c = Gdd03();+ var s = Dark(c);+ var ledger = s.PopulationLedger;+ var source = Qualification.ReturnedUnitPrefix + TelAviv;+ Assert.Equal("returned_pioneer_unit/tel_aviv", source);+ var halutz = Unlinked(c, s, "halutz", 2);+ var veteran = Unlinked(c, s, Projects.VeteranType, c.RulesAt(s.Date).Mvp!.VeteranHalutzService!.Value);+ var (count, people, next) = (ledger.Units.Count, ledger.TotalPeople, ledger.NextPopulationId);+ var why = new List<Cause>();++ Assert.Null(Qualification.Return(c, s, halutz, why));+ Assert.Equal((count + 1, next + 1), (ledger.Units.Count, ledger.NextPopulationId));+ Assert.Equal(people + ledger.PeoplePerUnit, ledger.TotalPeople); // one more record's worth of people, as an arrival adds+ Assert.True(ledger.HasArrived(source, 0));+ Assert.False(ledger.HasArrived(source, 1));+ var p = ledger.Get(next);+ Assert.Equal((PopulationStatus.FreeCivilian, c.RequirePopulationInteger("reception.turns"), PopulationAssignmentKind.Unassigned),+ (p.Status, p.ReceptionTicks, p.Assignment.Kind));+ Assert.Equal((Region(c, TelAviv), (string?)TelAviv), (p.Location!.Region, p.Location.City));+ Assert.Equal((CivilianProfession.Pioneer, CivilianTier.Novice, 0, "", 0, (string?)null, (string?)null),+ (p.Profession, p.Tier, p.WorkXp, p.Qualification, p.CombatXp, p.Equipment.ToolsId, p.Equipment.MilitaryId));+ Assert.Equal(new[] { 2 }, s.Cities[TelAviv].Qualified.Halutzim);+ Assert.False(s.Units.ContainsKey(halutz));+ ledger.Reconcile();++ Assert.Null(Qualification.Return(c, s, veteran, why));+ Assert.Equal((count + 2, next + 2), (ledger.Units.Count, ledger.NextPopulationId));+ Assert.True(ledger.HasArrived(source, 1));+ var v = ledger.Get(next + 1);+ Assert.Equal((CivilianProfession.Pioneer, CivilianTier.Veteran, 0, TelAviv), (v.Profession, v.Tier, v.WorkXp, v.Location!.City));+ Assert.Equal(1, s.Cities[TelAviv].Qualified.Veterans);+ ledger.Reconcile();++ // The new people are ordinary returned pioneers: Reassign links its unit to the lowest-id one.+ Assert.Equal(new[] { next, next + 1 }, FreePioneers(s, TelAviv));+ var id = s.NextId;+ Assert.Null(Qualification.ReassignPioneers(c, s, TelAviv, "halutz", 1, why));+ Assert.Equal((2, Ids(next)), (s.Units[id].Service, Ids(s.Units[id].Records!)));+ ledger.Reconcile();+ }++ // The new records are deterministic: the same returns on two dark starts give the same hash and ledger text.+ [Fact]+ public void NewRecordsForAnUnlinkedUnitAreDeterministic()+ {+ var c = Gdd03();+ (string, string) Run()+ {+ var s = Dark(c);+ var why = new List<Cause>();+ Assert.Null(Qualification.Return(c, s, Unlinked(c, s, "halutz", 1), why));+ Assert.Null(Qualification.Return(c, s, Unlinked(c, s, "halutz", 0), why));+ return (s.Hash(), string.Join("\n", s.PopulationLedger.Canonical()));+ }+ Assert.Equal(Run(), Run());+ }++ const string Haifa = HistoricalPopulation.TeacherCity;++ // The training centre's veteran pioneer teacher: the dark start's one Pioneer record in Haifa (#1689).+ static int Teacher(GameState s) => Assert.Single(s.PopulationLedger.Units, p => p.Profession == CivilianProfession.Pioneer+ && p.Tier == CivilianTier.Veteran && p.Location?.City == Haifa).Id;++ // "Takeable, but last (Recommended)" (#1689 comment 6710877137) with "Add the link first (Recommended)": a Reassign in+ // Haifa takes the returned pioneer's record before the census teacher, on both tracks, and the teacher stays in Haifa.+ [Theory]+ [InlineData("halutz")]+ [InlineData("veteran_halutz")]+ public void ReassignInHaifaTakesTheReturnedPioneerBeforeTheTeacher(string track)+ {+ var c = Gdd03();+ var s = Dark(c);+ var teacher = Teacher(s);+ var unit = Unlinked(c, s, track, track == "halutz" ? 1 : c.RulesAt(s.Date).Mvp!.VeteranHalutzService!.Value, Haifa);+ var returned = s.PopulationLedger.NextPopulationId;+ var why = new List<Cause>();+ Assert.Null(Qualification.Return(c, s, unit, why));+ Assert.True(returned > teacher);+ var id = s.NextId;+ Assert.Null(Qualification.ReassignPioneers(c, s, Haifa, track, 1, why));+ Assert.Equal(Ids(returned), Ids(s.Units[id].Records!));+ var t = s.PopulationLedger.Get(teacher);+ Assert.Equal((Haifa, PopulationAssignmentKind.Unassigned, CivilianTier.Veteran), (t.Location!.City, t.Assignment.Kind, t.Tier));+ s.PopulationLedger.Reconcile();+ }++ // "Yes, lower it (Recommended)" with "Only as needed (Recommended)": the census teacher is not a returned pioneer, so it+ // cannot hold a qualified group. The teacher is placed at work in Tel Aviv (on a field target of its region, as a+ // teaching assignment would hold it; Tel Aviv has the only Hakhshara), so a Train order there takes the one returned+ // pioneer and leaves the teacher. The count is lowered, and a later Reassign is refused for the count, not for missing+ // records.+ [Fact]+ public void TheTeacherDoesNotHoldAQualifiedGroupWhenTrainTakesTheReturnedPioneer()+ {+ var c = Gdd03();+ var s = Dark(c);+ var ledger = s.PopulationLedger;+ var teacher = ledger.Get(Teacher(s));+ var region = Region(c, TelAviv);+ var field = ledger.Units.First(p => p.Assignment.Kind == PopulationAssignmentKind.Work && p.Location?.Region == region);+ ledger.Replace(teacher.WithPlacement(teacher.Status, new PopulationLocation(region, city: TelAviv), field.Assignment, teacher.Captor, teacher.Home));+ var why = new List<Cause>();+ var returned = ledger.NextPopulationId;+ Assert.Null(Qualification.Return(c, s, Unlinked(c, s, "halutz", 2), why));+ Assert.Equal(new[] { 2 }, s.Cities[TelAviv].Qualified.Halutzim);+ var unskilled = ledger.Units.Count(p => p.Status == PopulationStatus.FreeCivilian && p.Assignment.Kind == PopulationAssignmentKind.Unassigned+ && p.Location?.City == TelAviv && p.Profession == CivilianProfession.None);+ Assert.Null(Training.Start(c, s, TelAviv, "halutz", unskilled + 1, why));+ Assert.Equal(PopulationStatus.Trainee, ledger.Get(returned).Status);+ Assert.Equal((PopulationStatus.FreeCivilian, TelAviv), (ledger.Get(teacher.Id).Status, ledger.Get(teacher.Id).Location!.City));+ Assert.Empty(s.Cities[TelAviv].Qualified.Halutzim);+ Assert.Equal("Tel Aviv has 0 qualified halutzim", Qualification.ReassignPioneers(c, s, TelAviv, "halutz", 1, why));+ ledger.Reconcile();+ }++ static int Unskilled(GameState s, string city) => s.PopulationLedger.Units.Count(p => p.Status == PopulationStatus.FreeCivilian+ && p.Assignment.Kind == PopulationAssignmentKind.Unassigned && p.Location?.City == city && p.Profession == CivilianProfession.None);++ // The track is a preference, not a filter. A Veteran pioneer record trained on the halutz track keeps its tier ("Keeps tier+ // and XP (Recommended)"), so it graduates as a halutz unit linked to a Veteran record; returned, its halutz group comes+ // back as a halutz unit linked to that record, because the halutz track has no other record to take.+ [Fact]+ public void AHalutzGroupWhoseRecordIsVeteranCanBeReassigned()+ {+ var c = Gdd03();+ var s = Dark(c);+ var why = new List<Cause>();+ var veteran = s.PopulationLedger.NextPopulationId;+ Assert.Null(Qualification.Return(c, s, Unlinked(c, s, Projects.VeteranType, c.RulesAt(s.Date).Mvp!.VeteranHalutzService!.Value), why));+ Assert.Equal(CivilianTier.Veteran, s.PopulationLedger.Get(veteran).Tier);+ var before = s.Units.Keys.ToHashSet();+ Assert.Null(Training.Start(c, s, TelAviv, "halutz", Unskilled(s, TelAviv) + 1, why));+ Assert.Equal(PopulationStatus.Trainee, s.PopulationLedger.Get(veteran).Status);+ for (int t = 0; t < c.UnitTypes.First(x => x.Id == "halutz").TrainingTurns; t++) Training.Progress(c, s, why);+ var unit = Assert.Single(s.Units.Values, u => !before.Contains(u.Id) && u.Records!.Contains(veteran));+ Assert.Equal(("halutz", CivilianTier.Veteran), (unit.Type, s.PopulationLedger.Get(veteran).Tier));+ Assert.Null(Qualification.Return(c, s, unit.Id, why));+ Assert.Equal(new[] { 0 }, s.Cities[TelAviv].Qualified.Halutzim);+ var id = s.NextId;+ Assert.Null(Qualification.ReassignPioneers(c, s, TelAviv, "halutz", 1, why));+ Assert.Equal(("halutz", Ids(veteran)), (s.Units[id].Type, Ids(s.Units[id].Records!)));+ s.PopulationLedger.Reconcile();+ }++ // R-QUAL-006 lowers the halutz groups first whatever record the Train order took. With a Veteran record (the veteran's)+ // and a Novice one (the halutz's) returned, training one past the unskilled takes the Veteran record and leaves one+ // qualified veteran; the veteran track then takes the Novice record, its only one.+ [Fact]+ public void AVeteranGroupFallsBackToANoviceRecordAfterTrainLowersTheHalutzCount()+ {+ var c = Gdd03();+ var s = Dark(c);+ var why = new List<Cause>();+ var (records, units) = Graduate(c, s, 2, why);+ SetService(s, units[0], c.RulesAt(s.Date).Mvp!.VeteranHalutzService!.Value, Projects.VeteranType);+ SetService(s, units[1], 1);+ Assert.Null(Qualification.Return(c, s, units[0], why));+ Assert.Null(Qualification.Return(c, s, units[1], why));+ Assert.Null(Training.Start(c, s, TelAviv, "halutz", Unskilled(s, TelAviv) + 1, why));+ Assert.Equal(PopulationStatus.Trainee, s.PopulationLedger.Get(records[0]).Status);+ Assert.Equal((0, 1), (s.Cities[TelAviv].Qualified.Halutzim.Count, s.Cities[TelAviv].Qualified.Veterans));+ var id = s.NextId;+ Assert.Null(Qualification.ReassignPioneers(c, s, TelAviv, Projects.VeteranType, 1, why));+ Assert.Equal((Projects.VeteranType, Ids(records[1])), (s.Units[id].Type, Ids(s.Units[id].Records!)));+ s.PopulationLedger.Reconcile();+ }++ // "Takeable, but last (Recommended)": the untouched teacher comes after every other record in the pool, not only after+ // the records of its own tier. A veteran Reassign in Haifa that falls back to the other tier takes a free returned Novice+ // pioneer before the teacher. Haifa's counts are set by hand to the shape a Train there would leave after taking a+ // Veteran record by R-QUAL-006 (no qualified halutz group, one veteran); no Haifa Train exists in the content today.+ [Fact]+ public void AVeteranFallbackInHaifaTakesAReturnedNoviceBeforeTheTeacher()+ {+ var c = Gdd03();+ var s = Dark(c);+ var teacher = Teacher(s);+ var why = new List<Cause>();+ var returned = s.PopulationLedger.NextPopulationId;+ Assert.Null(Qualification.Return(c, s, Unlinked(c, s, "halutz", 1, Haifa), why));+ Assert.Equal(CivilianTier.Novice, s.PopulationLedger.Get(returned).Tier);+ var h = s.Cities[Haifa];+ s.Cities[Haifa] = h.WithQualified(new Qualified(0, 1, Array.Empty<int>()));+ var id = s.NextId;+ Assert.Null(Qualification.ReassignPioneers(c, s, Haifa, Projects.VeteranType, 1, why));+ Assert.Equal(Ids(returned), Ids(s.Units[id].Records!));+ Assert.Equal(Haifa, s.PopulationLedger.Get(teacher).Location!.City);+ Assert.False(s.PopulationLedger.TeacherLinked);+ s.PopulationLedger.Reconcile();+ }++ // A halutz graduation that links the untouched teacher marks it linked, as a Reassign does. The teacher is placed free+ // in Tel Aviv by hand (it can reach a city that trains only through a Reassign today, which marks it already); the+ // Train order and the graduation are ordinary orders.+ [Fact]+ public void AHalutzGraduationThatLinksTheTeacherMarksItLinked()+ {+ var c = Gdd03();+ var s = Dark(c);+ var ledger = s.PopulationLedger;+ var teacher = ledger.Get(Teacher(s));+ ledger.Replace(teacher.WithPlacement(teacher.Status, new PopulationLocation(Region(c, TelAviv), city: TelAviv), teacher.Assignment, teacher.Captor, teacher.Home));+ var why = new List<Cause>();+ var before = s.Units.Keys.ToHashSet();+ Assert.Null(Training.Start(c, s, TelAviv, "halutz", Unskilled(s, TelAviv) + 1, why));+ Assert.Equal(PopulationStatus.Trainee, ledger.Get(teacher.Id).Status);+ Assert.False(ledger.TeacherLinked);+ for (int t = 0; t < c.UnitTypes.First(x => x.Id == "halutz").TrainingTurns; t++) Training.Progress(c, s, why);+ Assert.Single(s.Units.Values, u => !before.Contains(u.Id) && u.Records!.Contains(teacher.Id));+ Assert.True(ledger.TeacherLinked);+ Assert.Contains(ledger.Canonical(), line => line.Contains("teacher-linked"));+ ledger.Reconcile();+ }++ // "Takeable, but last (Recommended)": the census teacher is set apart only while it is untouched. Once a Reassign has+ // linked it to a unit, it is a pioneer like any other: returned, it holds its qualified group, and a Train order that+ // takes only an unskilled civilian lowers nothing. The ledger records the link (hashed only once set), so a replay of+ // the same orders gives the same state.+ // No order in the real content links the teacher today (Haifa has no training facility, and every ascending-id pick+ // reaches the teacher before any later record), so Haifa's qualified veterans are raised by hand to make the Reassign+ // reach it. Later, a Haifa training facility would let a Train take the teacher as a trainee, linked at graduation+ // (AHalutzGraduationThatLinksTheTeacherMarksItLinked).+ [Fact]+ public void ATeacherOnceLinkedHoldsItsGroupLikeAnyReturnedPioneer()+ {+ var c = Gdd03();+ GameState Run()+ {+ var s = Dark(c);+ var teacher = Teacher(s);+ var why = new List<Cause>();+ var h = s.Cities[Haifa];+ s.Cities[Haifa] = h.WithQualified(h.Qualified.WithVeterans(1));+ var id = s.NextId;+ Assert.Null(Qualification.ReassignPioneers(c, s, Haifa, Projects.VeteranType, 1, why));+ Assert.Equal(Ids(teacher), Ids(s.Units[id].Records!));+ Assert.True(s.PopulationLedger.TeacherLinked);+ var hex = c.SettlementHexes.First(x => x.Id == TelAviv);+ var u = s.Units[id];+ s.Units[id] = new Unit(u.Id, u.Type, hex.Q, hex.R, u.Service, records: u.Records);+ Assert.Null(Qualification.Return(c, s, id, why));+ Assert.Equal((TelAviv, 1), (s.PopulationLedger.Get(teacher).Location!.City, s.Cities[TelAviv].Qualified.Veterans));+ Assert.Null(Training.Start(c, s, TelAviv, "halutz", 1, why));+ Assert.Equal(1, s.Cities[TelAviv].Qualified.Veterans);+ s.PopulationLedger.Reconcile();+ return s;+ }+ var a = Run(); var b = Run();+ Assert.Equal(a.Hash(), b.Hash());+ Assert.Contains(a.PopulationLedger.Canonical(), line => line.Contains("teacher-linked"));+ Assert.DoesNotContain(Dark(c).PopulationLedger.Canonical(), line => line.Contains("teacher-linked"));+ }++ // Following "Yes, keep the link (Recommended)" (a returned veteran record counts for the veteran track): a linked veteran+ // unit's record returns as a Veteran pioneer, as a new record from a veteran unit is ("Beginner; veteran stays+ // (Recommended)"), and each track takes only its own records: Veteran ones for veteran_halutz, the others for halutz.+ [Fact]+ public void TheHalutzAndVeteranTracksTakeTheirOwnRecords()+ {+ var c = Gdd03();+ var s = Dark(c);+ var why = new List<Cause>();+ var (records, units) = Graduate(c, s, 2, why);+ var service = c.RulesAt(s.Date).Mvp!.VeteranHalutzService!.Value;+ SetService(s, units[0], service, Projects.VeteranType);+ SetService(s, units[1], 1);+ Assert.Null(Qualification.Return(c, s, units[0], why));+ Assert.Null(Qualification.Return(c, s, units[1], why));+ Assert.Equal((CivilianTier.Veteran, CivilianTier.Novice), (s.PopulationLedger.Get(records[0]).Tier, s.PopulationLedger.Get(records[1]).Tier));++ var halutz = s.NextId;+ Assert.Null(Qualification.ReassignPioneers(c, s, TelAviv, "halutz", 1, why));+ Assert.Equal((1, Ids(records[1])), (s.Units[halutz].Service, Ids(s.Units[halutz].Records!)));+ var veteran = s.NextId;+ Assert.Null(Qualification.ReassignPioneers(c, s, TelAviv, Projects.VeteranType, 1, why));+ Assert.Equal((Projects.VeteranType, Ids(records[0])), (s.Units[veteran].Type, Ids(s.Units[veteran].Records!)));+ s.PopulationLedger.Reconcile();+ }++ // "Yes, keep the link": a veteran pioneer unit keeps its record; returned, the record counts for the veteran track, and+ // reassigned as a veteran it comes back with veteran_halutz_service and the same link rule.+ [Fact]+ public void AVeteranPioneerOnTheLedgerReturnsAndIsReassignedWithItsRecord()+ {+ var c = Gdd03();+ var s = Dark(c);+ var (records, units) = Graduate(c, s, 1, new List<Cause>());+ var service = c.RulesAt(s.Date).Mvp!.VeteranHalutzService!.Value;+ SetService(s, units[0], service, Projects.VeteranType);+ var why = new List<Cause>();+ Assert.Null(Qualification.Return(c, s, units[0], why));+ Assert.Equal((1, 0), (s.Cities[TelAviv].Qualified.Veterans, s.Cities[TelAviv].Qualified.Halutzim.Count));+ Assert.Equal(TelAviv, s.PopulationLedger.Get(records[0]).Location!.City);+ var free = FreePioneers(s, TelAviv);+ var id = s.NextId;+ Assert.Null(Qualification.ReassignPioneers(c, s, TelAviv, Projects.VeteranType, 1, why));+ Assert.Equal((Projects.VeteranType, service, Ids(free[0])), (s.Units[id].Type, s.Units[id].Service, Ids(s.Units[id].Records!)));+ Assert.Null(s.PopulationLedger.Get(free[0]).Location!.City);+ Assert.Equal(0, s.Cities[TelAviv].Qualified.Veterans);+ s.PopulationLedger.Reconcile();+ }++ // "Yes, keep the link": the promotion to veteran pioneer (R-VET-001) keeps the unit's record list, as do the other+ // changes of a unit (an order, a move). Run on the GDD fixture, where Simulation.Step runs.+ [Fact]+ public void ThePromotionKeepsTheUnitsRecords()+ {+ var files = Fixture.Gdd();+ files["rules.yaml"] = files["rules.yaml"].Replace("veteran_halutz_service: 4", "veteran_halutz_service: 2");+ var c = ContentLoader.Load(Fixture.Write(files));+ var s = Simulation.NewGame(c, 1, Mode.Historical);+ var id = s.NextId++;+ s.Units.Add(id, new Unit(id, "halutz", 1, 0, records: new[] { 7 }));+ s = Simulation.Step(c, s, new Command[] { new PioneerWork(id, Projects.BuildYishuv, "site_a") }).State;+ s = Simulation.Step(c, s, Array.Empty<Command>()).State;+ Assert.Equal((Projects.VeteranType, Ids(7)), (s.Units[id].Type, Ids(s.Units[id].Records!)));+ Assert.EndsWith("|records=7", s.Units[id].Canonical());+ }++ // The link, the return and the reassignment are deterministic: the same orders on two dark starts give the same state+ // hash and the same ledger text.+ [Fact]+ public void TheLinkAndItsOrdersAreDeterministic()+ {+ var c = Gdd03();+ string Run(out string ledger)+ {+ var s = Dark(c);+ var why = new List<Cause>();+ var (_, units) = Graduate(c, s, 2, why);+ Assert.Null(Qualification.Return(c, s, units[1], why));+ Assert.Null(Qualification.ReassignPioneers(c, s, TelAviv, "halutz", 1, why));+ ledger = string.Join("\n", s.PopulationLedger.Canonical());+ Assert.Contains("|records=", string.Join(";", s.Units.Values.Select(x => x.Canonical())));+ return s.Hash();+ }+ var a = Run(out var la); var b = Run(out var lb);+ Assert.Equal(a, b);+ Assert.Equal(la, lb);+ }+}diff --git a/sim/Statecraft.Sim.Tests/LedgerTrainingTests.cs b/sim/Statecraft.Sim.Tests/LedgerTrainingTests.csindex f1c44e459..9453e06d4 100644--- a/sim/Statecraft.Sim.Tests/LedgerTrainingTests.cs+++ b/sim/Statecraft.Sim.Tests/LedgerTrainingTests.cs@@ -290,7 +290,12 @@ public class LedgerTrainingTestsvar turns = c.UnitTypes.First(t => t.Id == "halutz").TrainingTurns;for (int t = 0; t < turns; t++) { Training.Progress(c, s, why); Training.Progress(c, twin, twinWhy); }Assert.Equal(Lines(twinWhy), Lines(why));- Assert.Equal(twin.Units.Values.Select(x => x.Canonical()), s.Units.Values.Select(x => x.Canonical()));+ // Owner, 9 November 2026, "List on the unit (Recommended)": each new unit also lists its record, ascending id in unit+ // id order; otherwise the units are the aggregate game's.+ var made = s.Units.Keys.Where(k => s.Units[k].Records != null).OrderBy(k => k).ToList();+ Assert.Equal(picked.OrderBy(x => x).Select(x => new[] { x }), made.Select(k => s.Units[k].Records!.ToArray()));+ Assert.Equal(twin.Units.Values.Select(x => x.Canonical() + (s.Units[x.Id].Records is { } r ? "|records=" + string.Join(",", r) : "")),+ s.Units.Values.Select(x => x.Canonical()));Assert.Equal(twin.NextId, s.NextId);foreach (var id in picked){diff --git a/sim/Statecraft.Sim/Combat.cs b/sim/Statecraft.Sim/Combat.csindex fe49baa36..135c00566 100644--- a/sim/Statecraft.Sim/Combat.cs+++ b/sim/Statecraft.Sim/Combat.cs@@ -126,7 +126,7 @@ namespace Statecraft.Simvar refused = Check(c, s, unitId, q, r, enemy);if (refused != null) return refused;var u = s.Units[unitId]; var target = Hex(q!.Value, r!.Value);- s.Units[unitId] = new Unit(u.Id, u.Type, u.Q, u.R, u.Service, u.Side, u.Strength, Attack, target, u.HomeCity, u.Full, u.CombatXp);+ s.Units[unitId] = new Unit(u.Id, u.Type, u.Q, u.R, u.Service, u.Side, u.Strength, Attack, target, u.HomeCity, u.Full, u.CombatXp, u.Records);var line = UnitLines.Line(WhyKeys.AttackOrdered, $"Unit {unitId} will attack hex {target}", new[] { u }, target);// #2534: the enemy's attack order names itself for the turn report's enemy-orders row, as an engagement's does (#1297).// UnitLines.Line's system is always "map" (UnitLines.cs); name it as a literal so the Why-screen scan sees it.@@ -148,7 +148,7 @@ namespace Statecraft.Simvar mvp = c.RulesAt(s.Date).Mvp!;var u = s.Units[unitId];if (SpendsArms(c)) s.Arms -= Need(c, mvp, u);- var attacker = new Unit(u.Id, u.Type, u.Q, u.R, u.Service, u.Side, u.Strength, "", "", u.HomeCity, u.Full, u.CombatXp);+ var attacker = new Unit(u.Id, u.Type, u.Q, u.R, u.Service, u.Side, u.Strength, "", "", u.HomeCity, u.Full, u.CombatXp, u.Records);s.Units[unitId] = attacker;if (u.Order == Orders.Fortify)why.Add(UnitLines.Line(WhyKeys.FortifyLost,@@ -313,7 +313,7 @@ namespace Statecraft.Simstatic void End(GameState s, Unit u, string key, string line, List<Cause> why, params string[] args){- s.Units[u.Id] = new Unit(u.Id, u.Type, u.Q, u.R, u.Service, u.Side, u.Strength, "", "", u.HomeCity, u.Full, u.CombatXp);+ s.Units[u.Id] = new Unit(u.Id, u.Type, u.Q, u.R, u.Service, u.Side, u.Strength, "", "", u.HomeCity, u.Full, u.CombatXp, u.Records);why.Add(UnitLines.Line(key, line, new[] { u }, args));}@@ -340,7 +340,7 @@ namespace Statecraft.Sim{if (!s.Units.TryGetValue(id, out var u) || u.Type == Statecraft.Sim.Military.VeteranSoldier) continue;var xp = (int)Math.Min(full, (long)u.CombatXp + gain);- var gained = new Unit(u.Id, u.Type, u.Q, u.R, u.Service, u.Side, u.Strength, u.Order, u.OrderTarget, u.HomeCity, u.Full, xp);+ var gained = new Unit(u.Id, u.Type, u.Q, u.R, u.Service, u.Side, u.Strength, u.Order, u.OrderTarget, u.HomeCity, u.Full, xp, u.Records);s.Units[id] = xp == full && Statecraft.Sim.Military.Promotes(u) ? Statecraft.Sim.Military.Promote(gained, why) : gained;}}@@ -380,7 +380,7 @@ namespace Statecraft.Simif (!s.Units.TryGetValue(d.Id, out var u)) continue;if (Retreat(c, s, mvp, u) is (int, int) to){- s.Units[u.Id] = new Unit(u.Id, u.Type, to.Item1, to.Item2, u.Service, u.Side, u.Strength, u.Order, u.OrderTarget, u.HomeCity, u.Full, u.CombatXp);+ s.Units[u.Id] = new Unit(u.Id, u.Type, to.Item1, to.Item2, u.Service, u.Side, u.Strength, u.Order, u.OrderTarget, u.HomeCity, u.Full, u.CombatXp, u.Records);var hex = Hex(to.Item1, to.Item2);why.Add(UnitLines.Line(WhyKeys.Retreated, $"Unit {u.Id} retreated to hex {hex}", new[] { u }, hex));}@@ -472,7 +472,7 @@ namespace Statecraft.Sim/// strength it had as its Full, the most replacements refill it to; no rule reads an enemy's, so it stores none.</summary>internal static Unit Lose(Unit u) =>new Unit(u.Id, u.Type, u.Q, u.R, u.Service, u.Side, u.Strength - 1, u.Order, u.OrderTarget, u.HomeCity,- u.Full == 0 && u.Side == Movement.PlayerSide ? u.Strength : u.Full, u.CombatXp);+ u.Full == 0 && u.Side == Movement.PlayerSide ? u.Strength : u.Full, u.CombatXp, u.Records);/// <summary>R-COMBAT-003: the first neighbour of the unit's hex, in the fixed order (R-MOVE-002), that is land, holds no/// unit of the other team, has room under mvp.stack_limit for the unit's side (R-MOVE-003) and, for the player's unit,diff --git a/sim/Statecraft.Sim/Corridors.cs b/sim/Statecraft.Sim/Corridors.csindex cb3ace3fd..4c7d8b489 100644--- a/sim/Statecraft.Sim/Corridors.cs+++ b/sim/Statecraft.Sim/Corridors.cs@@ -129,7 +129,7 @@ namespace Statecraft.Simif (u.Type != "halutz") continue;var service = u.Service + 1;var promoted = service >= r.VeteranHalutzService!.Value;- s.Units[u.Id] = new Unit(u.Id, promoted ? Projects.VeteranType : u.Type, u.Q, u.R, service, u.Side, u.Strength, u.Order, u.OrderTarget, u.HomeCity, u.Full, u.CombatXp);+ s.Units[u.Id] = new Unit(u.Id, promoted ? Projects.VeteranType : u.Type, u.Q, u.R, service, u.Side, u.Strength, u.Order, u.OrderTarget, u.HomeCity, u.Full, u.CombatXp, u.Records);if (promoted) why.Add(new Cause("map", w.Id, 1, "A group of halutzim became veteran pioneers", key: CauseKeys.PioneersVeteran));}s.Corridors[w.Id] = cur;diff --git a/sim/Statecraft.Sim/EnemyAI.cs b/sim/Statecraft.Sim/EnemyAI.csindex 5021a8919..f05490f92 100644--- a/sim/Statecraft.Sim/EnemyAI.cs+++ b/sim/Statecraft.Sim/EnemyAI.cs@@ -56,7 +56,7 @@ namespace Statecraft.Sim// fortify (Movement.Move), and step 2 would resolve it inside the truce (owner, #1263).if (truce && u.Order == Combat.Attack){- s.Units[id] = new Unit(u.Id, u.Type, u.Q, u.R, u.Service, u.Side, u.Strength, "", "", u.HomeCity, u.Full, u.CombatXp);+ s.Units[id] = new Unit(u.Id, u.Type, u.Q, u.R, u.Service, u.Side, u.Strength, "", "", u.HomeCity, u.Full, u.CombatXp, u.Records);why.Add(UnitLines.Line(WhyKeys.AttackEndedTruce,$"Unit {id}'s attack on hex {u.OrderTarget} ends: a truce is on", new[] { u }, u.OrderTarget));}diff --git a/sim/Statecraft.Sim/GddState.cs b/sim/Statecraft.Sim/GddState.csindex 2190f7057..7ffa87d47 100644--- a/sim/Statecraft.Sim/GddState.cs+++ b/sim/Statecraft.Sim/GddState.cs@@ -204,9 +204,22 @@ namespace Statecraft.Sim/// Always 0 under every other ruleset.</summary>public int CombatXp { get; }- public Unit(int id, string type, int q, int r, int service = 0, string side = "", int strength = 0, string order = "", string orderTarget = "", string homeCity = "", int full = 0, int combatXp = 0)+ /// <summary>#1725 PR 7 (owner, 9 November 2026, "Add the link first (Recommended)" and "List on the unit (Recommended)"):+ /// on a Historical ledger game, the population ids of the pioneer records that form this halutz or veteran pioneer+ /// unit, ascending, hashed only when set, like a cohort's members; null on any other game and for any other unit. A+ /// promotion keeps it ("Yes, keep the link (Recommended)"), as every change of a unit does (R-UNIT-002).</summary>+ public IReadOnlyList<int>? Records { get; }++ public Unit(int id, string type, int q, int r, int service = 0, string side = "", int strength = 0, string order = "", string orderTarget = "", string homeCity = "", int full = 0, int combatXp = 0, IEnumerable<int>? records = null){Id = id; Type = type; Q = q; R = r; Service = service; Side = side; Strength = strength; Order = order; OrderTarget = orderTarget; HomeCity = homeCity; Full = full; CombatXp = combatXp;+ if (records != null)+ {+ var sorted = records.OrderBy(x => x).ToArray();+ if (sorted.Length == 0 || sorted.Distinct().Count() != sorted.Length)+ throw new ArgumentException("A unit's records are one or more distinct population ids.", nameof(records));+ Records = Array.AsReadOnly(sorted);+ }}/// <summary>The record as the state hash writes it. Each field after the hex is written only when it is not at its@@ -220,7 +233,8 @@ namespace Statecraft.Sim+ (OrderTarget == "" ? "" : "|target=" + OrderTarget)+ (HomeCity == "" ? "" : "|home=" + HomeCity)+ (Full == 0 ? "" : "|full=" + Full.ToString(CultureInfo.InvariantCulture))- + (CombatXp == 0 ? "" : "|xp=" + CombatXp.ToString(CultureInfo.InvariantCulture));+ + (CombatXp == 0 ? "" : "|xp=" + CombatXp.ToString(CultureInfo.InvariantCulture))+ + (Records == null ? "" : "|records=" + string.Join(",", Records.Select(x => x.ToString(CultureInfo.InvariantCulture))));}/// <summary>A group of a city's people in training (GDD "Progression"; R-TRAIN-001): <see cref="Count"/> population unitsdiff --git a/sim/Statecraft.Sim/HistoricalPopulation.cs b/sim/Statecraft.Sim/HistoricalPopulation.csindex 3d4662155..ba41f6ece 100644--- a/sim/Statecraft.Sim/HistoricalPopulation.cs+++ b/sim/Statecraft.Sim/HistoricalPopulation.cs@@ -66,6 +66,32 @@ namespace Statecraft.Sim/// comment 6704565066: "the training centre's one veteran pioneer teacher is a Haifa census unit").</summary>internal const string TeacherCity = "haifa";+ /// <summary>The population id of the training centre's veteran pioneer teacher on a Historical ledger: the last+ /// census/haifa record, as the start makes it (#1689), or null when the ledger has no census/haifa record. Owner, 7+ /// November 2026, relayed: "Takeable, but last (Recommended)": the rules that pick by ascending id take it last, so+ /// a rule whose pool also holds records made later (#1725 PR 7, ReassignPioneers) orders it last by this id.</summary>+ internal static int? TeacherId(PopulationLedger ledger)+ {+ var source = CensusPrefix + TeacherCity;+ var last = -1;+ while (ledger.HasArrived(source, last + 1)) last = checked(last + 1);+ return last < 0 ? null : ledger.IdOf(source, last);+ }++ /// <summary><see cref="TeacherId"/> while the teacher is untouched, never linked to a map unit since the start+ /// (PopulationLedger.TeacherLinked); null once it has been. An untouched teacher holds no qualified group and comes last+ /// in ReassignPioneers' pool; a linked one is a pioneer like any other.</summary>+ internal static int? UntouchedTeacherId(PopulationLedger ledger) => ledger.TeacherLinked ? null : TeacherId(ledger);++ /// <summary>Marks the teacher linked (PopulationLedger.MarkTeacherLinked) when <paramref name="records"/>, the records a+ /// map unit is now linked to, hold it.</summary>+ internal static void NoteLinked(PopulationLedger ledger, IEnumerable<int> records)+ {+ if (ledger.TeacherLinked) return;+ var teacher = TeacherId(ledger);+ if (teacher is int t && records.Contains(t)) ledger.MarkTeacherLinked();+ }+/// <summary>The own opening formations, the one predicate for them (review S2-2): the map/units_1948.yaml rows that/// give the start inventory soldiers, Israeli, in the start (no dated arrival), with a strength. The inventory, the/// loader's formation_combat_xp check and StartingForces.Init's ledger check all read it.</summary>diff --git a/sim/Statecraft.Sim/Military.cs b/sim/Statecraft.Sim/Military.csindex 98731b0a6..fe3afa48f 100644--- a/sim/Statecraft.Sim/Military.cs+++ b/sim/Statecraft.Sim/Military.cs@@ -19,7 +19,7 @@ namespace Statecraft.Simforeach (var u in s.Units.Values.ToList()){if (!Promotes(u)) continue;- var served = new Unit(u.Id, u.Type, u.Q, u.R, u.Service + 1, u.Side, u.Strength, u.Order, u.OrderTarget, u.HomeCity, u.Full, u.CombatXp);+ var served = new Unit(u.Id, u.Type, u.Q, u.R, u.Service + 1, u.Side, u.Strength, u.Order, u.OrderTarget, u.HomeCity, u.Full, u.CombatXp, u.Records);s.Units[u.Id] = byService && served.Service >= r.VeteranSoldierService!.Value ? Promote(served, why) : served;}}@@ -32,7 +32,7 @@ namespace Statecraft.Siminternal static Unit Promote(Unit u, List<Cause> why){why.Add(new Cause("city", "units", u.Strength, "Recruits became veteran soldiers", key: CauseKeys.RecruitsVeteran));- return new Unit(u.Id, VeteranSoldier, u.Q, u.R, u.Service, u.Side, u.Strength, u.Order, u.OrderTarget, u.HomeCity, u.Full, u.CombatXp);+ return new Unit(u.Id, VeteranSoldier, u.Q, u.R, u.Service, u.Side, u.Strength, u.Order, u.OrderTarget, u.HomeCity, u.Full, u.CombatXp, u.Records);}/// <summary>The Israeli veteran infantry type the loader requires when recruits exist (R-UNIT-004).</summary>diff --git a/sim/Statecraft.Sim/Movement.cs b/sim/Statecraft.Sim/Movement.csindex 08c6d0eff..0acdb0e47 100644--- a/sim/Statecraft.Sim/Movement.cs+++ b/sim/Statecraft.Sim/Movement.cs@@ -174,7 +174,7 @@ namespace Statecraft.Sim/// <summary>Takes the unit's go-to away where it stands.</summary>static void Clear(GameState s, Unit u){- s.Units[u.Id] = new Unit(u.Id, u.Type, u.Q, u.R, u.Service, u.Side, u.Strength, "", "", u.HomeCity, u.Full, u.CombatXp);+ s.Units[u.Id] = new Unit(u.Id, u.Type, u.Q, u.R, u.Service, u.Side, u.Strength, "", "", u.HomeCity, u.Full, u.CombatXp, u.Records);s.CardOrders.Remove(u.Id); // a stopped go-to is no operation card's order any more (R-ENEMY-005)}@@ -195,7 +195,7 @@ namespace Statecraft.Simif (Closed(c, s, false).Contains((q.Value, r.Value))) return RefusedClosed;if (Route(c, s, unitId, q.Value, r.Value, spent, cardUntil != null).Count == 0) return RefusedNoRoute;var target = HexText(q.Value, r.Value);- var given = new Unit(u.Id, u.Type, u.Q, u.R, u.Service, u.Side, u.Strength, GoTo, target, u.HomeCity, u.Full, u.CombatXp);+ var given = new Unit(u.Id, u.Type, u.Q, u.R, u.Service, u.Side, u.Strength, GoTo, target, u.HomeCity, u.Full, u.CombatXp, u.Records);s.Units[unitId] = given;if (cardUntil is DateTime until) s.CardOrders[unitId] = until; else s.CardOrders.Remove(unitId);why.Add(UnitLines.Line(WhyKeys.OnItsWay, $"Unit {unitId} is on its way to hex {target}", new[] { given }, target));@@ -296,7 +296,7 @@ namespace Statecraft.Sim// is given, with the hex it names), so a unit that goes out and comes back the same turn is not fortified; hold moves with// the unit. The order step at the end of the turn only sees the final hex.var fortified = u.Order == "fortify" || u.Order == "fortifying";- s.Units[unitId] = new Unit(u.Id, u.Type, q, r, u.Service, u.Side, u.Strength, fortified ? "" : u.Order, fortified ? "" : u.OrderTarget, u.HomeCity, u.Full, u.CombatXp);+ s.Units[unitId] = new Unit(u.Id, u.Type, q, r, u.Service, u.Side, u.Strength, fortified ? "" : u.Order, fortified ? "" : u.OrderTarget, u.HomeCity, u.Full, u.CombatXp, u.Records);spent[unitId] = used + cost;why.Add(new Cause("map", unitId.ToString(CultureInfo.InvariantCulture), cost,FormattableString.Invariant($"Unit {unitId} moved to hex {q},{r} for {cost} movement points"), enemy ? Kind : "",diff --git a/sim/Statecraft.Sim/Orders.cs b/sim/Statecraft.Sim/Orders.csindex 5f35ced79..33d945a22 100644--- a/sim/Statecraft.Sim/Orders.cs+++ b/sim/Statecraft.Sim/Orders.cs@@ -42,7 +42,7 @@ namespace Statecraft.Simstatic string Hex(Unit u) => string.Format(CultureInfo.InvariantCulture, "{0},{1}", u.Q, u.R);static Unit With(Unit u, string order, string target) =>- new Unit(u.Id, u.Type, u.Q, u.R, u.Service, u.Side, u.Strength, order, target, u.HomeCity, u.Full, u.CombatXp);+ new Unit(u.Id, u.Type, u.Q, u.R, u.Service, u.Side, u.Strength, order, target, u.HomeCity, u.Full, u.CombatXp, u.Records);/// <summary>R-ORDER-001's refusals: null when <see cref="Give"/> takes the order, else the reason shown to the player./// Changes nothing: the unit card asks it before it offers fortify or hold (#754). Refused for an unknown order ordiff --git a/sim/Statecraft.Sim/PopulationLedger.cs b/sim/Statecraft.Sim/PopulationLedger.csindex f46c4ff2c..39e1e41e0 100644--- a/sim/Statecraft.Sim/PopulationLedger.cs+++ b/sim/Statecraft.Sim/PopulationLedger.cs@@ -143,6 +143,13 @@ namespace Statecraft.Siminternal double NaturalIncreaseCarry { get; private set; }/// <summary>The natural-increase records added so far: their split over the cities is Cities.Apportion of this count.</summary>internal int NaturalIncreaseRecords { get; private set; }+ /// <summary>#1725 PR 7: whether the training centre's census teacher (HistoricalPopulation.TeacherId) has ever been+ /// linked to a pioneer map unit (Unit.Records). Until then it is set apart as the untouched teacher ("Takeable, but last+ /// (Recommended)"); after it, its record is a pioneer like any other. Written to the canonical text only once set, so+ /// a ledger that never linked it hashes as before; a save replays the orders that set it.</summary>+ internal bool TeacherLinked { get; private set; }+ /// <summary>Records that the census teacher is linked to a map unit (<see cref="TeacherLinked"/>); once set it stays set.</summary>+ internal void MarkTeacherLinked() { RequireInitialized(); TeacherLinked = true; }public bool IsInitialized { get; private set; }public int NextPopulationId { get; private set; }public double TotalPeople => (double)units.Count * peoplePerUnit;@@ -272,6 +279,9 @@ namespace Statecraft.Sim/// <summary>Whether the manifest item <paramref name="source"/>, <paramref name="ordinal"/> has arrived, even if its/// population id was lost since.</summary>internal bool HasArrived(string source, int ordinal) => sources.ContainsKey(PopulationText.Fields(source, ordinal));+ /// <summary>The population id the manifest item <paramref name="source"/>, <paramref name="ordinal"/> was given, even if+ /// it was lost since; null if the item never arrived.</summary>+ internal int? IdOf(string source, int ordinal) => sources.TryGetValue(PopulationText.Fields(source, ordinal), out var id) ? id : (int?)null;/// <summary><see cref="RegisterArrival"/> for several items, in order, all or nothing (#1725 PR 7, Cities.Arrive): every/// record is validated in one candidate before any is committed, so a refused item adds none of the others.</summary>internal IReadOnlyList<int> RegisterArrivals(IReadOnlyList<PopulationInventoryRow> rows)@@ -450,6 +460,7 @@ namespace Statecraft.Sim? PopulationText.Fields("natural-increase", "records", NaturalIncreaseRecords): PopulationText.Fields("natural-increase", "records", NaturalIncreaseRecords, "carry",BitConverter.DoubleToInt64Bits(NaturalIncreaseCarry).ToString("X16", CultureInfo.InvariantCulture));+ if (TeacherLinked) yield return PopulationText.Fields("teacher-linked", true);if (bindings != null) foreach (var b in bindings.Canonical()) yield return b;foreach (var p in units.Values) yield return PopulationText.Fields("unit", p.Canonical());foreach (var source in sources) yield return PopulationText.Fields("source", source.Key, source.Value);diff --git a/sim/Statecraft.Sim/Projects.cs b/sim/Statecraft.Sim/Projects.csindex 6738a528e..66d14d1f0 100644--- a/sim/Statecraft.Sim/Projects.cs+++ b/sim/Statecraft.Sim/Projects.cs@@ -94,7 +94,7 @@ namespace Statecraft.Simif (u.Type == "halutz"){var service = u.Service + 1;- u = new Unit(u.Id, service >= r.VeteranHalutzService!.Value ? VeteranType : u.Type, u.Q, u.R, service, u.Side, u.Strength, u.Order, u.OrderTarget, u.HomeCity, u.Full, u.CombatXp);+ u = new Unit(u.Id, service >= r.VeteranHalutzService!.Value ? VeteranType : u.Type, u.Q, u.R, service, u.Side, u.Strength, u.Order, u.OrderTarget, u.HomeCity, u.Full, u.CombatXp, u.Records);}}}@@ -245,7 +245,7 @@ namespace Statecraft.Simif (u.Type != "halutz") continue;var service = u.Service + 1;var promoted = service >= r.VeteranHalutzService!.Value;- s.Units[u.Id] = new Unit(u.Id, promoted ? VeteranType : u.Type, u.Q, u.R, service, u.Side, u.Strength, u.Order, u.OrderTarget, u.HomeCity, u.Full, u.CombatXp);+ s.Units[u.Id] = new Unit(u.Id, promoted ? VeteranType : u.Type, u.Q, u.R, service, u.Side, u.Strength, u.Order, u.OrderTarget, u.HomeCity, u.Full, u.CombatXp, u.Records);if (promoted) why.Add(new Cause("map", w.Site, 1, "A group of halutzim became veteran pioneers", key: CauseKeys.PioneersVeteran));}Corridors.Advance(c, s, next, why); // R-COR-002: after the sites (Phase 4 PR 2)diff --git a/sim/Statecraft.Sim/Qualification.cs b/sim/Statecraft.Sim/Qualification.csindex 7008febd9..03e4bb7ba 100644--- a/sim/Statecraft.Sim/Qualification.cs+++ b/sim/Statecraft.Sim/Qualification.cs@@ -43,6 +43,15 @@ namespace Statecraft.Simreturn new Qualified(Craftsmen - c, Veterans - n, Halutzim.Skip(h).ToArray());}+ /// <summary>Without <paramref name="n"/> qualified pioneers, in R-QUAL-006's order without the craftsmen: halutz groups+ /// with the least service, then veterans (#1725 PR 7, a ledger Train order; owner, 9 November 2026, "Yes, lower it+ /// (Recommended)").</summary>+ public Qualified LosePioneers(int n)+ {+ var h = Math.Min(n, Halutzim.Count);+ return new Qualified(Craftsmen, Veterans - Math.Min(n - h, Veterans), Halutzim.Skip(h).ToArray());+ }+/// <summary>The state hash's text: nothing at all when nobody is qualified, so a city without them hashes as before/// (R-LOOP-002's rule).</summary>public string Canonical()@@ -74,6 +83,12 @@ namespace Statecraft.Sim/// course is refused until then, Training.LedgerRefusedCraftsman).</summary>internal const string LedgerRefusedCraftsmen = "Craftsmen are not on the population ledger yet (#2476)";+ /// <summary>#1725 PR 7 (owner, 9 November 2026, "Own heading (Recommended)"): the source heading of a person record made+ /// when a pioneer unit with no linked records returns (<see cref="LedgerReturn"/>): this prefix and the city+ /// (<c>returned_pioneer_unit/<city></c>, ordinals from 0), kept apart from the census, the natural increase+ /// (PopulationSystem.IncreasePrefix) and the arrivals (Cities.ArrivalPrefix), as they are a short heading and the city.</summary>+ internal const string ReturnedUnitPrefix = "returned_pioneer_unit/";+public const string ReturnCraftsmenKind = "return_craftsmen";public const string ReassignCraftsmenKind = "reassign_craftsmen";public const string ReassignPioneersKind = "reassign_pioneers";@@ -129,29 +144,96 @@ namespace Statecraft.Simreturn null;}+ /// <summary>R-QUAL-003's order (<see cref="CheckReturn"/>'s refusals). On a Historical ledger game (#1725 PR 7) the unit's+ /// own record returns too (<see cref="LedgerReturn"/>), and the city's civilian count is the records', so only+ /// <see cref="City.Qualified"/> is written (owner, 9 November 2026, "City counts, as today (Recommended)").</summary>internal static string? Return(Content c, GameState s, int unitId, List<Cause> why){- PopulationLedger.RefuseAggregate(s);+ PopulationLedger.RefuseUnlessHistorical(s); // #1725 PR 7: on a Historical ledger the unit's record returnsvar refused = CheckReturn(s, unitId);if (refused != null) return refused;var u = s.Units[unitId];var city = Demobilization.Nearest(c, u.Q, u.R);+ var ledger = s.PopulationLedger.IsHistorical;+ if (ledger) LedgerReturn(c, s, u, city);s.Units.Remove(unitId);var x = s.Cities[city];var q = u.Type == Projects.VeteranType ? x.Qualified.WithVeterans(x.Qualified.Veterans + 1) : x.Qualified.AddHalutz(u.Service);- s.Cities[city] = x.WithCounts(x.Civilians + 1, x.Employed, x.Refugees).WithQualified(q);+ s.Cities[city] = (ledger ? x : x.WithCounts(x.Civilians + 1, x.Employed, x.Refugees)).WithQualified(q);why.Add(new Cause("map", unitId.ToString(CultureInfo.InvariantCulture), 1,$"Unit {unitId} returned to civilian life in {PlayerText.Settlement(c, city)} and keeps its training", key: CauseKeys.PioneerReturned, args: new[] { city }));return null;}+ /// <summary>#1725 PR 7 (owner, 9 November 2026, "Add the link first (Recommended)"): R-QUAL-003 on a Historical ledger+ /// game moves exactly the record of <paramref name="u"/> (<see cref="Unit.Records"/>, one per group). "Nearest city,+ /// settled (Recommended)": it becomes a free civilian without an assignment located in <paramref name="city"/> (its+ /// region plus the city), with reception ticks = reception.turns, as Send home does; its profession, tier, work XP,+ /// qualification, combat XP and items stay. "City counts, as today (Recommended)": the service is the caller's, in+ /// <see cref="City.Qualified"/>. One validated commit; a linked unit without its one free pioneer record is a broken+ /// invariant, not a refusal. A unit with no records (one an event grants) makes a new one: see <see cref="NewRecord"/>.</summary>+ static void LedgerReturn(Content c, GameState s, Unit u, string city)+ {+ if (u.Records == null) { NewRecord(c, s, u, city); return; }+ var ids = u.Records;+ if (ids.Count != 1)+ throw new InvalidOperationException("Unit " + u.Id.ToString(CultureInfo.InvariantCulture) + " is one group but has " + ids.Count.ToString(CultureInfo.InvariantCulture) + " records.");+ 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");+ // Following "Yes, keep the link (Recommended)" (a returned veteran record counts for the veteran track): a veteran+ // pioneer unit's record returns a Veteran pioneer, as a new record from one does ("Beginner; veteran stays+ // (Recommended)"), so ReassignPioneers finds it on the veteran track.+ var veteran = u.Type == Projects.VeteranType;+ var records = ids.Select(id =>+ {+ var p = s.PopulationLedger.Get(id);+ if (!IsFreePioneer(p))+ throw new InvalidOperationException("Unit " + u.Id.ToString(CultureInfo.InvariantCulture) + "'s record " + id.ToString(CultureInfo.InvariantCulture) + " is not a free pioneer.");+ return new PopulationUnit(p.Id, PopulationStatus.FreeCivilian, received, location, PopulationAssignment.Unassigned,+ p.Profession, veteran ? CivilianTier.Veteran : p.Tier, p.WorkXp, p.Qualification, p.CombatXp, p.Equipment, p.Captor, p.Home);+ }).ToList();+ s.PopulationLedger.Commit(records, Array.Empty<PopulationTarget>());+ }++ /// <summary>Owner, 9 November 2026, "Make new records": a returned pioneer unit with no linked records makes "One per unit+ /// (Recommended)" new person record, registered as an arrival is under its "Own heading (Recommended)",+ /// <see cref="ReturnedUnitPrefix"/> and the city, at the heading's next unused ordinal, so it counts as a new person+ /// ("Yes, new people (Recommended)") and Reconcile holds. "Beginner; veteran stays (Recommended)": a halutz gives a+ /// Novice pioneer with 0 work XP, a veteran pioneer a Veteran pioneer. It lands as other returned pioneers do ("Nearest+ /// city, settled (Recommended)"): a free civilian without an assignment in <paramref name="city"/>, reception ticks =+ /// reception.turns; like a census civilian a halutz graduate came from, it has no qualification, combat XP or item.</summary>+ static void NewRecord(Content c, GameState s, Unit u, string city)+ {+ var ledger = s.PopulationLedger;+ var source = ReturnedUnitPrefix + city;+ var ordinal = 0;+ while (ledger.HasArrived(source, ordinal)) ordinal = checked(ordinal + 1);+ var region = c.PlayerRegions.AtLocation(city)?.Id+ ?? throw new InvalidOperationException("No region in regions.yaml for " + city + " (R-POP-004).");+ ledger.RegisterArrival(source, ordinal, new PopulationUnit(0, PopulationStatus.FreeCivilian, c.RequirePopulationInteger("reception.turns"),+ new PopulationLocation(region, city: city), PopulationAssignment.Unassigned, CivilianProfession.Pioneer,+ u.Type == Projects.VeteranType ? CivilianTier.Veteran : CivilianTier.Novice, 0, "", 0, PopulationEquipment.None));+ }++ /// <summary>A free civilian pioneer without an assignment: a halutz graduate ("Free pioneer, not housed (Rec.)"), or one+ /// returned to a city.</summary>+ static bool IsFreePioneer(PopulationUnit p) => p.Status == PopulationStatus.FreeCivilian+ && p.Assignment.Kind == PopulationAssignmentKind.Unassigned && p.Profession == CivilianProfession.Pioneer;++ /// <summary>#1725 PR 7: R-QUAL-005's refusal on a Historical ledger game when the city has fewer free pioneer records+ /// than the groups asked for. Internal, as Training's ledger refusals are: no player reaches it yet (R-POP-002).</summary>+ internal const string LedgerRefusedFreePioneers = "{0} has {1} free pioneers without work";+/// <summary>R-QUAL-005: <paramref name="count"/> of the city's qualified halutz groups (<paramref name="track"/>/// `halutz`) or veteran pioneers (`veteran_halutz`), without a job, reappear as units at its settlement hex. Refused,/// state untouched, for an unknown city, another track, a count below 1, more than the city's qualified ones, or more- /// than its civilians without work.</summary>+ /// than its civilians without work. On a Historical ledger game (#1725 PR 7) the groups are the city's free pioneer records+ /// (refused with <see cref="LedgerRefusedFreePioneers"/> when it has fewer), and only <see cref="City.Qualified"/> is written.</summary>public static string? ReassignPioneers(Content c, GameState s, string city, string track, int count, List<Cause> why){- PopulationLedger.RefuseAggregate(s);+ PopulationLedger.RefuseUnlessHistorical(s); // #1725 PR 7: on a Historical ledger the groups are pioneer recordsif (!s.Cities.TryGetValue(city, out var x)) return "There is no such city";var veteran = track == Projects.VeteranType;if (!veteran && track != "halutz") return RefusedNoQualification;@@ -159,20 +241,54 @@ namespace Statecraft.Simvar name = PlayerText.Settlement(c, city);var have = veteran ? x.Qualified.Veterans : x.Qualified.Halutzim.Count;if (count > have) return FormattableString.Invariant($"{name} has {have} qualified {(veteran ? "veteran pioneers" : "halutzim")}");- var idle = Training.Idle(s, x); // R-ARMS-005: a staffed workshop's worker is not idle- if (count > idle) return FormattableString.Invariant($"{name} has {idle} civilians without work");+ var ledger = s.PopulationLedger.IsHistorical;+ List<int>? picked = null;+ if (ledger)+ {+ // #1725 PR 7 (owner, 9 November 2026, "Free pioneers by service (Recommended)"): the city's free, unassigned+ // pioneer records, lowest id first, are the groups that come back; the city's counts are not the ledger's.+ // Each track prefers its own records, following "Yes, keep the link (Recommended)": Veteran ones for+ // veteran_halutz, the others for halutz, then the other tier's when it has too few. The training centre's+ // census teacher, while untouched, comes after every other record of either tier ("Takeable, but last+ // (Recommended)", #1689), so a track that falls back takes the other tier's records before the teacher.+ var teacher = HistoricalPopulation.UntouchedTeacherId(s.PopulationLedger);+ var free = s.PopulationLedger.Units.Where(p => IsFreePioneer(p) && string.Equals(p.Location?.City, city, StringComparison.Ordinal))+ .OrderBy(p => p.Id == teacher ? 1 : 0).ThenBy(p => (p.Tier == CivilianTier.Veteran) == veteran ? 0 : 1).ThenBy(p => p.Id)+ .Select(p => p.Id).ToList();+ if (count > free.Count) return string.Format(CultureInfo.InvariantCulture, LedgerRefusedFreePioneers, name, free.Count);+ picked = free.Take(count).ToList();+ }+ else+ {+ var idle = Training.Idle(s, x); // R-ARMS-005: a staffed workshop's worker is not idle+ if (count > idle) return FormattableString.Invariant($"{name} has {idle} civilians without work");+ }var hex = c.SettlementHexes.First(h => h.Id == city); // every settlement has one (ValidateMap)var q = x.Qualified;// R-QUAL-005: the most service first (owner, 24 October 2026: "Accept all as built", https://github.com/eyalgolan/statecraft-israel/issues/1511#issuecomment-6375597377). A veteran comes back with the service- // that made it one (R-VET-001).+ // that made it one (R-VET-001). On a ledger the i-th most served group is the i-th lowest record id ("Free+ // pioneers by service (Recommended)"), and its unit is linked to that record ("Add the link first (Recommended)").var served = veteran ? new int[count] : q.Halutzim.Skip(q.Halutzim.Count - count).Reverse().ToArray();+ if (picked != null)+ {+ // "Free pioneers by service (Recommended)": the records go back to region-only with no city, as at graduation.+ var region = c.PlayerRegions.AtLocation(city)?.Id+ ?? throw new InvalidOperationException("No region in regions.yaml for " + city + " (R-POP-004).");+ s.PopulationLedger.Commit(picked.Select(id =>+ {+ var p = s.PopulationLedger.Get(id);+ return p.WithPlacement(p.Status, new PopulationLocation(region), p.Assignment, p.Captor, p.Home);+ }).ToList(), Array.Empty<PopulationTarget>());+ HistoricalPopulation.NoteLinked(s.PopulationLedger, picked);+ }for (int i = 0; i < count; i++){var id = s.NextId++;- s.Units.Add(id, new Unit(id, track, hex.Q, hex.R, veteran ? c.RulesAt(s.Date).Mvp!.VeteranHalutzService!.Value : served[i]));+ s.Units.Add(id, new Unit(id, track, hex.Q, hex.R, veteran ? c.RulesAt(s.Date).Mvp!.VeteranHalutzService!.Value : served[i],+ records: picked == null ? null : new[] { picked[i] }));}- s.Cities[city] = x.WithCounts(x.Civilians - count, x.Employed, x.Refugees)- .WithQualified(veteran ? q.WithVeterans(q.Veterans - count) : q.TakeHalutzim(count));+ var left = veteran ? q.WithVeterans(q.Veterans - count) : q.TakeHalutzim(count);+ s.Cities[city] = (ledger ? x : x.WithCounts(x.Civilians - count, x.Employed, x.Refugees)).WithQualified(left);why.Add(new Cause("city", city, -count, $"{name}: {Groups(count)} of qualified {(veteran ? "veteran pioneers" : "halutzim")} are units again", key: CauseKeys.PioneersReassigned, args: new[] { CauseKeys.Number(count), veteran ? "veteran" : "halutz" }));return null;}diff --git a/sim/Statecraft.Sim/SettlementControl.cs b/sim/Statecraft.Sim/SettlementControl.csindex 184198fa1..75ecaae16 100644--- a/sim/Statecraft.Sim/SettlementControl.cs+++ b/sim/Statecraft.Sim/SettlementControl.cs@@ -266,7 +266,7 @@ namespace Statecraft.Simmoved.Clear();return new CaptureRefusal(CaptureRefusal.NoFreeHex, string.Format(CultureInfo.InvariantCulture, RefusedNoFreeHex, name));}- var w = new Unit(u.Id, u.Type, to.Value.Q, to.Value.R, u.Service, u.Side, u.Strength, u.Order, u.OrderTarget, u.HomeCity, u.Full, u.CombatXp);+ var w = new Unit(u.Id, u.Type, to.Value.Q, to.Value.R, u.Service, u.Side, u.Strength, u.Order, u.OrderTarget, u.HomeCity, u.Full, u.CombatXp, u.Records);s.Units[u.Id] = w;moved.Add((u, w));}diff --git a/sim/Statecraft.Sim/Training.cs b/sim/Statecraft.Sim/Training.csindex 533963488..fea08eff2 100644--- a/sim/Statecraft.Sim/Training.cs+++ b/sim/Statecraft.Sim/Training.cs@@ -289,7 +289,7 @@ namespace Statecraft.Sim{var first = s.NextId;s.NextId += k.Count;- Halutzim(c, s, k, type, name, first, why);+ Halutzim(c, s, k, type, name, first, null, why);}else if (type.Id == Craftsman){@@ -310,7 +310,7 @@ namespace Statecraft.Simvar target = s.Units[unit];var strength = target.Strength + k.Count;s.Units[target.Id] = new Unit(target.Id, target.Type, target.Q, target.R, target.Service, target.Side, strength,- target.Order, target.OrderTarget, target.HomeCity, strength >= target.Full ? 0 : target.Full, target.CombatXp);+ target.Order, target.OrderTarget, target.HomeCity, strength >= target.Full ? 0 : target.Full, target.CombatXp, target.Records);why.Add(new Cause("city", k.City, k.Count, FormattableString.Invariant($"{name}: {Groups(k.Count)} finished {Course(type)} and joined unit {target.Id}"), key: CauseKeys.ReplacementsJoined, args: new[] { CauseKeys.Number(k.Count), CourseId(type), CauseKeys.Number(target.Id) }));}@@ -322,11 +322,15 @@ namespace Statecraft.Simwhy.Add(new Cause("city", k.City, k.Count, $"{name}: {Groups(k.Count)} finished {Course(type)} and are {Trained(type)}", key: CauseKeys.MilitaryTrained, args: new[] { CauseKeys.Number(k.Count), CourseId(type), type.Class == Combat.ArtilleryClass ? "artillery" : type.Class == Armour ? "armour" : "recruit" }));}- /// <summary>R-TRAIN-003: finished halutzim are one map unit per group, ids <paramref name="first"/> on.</summary>- static void Halutzim(Content c, GameState s, Cohort k, UnitType type, string name, int first, List<Cause> why)+ /// <summary>R-TRAIN-003: finished halutzim are one map unit per group, ids <paramref name="first"/> on. On a Historical+ /// ledger game <paramref name="records"/> are the cohort's records, ascending, one per group, and unit+ /// <c>first + i</c> is linked to record i (owner, 9 November 2026, "Add the link first (Recommended)" and "List on+ /// the unit (Recommended)"); null on any other game.</summary>+ static void Halutzim(Content c, GameState s, Cohort k, UnitType type, string name, int first, IReadOnlyList<int>? records, List<Cause> why){var hex = c.SettlementHexes.First(h => h.Id == k.City); // every settlement has one (ValidateMap)- for (int i = 0; i < k.Count; i++) s.Units.Add(first + i, new Unit(first + i, type.Id, hex.Q, hex.R));+ for (int i = 0; i < k.Count; i++)+ s.Units.Add(first + i, new Unit(first + i, type.Id, hex.Q, hex.R, records: records == null ? null : new[] { records[i] }));why.Add(new Cause("city", k.City, k.Count, $"{name}: {Groups(k.Count)} finished {Course(type)} and are halutzim", key: CauseKeys.PioneersTrained, args: new[] { CauseKeys.Number(k.Count), CourseId(type) }));}@@ -395,7 +399,8 @@ namespace Statecraft.Sim/// facility's course in the same place (27M-7), keeping their profession dormant (owner, 8 November 2026, "Unskilled/// first, keep (Rec.)"), and are validated as one candidate with any Course target a built camp still needs/// (owner, "Start + runtime bind (Rec.)"). The Money, the cohort's id and the Why lines are the aggregate game's; no- /// city field is written.</summary>+ /// city field is written, but for City.Qualified when the order takes a returned pioneer (R-QUAL-006; owner, 9 November+ /// 2026, "Yes, lower it (Recommended)").</summary>static string? LedgerStart(Content c, GameState s, string city, UnitType type, int count, List<Cause> why, int? unit, string name){var ledger = s.PopulationLedger;@@ -424,6 +429,17 @@ namespace Statecraft.Simif (per > 0 && taken.Any(p => p.Equipment.MilitaryId != null)) return Refused(LedgerRefusedCarried, name);if (type.Side == "" && taken.Any(p => p.Profession == CivilianProfession.Farmer || p.Profession == CivilianProfession.Craftsman))return Refused(LedgerRefusedHalutzTrade, name);+ // R-QUAL-006 on the ledger (owner, 9 November 2026, "Yes, lower it (Recommended)"): a returned pioneer record the+ // order takes loses its qualification, so the city's qualified pioneers (City.Qualified) never outnumber its+ // free pioneer records. As the aggregate path counts it, only what the remaining records cannot hold is lost.+ // The training centre's census teacher (#1689), while untouched, is not a returned pioneer, so it holds no+ // qualified group; once linked to a unit it is a pioneer like any other (HistoricalPopulation.UntouchedTeacherId).+ var x = s.Cities[city];+ var teacher = HistoricalPopulation.UntouchedTeacherId(ledger);+ bool CityPioneer(PopulationUnit p) => p.Status == PopulationStatus.FreeCivilian && p.Profession == CivilianProfession.Pioneer+ && string.Equals(p.Location?.City, city, StringComparison.Ordinal) && p.Id != teacher;+ var pioneers = ledger.Units.Count(CityPioneer) - taken.Count(CityPioneer);+ var lost = Math.Max(0, x.Qualified.Halutzim.Count + x.Qualified.Veterans - pioneers);var id = s.NextId;var course = new PopulationAssignment(PopulationAssignmentKind.Course, target);var bind = ledger.Target(target) == null@@ -435,6 +451,7 @@ namespace Statecraft.Simp.WorkXp, p.Qualification, p.CombatXp, per > 0 ? new PopulationEquipment(e.ToolsId, e.ToolsPaid, IssuedId(id, p.Id), true) : e,p.Captor, p.Home);}).ToList(), bind);+ if (lost > 0) s.Cities[city] = x.WithQualified(x.Qualified.LosePioneers(lost));Open(c, s, city, name, type, count, arms, (int)(arms - (per > 0 ? count : 0)), unit, taken.Select(p => p.Id), why);return null;}@@ -487,7 +504,7 @@ namespace Statecraft.Sim/// records changed as its outcome says. A cohort with turns to go counts one course tick on each record; replacements/// whose unit is gone are released as <see cref="Cancel"/> releases them; replacements that finish serve their/// formation; a recruit or crew cohort that finishes serves a new formation target bound for its new map unit (owner,- /// 8 November 2026, "New unit at graduation (Rec.)"); halutzim become free pioneers (<see cref="Pioneer"/>). Every+ /// 8 November 2026, "New unit at graduation (Rec.)"); halutzim become free pioneers (<see cref="Pioneer"/>), each map unit linked to its record (<see cref="Unit.Records"/>). Every/// record change and new target of the turn is validated as one candidate before any write; the state's writes then/// follow in cohort order, taking the same ids as the aggregate step.</summary>static void LedgerProgress(Content c, GameState s, List<Cause> why)@@ -545,7 +562,8 @@ namespace Statecraft.Simrecords.AddRange(members.Select(p => Pioneer(p, region)));var first = next;next = checked(next + k.Count);- apply.Add(() => { s.Cohorts.Remove(k.Id); Halutzim(c, s, k, type, name, first, why); });+ var linked = members.Select(p => p.Id).ToList(); // ascending id, one per group (Members, Cohort)+ apply.Add(() => { s.Cohorts.Remove(k.Id); Halutzim(c, s, k, type, name, first, linked, why); HistoricalPopulation.NoteLinked(ledger, linked); });}else throw new InvalidOperationException("Cohort " + k.Id.ToString(CultureInfo.InvariantCulture) + " of type " + k.Type + " does not run on the population ledger.");}