Skip to content

A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.

feat(sim): training runs on a Historical ledger game (#1725 PR 7, producer 12) (#2964)

Eyal Golan81ba61148140
diff --git a/changelog.d/1725-pr7-training.md b/changelog.d/1725-pr7-training.md
new file mode 100644
index 000000000..db50b71cd
--- /dev/null
+++ b/changelog.d/1725-pr7-training.md
@@ -0,0 +1,5 @@
+- GDD 0.3 starting population (Refs #1725): on the inactive dark start's Historical ledger, Train, Reinforce,
+ CancelTraining and the training step now move people records: a city's free civilians without a job become trainees
+ on their camp's or Hakhshara's course, each recruit and crew trainee is issued one item of Arms, a camp holds 50
+ trainees, a cancel returns the same people and their Arms, and graduates become soldiers of one new formation or free
+ pioneers. Craft training is refused there until #2476. No new-game wiring, so there is no change in the game.
diff --git a/docs/population-ledger.md b/docs/population-ledger.md
index c26bd7575..4fe0647ee 100644
--- a/docs/population-ledger.md
+++ b/docs/population-ledger.md
@@ -14,4 +14,4 @@ No save/reload round trip for population identity is claimed. The existing seed/
## Historical start inventory (R-POP-004)
-`HistoricalPopulation.Inventory` is internal and reads the shipped content under exact `gdd-0.3`: one free-civilian row per census city start unit (R-CITY-007) and one active-soldier row per population unit of each Israeli starting formation of `map/units_1948.yaml` (R-UNIT-006), at `rules.yaml`'s 1,000 people a unit (owner, 1 November 2026, D2). Rows carry a source key (`census/<city id>`, `units_1948/<row id>`) and a within-source ordinal, in R-POP-001's order. Enemy formations and dated arrivals (R-UNIT-009) are not in it: an own dated brigade is bound at the start with no record and arrives on its day as new active-soldier records (`StartingForces.Arrive`, #1725 PR 7, producer 08; see R-UNIT-009). It builds no `PopulationUnit` itself. `HistoricalPopulation.LedgerFixture` (internal, fixture-only) turns it into an initialized Historical ledger and binds each record to a region of `content/regions.yaml`: a census record takes the region whose `member_locations` hold its city, and its location names that city (`PopulationLocation.City`), a formation record the region whose member hexes hold its starting anchor hex (R-POP-004); a source with no region is refused. Census records start with their reception done (`reception.turns`), so R-VET-001's received-free-civilian work XP can apply to them. One census record, the last `census/haifa` ordinal, is the training centre's veteran pioneer teacher (#1689, `start.pioneer_teachers` 1): a pioneer at the veteran tier with work XP 0 and no assignment, since a teaching teacher with no pupil is refused (R-TRAIN-008); see R-POP-004. The 20 opening field farmers (#1725 PR 4) are records too, on top of the census: source `field/<label>`, ordinal 0, each a free civilian farmer working its field from turn 1 and living in the field's host, split 1:2:1 per host (`HistoricalPopulation.FieldFarmerHosts`; 1 / 18 / 1 in all), work XP 0 and reception done; the dark start adds one housing place per farmer in a census host (18 of 20; Nir Am and Nirim have no city record); see R-POP-004. Each formation record carries one issued military item (`units_1948/<row id>/<ordinal>`, recorded as paid), apart from the spare Arms (#1717). A formation record's military qualification is its type's `unit_types.yaml` class, and its combat XP is `gdd03-start.yaml`'s `formation_combat_xp` (#1689 rows 5 to 8, R-POP-004). The public `NewGame` does not call it, because an initialized ledger refuses the aggregate systems a `gdd-0.3` game still runs (R-POP-002). The dark start, `NewGame`'s internal fixture-only overload (#1725 PR 5), initializes the same ledger in place (`HistoricalPopulation.Initialize`, all or nothing) before `Pools.Init`, which then starts Food at `cover_months` of the ledger's rations; it places the starting forces against the ledger's soldiers and fires no opening event, since `EventSystem.Trigger` still refuses a ledger. The test `HistoricalPopulationTests` checks it, city by city and formation by formation, against the aggregate start of the same content.
+`HistoricalPopulation.Inventory` is internal and reads the shipped content under exact `gdd-0.3`: one free-civilian row per census city start unit (R-CITY-007) and one active-soldier row per population unit of each Israeli starting formation of `map/units_1948.yaml` (R-UNIT-006), at `rules.yaml`'s 1,000 people a unit (owner, 1 November 2026, D2). Rows carry a source key (`census/<city id>`, `units_1948/<row id>`) and a within-source ordinal, in R-POP-001's order. Enemy formations and dated arrivals (R-UNIT-009) are not in it: an own dated brigade is bound at the start with no record and arrives on its day as new active-soldier records (`StartingForces.Arrive`, #1725 PR 7, producer 08; see R-UNIT-009). It builds no `PopulationUnit` itself. `HistoricalPopulation.LedgerFixture` (internal, fixture-only) turns it into an initialized Historical ledger and binds each record to a region of `content/regions.yaml`: a census record takes the region whose `member_locations` hold its city, and its location names that city (`PopulationLocation.City`), a formation record the region whose member hexes hold its starting anchor hex (R-POP-004); a source with no region is refused. Census records start with their reception done (`reception.turns`), so R-VET-001's received-free-civilian work XP can apply to them. One census record, the last `census/haifa` ordinal, is the training centre's veteran pioneer teacher (#1689, `start.pioneer_teachers` 1): a pioneer at the veteran tier with work XP 0 and no assignment, since a teaching teacher with no pupil is refused (R-TRAIN-008); see R-POP-004. The 20 opening field farmers (#1725 PR 4) are records too, on top of the census: source `field/<label>`, ordinal 0, each a free civilian farmer working its field from turn 1 and living in the field's host, split 1:2:1 per host (`HistoricalPopulation.FieldFarmerHosts`; 1 / 18 / 1 in all), work XP 0 and reception done; the dark start adds one housing place per farmer in a census host (18 of 20; Nir Am and Nirim have no city record); see R-POP-004. Each formation record carries one issued military item (`units_1948/<row id>/<ordinal>`, recorded as paid), apart from the spare Arms (#1717). A formation record's military qualification is its type's `unit_types.yaml` class, and its combat XP is `gdd03-start.yaml`'s `formation_combat_xp` (#1689 rows 5 to 8, R-POP-004). The public `NewGame` does not call it, because an initialized ledger refuses the aggregate systems a `gdd-0.3` game still runs (R-POP-002). The dark start, `NewGame`'s internal fixture-only overload (#1725 PR 5), initializes the same ledger in place (`HistoricalPopulation.Initialize`, all or nothing) before `Pools.Init`, which then starts Food at `cover_months` of the ledger's rations; it places the starting forces against the ledger's soldiers and fires no opening event, since `EventSystem.Trigger` still refuses a ledger. The test `HistoricalPopulationTests` checks it, city by city and formation by formation, against the aggregate start of the same content. The ledger also binds each start facility's Course target (`military_camp/<city>`, `hakhshara/<city>`, in the city's region) and each military track's unit class as a qualification, and `PopulationLedger.BindTarget` and `Commit` bind a built camp's course or a trained formation's `formation/<unit id>` at runtime, all or nothing (owner, 8 November 2026, "Start + runtime bind (Rec.)"; R-TRAIN-001, #1725 PR 7).
diff --git a/docs/rules/mvp.md b/docs/rules/mvp.md
index bd1fd29c5..1d40709e7 100644
--- a/docs/rules/mvp.md
+++ b/docs/rules/mvp.md
@@ -172,13 +172,13 @@ Then changed (3 Nov 2026, [#1700](https://github.com/eyalgolan/statecraft-israel
Training is step 4 of the turn in the approved order (§2.3, D-A6): it runs before production. One military camp and one Hakhshara exist in Tel Aviv at the start, a labelled design assumption (D-D5); pioneers build more at camp sites (R-CAMP-001). Scope note: this is the live `gdd-0.1` start. Under `gdd-0.3`, 27M-25 says: "Schneller and Tel HaShomer operate from the start, the other military camps are build sites, every camp uses `military.camp_capacity` 5, and the reception site is Kiryat Shmuel, Haifa" (that 5 is #1668's value at 10,000 people a unit; at D2's 1,000 people a unit it is 50 units, `content/gdd03-balance.yaml:307`). R-CAMP-003 defines the `gdd-0.3` start camps. The Hakhshara and its `Train` track stay under `gdd-0.3` (owner, 4 November 2026: "Keep the Hakhshara", [#2484](https://github.com/eyalgolan/statecraft-israel/issues/2484)).
-R-TRAIN-001: `Train(city, track, n)` takes `n` of the city's civilians without a job (not a staffed arms workshop's worker, R-ARMS-005, or a builder, R-CITY-011) into a cohort that trains as `track` (a unit type with a `facility`: `recruit`, `artillery` and `armoured_car` in a military camp (R-UNIT-008), `halutz` in a Hakhshara, `craftsman` at industry, R-CRAFT-001) for the type's `training_turns`, counting the turn it was ordered in. The Treasury pays `n * training_cost` at once. When the Treasury holds less, the shortfall is borrowed, as for map actions: it is added to the debt and the Treasury stops at 0 (owner decision "Allow borrowing", 15 October 2026). The trainees leave the civilians at once; the cohort takes the next id, which units share. It is refused, with the state unchanged and the Attention refunded, when the city or track is unknown, `n` is below 1, the city lacks the facility, or it has fewer civilians without a job. A city has a facility when `cities.yaml` gives it one at the start, `gdd03-start.yaml` gives it one under R-CAMP-003, or a camp site of that kind built for it is in the state (R-CAMP-001). The legacy loop refuses it before charging Attention. `Reinforce` (R-TRAIN-004) starts a cohort by the same rules, aimed at a unit. A queued `ReassignCraftsmen` or `ReassignPioneers` (R-QUAL-004, R-QUAL-005) takes its civilians without a job as a queued `Train` does (counted in full, so the orders are accepted in any order), in `Training.Ordered` and `Training.Available` (#1548; owner, 24 October 2026: "Yes, count them", https://github.com/eyalgolan/statecraft-israel/issues/1511#issuecomment-6378360813). Under `gdd-0.3` the `halutz` track still trains in a Hakhshara (owner, 4 November 2026: "Keep the Hakhshara", [#2484](https://github.com/eyalgolan/statecraft-israel/issues/2484)).
+R-TRAIN-001: `Train(city, track, n)` takes `n` of the city's civilians without a job (not a staffed arms workshop's worker, R-ARMS-005, or a builder, R-CITY-011) into a cohort that trains as `track` (a unit type with a `facility`: `recruit`, `artillery` and `armoured_car` in a military camp (R-UNIT-008), `halutz` in a Hakhshara, `craftsman` at industry, R-CRAFT-001) for the type's `training_turns`, counting the turn it was ordered in. The Treasury pays `n * training_cost` at once. When the Treasury holds less, the shortfall is borrowed, as for map actions: it is added to the debt and the Treasury stops at 0 (owner decision "Allow borrowing", 15 October 2026). The trainees leave the civilians at once; the cohort takes the next id, which units share. It is refused, with the state unchanged and the Attention refunded, when the city or track is unknown, `n` is below 1, the city lacks the facility, or it has fewer civilians without a job. A city has a facility when `cities.yaml` gives it one at the start, `gdd03-start.yaml` gives it one under R-CAMP-003, or a camp site of that kind built for it is in the state (R-CAMP-001). The legacy loop refuses it before charging Attention. `Reinforce` (R-TRAIN-004) starts a cohort by the same rules, aimed at a unit. A queued `ReassignCraftsmen` or `ReassignPioneers` (R-QUAL-004, R-QUAL-005) takes its civilians without a job as a queued `Train` does (counted in full, so the orders are accepted in any order), in `Training.Ordered` and `Training.Available` (#1548; owner, 24 October 2026: "Yes, count them", https://github.com/eyalgolan/statecraft-israel/issues/1511#issuecomment-6378360813). Under `gdd-0.3` the `halutz` track still trains in a Hakhshara (owner, 4 November 2026: "Keep the Hakhshara", [#2484](https://github.com/eyalgolan/statecraft-israel/issues/2484)). It runs on a game with an initialized Historical ledger (the dark start, R-POP-002; #1725 PR 7, producer 12) under the owner's rulings of 8 November 2026 (#1725 issuecomment-6724941867). "Recruit+crews+halutz (Rec.)": the recruit, crew and halutz tracks run, and the craftsman track is refused with a plain reason until #2476, the reason "Craft training does not run on the population ledger yet (#2476)". "Cohorts stay main (Rec.)": `State.Cohorts` stays the record of truth, each trainee's Course target is per facility (`military_camp/<city>`, `hakhshara/<city>`), and the cohort keeps a sorted list of its members' ids, hashed only when set. "Unskilled first, keep (Rec.)": civilians with no profession first, then the qualified, each in ascending id, and a qualified trainee's profession is kept dormant, not cleared. "Keep costs, pool rest (Rec.)": one item is issued per record, and the rest of `training_arms` is taken from the stock and kept in `Cohort.Arms`, so a cancel returns it. "Enforce it here (Rec.)": the camp capacity, 50 records per camp city over all military tracks, is enforced here, refused with "<city>'s military camp has room for <n> more trainees (capacity 50)". "Start + runtime bind (Rec.)": the start facilities' Course targets are bound at the start, plus one all-or-nothing runtime bind for new formations and built camps. There the trainees are the city's free-civilian records without an assignment, located in the city; a refugee, a worker and a farmer on a field are not idle. Each becomes a trainee on its facility's course in the same place (27M-7), and each military trainee is issued one military item, `training/<cohort>/<id>`, from the Arms stock. Every check (city, track, count, facility, idle records, camp capacity, Arms) comes before the first write, and the records and any Course target a built camp still needs are validated as one candidate. The Money, the cohort id and the Why lines are the aggregate game's; no aggregate city field is written. The ledger also binds each military track's unit class as a qualification at Initialize. A trainee who already carries a military item, and a farmer or craftsman on the halutz track, are refused before any write, the state unchanged (owner, 8 November 2026, Q3: "Refuse, with reason (Recommended)"), with "A civilian without work in <city> already carries a military item" and "A farmer or craftsman in <city> cannot train as a halutz"; neither is idle on the dark start, and a replacement cohort (R-TRAIN-004) is refused the same way. These ledger refusals are internal English text: their Hebrew comes with the UI wiring PR (owner, 8 November 2026, Q4: "With the UI PR (Recommended)"). A synthetic or Open ledger is still refused.
-R-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.
+R-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).
+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-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 }`.
+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.
R-TRAIN-005: In gdd-0.3 synthetic fixtures only (#1697; nothing in the game calls it), a farmer or pioneer course starts at an operating training centre, a facility in its host city with no reception camp, centre upgrade or reception bed (owner, 1 November 2026, "No reception-bed layer (Recommended)"; `docs/gdd/training.md:38`, "The MVP has no reception-bed layer"). A centre has one veteran teacher and one pupil, the teacher housed in the centre's city (GDD, 1 November 2026 answers, `docs/GDD.md:372`: "One veteran teacher and one pupil per centre, the teacher housed in the centre's city (Q42)."). A population location has a region and an optional hex, facility or city (R-POP-003; the Historical fixture names each census record's city, R-POP-004), but this fixture does not read the city yet, so the centre's region stands in for its host city, an approximation until it does (#1691). A teacher outside the centre's region is refused with a plain reason that cites Q42. Q42 rules only on the teacher; that the trainee lives in the centre's host city too was our reading (#1697 body: "the teacher and the trainee are housed there as ordinary residents"; `docs/GDD.md:374`, "Training is ordered in the camp's city, with no travel (27M-7)."), and is now the owner's ruling (owner, 4 November 2026, Q23: asked "Must a farmer-course or pioneer-course pupil live in the training centre's host city?", the owner answered "yes", [recorded on #1697](https://github.com/eyalgolan/statecraft-israel/issues/1697#issuecomment-6623127820)). The fixture still uses the centre's region as the stand-in for its host city, so a trainee outside the region is refused with a plain reason that says so; the rule tightens to the host city once centres are bound to real cities (#1691). A centre takes at most one teacher and one pupil, whatever `profession.trainees_per_teacher` says: a second teacher, or a second pupil while one is on a course there, is refused with a plain reason that cites Q42, not as Deferred, and an inventory with either is refused the same way. The teacher is a free civilian, a veteran of the matching profession; the trainee is a free civilian who is a novice of that profession, or a free civilian with no profession (#2464; `docs/gdd/training.md:48`: "An eligible free civilian may train under the retained course rules."). That such a pupil stays without a profession on the course is a maintainer reading, not an owner ruling: [#1697](https://github.com/eyalgolan/statecraft-israel/issues/1697), update of 3 November 2026, "the MVP has no novice stage for farmers or pioneers: an entrant is a free civilian with no profession label until completion, and a cancel leaves an ordinary civilian", built on the owner's #1693 answers of 3 November 2026 ([answers](https://github.com/eyalgolan/statecraft-israel/issues/1693#issuecomment-6606032643)), which do not say this in those words. The craftsman course differs under an owner-approved answer: "The novice craftsman label starts with the craftsman course" (`docs/GDD.md:372`, #1698 follow-up; R-CRAFT-003). Either may hold a job, which is released in the same commit that starts the course (a reading of `docs/gdd/cities.md:42`, "Reassignment releases old capacity atomically.", with `docs/GDD.md:372`, Q43(b) and (c), "can be assigned from the next planning, or at once on cancellation", and `docs/gdd/training.md:66`, people "return at once"); a teacher teaching elsewhere, or a pupil on a course, is refused, since only a cancel or a graduation ends those here. No reception progress is read (`docs/GDD.md:374`, "Refugees cannot train until they become civilians"), and refugees in a reception camp take no course place. No tools are needed or charged: tools are post-MVP (#1693, owner answers of 3 November 2026, answer 1: "Tools in the MVP: no."), and the record's tools fields are kept unchanged. A teacher also takes at most Agreed `profession.trainees_per_teacher` pupils (currently 1; the approved Q42 answer names this value as its basis), so a busy teacher refuses another pupil; a synthetic value above 1 admits no second pupil, because the centre's own limit is one. No Money is charged. Teacher and trainee then hold exclusive Teaching and Course assignments, so other assignment paths refuse them (`docs/gdd/training.md:31` at `605277dfa511dc512562ececeb273b8393b21d35`, "The teacher is fully occupied and cannot work, fight, build, travel or teach another pupil simultaneously."). Every refusal leaves the state unchanged. Craftsmen, soldiers and refugees cannot enrol. Only exact gdd-0.3 states with an initialized population ledger are accepted; legacy and gdd-0.1 are refused unchanged. The centre course does not retire the Hakhshara: the owner kept it under `gdd-0.3` (4 November 2026: "Keep the Hakhshara", [#2484](https://github.com/eyalgolan/statecraft-israel/issues/2484)), and R-TRAIN-001's `halutz` track stays.
@@ -605,7 +605,7 @@ These contracts cover #1689 steps 1–2 and the Historical start inventory (R-PO
R-POP-001: Only exact `gdd-0.3` enables the population-ledger capability, independently of the broad GDD loop and Attention (R-LOOP-002/005). An immutable own-population record has a dedicated nonnegative ordinal id. Synthetic fixture inventory is ordered by source key (ordinal string comparison), then within-source ordinal. Registered arrivals allocate monotonically; only explicit combat losses remove living ids. Sources remain registered after loss, and ids are never reused. Reconciliation checks the exact created-minus-lost id set against the living ledger, not just equal totals. Status/region counts include every matching record once. The gdd-0.3 scale of a synthetic or Open fixture reads one positive Agreed integer from `population.people_per_unit` in its catalogue (currently 10,000, Open mode's scale under D2); a Historical fixture reads `rules.yaml`'s `people_per_unit` for the start day (1,000), as R-UNIT-006 does (owner, 1 November 2026, D2: "Approve all six (Recommended)", "The Historical MVP keeps main's start: census cities at 1,000 people a unit (`R-CITY-007`)"; R-POP-004); rows with a `census/`, `units_1948/` or `field/` source key are the Historical start's and are refused in any other fixture. Old identities retain the common rules scale. Missing, fractional, nonpositive, overflowing or Deferred values have no fallback, in either source.
-R-POP-002: A ledger record has exactly one typed status and assignment, validated location, home and captor references, whole reception-turn ticks capped by the catalogue requirement, civilian profession-specific tier and actual-work XP, separate military qualification/combat XP, and distinct issued civilian/military equipment and paid facts. Unknown references, unresolved teacher ids, incompatible statuses/assignments, inconsistent region/hex/facility bindings, invalid progress/tiers and duplicate issued-item ownership are refused before mutation. Moves and atomic status/location/assignment transitions retain identity/history. Capture retains home context without inventing a prison hex or refunding equipment. Ledger changes never touch resources, causes, RNG or Attention. Initialization is internal and fixture-only; initialized ledger fixtures refuse aggregate Simulation commands and turns. The dark start (#1725 PR 5) is the internal, fixture-only `Simulation.NewGame` overload that initializes the Historical ledger (R-POP-004) in place before `Pools.Init`: `Pools.Init` then reads the ledger's need, one ration for each living own population id (R-FOOD-001, #2470), after the ledger reconciles, and `StartingForces.Init` places the forces once each own starting formation's strength is its ledger soldiers, refusing otherwise. Both read only a ledger initialized with mode Historical, the dark start's; a synthetic or Open ledger is refused by both, as by the other aggregate systems, with the state unchanged. An aggregate system whose own rule says it runs on that Historical ledger (#1725 PR 7: civilian upkeep, R-MONEY-002, the first, and food_supply's stock term, R-FOOD-003) also reads only that ledger; a synthetic or Open ledger is still refused by it. `EventSystem.Trigger` still refuses a ledger, so a dark start fires no opening event; the public `NewGame` is unchanged. The step-7 Food settlement given a month's synthetic context is another exception to that refusal: it reads its need from that month's frozen snapshot (R-FOOD-002, #2470). Old identities refuse ledger mutation. Prices, progression awards, return destinations, tool lock-in and captive-equipment outcomes remain with their owning issues. A craftsman's tier is novice, apprentice or expert (R-CRAFT-003); a farmer's or pioneer's is novice, trained or veteran.
+R-POP-002: A ledger record has exactly one typed status and assignment, validated location, home and captor references, whole reception-turn ticks capped by the catalogue requirement, civilian profession-specific tier and actual-work XP, separate military qualification/combat XP, and distinct issued civilian/military equipment and paid facts. Unknown references, unresolved teacher ids, incompatible statuses/assignments, inconsistent region/hex/facility bindings, invalid progress/tiers and duplicate issued-item ownership are refused before mutation. Moves and atomic status/location/assignment transitions retain identity/history. Capture retains home context without inventing a prison hex or refunding equipment. Ledger changes never touch resources, causes, RNG or Attention. Initialization is internal and fixture-only; initialized ledger fixtures refuse aggregate Simulation commands and turns. The dark start (#1725 PR 5) is the internal, fixture-only `Simulation.NewGame` overload that initializes the Historical ledger (R-POP-004) in place before `Pools.Init`: `Pools.Init` then reads the ledger's need, one ration for each living own population id (R-FOOD-001, #2470), after the ledger reconciles, and `StartingForces.Init` places the forces once each own starting formation's strength is its ledger soldiers, refusing otherwise. Both read only a ledger initialized with mode Historical, the dark start's; a synthetic or Open ledger is refused by both, as by the other aggregate systems, with the state unchanged. An aggregate system whose own rule says it runs on that Historical ledger (#1725 PR 7: civilian upkeep, R-MONEY-002, the first, and food_supply's stock term, R-FOOD-003; training, R-TRAIN-001 to R-TRAIN-004) also reads only that ledger; a synthetic or Open ledger is still refused by it. `EventSystem.Trigger` still refuses a ledger, so a dark start fires no opening event; the public `NewGame` is unchanged. The step-7 Food settlement given a month's synthetic context is another exception to that refusal: it reads its need from that month's frozen snapshot (R-FOOD-002, #2470). Old identities refuse ledger mutation. Prices, progression awards, return destinations, tool lock-in and captive-equipment outcomes remain with their owning issues. A craftsman's tier is novice, apprentice or expert (R-CRAFT-003); a farmer's or pioneer's is novice, trained or veteran.
R-POP-003: Clone copies all ledger containers; immutable records and frozen bindings may be shared. The canonical writer emits a gdd-0.3-only section ordered by numeric population id, with fixed field order, stable machine tokens, invariant integer formatting and length-prefixed reference strings. It covers every record/assignment/equipment/reference field, binding, creation/loss provenance and allocator even after the last combat loss. Legacy/gdd-0.1 emit no ledger section or allocator marker. A location's optional city (a `regions.yaml` member location of its region that is a census city of `cities.yaml` or one of that region's field hosts, where R-POP-004 houses own people: a settlement hosts only F19 and F20, owner, 7 November 2026, #1689: "These two only (Recommended)"; any other, including a locality, a `sites.yaml` id or a map location, is refused when a fixture is created, naming the city and the region, R-POP-002) is written after its other fields as `|city=` with a length-prefixed id, only when set, as R-UNIT-002's `|home=` is, so a location without a city keeps its canonical text and hash. R-SAVE-001/002 still govern identity mismatch refusal and replay: no ledger snapshot or new command syntax is added in this foundation, and fixture injection is not replay evidence. Existing unpublished schema-4 draft hashes change; no migration promise is made.
diff --git a/sim/Statecraft.Sim.Tests/LedgerTrainingTests.cs b/sim/Statecraft.Sim.Tests/LedgerTrainingTests.cs
new file mode 100644
index 000000000..f1c44e459
--- /dev/null
+++ b/sim/Statecraft.Sim.Tests/LedgerTrainingTests.cs
@@ -0,0 +1,575 @@
+using Statecraft.Sim;
+
+/// <summary>#1725 PR 7, producer 12: Train, Reinforce, CancelTraining and the training step (R-TRAIN-001 to R-TRAIN-004) run
+/// on a game with an initialized Historical ledger, the dark start (R-POP-002). The trainees are the city's free-civilian
+/// records without an assignment; the aggregate city fields are not written. The owner's rulings, 8 November 2026, each the
+/// recommended option of the plan's section 6:
+/// 1. "Recruit+crews+halutz (Rec.)": recruit, crews and halutz run; craftsman is refused with a plain reason until #2476.
+/// 2. "Cohorts stay main (Rec.)": State.Cohorts stays canonical; a per-facility Course target (military_camp/&lt;city&gt;,
+/// hakhshara/&lt;city&gt;); the cohort gets a sorted member-id list, hashed only when set.
+/// 3. "Unskilled first, keep (Rec.)": Profession None first, then the qualified, each ascending id; the profession is kept dormant.
+/// 4. "Full minus strength (Rec.)": Reinforce room is Unit.Full - Strength - training; refuse when Strength != the serving records.
+/// 5. "Keep costs, pool rest (Rec.)": one issued item per record; training_arms - 1 more from stock, kept in Cohort.Arms for refund.
+/// 6. "New unit at graduation (Rec.)": bind a new formation target at graduation, one formation per cohort (R-UNIT-003).
+/// 7. "Free pioneer, not housed (Rec.)": a halutz graduate is FreeCivilian Pioneer Novice, Unassigned, in the city's region with no city.
+/// 8. "Enforce it here (Rec.)": camp capacity, 50 records per camp city, over all military tracks.
+/// 9. "Start + runtime bind (Rec.)": the start facilities' Course targets are bound at Initialize, plus one all-or-nothing
+/// runtime BindTarget for new formations and built camps.
+/// The tests call Training directly: Simulation.Step and TurnResolver.Resolve still refuse a ledger game (R-POP-002).</summary>
+public class LedgerTrainingTests
+{
+ 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;
+ }
+
+ // Ruling 3, "Unskilled first, keep (Rec.)": the city's free civilians without an assignment, Profession None first, then
+ // the qualified, each ascending id.
+ static List<PopulationUnit> Idle(GameState s, string city) => 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).ToList();
+
+ static string Region(Content c, string city) => c.PlayerRegions.AtLocation(city)!.Id;
+
+ static (int Q, int R) Hex(Content c, string city) { var h = c.SettlementHexes.First(x => x.Id == city); return (h.Q, h.R); }
+
+ static int OnlyCohort(GameState s) => Assert.Single(s.Cohorts).Key;
+
+ static IEnumerable<(string, string, double, string, string)> Lines(IEnumerable<Cause> why) => why.Select(x => (x.System, x.Target, x.Delta, x.Message, x.Key));
+
+ // A target binding line of the ledger's canonical text (R-POP-003) whose target id is <paramref name="id"/>.
+ static bool Bound(GameState s, string id) => s.PopulationLedger.Canonical().Any(line =>
+ line.StartsWith("6:target|", StringComparison.Ordinal) && line.Contains(":" + id.Length + ":" + id + "|", StringComparison.Ordinal));
+
+ static string Cities(GameState s) => string.Join(";", s.Cities.Values.Select(x => x.Canonical()));
+
+ // R-TRAIN-001 on the ledger. Ruling 3: the first n idle records in Profession None then id order become trainees on
+ // the facility's course (ruling 2: military_camp/<city>) in the same place (27M-7, no travel), progress 0. Ruling 5: each
+ // is issued one military item from the stock. The Treasury pays once and the Why lines are the aggregate game's. No city
+ // field is written, no id is made or lost, and the cohort lists its members.
+ [Fact]
+ public void TrainOnTheDarkStartTurnsFreeCiviliansIntoTrainees()
+ {
+ var c = Gdd03();
+ var s = Dark(c); var twin = Aggregate(c);
+ var picked = Idle(s, TelAviv).Take(2).ToList();
+ var cities = Cities(s); var next = s.PopulationLedger.NextPopulationId; var count = s.PopulationLedger.Units.Count;
+ var why = new List<Cause>(); var twinWhy = new List<Cause>();
+
+ Assert.Null(Training.Start(c, s, TelAviv, "recruit", 2, why));
+ Assert.Null(Training.Start(c, twin, TelAviv, "recruit", 2, twinWhy));
+
+ Assert.Equal(Lines(twinWhy), Lines(why));
+ Assert.Equal((198, 99.0, 0.0), (s.Arms, s.Treasury, s.Debt));
+ Assert.Equal((twin.Arms, twin.Treasury, twin.Debt), (s.Arms, s.Treasury, s.Debt));
+ Assert.Equal(cities, Cities(s));
+ var id = OnlyCohort(s);
+ Assert.Equal(twin.Cohorts.Keys, s.Cohorts.Keys);
+ Assert.EndsWith("|members=" + string.Join(",", picked.Select(p => p.Id)), s.Cohorts[id].Canonical());
+ Assert.DoesNotContain("members", twin.Cohorts[id].Canonical());
+ foreach (var before in picked)
+ {
+ var p = s.PopulationLedger.Get(before.Id);
+ Assert.Equal(PopulationStatus.Trainee, p.Status);
+ Assert.Equal((PopulationAssignmentKind.Course, "military_camp/" + TelAviv, 0, (int?)null),
+ (p.Assignment.Kind, p.Assignment.Target, p.Assignment.ProgressTicks, p.Assignment.TeacherId));
+ Assert.Equal(before.Location!.Canonical(), p.Location!.Canonical());
+ Assert.Equal(("training/" + id + "/" + p.Id, true), (p.Equipment.MilitaryId, p.Equipment.MilitaryPaid));
+ Assert.Equal((before.ReceptionTicks, before.Profession, before.Tier, before.Qualification), (p.ReceptionTicks, p.Profession, p.Tier, p.Qualification));
+ }
+ Assert.Equal((next, count), (s.PopulationLedger.NextPopulationId, s.PopulationLedger.Units.Count));
+ s.PopulationLedger.Reconcile();
+ }
+
+ // R-TRAIN-002 on the ledger: the same records go back to free civilians without a job, in place, with their reception;
+ // the items this course issued return to the stock (R-ARMS-003), so the ledger's records are as before the order and
+ // spare plus issued Arms is unchanged. The Money is not refunded (D-A3). The Why lines are the aggregate game's.
+ [Fact]
+ public void CancelReturnsTheSameRecordsAndTheirArms()
+ {
+ var c = Gdd03();
+ var s = Dark(c); var twin = Aggregate(c);
+ var ledger = s.PopulationLedger.Canonical().ToList(); var cities = Cities(s);
+ Assert.Null(Training.Start(c, s, TelAviv, "recruit", 3, new List<Cause>()));
+ Assert.Null(Training.Start(c, twin, TelAviv, "recruit", 3, new List<Cause>()));
+ var why = new List<Cause>(); var twinWhy = new List<Cause>();
+
+ Assert.Null(Training.Cancel(c, s, OnlyCohort(s), why));
+ Assert.Null(Training.Cancel(c, twin, OnlyCohort(twin), twinWhy));
+
+ Assert.Equal(Lines(twinWhy), Lines(why));
+ Assert.Empty(s.Cohorts);
+ Assert.Equal(ledger, s.PopulationLedger.Canonical());
+ Assert.Equal((200, 98.5), (s.Arms, s.Treasury));
+ Assert.Equal(cities, Cities(s));
+ Assert.Equal(Training.RefusedNoCohort, Training.Cancel(c, s, 12345, why));
+ s.PopulationLedger.Reconcile();
+ }
+
+ // R-TRAIN-003 and R-UNIT-003 on the ledger. Ruling 6, "New unit at graduation (Rec.)": at the turn the cohort ends, a new
+ // formation target is bound for the new map unit, and the records serve it as active soldiers with the type's class as
+ // their qualification, keeping their item; the map unit's strength is its serving records. Each earlier turn counts one
+ // course tick on each record.
+ [Fact]
+ public void ProgressGraduatesRecruitsIntoOneNewFormation()
+ {
+ var c = Gdd03();
+ var s = Dark(c); var twin = Aggregate(c);
+ var picked = Idle(s, TelAviv).Take(2).Select(p => p.Id).ToList();
+ Assert.Null(Training.Start(c, s, TelAviv, "recruit", 2, new List<Cause>()));
+ Assert.Null(Training.Start(c, twin, TelAviv, "recruit", 2, new List<Cause>()));
+ var cohort = OnlyCohort(s);
+ var turns = c.UnitTypes.First(t => t.Id == "recruit").TrainingTurns;
+ Assert.True(turns > 1);
+ var why = new List<Cause>(); var twinWhy = new List<Cause>();
+ for (int i = 1; i < turns; i++)
+ {
+ Training.Progress(c, s, why); Training.Progress(c, twin, twinWhy);
+ Assert.All(picked, id => Assert.Equal(i, s.PopulationLedger.Get(id).Assignment.ProgressTicks));
+ Assert.EndsWith("|members=" + string.Join(",", picked), s.Cohorts[cohort].Canonical());
+ }
+ var unitId = s.NextId;
+ Assert.False(Bound(s, "formation/" + unitId));
+ Training.Progress(c, s, why); Training.Progress(c, twin, twinWhy);
+
+ Assert.Equal(Lines(twinWhy), Lines(why));
+ Assert.Empty(s.Cohorts);
+ Assert.Equal(twin.Units[unitId].Canonical(), s.Units[unitId].Canonical());
+ Assert.Equal(2, s.Units[unitId].Strength);
+ Assert.Equal(unitId + 1, s.NextId);
+ var target = "formation/" + unitId;
+ foreach (var id in picked)
+ {
+ var p = s.PopulationLedger.Get(id);
+ Assert.Equal((PopulationStatus.ActiveSoldier, PopulationAssignmentKind.ActiveService, target, "infantry"),
+ (p.Status, p.Assignment.Kind, p.Assignment.Target, p.Qualification));
+ Assert.Equal("training/" + cohort + "/" + id, p.Equipment.MilitaryId);
+ Assert.Equal((Region(c, TelAviv), (string?)null), (p.Location!.Region, p.Location.City));
+ }
+ Assert.Equal(s.Units[unitId].Strength, s.PopulationLedger.Units.Count(p => p.Status == PopulationStatus.ActiveSoldier && p.Assignment.Target == target));
+ Assert.True(Bound(s, target));
+ Assert.Equal(198, s.Arms);
+ s.PopulationLedger.Reconcile();
+ }
+
+ // Ruling 5, "Keep costs, pool rest (Rec.)": a gun crew takes its type's training_arms a group (R-ARMS-003), one as the
+ // record's issued item and the rest from the stock into Cohort.Arms; cancelling returns them all.
+ [Fact]
+ public void ACrewTakesOneItemPerRecordAndPoolsTheRest()
+ {
+ var c = Gdd03();
+ var s = Dark(c); var twin = Aggregate(c);
+ var arty = c.UnitTypes.First(t => t.Id == "artillery");
+ var per = arty.TrainingArms!.Value;
+ Assert.True(per > 1);
+ var why = new List<Cause>(); var twinWhy = new List<Cause>();
+ Assert.Null(Training.Start(c, s, TelAviv, "artillery", 2, why));
+ Assert.Null(Training.Start(c, twin, TelAviv, "artillery", 2, twinWhy));
+ Assert.Equal(Lines(twinWhy), Lines(why));
+ Assert.Equal(200 - 2 * per, s.Arms);
+ var k = s.Cohorts[OnlyCohort(s)];
+ Assert.Equal(2 * (per - 1), k.Arms);
+ Assert.Equal(2, s.PopulationLedger.Units.Count(p => p.Equipment.MilitaryId?.StartsWith("training/" + k.Id + "/", StringComparison.Ordinal) == true));
+ var back = new List<Cause>(); var twinBack = new List<Cause>();
+ Assert.Null(Training.Cancel(c, s, k.Id, back));
+ Assert.Null(Training.Cancel(c, twin, k.Id, twinBack));
+ Assert.Equal(Lines(twinBack), Lines(back));
+ Assert.Equal(200, s.Arms);
+ s.PopulationLedger.Reconcile();
+ }
+
+ // An own opening infantry formation of the dark start, moved onto Tel Aviv's hex, after one of its records is lost in
+ // combat: strength one less, Full the strength it had (R-TRAIN-004).
+ static (GameState S, Unit U, string Target) Wounded(Content c)
+ {
+ var s = Dark(c);
+ var i = Enumerable.Range(0, c.StartingForces.Count).First(j =>
+ {
+ var f = c.StartingForces[j];
+ return f.Side == Movement.PlayerSide && f.Arrives == null && f.Strength >= 2
+ && c.UnitTypes.First(t => t.Id == f.Type).Class == "infantry";
+ });
+ var target = HistoricalPopulation.FormationPrefix + c.StartingForces[i].Row;
+ var u = s.Units[i];
+ var lost = s.PopulationLedger.Units.First(p => p.Assignment.Target == target);
+ s.PopulationLedger.RegisterCombatLoss(lost.Id, "fixture-loss");
+ var (q, r) = Hex(c, TelAviv);
+ s.Units[i] = new Unit(u.Id, u.Type, q, r, u.Service, u.Side, u.Strength - 1, u.Order, u.OrderTarget, u.HomeCity, u.Strength, u.CombatXp);
+ return (s, s.Units[i], target);
+ }
+
+ // R-TRAIN-004 on the ledger. Ruling 4, "Full minus strength (Rec.)": the room is Unit.Full - Strength - training, and the
+ // replacements graduate into the formation's own target as active soldiers, its strength back to Full.
+ [Fact]
+ public void ReinforceRefillsAStartingFormation()
+ {
+ var c = Gdd03();
+ var (s, u, target) = Wounded(c);
+ var why = new List<Cause>();
+ Assert.Equal(string.Format(Training.RefusedRoomOne, u.Id, 1), Training.Reinforce(c, s, u.Id, TelAviv, 2, why));
+ Assert.Empty(why);
+ var picked = Idle(s, TelAviv).First().Id;
+ Assert.Null(Training.Reinforce(c, s, u.Id, TelAviv, 1, why));
+ Assert.Equal(string.Format(Training.RefusedNoLosses, u.Id), Training.Reinforce(c, s, u.Id, TelAviv, 1, why));
+ var turns = c.UnitTypes.First(t => t.Id == "recruit").TrainingTurns;
+ for (int t = 0; t < turns; t++) Training.Progress(c, s, why);
+ Assert.Empty(s.Cohorts);
+ Assert.Equal((u.Full, 0), (s.Units[u.Id].Strength, s.Units[u.Id].Full));
+ var p = s.PopulationLedger.Get(picked);
+ Assert.Equal((PopulationStatus.ActiveSoldier, target, "infantry"), (p.Status, p.Assignment.Target, p.Qualification));
+ Assert.Equal(s.Units[u.Id].Strength, s.PopulationLedger.Units.Count(x => x.Status == PopulationStatus.ActiveSoldier && x.Assignment.Target == target));
+ s.PopulationLedger.Reconcile();
+ }
+
+ // Ruling 4: "refuse when Strength != the serving records", with the state unchanged.
+ [Fact]
+ public void ReinforceIsRefusedWhenTheStrengthIsNotTheServingRecords()
+ {
+ var c = Gdd03();
+ var (s, u, _) = Wounded(c);
+ s.Units[u.Id] = 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, u.CombatXp);
+ var hash = s.Hash(); var why = new List<Cause>();
+ Assert.Equal(string.Format("Unit {0} has {1} soldiers on record but strength {2}", u.Id, u.Strength, u.Strength - 1),
+ Training.Reinforce(c, s, u.Id, TelAviv, 1, why));
+ Assert.Empty(why);
+ Assert.Equal(hash, s.Hash());
+ }
+
+ // R-TRAIN-004 (owner, 23 October 2026, "Default"): replacements whose unit is gone are cancelled as R-TRAIN-002 cancels a
+ // cohort, on the ledger too: the records are free civilians again and the item returns to the stock.
+ [Fact]
+ public void ReplacementsWhoseUnitIsGoneAreCancelledOnTheLedger()
+ {
+ var c = Gdd03();
+ var (s, u, _) = Wounded(c);
+ var picked = Idle(s, TelAviv).First().Id;
+ var arms = s.Arms;
+ Assert.Null(Training.Reinforce(c, s, u.Id, TelAviv, 1, new List<Cause>()));
+ s.Units.Remove(u.Id);
+ var why = new List<Cause>();
+ Training.Progress(c, s, why);
+ Assert.Empty(s.Cohorts);
+ Assert.Contains(why, x => x.Key == CauseKeys.ReplacementsStopped);
+ Assert.Contains(why, x => x.Key == CauseKeys.TrainingCancelled);
+ var p = s.PopulationLedger.Get(picked);
+ Assert.Equal((PopulationStatus.FreeCivilian, PopulationAssignmentKind.Unassigned, (string?)null), (p.Status, p.Assignment.Kind, p.Equipment.MilitaryId));
+ Assert.Equal(arms, s.Arms);
+ s.PopulationLedger.Reconcile();
+ }
+
+ // Ruling 7, "Free pioneer, not housed (Rec.)": halutz trainees take the Hakhshara's course (hakhshara/<city>) and no
+ // Arms; a graduate is a free civilian pioneer novice without an assignment in the city's region with no city, so the
+ // city houses them no longer (27M-18). The map gets one halutz unit per group, as in the aggregate game.
+ [Fact]
+ public void HalutzTrainingOnTheLedger()
+ {
+ var c = Gdd03();
+ var s = Dark(c); var twin = Aggregate(c);
+ var picked = Idle(s, TelAviv).Take(2).Select(p => p.Id).ToList();
+ var housed = Statecraft.Sim.Cities.Housed(s, s.Cities[TelAviv]);
+ var why = new List<Cause>(); var twinWhy = new List<Cause>();
+ Assert.Null(Training.Start(c, s, TelAviv, "halutz", 2, why));
+ Assert.Null(Training.Start(c, twin, TelAviv, "halutz", 2, twinWhy));
+ Assert.Equal(200, s.Arms);
+ Assert.All(picked, id => Assert.Equal(("hakhshara/" + TelAviv, (string?)null),
+ (s.PopulationLedger.Get(id).Assignment.Target, s.PopulationLedger.Get(id).Equipment.MilitaryId)));
+ Assert.Equal(housed, Statecraft.Sim.Cities.Housed(s, s.Cities[TelAviv]));
+ var 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()));
+ Assert.Equal(twin.NextId, s.NextId);
+ foreach (var id in picked)
+ {
+ var p = s.PopulationLedger.Get(id);
+ Assert.Equal((PopulationStatus.FreeCivilian, PopulationAssignmentKind.Unassigned, CivilianProfession.Pioneer, CivilianTier.Novice),
+ (p.Status, p.Assignment.Kind, p.Profession, p.Tier));
+ Assert.Equal((Region(c, TelAviv), (string?)null), (p.Location!.Region, p.Location.City));
+ }
+ Assert.Equal(housed - 2, Statecraft.Sim.Cities.Housed(s, s.Cities[TelAviv]));
+ s.PopulationLedger.Reconcile();
+ }
+
+ // Ruling 1, "Recruit+crews+halutz (Rec.)": craftsman is refused with a plain reason until #2476, before any other check of
+ // the facility, with the state unchanged.
+ [Fact]
+ public void CraftsmanTrackIsRefusedOnTheLedger()
+ {
+ var c = Gdd03();
+ var s = Dark(c);
+ var hash = s.Hash(); var why = new List<Cause>();
+ Assert.Equal("Craft training does not run on the population ledger yet (#2476)", Training.Start(c, s, TelAviv, "craftsman", 1, why));
+ Assert.Empty(why);
+ Assert.Equal(hash, s.Hash());
+ }
+
+ // Owner, 8 November 2026, Q3, "Refuse, with reason (Recommended)": a military trainee who already carries a military item
+ // is refused with a plain reason before any write, the state and the ledger unchanged. It was an error before the ruling.
+ [Fact]
+ public void ATraineeWhoCarriesAnItemIsRefusedWithAReason()
+ {
+ var c = Gdd03();
+ var s = Dark(c);
+ var first = Idle(s, TelAviv).First();
+ s.PopulationLedger.Replace(new PopulationUnit(first.Id, first.Status, first.ReceptionTicks, first.Location, first.Assignment,
+ first.Profession, first.Tier, first.WorkXp, first.Qualification, first.CombatXp, new PopulationEquipment(null, false, "carried", true),
+ first.Captor, first.Home));
+ var ledger = s.PopulationLedger.Canonical().ToList(); var hash = s.Hash(); var cities = Cities(s); var why = new List<Cause>();
+ Assert.Equal("A civilian without work in Tel Aviv already carries a military item", Training.Start(c, s, TelAviv, "recruit", 1, why));
+ Assert.Empty(why);
+ Assert.Empty(s.Cohorts);
+ Assert.Equal(ledger, s.PopulationLedger.Canonical());
+ Assert.Equal(hash, s.Hash()); Assert.Equal(cities, Cities(s));
+ }
+
+ // Owner, 8 November 2026, Q3, "Refuse, with reason (Recommended)": a farmer or craftsman on the halutz track is refused
+ // with a plain reason before any write, the state and the ledger unchanged. It was an error before the ruling.
+ [Theory]
+ [InlineData(CivilianProfession.Farmer)] [InlineData(CivilianProfession.Craftsman)]
+ public void AFarmerOrCraftsmanOnTheHalutzTrackIsRefusedWithAReason(CivilianProfession profession)
+ {
+ var c = Gdd03();
+ var s = Dark(c);
+ var first = Idle(s, TelAviv).First();
+ s.PopulationLedger.Replace(new PopulationUnit(first.Id, first.Status, first.ReceptionTicks, first.Location, first.Assignment,
+ profession, CivilianTier.Novice, 0, first.Qualification, first.CombatXp, first.Equipment, first.Captor, first.Home));
+ var count = Idle(s, TelAviv).Count;
+ var ledger = s.PopulationLedger.Canonical().ToList(); var hash = s.Hash(); var cities = Cities(s); var why = new List<Cause>();
+ Assert.Equal("A farmer or craftsman in Tel Aviv cannot train as a halutz", Training.Start(c, s, TelAviv, "halutz", count, why));
+ Assert.Empty(why);
+ Assert.Empty(s.Cohorts);
+ Assert.Equal(ledger, s.PopulationLedger.Canonical());
+ Assert.Equal(hash, s.Hash()); Assert.Equal(cities, Cities(s));
+ }
+
+ // Ruling 8, "Enforce it here (Rec.)": 50 records per camp city, over all military tracks; the 51st is refused, a crew
+ // counting as a recruit, with the state unchanged. The Hakhshara is not a camp.
+ [Fact]
+ public void TheCampCapRefusesTheFiftyFirstTrainee()
+ {
+ var c = Gdd03();
+ Assert.Equal(50, Gdd03MilitaryCatalogue.ReadCampCapacity(c.Gdd03Balance!));
+ var s = Dark(c);
+ Assert.True(Idle(s, TelAviv).Count > 60);
+ var why = new List<Cause>();
+ Assert.Null(Training.Start(c, s, TelAviv, "recruit", 49, why));
+ Assert.Equal("Tel Aviv's military camp has room for 1 more trainees (capacity 50)", Training.Start(c, s, TelAviv, "artillery", 2, why));
+ Assert.Null(Training.Start(c, s, TelAviv, "armoured_car", 1, why));
+ var hash = s.Hash(); var count = why.Count;
+ Assert.Equal("Tel Aviv's military camp has room for 0 more trainees (capacity 50)", Training.Start(c, s, TelAviv, "recruit", 1, why));
+ Assert.Equal(hash, s.Hash()); Assert.Equal(count, why.Count);
+ Assert.Null(Training.Start(c, s, TelAviv, "halutz", 1, why));
+ s.PopulationLedger.Reconcile();
+ }
+
+ // Ruling 3, "Unskilled first, keep (Rec.)": the training centre's teacher, a Haifa pioneer veteran, is taken last (the
+ // ruling on #1689: "Takeable, but last (Recommended)"), and keeps the profession dormant as a trainee. Haifa is given a
+ // Hakhshara here, which has no camp cap, so every idle record can be ordered.
+ [Fact]
+ public void TheHaifaTeacherIsTakenLast()
+ {
+ var c = Gdd03();
+ c.Cities.First(x => x.Id == HistoricalPopulation.TeacherCity).Facilities.Add("hakhshara");
+ var s = Dark(c);
+ var idle = Idle(s, HistoricalPopulation.TeacherCity);
+ var teacher = Assert.Single(idle, p => p.Profession == CivilianProfession.Pioneer);
+ Assert.Equal(teacher.Id, idle.Last().Id);
+ Assert.True(idle.Count > 1);
+ Assert.Null(Training.Start(c, s, HistoricalPopulation.TeacherCity, "halutz", idle.Count - 1, new List<Cause>()));
+ Assert.Equal(PopulationStatus.FreeCivilian, s.PopulationLedger.Get(teacher.Id).Status);
+ Assert.Null(Training.Start(c, s, HistoricalPopulation.TeacherCity, "halutz", 1, new List<Cause>()));
+ var p = s.PopulationLedger.Get(teacher.Id);
+ Assert.Equal((PopulationStatus.Trainee, CivilianProfession.Pioneer, CivilianTier.Veteran), (p.Status, p.Profession, p.Tier));
+ s.PopulationLedger.Reconcile();
+ }
+
+ // R-TRAIN-001: only free civilians without an assignment are idle. A field farmer (Work) and a refugee are not, so a
+ // count past the city's idle records is refused with that count.
+ [Fact]
+ public void RefugeesAndFarmersAreNotIdle()
+ {
+ var c = Gdd03();
+ var host = HistoricalPopulation.FieldFarmerHosts(c).First(h => c.Cities.Any(x => x.Id == h.Host)).Host;
+ c.Cities.First(x => x.Id == host).Facilities.Add("hakhshara");
+ var s = Dark(c);
+ Assert.Contains(s.PopulationLedger.Units, p => p.Location?.City == host && p.Assignment.Kind == PopulationAssignmentKind.Work);
+ var refugee = Idle(s, host).First();
+ s.PopulationLedger.Transition(refugee.Id, PopulationStatus.Refugee, refugee.Location, PopulationAssignment.Unassigned);
+ var idle = Idle(s, host).Count;
+ var name = PlayerText.Settlement(c, host);
+ var hash = s.Hash(); var why = new List<Cause>();
+ Assert.Equal(string.Format(Training.RefusedIdle, name, idle), Training.Start(c, s, host, "halutz", idle + 1, why));
+ Assert.Empty(why);
+ Assert.Equal(hash, s.Hash());
+ }
+
+ // Ruling 9, "Start + runtime bind (Rec.)": a camp built at a camp site (R-CAMP-001) has no Course target at Initialize;
+ // the first Train there binds it, all or nothing with the trainees.
+ [Fact]
+ public void ABuiltCampBindsItsCourseTargetAtRuntime()
+ {
+ var c = Gdd03();
+ var site = c.Sites.First(x => x.Kinds.Contains("military_camp") && x.City != "" && c.Cities.Any(k => k.Id == x.City && !k.Facilities.Contains("military_camp")));
+ var s = Dark(c);
+ var target = "military_camp/" + site.City;
+ Assert.True(Bound(s, "military_camp/" + TelAviv));
+ Assert.True(Bound(s, "hakhshara/" + TelAviv));
+ Assert.True(Bound(s, "military_camp/jerusalem"));
+ Assert.False(Bound(s, target));
+ s.Sites[site.Id] = new SiteWork(site.Id, null, 0, s.Date);
+ Assert.Null(Training.Start(c, s, site.City, "recruit", 1, new List<Cause>()));
+ Assert.True(Bound(s, target));
+ s.PopulationLedger.Reconcile();
+ }
+
+ // R-POP-002: only a ledger initialized with mode Historical is let through. An Open or synthetic ledger is still refused
+ // by all four, with the state unchanged.
+ [Theory]
+ [InlineData("start", true)] [InlineData("start", false)] [InlineData("cancel", true)] [InlineData("cancel", false)]
+ [InlineData("progress", true)] [InlineData("progress", false)] [InlineData("reinforce", true)] [InlineData("reinforce", false)]
+ public void AnOpenOrSyntheticLedgerIsStillRefused(string call, bool open)
+ {
+ var c = PopulationLedgerTests.Content();
+ var s = PopulationLedger.CreateFixture(c, PopulationLedgerTests.Bindings(),
+ new[] { new PopulationInventoryRow("fixture", 0, PopulationLedgerTests.Person()) }, mode: open ? Mode.Open : null);
+ Assert.Equal((true, false), (s.PopulationLedger.IsInitialized, s.PopulationLedger.IsHistorical));
+ var why = new List<Cause>();
+ var before = s.Describe(); var hash = s.Hash();
+ void Invoke()
+ {
+ switch (call)
+ {
+ case "start": Training.Start(c, s, "missing", "missing", 1, why); break;
+ case "cancel": Training.Cancel(c, s, 0, why); break;
+ case "progress": Training.Progress(c, s, why); break;
+ default: Training.Reinforce(c, s, 0, "missing", 1, why); break;
+ }
+ }
+ Assert.Contains("integration is held", Assert.Throws<NotSupportedException>(Invoke).Message);
+ Assert.Equal(before, s.Describe()); Assert.Equal(hash, s.Hash()); Assert.Empty(why);
+ }
+
+ // R-POP-003: the same orders on the same seed give the same ledger and state hash; Clone keeps the cohort's members, and a
+ // clone's run matches the original's.
+ [Fact]
+ public void SameSeedSameLedgerCanonicalAndStateHash()
+ {
+ var c = Gdd03();
+ GameState Run()
+ {
+ var s = Dark(c);
+ Assert.Null(Training.Start(c, s, TelAviv, "recruit", 3, new List<Cause>()));
+ Assert.Null(Training.Start(c, s, TelAviv, "halutz", 2, new List<Cause>()));
+ Training.Progress(c, s, new List<Cause>());
+ return s;
+ }
+ var a = Run(); var b = Run();
+ Assert.Equal(a.PopulationLedger.Canonical(), b.PopulationLedger.Canonical());
+ Assert.Equal(a.Hash(), b.Hash());
+ var clone = a.Clone();
+ Assert.Equal(a.Hash(), clone.Hash());
+ for (int t = 0; t < 4; t++) { Training.Progress(c, a, new List<Cause>()); Training.Progress(c, clone, new List<Cause>()); }
+ Assert.Equal(a.PopulationLedger.Canonical(), clone.PopulationLedger.Canonical());
+ Assert.Equal(a.Hash(), clone.Hash());
+ Assert.NotEqual(b.Hash(), a.Hash());
+ a.PopulationLedger.Reconcile();
+ }
+
+ // Ruling 6 for a crew, and ruling 5 at graduation (#1725 issuecomment-6724941867): an artillery or armoured car cohort
+ // ends as one new formation of its own type (R-UNIT-008), its records active soldiers serving formation/<unit id> with
+ // the type's class as their qualification and their issued item kept. The pooled rest of training_arms is used up, so
+ // the stock ends at the aggregate cost, as on the twin aggregate game.
+ [Theory]
+ [InlineData("artillery")] [InlineData("armoured_car")]
+ public void ACrewCohortGraduatesIntoOneNewFormationOfItsType(string track)
+ {
+ var c = Gdd03();
+ var s = Dark(c); var twin = Aggregate(c);
+ var type = c.UnitTypes.First(t => t.Id == track);
+ var per = type.TrainingArms!.Value;
+ var picked = Idle(s, TelAviv).Take(2).Select(p => p.Id).ToList();
+ Assert.Null(Training.Start(c, s, TelAviv, track, 2, new List<Cause>()));
+ Assert.Null(Training.Start(c, twin, TelAviv, track, 2, new List<Cause>()));
+ var cohort = OnlyCohort(s);
+ Assert.Equal(2 * (per - 1), s.Cohorts[cohort].Arms);
+ var unitId = s.NextId;
+ var why = new List<Cause>(); var twinWhy = new List<Cause>();
+ for (int i = 0; i < type.TrainingTurns; i++) { Training.Progress(c, s, why); Training.Progress(c, twin, twinWhy); }
+
+ Assert.Equal(Lines(twinWhy), Lines(why));
+ Assert.Empty(s.Cohorts);
+ var unit = Assert.Single(s.Units.Values, u => u.Id >= unitId);
+ Assert.Equal((unitId, track, 2), (unit.Id, unit.Type, unit.Strength));
+ Assert.Equal(twin.Units[unitId].Canonical(), unit.Canonical());
+ Assert.Equal(unitId + 1, s.NextId);
+ var target = "formation/" + unitId;
+ Assert.True(Bound(s, target));
+ foreach (var id in picked)
+ {
+ var p = s.PopulationLedger.Get(id);
+ Assert.Equal((PopulationStatus.ActiveSoldier, PopulationAssignmentKind.ActiveService, target, type.Class),
+ (p.Status, p.Assignment.Kind, p.Assignment.Target, p.Qualification));
+ Assert.Equal(("training/" + cohort + "/" + id, true), (p.Equipment.MilitaryId, p.Equipment.MilitaryPaid));
+ Assert.Equal((Region(c, TelAviv), (string?)null), (p.Location!.Region, p.Location.City));
+ }
+ Assert.Equal(2, s.PopulationLedger.Units.Count(p => p.Status == PopulationStatus.ActiveSoldier && p.Assignment.Target == target));
+ Assert.Equal(200 - 2 * per, s.Arms);
+ Assert.Equal(twin.Arms, s.Arms);
+ s.PopulationLedger.Reconcile();
+ }
+
+ // Ruling 9, "Start + runtime bind (Rec.)" (#1725 issuecomment-6724941867): the runtime bind is all or nothing. A target
+ // id already bound is refused, and a Commit with one invalid record and one new target changes neither; the ledger's
+ // canonical text, the state and its hash are unchanged.
+ [Fact]
+ public void ARefusedBindTargetLeavesTheLedgerUnchanged()
+ {
+ var c = Gdd03();
+ var s = Dark(c);
+ var ledger = s.PopulationLedger.Canonical().ToList(); var before = s.Describe(); var hash = s.Hash();
+ var bound = "military_camp/" + TelAviv;
+ Assert.True(Bound(s, bound));
+
+ Assert.ThrowsAny<ArgumentException>(() => s.PopulationLedger.BindTarget(
+ new PopulationTarget(bound, PopulationAssignmentKind.Course, Region(c, TelAviv), 0)));
+
+ Assert.Equal(ledger, s.PopulationLedger.Canonical());
+ Assert.Equal(before, s.Describe()); Assert.Equal(hash, s.Hash());
+ s.PopulationLedger.Reconcile();
+ }
+
+ [Fact]
+ public void ARefusedCommitLeavesTheRecordsAndBindingsUnchanged()
+ {
+ var c = Gdd03();
+ var s = Dark(c);
+ var ledger = s.PopulationLedger.Canonical().ToList(); var before = s.Describe(); var hash = s.Hash();
+ var p = Idle(s, TelAviv).First();
+ var invalid = new PopulationUnit(p.Id, p.Status, p.ReceptionTicks, p.Location, p.Assignment, p.Profession, p.Tier, p.WorkXp,
+ "no_such_class", p.CombatXp, p.Equipment, p.Captor, p.Home);
+ var fresh = "formation/999999";
+ Assert.False(Bound(s, fresh));
+
+ Assert.ThrowsAny<ArgumentException>(() => s.PopulationLedger.Commit(new[] { invalid },
+ new[] { new PopulationTarget(fresh, PopulationAssignmentKind.ActiveService, Region(c, TelAviv)) }));
+
+ Assert.False(Bound(s, fresh));
+ Assert.Equal(p.Qualification, s.PopulationLedger.Get(p.Id).Qualification);
+ Assert.Equal(ledger, s.PopulationLedger.Canonical());
+ Assert.Equal(before, s.Describe()); Assert.Equal(hash, s.Hash());
+ s.PopulationLedger.Reconcile();
+ }
+}
diff --git a/sim/Statecraft.Sim/GddState.cs b/sim/Statecraft.Sim/GddState.cs
index 0151bee2f..2190f7057 100644
--- a/sim/Statecraft.Sim/GddState.cs
+++ b/sim/Statecraft.Sim/GddState.cs
@@ -238,17 +238,32 @@ namespace Statecraft.Sim
/// <summary>The formation these replacements join when they finish (R-TRAIN-004), or null for a cohort that becomes
/// something new (R-TRAIN-003).</summary>
public int? Unit { get; }
+ /// <summary>#1725 PR 7, producer 12 (owner, 8 November 2026, "Cohorts stay main (Rec.)" (#1725 issuecomment-6724941867): the cohort keeps a
+ /// sorted list of its members' ids, hashed only when set): on a Historical ledger game, the population ids of the cohort's trainee
+ /// records, ascending, one per <see cref="Count"/>; null on any other game.</summary>
+ public IReadOnlyList<int>? Members { get; }
- public Cohort(int id, string type, string city, int count, int turnsLeft, int arms = 0, int? unit = null) { Id = id; Type = type; City = city; Count = count; TurnsLeft = turnsLeft; Arms = arms; Unit = unit; }
+ public Cohort(int id, string type, string city, int count, int turnsLeft, int arms = 0, int? unit = null, IEnumerable<int>? members = null)
+ {
+ Id = id; Type = type; City = city; Count = count; TurnsLeft = turnsLeft; Arms = arms; Unit = unit;
+ if (members != null)
+ {
+ var sorted = members.OrderBy(x => x).ToArray();
+ if (sorted.Length != count || sorted.Distinct().Count() != sorted.Length)
+ throw new ArgumentException("A cohort's members are its count of distinct population ids.", nameof(members));
+ Members = Array.AsReadOnly(sorted);
+ }
+ }
/// <summary>The same cohort with <paramref name="turnsLeft"/> turns to go.</summary>
- public Cohort WithTurnsLeft(int turnsLeft) => new Cohort(Id, Type, City, Count, turnsLeft, Arms, Unit);
+ public Cohort WithTurnsLeft(int turnsLeft) => new Cohort(Id, Type, City, Count, turnsLeft, Arms, Unit, Members);
- /// <summary>The record as the state hash writes it. Arms only when the cohort holds some, and the target unit only when
- /// it has one, so other cohorts hash as before.</summary>
+ /// <summary>The record as the state hash writes it. Arms only when the cohort holds some, the target unit only when
+ /// it has one, and the members only when set, so other cohorts hash as before.</summary>
public string Canonical() => string.Format(CultureInfo.InvariantCulture, "{0}:{1}@{2}x{3}/{4}", Id, Type, City, Count, TurnsLeft)
+ (Arms == 0 ? "" : "|arms=" + Arms.ToString(CultureInfo.InvariantCulture))
- + (Unit is int u ? "|unit=" + u.ToString(CultureInfo.InvariantCulture) : "");
+ + (Unit is int u ? "|unit=" + u.ToString(CultureInfo.InvariantCulture) : "")
+ + (Members == null ? "" : "|members=" + string.Join(",", Members.Select(m => m.ToString(CultureInfo.InvariantCulture))));
}
/// <summary>Pioneer work at a designated site (sites.yaml; R-SITE-001 to R-SITE-003): <see cref="Unit"/> building it with
diff --git a/sim/Statecraft.Sim/HistoricalPopulation.cs b/sim/Statecraft.Sim/HistoricalPopulation.cs
index 03fb77aa4..60b82bb46 100644
--- a/sim/Statecraft.Sim/HistoricalPopulation.cs
+++ b/sim/Statecraft.Sim/HistoricalPopulation.cs
@@ -208,13 +208,18 @@ namespace Statecraft.Sim
var targets = regions.Where(x => x.Key.StartsWith(FormationPrefix, StringComparison.Ordinal))
.Select(x => new PopulationTarget(x.Key, PopulationAssignmentKind.ActiveService, x.Value))
// A field is its farmer's Work target in the field's region (Gdd03FieldFixture.Targets' ids, field/q,r).
- .Concat(farmer.Select(x => new PopulationTarget(x.Value.Field, PopulationAssignmentKind.Work, regions[x.Key])));
+ .Concat(farmer.Select(x => new PopulationTarget(x.Value.Field, PopulationAssignmentKind.Work, regions[x.Key])))
+ // #1725 PR 7, producer 12. Owner, 8 November 2026 (#1725 issuecomment-6724941867), "Start + runtime bind (Rec.)": the start
+ // facilities' Course targets are bound at the start; and "Cohorts stay main (Rec.)": each trainee's Course
+ // target is per facility (military_camp/<city>, hakhshara/<city>), in the city's region (27M-7, no travel).
+ .Concat(c.Cities.Where(x => regions.ContainsKey(CensusPrefix + x.Id))
+ .SelectMany(x => Training.LedgerFacilities(c, x.Facilities).Select(f => Training.CourseTargetOf(c, f, x.Id, regions[CensusPrefix + x.Id]))));
// #1689 rows 5 to 8 and the 7th Brigade's combat XP: see SoldierValues.
var soldier = new Dictionary<string, (string Qualification, int CombatXp)>(StringComparer.Ordinal);
foreach (var f in c.StartingForces.Where(Bound)) soldier[FormationPrefix + f.Row] = SoldierValues(c, f);
var bindings = new PopulationBindings(locations.Values.Concat(placed.Values.Where(l => l.City != null)
.GroupBy(l => l.Canonical(), StringComparer.Ordinal).Select(g => g.First())), targets,
- Array.Empty<string>(), soldier.Values.Select(x => x.Qualification).Distinct(StringComparer.Ordinal));
+ Array.Empty<string>(), soldier.Values.Select(x => x.Qualification).Concat(Training.TrainedClasses(c)).Distinct(StringComparer.Ordinal));
// reception.turns is the reception before free-civilian status (docs/gdd/balance.md:91), so a census free civilian
// starts with it done: R-VET-001 gives work XP only to a received free civilian. Soldiers keep 0 (not ruled).
var received = c.RequirePopulationInteger("reception.turns");
diff --git a/sim/Statecraft.Sim/PopulationLedger.cs b/sim/Statecraft.Sim/PopulationLedger.cs
index 5cbd7e893..db88db9a7 100644
--- a/sim/Statecraft.Sim/PopulationLedger.cs
+++ b/sim/Statecraft.Sim/PopulationLedger.cs
@@ -89,6 +89,13 @@ namespace Statecraft.Sim
+ " is neither a census city of cities.yaml nor a field host in regions.yaml (R-POP-002).");
}
}
+ /// <summary>#1725 PR 7, producer 12 (owner, 8 November 2026: "Start + runtime bind (Rec.)"): these bindings plus
+ /// <paramref name="added"/>, a new instance (bindings stay immutable). The constructor's checks apply: a target id
+ /// already bound, or a target whose region has no bound location, is refused.</summary>
+ internal PopulationBindings WithTargets(IEnumerable<PopulationTarget> added) =>
+ new PopulationBindings(locations, targets.Values.Concat(added), captors, qualifications);
+ /// <summary>The bound target <paramref name="id"/>, or null.</summary>
+ internal PopulationTarget? FindTarget(string id) => targets.TryGetValue(id, out var t) ? t : null;
internal bool HasCaptor(string captor) => captors.Contains(captor);
internal bool HasQualification(string qualification) => qualification == "" || qualifications.Contains(qualification);
internal IEnumerable<string> Canonical()
@@ -263,6 +270,30 @@ namespace Statecraft.Sim
RegisterArrivals(rows);
NaturalIncreaseCarry = carry; NaturalIncreaseRecords = records;
}
+ /// <summary>The bound target <paramref name="id"/>, or null (#1725 PR 7, producer 12).</summary>
+ internal PopulationTarget? Target(string id) { RequireInitialized(); return bindings!.FindTarget(id); }
+ /// <summary>#1725 PR 7, producer 12. Owner, 8 November 2026, "Start + runtime bind (Rec.)" (#1725 issuecomment-6724941867): the start
+ /// facilities' Course targets are bound at the start, plus one all-or-nothing runtime bind for new formations and
+ /// built camps. Binds <paramref name="target"/>, refusing an id already bound, with the ledger unchanged.</summary>
+ internal void BindTarget(PopulationTarget target) => Commit(Array.Empty<PopulationUnit>(), new[] { target });
+ /// <summary>#1725 PR 7, producer 12: several record replacements and new targets, all or nothing. The new bindings and
+ /// every replaced record are validated as one candidate before anything is committed, so a refused record or target
+ /// changes neither the records nor the bindings. Each record is replaced at most once, and must exist.</summary>
+ internal void Commit(IReadOnlyCollection<PopulationUnit> replacements, IReadOnlyCollection<PopulationTarget> bind)
+ {
+ RequireInitialized();
+ var b = bind.Count == 0 ? bindings! : bindings!.WithTargets(bind);
+ var candidate = new SortedDictionary<int, PopulationUnit>(units);
+ var seen = new HashSet<int>();
+ foreach (var r in replacements)
+ {
+ Get(r.Id);
+ if (!seen.Add(r.Id)) throw new ArgumentException("A record is replaced at most once in a commit.");
+ candidate[r.Id] = r;
+ }
+ Validate(candidate, b);
+ units = candidate; bindings = b;
+ }
public void RegisterCombatLoss(int id, string source)
{
RequireInitialized(); Get(id);
@@ -271,12 +302,13 @@ namespace Statecraft.Sim
var candidate = new SortedDictionary<int, PopulationUnit>(units); candidate.Remove(id);
Validate(candidate); units = candidate; losses.Add(id, source);
}
- void Validate(SortedDictionary<int, PopulationUnit> candidate)
+ void Validate(SortedDictionary<int, PopulationUnit> candidate) => Validate(candidate, bindings!);
+ void Validate(SortedDictionary<int, PopulationUnit> candidate, PopulationBindings bindings)
{
var issued = new HashSet<string>(StringComparer.Ordinal);
foreach (var p in candidate.Values)
{
- if (p.ReceptionTicks > receptionLimit || !bindings!.HasQualification(p.Qualification))
+ if (p.ReceptionTicks > receptionLimit || !bindings.HasQualification(p.Qualification))
throw new ArgumentException("Invalid reception progress or qualification.");
var tierValid = p.Profession switch {
CivilianProfession.None => p.Tier == CivilianTier.None && p.WorkXp == 0,
diff --git a/sim/Statecraft.Sim/Training.cs b/sim/Statecraft.Sim/Training.cs
index 38c491e4e..0dd0d9007 100644
--- a/sim/Statecraft.Sim/Training.cs
+++ b/sim/Statecraft.Sim/Training.cs
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
+using System.Globalization;
using System.Linq;
namespace Statecraft.Sim
@@ -42,6 +43,20 @@ namespace Statecraft.Sim
public const string RefusedIdle = "{0} has {1} civilians without work";
public const string RefusedArms = "{0}: not enough Arms for {1} (need {2}, have {3})";
+ // #1725 PR 7, producer 12: the refusals only a Historical ledger game gives. Internal, not Refused* constants: no
+ // player reaches them yet (Simulation.Step still refuses a ledger game, R-POP-002), and the UI strings follow when it
+ // does.
+ /// <summary>Owner, 8 November 2026, "Recruit+crews+halutz (Rec.)" (#1725 issuecomment-6724941867): the craftsman track is refused with a plain reason until #2476.</summary>
+ internal const string LedgerRefusedCraftsman = "Craft training does not run on the population ledger yet (#2476)";
+ /// <summary>Owner, 8 November 2026, "Enforce it here (Rec.)" (#1725 issuecomment-6724941867): the camp capacity, 50 records per camp city, over all military tracks.</summary>
+ internal const string LedgerRefusedCampFull = "{0}'s military camp has room for {1} more trainees (capacity {2})";
+ /// <summary>Owner, 8 November 2026, "Full minus strength (Rec.)" (#1725 issuecomment-6724941867): a formation whose strength differs from its serving records is refused.</summary>
+ internal const string LedgerRefusedStrength = "Unit {0} has {1} soldiers on record but strength {2}";
+ /// <summary>Owner, 8 November 2026, Q3, "Refuse, with reason (Recommended)": a military trainee who already carries a military item.</summary>
+ internal const string LedgerRefusedCarried = "A civilian without work in {0} already carries a military item";
+ /// <summary>Owner, 8 November 2026, Q3, "Refuse, with reason (Recommended)": a farmer or craftsman on the halutz track.</summary>
+ internal const string LedgerRefusedHalutzTrade = "A farmer or craftsman in {0} cannot train as a halutz";
+
static string Refused(string format, params object[] values) => string.Format(System.Globalization.CultureInfo.InvariantCulture, format, values);
/// <summary>The course a type trains in, in text the player reads: the facility's, or the guns' or the armoured cars' own
@@ -110,7 +125,8 @@ namespace Statecraft.Sim
/// <paramref name="track"/>, a unit type with a facility. The Treasury pays count * training_cost now and borrows what it
/// lacks. The trainees leave the civilians at once, and the cohort takes the next id. Refused, state untouched, when the
/// city or track is unknown, the count is below 1, the city has no such facility (<see cref="HasFacility"/>), or it has fewer civilians without
- /// work. Step has already refused it in the legacy loop.</summary>
+ /// work. Step has already refused it in the legacy loop. On a Historical ledger game the trainees are records
+ /// (<see cref="LedgerStart"/>, #1725 PR 7).</summary>
public static string? Start(Content c, GameState s, string city, string track, int count, List<Cause> why) => Start(c, s, city, track, count, why, null);
/// <summary>R-TRAIN-004 (#1510; owner, 23 October 2026: "Replacements cost Arms" and "Default (Recommended)"):
@@ -122,7 +138,7 @@ namespace Statecraft.Sim
/// its strength and the replacements already training for it.</summary>
public static string? Reinforce(Content c, GameState s, int unit, string city, int count, List<Cause> why)
{
- PopulationLedger.RefuseAggregate(s);
+ PopulationLedger.RefuseUnlessHistorical(s); // #1725 PR 7: on a Historical ledger the replacements are records
if (!s.Units.TryGetValue(unit, out var u)) return Orders.RefusedNoUnit;
if (u.Side == "") return Orders.RefusedNotMilitary;
if (u.Side != Movement.PlayerSide) return Orders.RefusedNotYours;
@@ -132,6 +148,13 @@ namespace Statecraft.Sim
var type = c.UnitTypes.First(t => t.Id == u.Type);
var course = c.UnitTypes.FirstOrDefault(t => t.Side == type.Side && t.Class == type.Class && t.Facility != "");
if (course == null) return Refused(RefusedNoCourse, unit);
+ if (s.PopulationLedger.IsHistorical)
+ {
+ // Owner, 8 November 2026, "Full minus strength (Rec.)" (#1725 issuecomment-6724941867): the Reinforce room is Unit.Full minus
+ // Strength minus training, and a formation whose strength differs from its serving records is refused.
+ var serving = Serving(s, FormationTarget(c, u.Id));
+ if (serving != u.Strength) return Refused(LedgerRefusedStrength, unit, serving, u.Strength);
+ }
var room = Room(s, u);
if (room <= 0) return Refused(RefusedNoLosses, unit);
if (count > room) return Refused(room == 1 ? RefusedRoomOne : RefusedRoomMany, unit, room);
@@ -146,13 +169,15 @@ namespace Statecraft.Sim
static string? Start(Content c, GameState s, string city, string track, int count, List<Cause> why, int? unit)
{
- PopulationLedger.RefuseAggregate(s);
+ PopulationLedger.RefuseUnlessHistorical(s); // #1725 PR 7: on a Historical ledger the trainees are records
if (!s.Cities.TryGetValue(city, out var x)) return RefusedNoCity;
var type = c.UnitTypes.FirstOrDefault(t => t.Id == track && t.Facility != "");
if (type == null) return RefusedNoTraining;
if (count < 1) return RefusedCount;
+ if (s.PopulationLedger.IsHistorical && type.Id == Craftsman) return LedgerRefusedCraftsman;
var name = PlayerText.Settlement(c, city);
if (!HasFacility(c, s, city, type.Facility)) return Refused(type.Facility == "military_camp" ? RefusedNoCamp : type.Facility == Industry ? RefusedNoIndustry : RefusedNoHakhshara, name);
+ if (s.PopulationLedger.IsHistorical) return LedgerStart(c, s, city, type, count, why, unit, name);
var idle = Idle(s, x);
if (count > idle) return Refused(RefusedIdle, name, idle);
// R-ARMS-003 (D-G6, Q-UNIT-3): a recruit group takes arms_per_recruit_group Arms when its training starts, a gun or
@@ -160,20 +185,29 @@ namespace Statecraft.Sim
// training takes none. The cohort keeps the count, and cancelling (R-TRAIN-002) returns it.
var arms = type.Id == "recruit" ? (long)count * c.RulesAt(s.Date).Mvp!.ArmsPerRecruitGroup!.Value : (long)count * (type.TrainingArms ?? 0);
if (arms > s.Arms) return Refused(RefusedArms, name, Course(type), arms, s.Arms);
- var cost = count * type.TrainingCost;
- // Owner decision "Allow borrowing" (2026-10-15, #468 question 1): a short Treasury borrows, as map actions do.
- EconomySystem.PayOrBorrow(c, s, cost, "for training", why, CauseKeys.Purpose.Training);
// R-HOUSE-003: trainees remain housed as a cohort, and recruits keep their home city's housing as formations.
// A pioneer unit leaves city housing; a craftsman remains. The employed share also reads the new counts.
// R-QUAL-006: the trainees are taken from the unqualified civilians first; a qualified one taken loses its
// qualification, which is part of the civilians that remain.
var lost = Math.Max(0, x.Qualified.Total - (x.Civilians - count));
s.Cities[city] = x.WithCounts(x.Civilians - count, x.Employed, x.Refugees).WithQualified(lost == 0 ? x.Qualified : x.Qualified.Lose(lost));
+ Open(c, s, city, name, type, count, arms, (int)arms, unit, null, why);
+ return null;
+ }
+
+ /// <summary><see cref="Start"/>'s last part, every check passed, on either path: the Treasury pays count *
+ /// training_cost, the cohort opens with the next id, holding <paramref name="pooled"/> of the <paramref name="arms"/>
+ /// its training takes from the stock, and the Why lines are written.</summary>
+ static void Open(Content c, GameState s, string city, string name, UnitType type, int count, long arms, int pooled, int? unit, IEnumerable<int>? members, List<Cause> why)
+ {
+ var cost = count * type.TrainingCost;
+ // Owner decision "Allow borrowing" (2026-10-15, #468 question 1): a short Treasury borrows, as map actions do.
+ EconomySystem.PayOrBorrow(c, s, cost, "for training", why, CauseKeys.Purpose.Training);
var id = s.NextId++;
// The plan's reading of D-A6, not part of the owner's ruling: the turn of the order is the first training turn, so
// with training_turns 3 an order on turn T is done at the end of T+2 (TrainingTests.ACohortOrderedOnTurnTWithThreeTurnsFinishesAtTheEndOfTurnTPlusTwo). For "done at the end of
// T+3", open the cohort with type.TrainingTurns + 1 here; nothing else changes.
- s.Cohorts.Add(id, new Cohort(id, type.Id, city, count, type.TrainingTurns, (int)arms, unit));
+ s.Cohorts.Add(id, new Cohort(id, type.Id, city, count, type.TrainingTurns, pooled, unit, members));
var aim = unit is int target ? FormattableString.Invariant($" as replacements for unit {target}") : "";
why.Add(new Cause("city", city, -count, $"{name}: {Groups(count)} began {Course(type)}{aim}, cost {PlayerText.Money(c, "treasury", cost)}", key: CauseKeys.TrainingStarted, args: new[] { CauseKeys.Number(count), CourseId(type), unit.HasValue ? CauseKeys.Number(unit.Value) : "", CauseKeys.Number(cost) }));
if (arms > 0)
@@ -181,38 +215,55 @@ namespace Statecraft.Sim
s.Arms -= (int)arms;
why.Add(new Cause("city", "arms", -arms, FormattableString.Invariant($"{name}: {Course(type)} took {arms} Arms"), key: CauseKeys.TrainingArms, args: new[] { city, CourseId(type) }));
}
- return null;
}
/// <summary>R-TRAIN-002 (D-A3): the cohort's people return to its city as civilians without work, and the Money spent is
/// not returned. The Arms its training took go back to the pool (R-ARMS-003; owner, #1047: "Refund on cancel"). Refused,
/// state untouched, for a cohort that does not exist, including one that has finished. Step has already refused it in
- /// the legacy loop.</summary>
+ /// the legacy loop. On a Historical ledger game the cohort's records are released (<see cref="Release"/>, #1725 PR 7).</summary>
public static string? Cancel(Content c, GameState s, int cohort, List<Cause> why)
{
- PopulationLedger.RefuseAggregate(s);
+ PopulationLedger.RefuseUnlessHistorical(s); // #1725 PR 7: on a Historical ledger the cohort's records go back
if (!s.Cohorts.TryGetValue(cohort, out var k)) return RefusedNoCohort;
+ if (s.PopulationLedger.IsHistorical)
+ {
+ var (released, issued) = Release(s, k);
+ s.PopulationLedger.Commit(released, Array.Empty<PopulationTarget>());
+ Cancelled(c, s, k, issued, why);
+ return null;
+ }
var x = s.Cities[k.City];
s.Cities[k.City] = x.WithCounts(x.Civilians + k.Count, x.Employed, x.Refugees);
- s.Cohorts.Remove(cohort);
+ Cancelled(c, s, k, 0, why);
+ return null;
+ }
+
+ /// <summary><see cref="Cancel"/>'s state part on either path: the cohort leaves, with its Why lines, and its Arms (the
+ /// <paramref name="issued"/> items a ledger course issued plus the cohort's own Arms) go back to the stock. The Money
+ /// is not refunded.</summary>
+ static void Cancelled(Content c, GameState s, Cohort k, int issued, List<Cause> why)
+ {
+ s.Cohorts.Remove(k.Id);
var type = c.UnitTypes.First(t => t.Id == k.Type);
why.Add(new Cause("city", k.City, k.Count,
$"{PlayerText.Settlement(c, k.City)}: {Groups(k.Count)} left {Course(type)}; the Money spent is not returned", key: CauseKeys.TrainingCancelled, args: new[] { CauseKeys.Number(k.Count), CourseId(type) }));
- if (k.Arms > 0)
+ var arms = (long)issued + k.Arms;
+ if (arms > 0)
{
- var back = (int)Math.Min(k.Arms, (long)int.MaxValue - s.Arms); // the stock stops at int.MaxValue, as an event or a purchase leaves it
+ var back = (int)Math.Min(arms, (long)int.MaxValue - s.Arms); // the stock stops at int.MaxValue, as an event or a purchase leaves it
s.Arms += back;
why.Add(new Cause("city", "arms", back, FormattableString.Invariant($"{PlayerText.Settlement(c, k.City)}: {Course(type)} returned {back} Arms"), key: CauseKeys.TrainingArmsReturned, args: new[] { k.City, CourseId(type) }));
}
- return null;
}
/// <summary>R-TRAIN-003, step 4 of the turn (spec 2026-10-12 section 2.3, D-A6): in ascending id, each cohort has one turn
/// less to go. One that reaches 0 leaves the state: a recruit, gun or armoured car cohort becomes one military formation
- /// of its type with its count as strength (R-UNIT-003, R-UNIT-008), craftsmen join the city's count, and halutzim become one unit per group at its hex.</summary>
+ /// of its type with its count as strength (R-UNIT-003, R-UNIT-008), craftsmen join the city's count, and halutzim become one unit per group at its hex. On a Historical ledger game the
+ /// records change too (<see cref="LedgerProgress"/>, #1725 PR 7).</summary>
public static void Progress(Content c, GameState s, List<Cause> why)
{
- PopulationLedger.RefuseAggregate(s);
+ PopulationLedger.RefuseUnlessHistorical(s); // #1725 PR 7: on a Historical ledger the cohorts' records progress
+ if (s.PopulationLedger.IsHistorical) { LedgerProgress(c, s, why); return; }
foreach (var k in s.Cohorts.Values.ToList())
{
// R-TRAIN-004 (owner, 23 October 2026, "Default"): replacements whose unit is gone (destroyed, captured, sent
@@ -223,7 +274,7 @@ namespace Statecraft.Sim
var at = c.SettlementHexes.First(h => h.Id == k.City);
if (!s.Units.TryGetValue(aim, out target) || (target.Q, target.R) != (at.Q, at.R))
{
- why.Add(new Cause("city", k.City, 0, FormattableString.Invariant($"{PlayerText.Settlement(c, k.City)}: unit {aim} is no longer in {PlayerText.Settlement(c, k.City)}, so its replacements stop training"), key: CauseKeys.ReplacementsStopped, args: new[] { CauseKeys.Number(aim) }));
+ why.Add(Stopped(c, k, aim));
Cancel(c, s, k.Id, why);
continue;
}
@@ -232,26 +283,13 @@ namespace Statecraft.Sim
s.Cohorts.Remove(k.Id);
var type = c.UnitTypes.First(t => t.Id == k.Type);
var name = PlayerText.Settlement(c, k.City);
- if (target != null)
- {
- // The unit keeps its type, service and order (a veteran stays one); full again, it forgets its Full.
- 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);
- 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) }));
- }
- else if (type.Side != "")
- {
- var hex = c.SettlementHexes.First(h => h.Id == k.City);
- var id = s.NextId++;
- s.Units.Add(id, new Unit(id, type.Id, hex.Q, hex.R, side: type.Side, strength: k.Count, homeCity: k.City));
- why.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" }));
- }
+ if (target != null) Joined(c, s, k, type, name, target.Id, why);
+ else if (type.Side != "") Formed(c, s, k, type, name, s.NextId++, why);
else if (type.Kind == "unit")
{
- var hex = c.SettlementHexes.First(h => h.Id == k.City); // every settlement has one (ValidateMap)
- for (int i = 0; i < k.Count; i++) { var id = s.NextId++; s.Units.Add(id, new Unit(id, type.Id, hex.Q, hex.R)); }
- 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) }));
+ var first = s.NextId;
+ s.NextId += k.Count;
+ Halutzim(c, s, k, type, name, first, why);
}
else if (type.Id == Craftsman)
{
@@ -261,5 +299,259 @@ namespace Statecraft.Sim
}
}
}
+
+ /// <summary>R-TRAIN-004: the line for replacements whose unit <paramref name="aim"/> is gone or off the city's hex.</summary>
+ static Cause Stopped(Content c, Cohort k, int aim) => new Cause("city", k.City, 0, FormattableString.Invariant($"{PlayerText.Settlement(c, k.City)}: unit {aim} is no longer in {PlayerText.Settlement(c, k.City)}, so its replacements stop training"), key: CauseKeys.ReplacementsStopped, args: new[] { CauseKeys.Number(aim) });
+
+ /// <summary>R-TRAIN-004: finished replacements join map unit <paramref name="unit"/>.</summary>
+ static void Joined(Content c, GameState s, Cohort k, UnitType type, string name, int unit, List<Cause> why)
+ {
+ // The unit keeps its type, service and order (a veteran stays one); full again, it forgets its Full.
+ var 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);
+ 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) }));
+ }
+
+ /// <summary>R-UNIT-003, R-UNIT-008: a finished recruit, gun or armoured car cohort is map unit <paramref name="id"/>.</summary>
+ static void Formed(Content c, GameState s, Cohort k, UnitType type, string name, int id, List<Cause> why)
+ {
+ var hex = c.SettlementHexes.First(h => h.Id == k.City);
+ s.Units.Add(id, new Unit(id, type.Id, hex.Q, hex.R, side: type.Side, strength: k.Count, homeCity: k.City));
+ why.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)
+ {
+ 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));
+ 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) }));
+ }
+
+ // ---- #1725 PR 7, producer 12: training on a Historical ledger game (the dark start, R-POP-002) ----
+
+ /// <summary>The source of a ledger trainee's issued military item: this prefix, the cohort id and the population id
+ /// (<c>training/&lt;cohort&gt;/&lt;id&gt;</c>). It is disjoint from the census, units_1948, field and basic_training
+ /// prefixes, and names the course that issued it, so a cancel returns only that course's items (R-ARMS-003).</summary>
+ internal const string IssuedPrefix = "training/";
+
+ /// <summary>The ActiveService target of a formation a cohort becomes at graduation: this prefix and the map unit id
+ /// (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).</summary>
+ internal const string FormationPrefix = "formation/";
+
+ static string IssuedId(int cohort, int id) => IssuedPrefix + cohort.ToString(CultureInfo.InvariantCulture) + "/" + id.ToString(CultureInfo.InvariantCulture);
+
+ /// <summary>A track that runs on the ledger: every trained type but the craftsman (owner, 8 November 2026,
+ /// "Recruit+crews+halutz (Rec.)" (#1725 issuecomment-6724941867): the recruit, crew and halutz tracks run, and the craftsman track is
+ /// refused with a plain reason until #2476).</summary>
+ static bool RunsOnLedger(UnitType t) => t.Facility != "" && t.Id != Craftsman;
+
+ /// <summary>The facilities of <paramref name="facilities"/> some ledger track trains at, in ordinal order, each once.</summary>
+ internal static IEnumerable<string> LedgerFacilities(Content c, IEnumerable<string> facilities) => facilities
+ .Where(f => c.UnitTypes.Any(t => RunsOnLedger(t) && t.Facility == f)).Distinct(StringComparer.Ordinal).OrderBy(f => f, StringComparer.Ordinal);
+
+ /// <summary>Owner, 8 November 2026, "Cohorts stay main (Rec.)" (#1725 issuecomment-6724941867): each trainee's Course target is per
+ /// facility (military_camp/&lt;city&gt;, hakhshara/&lt;city&gt;).</summary>
+ internal static string CourseTarget(string facility, string city) => facility + "/" + city;
+
+ /// <summary><see cref="CourseTarget"/> as a ledger binding in <paramref name="region"/>, the city's. Its progress limit
+ /// is the longest training_turns of the ledger tracks at that facility, so no record's course ticks can pass it.</summary>
+ internal static PopulationTarget CourseTargetOf(Content c, string facility, string city, string region) =>
+ new PopulationTarget(CourseTarget(facility, city), PopulationAssignmentKind.Course, region,
+ c.UnitTypes.Where(t => RunsOnLedger(t) && t.Facility == facility).Max(t => t.TrainingTurns));
+
+ /// <summary>The unit_types.yaml classes of the military tracks (recruit, the gun and armoured car crews): a graduate's
+ /// military qualification, as the opening soldiers' is their formation type's class (#1689), so the ledger binds them
+ /// at Initialize (owner, 8 November 2026, "Start + runtime bind (Rec.)").</summary>
+ internal static IEnumerable<string> TrainedClasses(Content c) => c.UnitTypes
+ .Where(t => RunsOnLedger(t) && t.Side != "" && !string.IsNullOrWhiteSpace(t.Class)).Select(t => t.Class).Distinct(StringComparer.Ordinal);
+
+ /// <summary>The ActiveService target of map unit <paramref name="unit"/>: a starting force's own (unit id i is
+ /// <c>c.StartingForces[i]</c>, StartingForces.Init; R-POP-004), else the one bound at its graduation.</summary>
+ static string FormationTarget(Content c, int unit) => unit >= 0 && unit < c.StartingForces.Count
+ ? HistoricalPopulation.FormationPrefix + c.StartingForces[unit].Row
+ : FormationPrefix + unit.ToString(CultureInfo.InvariantCulture);
+
+ static int Serving(GameState s, string target) => s.PopulationLedger.Units.Count(p =>
+ p.Status == PopulationStatus.ActiveSoldier && string.Equals(p.Assignment.Target, target, StringComparison.Ordinal));
+
+ static string CityRegion(Content c, string city) => c.PlayerRegions.AtLocation(city)?.Id
+ ?? throw new InvalidOperationException("No region in regions.yaml for " + city + " (R-POP-004).");
+
+ /// <summary>R-TRAIN-001 and R-QUAL-006 on the ledger: the city's free-civilian records without an assignment, located in
+ /// the city. Owner, 8 November 2026, "Unskilled first, keep (Rec.)" (#1725 issuecomment-6724941867): civilians with no profession first, then
+ /// the qualified, each in ascending id. A refugee, a worker, a farmer on a field and a teaching teacher are not idle.</summary>
+ static List<PopulationUnit> LedgerIdle(GameState s, string city) => s.PopulationLedger.Units
+ .Where(p => p.Status == PopulationStatus.FreeCivilian && p.Assignment.Kind == PopulationAssignmentKind.Unassigned
+ && string.Equals(p.Location?.City, city, StringComparison.Ordinal))
+ .OrderBy(p => p.Profession == CivilianProfession.None ? 0 : 1).ThenBy(p => p.Id).ToList();
+
+ /// <summary>R-TRAIN-001, R-TRAIN-004, R-ARMS-003 and R-QUAL-006 on the ledger, after <see cref="Start"/>'s city, track,
+ /// count and facility checks. Then the idle records (<see cref="LedgerIdle"/>), the camp's capacity and the Arms are
+ /// checked, all before the first write. The first <paramref name="count"/> idle records become trainees on the
+ /// 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>
+ static string? LedgerStart(Content c, GameState s, string city, UnitType type, int count, List<Cause> why, int? unit, string name)
+ {
+ var ledger = s.PopulationLedger;
+ var idle = LedgerIdle(s, city);
+ if (count > idle.Count) return Refused(RefusedIdle, name, idle.Count);
+ var target = CourseTarget(type.Facility, city);
+ if (type.Facility == "military_camp")
+ {
+ // Owner, 8 November 2026, "Enforce it here (Rec.)" (#1725 issuecomment-6724941867): the camp capacity, 50 records per camp city,
+ // over all military tracks, is enforced here. military.camp_capacity counts population units at D2's 1,000 people (#2739, option 1), which is a
+ // Historical ledger's own scale, so the capacity is in records.
+ var capacity = Gdd03MilitaryCatalogue.ReadCampCapacity(c.Gdd03Balance
+ ?? throw new InvalidOperationException("The camp capacity needs gdd03-balance.yaml (R-POP-002)."));
+ var room = capacity - ledger.Units.Count(p => p.Status == PopulationStatus.Trainee
+ && string.Equals(p.Assignment.Target, target, StringComparison.Ordinal));
+ if (count > room) return Refused(LedgerRefusedCampFull, name, Math.Max(0, room), capacity);
+ }
+ // R-ARMS-003 as in Start. Owner, 8 November 2026, "Keep costs, pool rest (Rec.)" (#1725 issuecomment-6724941867): one item is issued
+ // per record, and the rest of training_arms is taken from the stock and kept in Cohort.Arms, so a cancel returns it.
+ var per = type.Id == "recruit" ? c.RulesAt(s.Date).Mvp!.ArmsPerRecruitGroup!.Value : type.TrainingArms ?? 0;
+ var arms = (long)count * per;
+ if (arms > s.Arms) return Refused(RefusedArms, name, Course(type), arms, s.Arms);
+ var taken = idle.Take(count).ToList();
+ // Owner, 8 November 2026, Q3, "Refuse, with reason (Recommended)": a military trainee who already carries a
+ // military item, and a farmer or craftsman on the halutz track, are refused with a plain reason before any write.
+ if (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);
+ var id = s.NextId;
+ var course = new PopulationAssignment(PopulationAssignmentKind.Course, target);
+ var bind = ledger.Target(target) == null
+ ? new[] { CourseTargetOf(c, type.Facility, city, CityRegion(c, city)) } : Array.Empty<PopulationTarget>();
+ ledger.Commit(taken.Select(p =>
+ {
+ var e = p.Equipment;
+ return new PopulationUnit(p.Id, PopulationStatus.Trainee, p.ReceptionTicks, p.Location, course, p.Profession, p.Tier,
+ p.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);
+ Open(c, s, city, name, type, count, arms, (int)(arms - (per > 0 ? count : 0)), unit, taken.Select(p => p.Id), why);
+ return null;
+ }
+
+ /// <summary>The cohort's trainee records, ascending id (owner, 8 November 2026, "Cohorts stay main (Rec.)").</summary>
+ static List<PopulationUnit> Members(GameState s, Cohort k)
+ {
+ var members = k.Members ?? throw new InvalidOperationException("Cohort " + k.Id.ToString(CultureInfo.InvariantCulture) + " has no member list on a ledger game.");
+ var list = members.Select(s.PopulationLedger.Get).ToList();
+ if (list.Any(p => p.Status != PopulationStatus.Trainee || p.Assignment.Kind != PopulationAssignmentKind.Course))
+ throw new InvalidOperationException("Cohort " + k.Id.ToString(CultureInfo.InvariantCulture) + " has a member who is not its trainee.");
+ return list;
+ }
+
+ /// <summary>R-TRAIN-002 on the ledger, the records' part: each member is a free civilian without a job again, in place,
+ /// its reception kept (docs/GDD.md:374, 27M-9). Only the item this course issued leaves the record, to go back to the
+ /// stock (R-ARMS-003, "the Arms it took"); a carried item stays. Returns the records and the items returned.</summary>
+ static (List<PopulationUnit> Records, int Issued) Release(GameState s, Cohort k)
+ {
+ var issued = 0;
+ var records = Members(s, k).Select(p =>
+ {
+ var e = p.Equipment;
+ var mine = e.MilitaryId == IssuedId(k.Id, p.Id);
+ if (mine) issued++;
+ return new PopulationUnit(p.Id, PopulationStatus.FreeCivilian, p.ReceptionTicks, p.Location, PopulationAssignment.Unassigned,
+ p.Profession, p.Tier, p.WorkXp, p.Qualification, p.CombatXp, mine ? new PopulationEquipment(e.ToolsId, e.ToolsPaid) : e, p.Captor, p.Home);
+ }).ToList();
+ return (records, issued);
+ }
+
+ /// <summary>A graduate soldier of formation <paramref name="target"/>: an active soldier serving it, with the course's
+ /// class as its military qualification and its item kept, its profession dormant (owner, 8 November 2026, "Unskilled
+ /// first, keep (Rec.)"). Like an opening soldier (R-POP-004) it has the region-only location of its formation's region
+ /// (owner, 8 November 2026, Q2: "Formation region (Recommended)").</summary>
+ static PopulationUnit Soldier(PopulationUnit p, string target, string region, string qualification) =>
+ new PopulationUnit(p.Id, PopulationStatus.ActiveSoldier, p.ReceptionTicks, new PopulationLocation(region),
+ new PopulationAssignment(PopulationAssignmentKind.ActiveService, target), p.Profession, p.Tier, p.WorkXp, qualification,
+ p.CombatXp, p.Equipment, p.Captor, p.Home);
+
+ /// <summary>Owner, 8 November 2026, "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 not housed. A record that is a pioneer already keeps its tier and work XP
+ /// (its profession kept, "Unskilled first, keep (Rec.)"; owner, 8 November 2026, Q1: "Keeps tier and XP (Recommended)").</summary>
+ static PopulationUnit Pioneer(PopulationUnit p, string region) =>
+ new PopulationUnit(p.Id, PopulationStatus.FreeCivilian, p.ReceptionTicks, new PopulationLocation(region), PopulationAssignment.Unassigned,
+ CivilianProfession.Pioneer, p.Profession == CivilianProfession.Pioneer ? p.Tier : CivilianTier.Novice,
+ p.Profession == CivilianProfession.Pioneer ? p.WorkXp : 0, p.Qualification, p.CombatXp, p.Equipment, p.Captor, p.Home);
+
+ /// <summary>R-TRAIN-003 and R-TRAIN-004 on the ledger: <see cref="Progress"/>'s order and Why lines, with each cohort's
+ /// 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
+ /// 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)
+ {
+ var ledger = s.PopulationLedger;
+ var records = new List<PopulationUnit>();
+ var bind = new List<PopulationTarget>();
+ var apply = new List<Action>();
+ var next = s.NextId;
+ foreach (var k in s.Cohorts.Values.ToList())
+ {
+ var members = Members(s, k);
+ Unit? target = null;
+ if (k.Unit is int aim)
+ {
+ var at = c.SettlementHexes.First(h => h.Id == k.City);
+ if (!s.Units.TryGetValue(aim, out target) || (target.Q, target.R) != (at.Q, at.R))
+ {
+ var (released, issued) = Release(s, k);
+ records.AddRange(released);
+ apply.Add(() => { why.Add(Stopped(c, k, aim)); Cancelled(c, s, k, issued, why); });
+ continue;
+ }
+ }
+ if (k.TurnsLeft > 1)
+ {
+ records.AddRange(members.Select(p => p.WithPlacement(p.Status, p.Location,
+ new PopulationAssignment(PopulationAssignmentKind.Course, p.Assignment.Target, checked(p.Assignment.ProgressTicks + 1)), p.Captor, p.Home)));
+ apply.Add(() => s.Cohorts[k.Id] = k.WithTurnsLeft(k.TurnsLeft - 1));
+ continue;
+ }
+ var type = c.UnitTypes.First(t => t.Id == k.Type);
+ var name = PlayerText.Settlement(c, k.City);
+ if (target != null)
+ {
+ var formation = FormationTarget(c, target.Id);
+ var region = ledger.Target(formation)?.Region
+ ?? throw new InvalidOperationException("Unit " + target.Id.ToString(CultureInfo.InvariantCulture) + " has no formation target on the ledger.");
+ records.AddRange(members.Select(p => Soldier(p, formation, region, type.Class)));
+ var joined = target.Id;
+ apply.Add(() => { s.Cohorts.Remove(k.Id); Joined(c, s, k, type, name, joined, why); });
+ }
+ else if (type.Side != "")
+ {
+ var id = next++;
+ var formation = FormationPrefix + id.ToString(CultureInfo.InvariantCulture);
+ var region = CityRegion(c, k.City);
+ bind.Add(new PopulationTarget(formation, PopulationAssignmentKind.ActiveService, region));
+ records.AddRange(members.Select(p => Soldier(p, formation, region, type.Class)));
+ apply.Add(() => { s.Cohorts.Remove(k.Id); Formed(c, s, k, type, name, id, why); });
+ }
+ else if (type.Kind == "unit")
+ {
+ var region = CityRegion(c, k.City);
+ records.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); });
+ }
+ else throw new InvalidOperationException("Cohort " + k.Id.ToString(CultureInfo.InvariantCulture) + " of type " + k.Type + " does not run on the population ledger.");
+ }
+ ledger.Commit(records, bind);
+ foreach (var a in apply) a();
+ s.NextId = next;
+ }
}
}