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.

sim: GDD Phase 1 PR 4, training in a military camp and a Hakhshara (refs #377) (#468)

Eyal Golanc2774ecc92fe
diff --git a/CHANGELOG.md b/CHANGELOG.md
index db901615a..407c4367e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,13 @@ adds a line under **Unreleased**; CI's `Changelog` job checks this (see `CONTRIB
## [Unreleased]
### Added
+- GDD v0.1 Phase 1, training (refs #377), behind the `systems.loop` switch: `Train` sends a city's civilians without work
+ to basic training in a military camp (recruits, a count) or pioneer training in a Hakhshara (halutzim, movable units at
+ the city's hex), paid from the Treasury without borrowing; `CancelTraining` returns the people but not the Money (D-A3).
+ Cohorts progress as step 4 of the GDD turn (D-A6) (R-TRAIN-001 to R-TRAIN-003). One camp and one Hakhshara at the start
+ is a labelled design assumption (D-D5); training turns, costs and Attention costs are placeholders in `MvpSlice.Overlay`,
+ never under `content/`. `mvp-slice` moves (the reference player trains one halutz group); the legacy goldens and
+ `scenario-mvp-absorb-first` do not.
- GDD v0.1 Phase 1, one city (refs #376), behind the `systems.loop` switch: Tel Aviv with housing, jobs, civilians and
refugees as counts; `AssignWorkers` (Attention, refused in the legacy loop); and a `TurnResolver` that runs, in the
approved order (D-A6), Money from jobs, housing, Social cohesion and arrivals from the CBS series as refugees, housed on
diff --git a/docs/determinism.md b/docs/determinism.md
index 586464e62..fa73b78b9 100644
--- a/docs/determinism.md
+++ b/docs/determinism.md
@@ -71,7 +71,8 @@ later era makes, so they move only when a 1948 rule or event does.
**MVP goldens (GDD v0.1, before cutover).** `mvp-slice` plays `MvpSlice.Load`, the real content with the loop switch on and
monthly turns (spec 2026-10-12 section 2.1, R-LOOP-003), from the golden seed in Historical mode with the reference player until
`MvpGolden.Until` (15 January 1949, eight monthly turns). The reference player (`Statecraft.Sim.Reference.ReferencePlayer`, decision
-D-A7) is a stated test policy, not game AI and not history: `HistoricalAI`'s orders, then each city's jobs filled. No game mode or UI
+D-A7) is a stated test policy, not game AI and not history: `HistoricalAI`'s orders, then each city's jobs filled, then one
+halutz group trained when there is none and none in training. No game mode or UI
reaches it (`ReferencePlayerTests`). `MvpGoldenTests` checks it against the manifest line `mvp-slice` and the
snapshot `golden/mvp-slice.txt`, and the update command re-pins it like the others. It is not shown in this file's table or in
`tools/web_check.py`, because the players run only the legacy goldens until cutover. A Phase 1 PR that adds a GDD rule the slice
@@ -189,3 +190,4 @@ The hash reads the state keys, so it never sees a record outside its window. An
| playtest 1 E fix 1 | 1952 | `73590e32` | same; still ends 1952-02-27, turn 43 |
| Issue #2 | 1952 | `62f8ec61` | sourced Yosef food-supply/rationing responsibility from 8 October 1951 replaces a vacancy and changes late-1951 rationing competence; 1950 and five-turn smoke unchanged |
| GDD Phase 1 PR 3 | mvp-slice | `f6931e24` | the slice gains its city (placeholder values) and the GDD turn: Money from jobs, housing, Social cohesion and arrivals, with the reference player filling the jobs (was `0451920a`); the legacy goldens do not move |
+| GDD Phase 1 PR 4 | mvp-slice | `6343eee8` | training runs in the slice (step 4 of the GDD turn) and the reference player trains one halutz group on the first turn: it becomes a unit at Tel Aviv's hex on the fourth, its IL 0.5m adds to the debt, and the civilian it took frees a place that one more refugee is housed in (was `f6931e24`); the legacy goldens and `scenario-mvp-absorb-first` do not move |
diff --git a/docs/gdd/training.md b/docs/gdd/training.md
new file mode 100644
index 000000000..bf9a96dcf
--- /dev/null
+++ b/docs/gdd/training.md
@@ -0,0 +1,45 @@
+# Training: military camp and Hakhshara
+
+## Player story
+
+As a player of the MVP, I want to send Tel Aviv's civilians without work to basic training or to pioneer training, so that the city has recruits for defence and halutzim to build new places (GDD "Progression" [S1]; decisions D-A3, D-D5 [S2]).
+
+## Rules
+
+- One military camp and one Hakhshara exist in Tel Aviv at the start. This is a design assumption, not a claim about the city, and pioneers will build more in Phase 4 (D-D5 [S2]). The GDD leaves training capacity open, so there is no capacity limit (unitless).
+- `Train(city, track, n)` takes civilians without a job into training as recruits (military camp) or halutzim (Hakhshara). It costs 1 Attention and IL 0.5m per group, both placeholders, paid at once and never borrowed (R-TRAIN-001).
+- It is refused, with the state unchanged, for fewer than 1 group (unitless), more than the city's civilians without a job, an unknown city or track, a city without the facility, a Treasury short of the cost, or the legacy loop (R-TRAIN-001).
+- People in training are neither civilians nor recruits: they hold no job and are not counted by housing or Social cohesion while they train.
+- `CancelTraining(cohort)` returns the people as civilians without a job; the Money spent is not returned (D-A3 [S2]). It costs 0.5 Attention, a placeholder (R-TRAIN-002).
+- Training resolves before production in each turn, in the order the owner approved (D-A6, #456 [S2][S3]). A cohort ordered this turn counts this turn: basic training takes 3 turns and pioneer training 4 turns, both placeholders (R-TRAIN-003).
+- A finished recruit cohort adds to the city's recruits, a count until soldiers become units. A finished halutz cohort becomes one movable unit per group at the city's hex, with consecutive ids (D-A2 [S2], R-TRAIN-003).
+
+## Data touched
+
+- `unit_types.yaml` (`recruit`, `halutz`: `facility`, `training_turns`, `training_cost`), `cities.yaml` (`facilities`) and `rules.yaml` `attention_cost.train` and `cancel_training`: supplied by `MvpSlice.Overlay` as placeholders, never under `content/` (ruling 2 [S3]).
+- `GameState`: `Cohorts` (hashed as `train[...]` when there are some), a city's `Recruits` (in its hash record when not 0), `Units`, `NextId`, `Treasury`.
+- Save files: the `train CITY TRACK N` and `untrain COHORT` lines. Scenarios: `train` and `cancel_training`.
+- `sim/Statecraft.Sim.Tests/golden/manifest.txt`: `mvp-slice` moves; `scenario-mvp-absorb-first` does not.
+
+## Done when
+
+- `dotnet test sim/Statecraft.sln` passes, including `TrainingTests`, `CitiesContentTests`, `GddStateTests` and `ReferencePlayerTests`.
+- `hash1950`, `hash1952`, `smoke5`, `scenario-cautious`, `scenario-reckless` and `scenario-mvp-absorb-first` do not move.
+
+## Out of scope
+
+- Building more camps or a Hakhshara (Phase 4), training capacity, recruits as units and combat (Phase 5), veterans, craftsmen (D-D4), Arms consumed by training (D-G6), and any display (PRs 7 and 8).
+
+## Sources
+
+- [S1] The game design of record, docs/GDD.md
+- [S2] GDD v0.1 impact analysis and phased plan, section 5, docs/superpowers/specs/2026-10-12-gdd-v0.1-impact-and-plan.md
+- [S3] GDD Phase 1 implementation plan, PR 4, docs/superpowers/plans/2026-10-12-gdd-phase-1.md
+
+## Open questions
+
+- The placeholder values (training turns, cost per group, the two Attention costs) wait for the owner.
+- Whether training may borrow from the Treasury, as map actions do. This PR refuses it.
+- Whether people in training, and recruits, take up the city's housing. Housing counts civilians only (R-CITY-004), so a group in training frees a place that a waiting refugee then takes.
+- Whether the turn of the order counts as a training turn. This is the plan's reading of D-A6, not part of the owner's ruling. The other reading adds a turn.
+- Social cohesion's employed share rises while civilians without work are in training, because they leave the civilians (R-CITY-005).
diff --git a/docs/rules/mvp.md b/docs/rules/mvp.md
index 9ab0613e6..737a09f7c 100644
--- a/docs/rules/mvp.md
+++ b/docs/rules/mvp.md
@@ -33,3 +33,13 @@ R-CITY-003: Arrivals from the CBS series (`aliyah.yaml`) become refugees in the
R-CITY-004: Each turn, `min(refugees, max(0, housing_capacity - civilians))` of a city's refugees become civilians without a job. The cap is a placeholder while overflow (D-D1) is open.
R-CITY-005: Social cohesion is `clamp(0, 1, cohesion_housing_weight * housed + cohesion_jobs_weight * employed)`, where `housed` is civilians over civilians and refugees (1 with nobody) and `employed` is employed over civilians (1 with none), over all cities. It is a placeholder while D-C1 is open: no other system reads it.
+
+## Training
+
+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 the slice's city at the start, a labelled design assumption (D-D5); pioneers will build more.
+
+R-TRAIN-001: `Train(city, track, n)` takes `n` of the city's civilians without a job into a cohort that trains as `track` (a unit type with a `facility`: `recruit` in a military camp, `halutz` in a Hakhshara) for the type's `training_turns`, counting the turn it was ordered in. The Treasury pays `n * training_cost` at once and training does not borrow. 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, it has fewer civilians without a job, or the Treasury holds less than the cost. The legacy loop refuses it before charging Attention.
+
+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 cohort that does not exist, or has finished, is refused with the state unchanged.
+
+R-TRAIN-003: Each turn, in ascending id, every cohort has one turn less to go. A cohort that reaches 0 ends: recruits are added to the city's count of recruits (a count until Phase 5), and halutzim become one movable unit per group at the city's settlement hex, taking the next ids in turn. A city's recruits and the cohorts are written into the state hash only when there are some.
diff --git a/docs/superpowers/plans/2026-10-12-gdd-phase-1.md b/docs/superpowers/plans/2026-10-12-gdd-phase-1.md
index cda5d894e..cb861ef6f 100644
--- a/docs/superpowers/plans/2026-10-12-gdd-phase-1.md
+++ b/docs/superpowers/plans/2026-10-12-gdd-phase-1.md
@@ -60,7 +60,7 @@
| 7 | `unity/gdd-ui-core` | new Task issue | Unity: `SimBridge` keys and validation with a reflection guard, the `?mvp` dev flag, the score on the HUD, the objective card's photograph |
| 8 | `unity/gdd-ui-city` | new Task issue | Unity: the city panel (assign, train), the site build button, the built yishuv on the map |
-**Status (14 October 2026):** PR 1 merged as #349, PR 2 as #364. The owner answered the seven decisions in Global constraints (#456). PR 3's tasks are rewritten to the answers; PRs 4 to 6 are rewritten as each starts.
+**Status (14 October 2026):** PR 1 merged as #349, PR 2 as #364. The owner answered the seven decisions in Global constraints (#456). PRs 3 and 4's tasks are rewritten to the answers; PRs 5 and 6 are rewritten as each starts.
PR 1 has no dependency. PR 2 needs PR 1 (the overlay sets `turn_lengths`). PRs 3 to 6 are sequential (each adds to `TurnResolver` and moves `mvp-slice`). The site research for PR 5 (Task 5.0) can run while PR 3 or 4 is in review. PR 7 needs PR 6; PR 8 needs PR 7.
@@ -905,18 +905,23 @@ public static class ReferencePlayer
## PR 4: training
-> **Waits for the owner (ruling 1):** D-D5 (and D-A6 for where training runs in the turn). The values below are overlay or fixture text (ruling 2). Rewrite this PR's tasks to the owner's answers before starting.
+> **Decided by the owner on 2026-10-14 (#456, recorded in the impact plan §5 and in #375):** D-D5 and D-A6, each as the impact plan recommends. The tasks below are written to those answers:
+> - D-D5: "One of each exists at start (a design assumption, labelled). More are built by pioneers." The slice's Tel Aviv starts with one military camp and one Hakhshara, in the overlay's `cities.yaml` (ruling 2), labelled `PLACEHOLDER: owner sets (D-D5: one of each exists at start; a design assumption, not a claim about 1948)`. Building more is a pioneer action ("build military training camp", Phase 4), not this PR. Capacity is not part of the answer and the GDD leaves training capacity open, so this PR sets no capacity limit. The facilities are read from the content, not held in the state, until pioneers can build one.
+> - D-A6: "The fixed order of §2.3." Training is step 4 of §2.3, after the enemy's orders, combat and capture (Phase 5) and before construction (PR 5) and production. In PR 4 it is therefore the first step `TurnResolver` runs. The plan reads D-A6 as follows, and this reading is not part of the owner's ruling: a cohort ordered this turn already counts this turn's step, so a cohort ordered on turn T with `training_turns` 3 is done at the end of turn T+2. The other reading (the end of T+3) is a one-line change in `Training.Start`.
+>
+> Placeholder values go in `MvpSlice.Overlay` or test fixtures, never `content/` (ruling 2): the training fields of `unit_types.yaml`, the facilities in `cities.yaml` and the two `attention_cost` kinds below are overlay text, marked `PLACEHOLDER: owner sets`. `scenario-mvp-absorb-first` orders no training, so it must not move: the new state (cohorts, recruits) is hashed only when it is set (R-LOOP-002's rule).
+Issue #377 (Task form): "GDD Phase 1: training in a military camp and a Hakhshara". Sign-off: placeholders, D-D5 as answered (#456), no borrowing for training, the `mvp-slice` move.
-Issue: "GDD Phase 1: training in a military camp and a Hakhshara". Sign-off: placeholders, D-D5 (waits for the owner).
+### Task 4.1: the training data (overlay text, ruling 2)
-### Task 4.1: content
+**Files:** `MvpSlice.cs` (overlay text), `Content.cs` (`UnitType` gains `Facility`, `TrainingTurns`, `TrainingCost`), `ContentLoader.cs` (`ValidateGdd`), `Fixture.cs` (the fixture's town gets both facilities and the two training types), `CitiesContentTests.cs` (one row per new check).
-`unit_types.yaml` gains:
+The overlay's `unit_types.yaml` gains:
```yaml
- id: recruit # civilian to recruit, through basic training (GDD "Progression")
- kind: population # a count until Phase 5 (spec §6 item 4)
+ kind: population # a count per city until Phase 5 (spec §6 item 4)
facility: military_camp
training_turns: 3 # PLACEHOLDER: owner sets
training_cost: 0.5 # PLACEHOLDER: owner sets (IL millions per group)
@@ -927,23 +932,25 @@ Issue: "GDD Phase 1: training in a military camp and a Hakhshara". Sign-off: pla
training_cost: 0.5 # PLACEHOLDER: owner sets (IL millions per group)
```
-`cities.yaml` `tel_aviv.facilities: [military_camp, hakhshara]` with `# PLACEHOLDER: owner sets (D-D5: one of each exists at start; a design assumption, not a claim about 1948)`. `attention_cost`: `train: 1`, `cancel_training: 0.5`, both `# PLACEHOLDER: owner sets`. Validation: a type with `facility` needs `training_turns ≥ 1` and `training_cost ≥ 0`; facility known.
+The overlay's `cities.yaml`: `tel_aviv.facilities: [military_camp, hakhshara] # PLACEHOLDER: owner sets (D-D5: one of each exists at start; a design assumption, not a claim about 1948)`. `attention_cost` gains `train: 1` and `cancel_training: 0.5`, both `PLACEHOLDER: owner sets`. Validation (each a `CitiesContentTests` row naming file and field): a type with a `facility` names a known facility and has `training_turns ≥ 1` and a finite `training_cost ≥ 0`; a type without one has neither; a trained `population` type is `recruit` (the only trained count until Phase 5).
### Task 4.2: `Train` and `CancelTraining` (R-TRAIN-001, R-TRAIN-002)
+**Files:** create `Training.cs`, `TrainingTests.cs`; `GddState.cs` (`Cohort`; `City.Recruits`), `GameState.cs` (`Cohorts`, `Clone`, the hash), `Commands.cs`, `AttentionSystem.cs` (`train`, `cancel_training`, both GDD kinds), `Simulation.cs` (`Execute`), `SaveGame.cs`, `Scenario.cs`, `CommandGuardTests.Samples`, `MvpSliceTests` (the slice's costs).
+
**Interfaces:**
-- Produces: `Train(string city, string track, int count)` (`train CITY TRACK N` in saves); `CancelTraining(int cohort)` (`untrain ID`); `Training.Start(c, s, city, track, count, why) : string?`; `Training.Cancel(c, s, cohort, why) : string?`.
+- Produces: `Train(string city, string track, int count)`, `Kind = "train"` (`train CITY TRACK N` in saves; the track is a unit type id with a facility); `CancelTraining(int cohort)`, `Kind = "cancel_training"` (`untrain ID`); `Training.Start(c, s, city, track, count, why) : string?`; `Training.Cancel(c, s, cohort, why) : string?`; `Cohort { Id, Type, City, Count, TurnsLeft }` (immutable); `GameState.Cohorts : SortedList<int, Cohort>`, hashed as `train[...]` only when not empty; `City.Recruits`, written into the city's hash record only when not 0, so a city with none hashes as before.
-R-TRAIN-001: `Train` takes `count ≥ 1` unemployed civilians (`civilians − employed`) of a city that has the track's facility, pays `count × training_cost` from the Treasury (refused if the Treasury is short; no borrowing for training: flag in the PR as a choice for the owner), and opens a cohort with `turnsLeft = training_turns`, id `s.NextId++`.
-R-TRAIN-002: `CancelTraining` returns the cohort's people to the city's civilians and refunds nothing (D-A3).
+R-TRAIN-001: `Train` takes `count ≥ 1` civilians without a job (`civilians − employed`) of a city that has the track's facility, pays `count × training_cost` from the Treasury (refused if the Treasury holds less; no borrowing for training: flagged in the PR as a choice for the owner), and opens a cohort with `TurnsLeft = training_turns` and id `s.NextId++` (cohorts and units share the id counter, so no id is reused). The trainees leave the city's civilians at once. Refused, state unchanged and Attention refunded: unknown city, unknown track (or a type with no facility), `count < 1`, no facility, more than the unemployed, Treasury short. The legacy loop refuses it before charging.
+R-TRAIN-002: `CancelTraining` returns the cohort's people to the city's civilians, without a job, and refunds nothing (D-A3). An unknown or finished cohort (a finished one has left the state) is refused, state unchanged.
-Tests: start, the limits (no facility, more than the unemployed, `count 0`, unknown track, Treasury short), cancel returns people and not money, cancelling an unknown or finished cohort is refused, save round-trip, legacy refusal. Mutation: refund the money on cancel; `CancellingReturnsPeopleNotMoney` fails.
+Tests: start; `[Theory]` of the limits; cancel returns people and not Money; cancelling an unknown or finished cohort; save round trip of both lines; legacy refusal with Attention refunded. Mutation: refund the Money on cancel; `CancellingReturnsPeopleNotMoney` fails.
### Task 4.3: progress in the resolver (R-TRAIN-003)
-Training runs first in `TurnResolver`. Each cohort's `turnsLeft` falls by 1 a turn; at 0 the cohort ends: `recruit` adds `count` to the city's `recruits`; `halutz` adds `count` units `Unit(id = s.NextId++, "halutz", city, q, r of the city's settlement hex, "idle", "", 0)` in cohort order. Cohorts are processed in list order (ascending id).
+Training is step 4 of `TurnResolver` (§2.3, D-A6), the first step PR 4 runs. In ascending cohort id, each cohort's `TurnsLeft` falls by 1; at 0 the cohort leaves the state and: a `population` type (`recruit`) adds `count` to the city's `Recruits`; a `unit` type (`halutz`) adds `count` units `Unit(s.NextId++, "halutz", q, r)` at the city's settlement hex (`map/settlement_hexes.yaml`; Tel Aviv is (−3, 19)), in order.
-Tests: a recruit cohort of 3 groups completes after exactly `training_turns` steps; halutz cohort creates units with consecutive ids at Tel Aviv's hex (−3, 19); trained people are not counted as civilians while training (cohesion uses civilians). Reference player: after filling jobs, trains 1 halutz group when it has none and none in training (stated policy). Re-pin `mvp-slice`. Docs, CHANGELOG, checks, Unity EditMode, web_check, PR, stop.
+Tests: a recruit cohort of 3 groups completes after exactly `training_turns` turns, counting the turn it was ordered in; a halutz cohort creates units with consecutive ids at Tel Aviv's hex; people in training are not civilians (cohesion and housing read civilians: flagged in the PR, since housing then sees the trainees' places as free while D-D1 and the population role model are open). Reference player (D-A7): after filling the jobs, it trains 1 halutz group when there is none, none in training, a civilian left without a job, and the Treasury and Attention to pay (a stated policy). Re-pin `mvp-slice`; `scenario-mvp-absorb-first` does not move. `docs/rules/mvp.md` R-TRAIN-001 to R-TRAIN-003, `docs/gdd/training.md`, CHANGELOG, checks, Unity EditMode, web_check, PR, stop.
---
diff --git a/sim/Statecraft.Sim.Tests/CitiesContentTests.cs b/sim/Statecraft.Sim.Tests/CitiesContentTests.cs
index a4dd24019..4eb69ae08 100644
--- a/sim/Statecraft.Sim.Tests/CitiesContentTests.cs
+++ b/sim/Statecraft.Sim.Tests/CitiesContentTests.cs
@@ -16,7 +16,10 @@ public class CitiesContentTests
var c = Load();
var city = Assert.Single(c.Cities);
Assert.Equal(("town_a", 12, 8, 10, 6), (city.Id, city.HousingCapacity, city.JobSlots, city.Civilians, city.Employed));
- Assert.Equal(new[] { "civilian", "refugee" }, c.UnitTypes.Select(t => t.Id));
+ Assert.Equal(new[] { "civilian", "refugee", "recruit", "halutz" }, c.UnitTypes.Select(t => t.Id));
+ var halutz = c.UnitTypes.Single(t => t.Id == "halutz");
+ Assert.Equal(("unit", "hakhshara", 3, 0.25), (halutz.Kind, halutz.Facility, halutz.TrainingTurns, halutz.TrainingCost));
+ Assert.Equal("", c.UnitTypes.Single(t => t.Id == "civilian").Facility);
var mvp = c.RulesAt(c.Eras[0].From).Mvp!;
Assert.Equal((10, 1.2, 0.5, 0.5, "town_a"), (mvp.PeoplePerUnit, mvp.IncomePerJobPerYear, mvp.CohesionHousingWeight, mvp.CohesionJobsWeight, mvp.ArrivalsCity));
Assert.Equal("Town A", c.SettlementNames["town_a"]);
@@ -39,6 +42,10 @@ public class CitiesContentTests
Assert.Equal("tel_aviv", Assert.Single(c.Cities).Id);
Assert.Equal("tel_aviv", c.RulesAt(c.Eras[0].From).Mvp!.ArrivalsCity);
Assert.True(c.Rules.AttentionCost.ContainsKey("assign_workers"));
+ Assert.Equal(new[] { "military_camp", "hakhshara" }, c.Cities[0].Facilities); // D-D5: one of each at the start
+ Assert.Equal(new[] { ("recruit", "military_camp"), ("halutz", "hakhshara") },
+ c.UnitTypes.Where(t => t.Facility != "").Select(t => (t.Id, t.Facility)));
+ Assert.True(c.Rules.AttentionCost.ContainsKey("train") && c.Rules.AttentionCost.ContainsKey("cancel_training"));
}
[Fact]
@@ -53,13 +60,15 @@ public class CitiesContentTests
var text = File.ReadAllText(Path.Combine(root, f));
Assert.DoesNotContain("mvp:", text);
Assert.DoesNotContain("assign_workers", text);
+ Assert.DoesNotMatch(@"\btrain:|cancel_training|training_turns|training_cost", text);
}
}
const string City = " - { id: town_a, housing_capacity: 12, job_slots: 8, civilians: 10, employed: 6, facilities: [] }\n";
static string Cities(string row) => "cities:\n" + row;
- static string Rules(string mvp) => Fixture.Files["rules.yaml"].Replace("map_action: 1 }", "map_action: 1, assign_workers: 1 }") + mvp;
+ static string Rules(string mvp) => Fixture.Files["rules.yaml"].Replace("map_action: 1 }", "map_action: 1, assign_workers: 1, train: 1, cancel_training: 1 }") + mvp;
+ static string Types(string row) => "types:\n - { id: civilian, kind: population }\n" + row;
public static IEnumerable<object[]> BadRows() => new List<object[]>
{
@@ -82,6 +91,14 @@ public class CitiesContentTests
new object[] { "rules.yaml", Rules(Fixture.GddRules.Replace("arrivals_city: town_a", "arrivals_city: nowhere")), "mvp.arrivals_city", "is not a city in cities.yaml" },
new object[] { "rules.yaml", Rules(""), "mvp", "required when eras.yaml systems.loop is gdd" },
new object[] { "rules.yaml", Fixture.Files["rules.yaml"] + Fixture.GddRules, "attention_cost.assign_workers", "missing cost" },
+ new object[] { "rules.yaml", Rules(Fixture.GddRules).Replace(", train: 1", ""), "attention_cost.train", "missing cost" },
+ new object[] { "rules.yaml", Rules(Fixture.GddRules).Replace(", cancel_training: 1", ""), "attention_cost.cancel_training", "missing cost" },
+ new object[] { "unit_types.yaml", Types(" - { id: halutz, kind: unit, facility: winery, training_turns: 3, training_cost: 0.25 }\n"), "types[halutz].facility", "unknown facility 'winery'" },
+ new object[] { "unit_types.yaml", Types(" - { id: halutz, kind: unit, facility: hakhshara, training_turns: 0, training_cost: 0.25 }\n"), "types[halutz].training_turns", "must be >= 1" },
+ new object[] { "unit_types.yaml", Types(" - { id: halutz, kind: unit, facility: hakhshara, training_turns: 3, training_cost: -1 }\n"), "types[halutz].training_cost", "must be a finite number >= 0" },
+ new object[] { "unit_types.yaml", Types(" - { id: halutz, kind: unit, training_turns: 3 }\n"), "types[halutz].training_turns", "only a type with a facility trains" },
+ new object[] { "unit_types.yaml", Types(" - { id: halutz, kind: unit, training_cost: 0.5 }\n"), "types[halutz].training_cost", "only a type with a facility trains" },
+ new object[] { "unit_types.yaml", Types(" - { id: craftsman, kind: population, facility: hakhshara, training_turns: 3, training_cost: 0.5 }\n"), "types[craftsman].kind", "only recruit is a trained count" },
};
[Theory]
diff --git a/sim/Statecraft.Sim.Tests/CitiesTests.cs b/sim/Statecraft.Sim.Tests/CitiesTests.cs
index ed64a8a03..0c794f7fc 100644
--- a/sim/Statecraft.Sim.Tests/CitiesTests.cs
+++ b/sim/Statecraft.Sim.Tests/CitiesTests.cs
@@ -170,7 +170,7 @@ public class CitiesTests
static Content Unequal() => ContentLoader.Load(Fixture.Write(Fixture.Gdd(new Dictionary<string, string>
{
["cities.yaml"] = "cities:\n - { id: town_a, housing_capacity: 12, job_slots: 20, civilians: 10, employed: 6, facilities: [] }\n",
- ["rules.yaml"] = Fixture.Files["rules.yaml"].Replace("map_action: 1 }", "map_action: 1, assign_workers: 1 }")
+ ["rules.yaml"] = Fixture.Files["rules.yaml"].Replace("map_action: 1 }", "map_action: 1, assign_workers: 1, train: 1, cancel_training: 1 }")
+ Fixture.GddRules.Replace("cohesion_housing_weight: 0.5", "cohesion_housing_weight: 0.8").Replace("cohesion_jobs_weight: 0.5", "cohesion_jobs_weight: 0.2"),
})));
diff --git a/sim/Statecraft.Sim.Tests/CommandGuardTests.cs b/sim/Statecraft.Sim.Tests/CommandGuardTests.cs
index 508abf219..b6ce683b8 100644
--- a/sim/Statecraft.Sim.Tests/CommandGuardTests.cs
+++ b/sim/Statecraft.Sim.Tests/CommandGuardTests.cs
@@ -19,6 +19,8 @@ public class CommandGuardTests
[typeof(Appoint)] = new Appoint("prime_minister", "pm_one"),
[typeof(MapAction)] = new MapAction("housing", 1, 2),
[typeof(AssignWorkers)] = new AssignWorkers("tel_aviv", "job", 1),
+ [typeof(Train)] = new Train("tel_aviv", "halutz", 1),
+ [typeof(CancelTraining)] = new CancelTraining(1),
};
static IEnumerable<Type> CommandTypes() =>
diff --git a/sim/Statecraft.Sim.Tests/Fixture.cs b/sim/Statecraft.Sim.Tests/Fixture.cs
index 4fd054dda..db48aaa21 100644
--- a/sim/Statecraft.Sim.Tests/Fixture.cs
+++ b/sim/Statecraft.Sim.Tests/Fixture.cs
@@ -203,7 +203,7 @@ series:
var o = new Dictionary<string, string>
{
["eras.yaml"] = Files["eras.yaml"] + " systems: { loop: gdd }\n",
- ["rules.yaml"] = Files["rules.yaml"].Replace("map_action: 1 }", "map_action: 1, assign_workers: 1 }") + GddRules,
+ ["rules.yaml"] = Files["rules.yaml"].Replace("map_action: 1 }", "map_action: 1, assign_workers: 1, train: 1, cancel_training: 1 }") + GddRules,
["cities.yaml"] = GddCities,
["unit_types.yaml"] = GddUnitTypes,
};
@@ -222,13 +222,15 @@ mvp:
public const string GddCities = @"
cities:
- - { id: town_a, housing_capacity: 12, job_slots: 8, civilians: 10, employed: 6, facilities: [] }
+ - { id: town_a, housing_capacity: 12, job_slots: 8, civilians: 10, employed: 6, facilities: [military_camp, hakhshara] }
";
public const string GddUnitTypes = @"
types:
- { id: civilian, kind: population }
- { id: refugee, kind: population }
+ - { id: recruit, kind: population, facility: military_camp, training_turns: 2, training_cost: 0.5 }
+ - { id: halutz, kind: unit, facility: hakhshara, training_turns: 3, training_cost: 0.25 }
";
public static string Write(Dictionary<string, string>? overrides = null, Dictionary<string, string>? events = null)
diff --git a/sim/Statecraft.Sim.Tests/GddStateTests.cs b/sim/Statecraft.Sim.Tests/GddStateTests.cs
index 1a70141a6..eccd6ac97 100644
--- a/sim/Statecraft.Sim.Tests/GddStateTests.cs
+++ b/sim/Statecraft.Sim.Tests/GddStateTests.cs
@@ -20,7 +20,7 @@ public class GddStateTests
public void AnEmptyStateWritesNoNewSection()
{
var text = new GameState().Describe();
- foreach (var label in new[] { "city{", "coh=", "units[", "next=", "obj{", "score=" }) Assert.DoesNotContain(label, text);
+ foreach (var label in new[] { "city{", "coh=", "units[", "train[", "next=", "obj{", "score=" }) Assert.DoesNotContain(label, text);
Assert.EndsWith("over=", text);
}
@@ -47,6 +47,7 @@ public class GddStateTests
{
("city{", x => x.Cities["tel_aviv"] = new City("tel_aviv", 10, 4, 6, 3, 2)),
("units[", x => x.Units.Add(1, new Unit(1, "halutz", -3, 19))),
+ ("train[", x => x.Cohorts.Add(2, new Cohort(2, "recruit", "tel_aviv", 3, 2))),
("next=", x => x.NextId = 2),
("obj{", x => x.Objectives["first_new_yishuv"] = new DateTime(1949, 3, 15)),
("score=", x => x.Score = 5),
@@ -71,6 +72,21 @@ public class GddStateTests
Assert.Equal(cities.Length, new HashSet<string>(Array.ConvertAll(cities, H)).Count);
var units = new[] { new Unit(1, "halutz", 0, 0), new Unit(2, "halutz", 0, 0), new Unit(1, "recruit", 0, 0), new Unit(1, "halutz", 1, 0), new Unit(1, "halutz", 0, 1) };
Assert.Equal(units.Length, new HashSet<string>(Array.ConvertAll(units, U)).Count);
+ string K(Cohort k) { var s = new GameState(); s.Cohorts.Add(k.Id, k); return s.Hash(); }
+ var cohorts = new[] { new Cohort(1, "recruit", "a", 1, 1), new Cohort(2, "recruit", "a", 1, 1), new Cohort(1, "halutz", "a", 1, 1),
+ new Cohort(1, "recruit", "b", 1, 1), new Cohort(1, "recruit", "a", 2, 1), new Cohort(1, "recruit", "a", 1, 2) };
+ Assert.Equal(cohorts.Length, new HashSet<string>(Array.ConvertAll(cohorts, K)).Count);
+ }
+
+ // R-LOOP-002, R-TRAIN-003: a city's recruits reach the hash, and a city with none hashes as it did before PR 4, so
+ // scenario-mvp-absorb-first (no training) does not move.
+ [Fact]
+ public void RecruitsReachTheHashOnlyWhenThereAreSome()
+ {
+ var none = new City("a", 1, 2, 3, 1, 0);
+ Assert.Equal("a=1,2,3,1,0", none.Canonical());
+ Assert.Equal("a=1,2,3,1,0,4", none.WithRecruits(4).Canonical());
+ Assert.Equal(4, none.WithRecruits(4).WithCounts(5, 1, 0).Recruits); // a change of counts keeps the recruits
}
[Fact]
@@ -79,13 +95,14 @@ public class GddStateTests
var a = new GameState();
a.Cities["x"] = new City("x", 1, 1, 1, 0, 0);
a.Units.Add(1, new Unit(1, "halutz", 0, 0));
+ a.Cohorts.Add(2, new Cohort(2, "recruit", "x", 1, 1));
a.Objectives["o"] = new DateTime(1949, 1, 1);
a.NextId = 2; a.Score = 3;
var before = a.Hash();
var b = a.Clone();
- b.Cities["y"] = a.Cities["x"]; b.Units.Add(2, a.Units[1]); b.Objectives.Clear(); b.NextId = 9; b.Score = 9;
+ b.Cities["y"] = a.Cities["x"]; b.Units.Add(2, a.Units[1]); b.Cohorts.Clear(); b.Objectives.Clear(); b.NextId = 9; b.Score = 9;
Assert.Equal(before, a.Hash());
- Assert.Single(a.Cities); Assert.Single(a.Units); Assert.Single(a.Objectives);
+ Assert.Single(a.Cities); Assert.Single(a.Units); Assert.Single(a.Cohorts); Assert.Single(a.Objectives);
}
[Fact]
diff --git a/sim/Statecraft.Sim.Tests/MvpSliceTests.cs b/sim/Statecraft.Sim.Tests/MvpSliceTests.cs
index 0df7689e0..42f6cdac2 100644
--- a/sim/Statecraft.Sim.Tests/MvpSliceTests.cs
+++ b/sim/Statecraft.Sim.Tests/MvpSliceTests.cs
@@ -28,7 +28,8 @@ public class MvpSliceTests
Assert.Equal(Real.Events.Select(e => e.Id), Mvp.Events.Select(e => e.Id));
Assert.Equal(Real.Rules.Start, Mvp.Rules.Start);
// The slice adds the GDD command kinds' costs (placeholders) and keeps every other cost.
- Assert.Equal(Real.Rules.AttentionCost.Append(new KeyValuePair<string, double>("assign_workers", 0.5)).OrderBy(kv => kv.Key, StringComparer.Ordinal),
+ Assert.Equal(Real.Rules.AttentionCost.Append(new KeyValuePair<string, double>("assign_workers", 0.5))
+ .Append(new KeyValuePair<string, double>("train", 1)).Append(new KeyValuePair<string, double>("cancel_training", 0.5)).OrderBy(kv => kv.Key, StringComparer.Ordinal),
Mvp.Rules.AttentionCost.OrderBy(kv => kv.Key, StringComparer.Ordinal));
Assert.Equal(Real.Rules.BudgetStart, Mvp.Rules.BudgetStart);
Assert.Equal(Real.Rules.CapitalInflowPerYear, Mvp.Rules.CapitalInflowPerYear);
diff --git a/sim/Statecraft.Sim.Tests/ReferencePlayerTests.cs b/sim/Statecraft.Sim.Tests/ReferencePlayerTests.cs
index cee153b6d..9102b6f7b 100644
--- a/sim/Statecraft.Sim.Tests/ReferencePlayerTests.cs
+++ b/sim/Statecraft.Sim.Tests/ReferencePlayerTests.cs
@@ -12,17 +12,45 @@ public class ReferencePlayerTests
static readonly Content Mvp = MvpSlice.Load(RealContentTests.ContentRoot());
[Fact]
- public void ItSendsHistoricalAIsOrdersThenFillsTheJobs()
+ public void ItSendsHistoricalAIsOrdersThenFillsTheJobsThenTrainsOneHalutzGroup()
{
var s = Simulation.NewGame(Mvp, GoldenRun.Seed, Mode.Historical);
var orders = ReferencePlayer.Commands(Mvp, s);
var history = HistoricalAI.Commands(Mvp, s);
Assert.Equal(history.Select(x => x.Kind), orders.Take(history.Count).Select(x => x.Kind));
- var assign = Assert.IsType<AssignWorkers>(orders.Last());
+ Assert.Equal(history.Count + 2, orders.Count);
+ var assign = Assert.IsType<AssignWorkers>(orders[history.Count]);
Assert.Equal(("tel_aviv", "job", 90), (assign.City, assign.Role, assign.Count)); // min(90 jobs, 100 civilians)
+ var train = Assert.IsType<Train>(orders.Last());
+ Assert.Equal(("tel_aviv", "halutz", 1), (train.City, train.Track, train.Count)); // 10 civilians left without work
Assert.Empty(Simulation.Step(Mvp, s, orders).Rejected);
}
+ // R-TRAIN-001: the stated policy trains a halutz group only when there is none, none in training, a civilian without
+ // work, and the Treasury and Attention to pay.
+ [Fact]
+ public void ItTrainsNoHalutzWhenOneExistsOrTrainsOrNobodyIsFreeOrMoneyIsShort()
+ {
+ var s = Simulation.NewGame(Mvp, GoldenRun.Seed, Mode.Historical);
+ var training = Simulation.Step(Mvp, s, ReferencePlayer.Commands(Mvp, s)).State;
+ Assert.Single(training.Cohorts);
+ training.Treasury = 100; // only the cohort in training holds it back: Money, Attention and free civilians are there
+ training.Attention = 10;
+ Assert.True(training.Cities["tel_aviv"].Civilians > training.Cities["tel_aviv"].Employed);
+ Assert.DoesNotContain(ReferencePlayer.Commands(Mvp, training), x => x is Train);
+ training.Cohorts.Clear();
+ Assert.Contains(ReferencePlayer.Commands(Mvp, training), x => x is Train);
+ var trained = s.Clone();
+ trained.Units.Add(1, new Unit(1, "halutz", -3, 19));
+ Assert.DoesNotContain(ReferencePlayer.Commands(Mvp, trained), x => x is Train);
+ var busy = s.Clone();
+ busy.Cities["tel_aviv"] = busy.Cities["tel_aviv"].WithCounts(90, 80, 0); // 90 jobs: all of them filled
+ Assert.DoesNotContain(ReferencePlayer.Commands(Mvp, busy), x => x is Train);
+ var poor = s.Clone();
+ poor.Treasury = 0.4;
+ Assert.DoesNotContain(ReferencePlayer.Commands(Mvp, poor), x => x is Train);
+ }
+
[Fact]
public void ItSendsNoOrderWhenTheJobsAreFilledOrAttentionIsShort()
{
diff --git a/sim/Statecraft.Sim.Tests/SaveGameTests.cs b/sim/Statecraft.Sim.Tests/SaveGameTests.cs
index 67972e954..09d11d4d1 100644
--- a/sim/Statecraft.Sim.Tests/SaveGameTests.cs
+++ b/sim/Statecraft.Sim.Tests/SaveGameTests.cs
@@ -28,7 +28,8 @@ public class SaveGameTests
new Command[] { new Appoint("finance_minister", "pm_one"), new MapAction("housing", 2, 0) },
new Command[] { new SetPolicy("odd id with spaces%", 0.5), new MapAction("transit_camp", 4, 0) },
new Command[] { new AssignWorkers("town_a", "job", 1) }, // a GDD order: the legacy fixture refuses it
- new Command[0], new Command[] { new SecurityOrder(1) }, new Command[0], new Command[0],
+ new Command[] { new Train("town_a", "halutz", 1), new CancelTraining(1) }, // GDD orders too
+ new Command[] { new SecurityOrder(1) }, new Command[0], new Command[0],
};
foreach (var o in orders) g.Step(o);
return g;
diff --git a/sim/Statecraft.Sim.Tests/TrainingTests.cs b/sim/Statecraft.Sim.Tests/TrainingTests.cs
new file mode 100644
index 000000000..bc8a86e65
--- /dev/null
+++ b/sim/Statecraft.Sim.Tests/TrainingTests.cs
@@ -0,0 +1,284 @@
+using System.Collections.Generic;
+using System.Linq;
+using Statecraft.Sim;
+
+/// <summary>The GDD slice's training (Phase 1 PR 4): Train (R-TRAIN-001) and CancelTraining (R-TRAIN-002) in a military camp
+/// and a Hakhshara, and the cohorts' progress in TurnResolver (R-TRAIN-003, step 4 of spec 2026-10-12 section 2.3, D-A6).</summary>
+public class TrainingTests
+{
+ static readonly Content Mvp = MvpSlice.Load(RealContentTests.ContentRoot());
+
+ /// <summary>The GDD fixture's town: 10 civilians, 6 of them employed, so 4 without work. The fixture's recruit trains for 2
+ /// turns at 0.5 a group, its halutz for 3 turns at 0.25.</summary>
+ static Content Town(string facilities = "[military_camp, hakhshara]") =>
+ ContentLoader.Load(Fixture.Write(Fixture.Gdd(new Dictionary<string, string>
+ {
+ ["cities.yaml"] = "cities:\n - { id: town_a, housing_capacity: 12, job_slots: 20, civilians: 10, employed: 6, facilities: " + facilities + " }\n",
+ })));
+
+ static StepResult Step(Content c, GameState s, params Command[] commands) => Simulation.Step(c, s, commands);
+
+ // D-D5 (#456): one military camp and one Hakhshara exist at the start, a labelled design assumption in the overlay.
+ [Fact]
+ public void TheSliceStartsWithOneCampAndOneHakhshara()
+ {
+ Assert.Equal(new[] { "military_camp", "hakhshara" }, Assert.Single(Mvp.Cities).Facilities);
+ var s = Simulation.NewGame(Mvp, GoldenRun.Seed, Mode.Historical);
+ Assert.Empty(s.Cohorts);
+ Assert.Equal(0, s.Cities["tel_aviv"].Recruits);
+ }
+
+ // R-TRAIN-001
+ [Fact]
+ public void TrainingTakesCiviliansWithoutWorkAndPays()
+ {
+ var c = Town();
+ var s = Simulation.NewGame(c, 1, Mode.Historical);
+ var id = s.NextId;
+ var r = Step(c, s, new Train("town_a", "recruit", 3));
+ Assert.Empty(r.Rejected);
+ var city = r.State.Cities["town_a"];
+ Assert.Equal((7, 6, 0), (city.Civilians, city.Employed, city.Recruits)); // in training: neither civilians nor recruits
+ var k = Assert.Single(r.State.Cohorts.Values);
+ Assert.Equal((id, "recruit", "town_a", 3, 1), (k.Id, k.Type, k.City, k.Count, k.TurnsLeft)); // 2 turns, one of them this one
+ Assert.Equal(id + 1, r.State.NextId);
+ Assert.Equal(Step(c, s).State.Treasury - 1.5, r.State.Treasury, 9);
+ Assert.Contains(r.Why, x => x.System == "city" && x.Message == "Town A: 3 groups began basic training, cost IL 1.5m");
+ }
+
+ // R-TRAIN-001
+ [Theory]
+ [InlineData("town_a", "recruit", 0, "Train at least one group")]
+ [InlineData("town_a", "recruit", -1, "Train at least one group")]
+ [InlineData("town_a", "recruit", 5, "Town A has 4 civilians without work")]
+ [InlineData("town_a", "halutz", 5, "Town A has 4 civilians without work")]
+ [InlineData("nowhere", "recruit", 1, "There is no such city")]
+ [InlineData("town_a", "soldier", 1, "There is no such training")]
+ [InlineData("town_a", "civilian", 1, "There is no such training")] // a type with no facility
+ public void TheLimitsAreRefusedAndChangeNothing(string city, string track, int count, string reason)
+ {
+ var c = Town();
+ var s = Simulation.NewGame(c, 1, Mode.Historical);
+ var r = Step(c, s, new Train(city, track, count));
+ Assert.Equal(reason, Assert.Single(r.Rejected).Reason);
+ Assert.Equal(Step(c, s).State.Hash(), r.State.Hash()); // as if the order had not been given: Attention refunded too
+ }
+
+ // R-TRAIN-001
+ [Theory]
+ [InlineData("[military_camp]", "halutz", "Town A has no Hakhshara")]
+ [InlineData("[hakhshara]", "recruit", "Town A has no military camp")]
+ public void ACityWithoutTheFacilityRefuses(string facilities, string track, string reason)
+ {
+ var c = Town(facilities);
+ var s = Simulation.NewGame(c, 1, Mode.Historical);
+ var r = Step(c, s, new Train("town_a", track, 1));
+ Assert.Equal(reason, Assert.Single(r.Rejected).Reason);
+ Assert.Equal(Step(c, s).State.Hash(), r.State.Hash());
+ }
+
+ // R-TRAIN-001: no borrowing for training (a choice flagged for the owner).
+ [Fact]
+ public void AShortTreasuryRefusesAndChangesNothing()
+ {
+ var c = Town();
+ var s = Simulation.NewGame(c, 1, Mode.Historical);
+ s.Treasury = 1.4;
+ var r = Step(c, s, new Train("town_a", "recruit", 3));
+ Assert.Equal("Training costs IL 1.5m and the Treasury holds IL 1.4m", Assert.Single(r.Rejected).Reason);
+ Assert.Equal(Step(c, s).State.Hash(), r.State.Hash());
+ Assert.Empty(Step(c, s, new Train("town_a", "recruit", 2)).Rejected); // IL 1.0m is affordable
+ }
+
+ // R-TRAIN-001: refused only when the Treasury holds less than the cost, so a Treasury of exactly the cost pays it.
+ [Fact]
+ public void ATreasuryOfExactlyTheCostPaysIt()
+ {
+ var c = Town();
+ var s = Simulation.NewGame(c, 1, Mode.Historical);
+ s.Treasury = 1.5;
+ var after = s.Clone();
+ Assert.Null(Training.Start(c, after, "town_a", "recruit", 3, new List<Cause>()));
+ Assert.Equal(0, after.Treasury);
+ Assert.Single(after.Cohorts);
+ }
+
+ // R-TRAIN-001, R-TRAIN-002
+ [Fact]
+ public void TheLegacyLoopRefusesBothOrdersAndRefundsAttention()
+ {
+ var c = ContentLoader.Load(RealContentTests.ContentRoot());
+ var s = Simulation.NewGame(c, GoldenRun.Seed, Mode.Historical);
+ var r = Step(c, s, new Train("tel_aviv", "recruit", 1), new CancelTraining(0));
+ Assert.All(r.Rejected, x => Assert.Equal("That order is not available in this game", x.Reason));
+ Assert.Equal(2, r.Rejected.Count);
+ Assert.Equal(Step(c, s).State.Hash(), r.State.Hash());
+ }
+
+ // R-TRAIN-002 (D-A3: cancelling returns the people but not the Money spent)
+ [Fact]
+ public void CancellingReturnsPeopleNotMoney()
+ {
+ var c = Town();
+ var s = Simulation.NewGame(c, 1, Mode.Historical);
+ var trained = Step(c, s, new Train("town_a", "halutz", 4)).State;
+ var id = Assert.Single(trained.Cohorts.Keys);
+ var cancelled = Step(c, trained, new CancelTraining(id));
+ Assert.Empty(cancelled.Rejected);
+ var kept = Step(c, trained).State;
+ var city = cancelled.State.Cities["town_a"];
+ Assert.Equal((10, 6), (city.Civilians, city.Employed)); // back as civilians without work
+ Assert.Empty(cancelled.State.Cohorts);
+ Assert.Equal(kept.Treasury, cancelled.State.Treasury, 9); // the IL 1.0m paid stays paid
+ var never = Step(c, Step(c, s).State).State;
+ Assert.Equal(never.Treasury - 1.0, cancelled.State.Treasury, 9);
+ Assert.Contains(cancelled.Why, x => x.System == "city" && x.Message == "Town A: 4 groups left pioneer training; the Money spent is not returned");
+ }
+
+ /// <summary>R-TRAIN-002 on its own, without the turn's housing step (which would house returned refugees and hide where
+ /// the people went): they come back as civilians without work, not as refugees.</summary>
+ // R-TRAIN-002
+ [Fact]
+ public void CancelledPeopleComeBackAsCiviliansWithoutWorkNotAsRefugees()
+ {
+ var c = Town();
+ var s = Step(c, Simulation.NewGame(c, 1, Mode.Historical), new Train("town_a", "recruit", 3)).State;
+ var before = s.Cities["town_a"];
+ var after = s.Clone();
+ Assert.Null(Training.Cancel(c, after, Assert.Single(s.Cohorts.Keys), new List<Cause>()));
+ var city = after.Cities["town_a"];
+ Assert.Equal((before.Civilians + 3, before.Employed, before.Refugees, before.Recruits), (city.Civilians, city.Employed, city.Refugees, city.Recruits));
+ Assert.Equal(s.Treasury, after.Treasury);
+ }
+
+ // R-TRAIN-002
+ [Fact]
+ public void CancellingAnUnknownOrFinishedCohortIsRefusedAndChangesNothing()
+ {
+ var c = Town();
+ var s = Simulation.NewGame(c, 1, Mode.Historical);
+ var r = Step(c, s, new CancelTraining(999));
+ Assert.Equal("There is no such training group", Assert.Single(r.Rejected).Reason);
+ Assert.Equal(Step(c, s).State.Hash(), r.State.Hash());
+
+ var one = Step(c, s, new Train("town_a", "recruit", 1)).State;
+ var id = Assert.Single(one.Cohorts.Keys);
+ var done = Step(c, one).State; // the fixture's recruit trains for 2 turns
+ Assert.Empty(done.Cohorts);
+ var late = Step(c, done, new CancelTraining(id));
+ Assert.Equal("There is no such training group", Assert.Single(late.Rejected).Reason);
+ Assert.Equal(Step(c, done).State.Hash(), late.State.Hash());
+ Assert.Equal(1, late.State.Cities["town_a"].Recruits);
+ }
+
+ // R-TRAIN-001, R-TRAIN-002
+ [Fact]
+ public void BothOrdersSurviveASave()
+ {
+ var g = GameSession.New(Mvp, GoldenRun.Seed, Mode.Historical);
+ g.Step(new Command[] { new Train("tel_aviv", "halutz", 2) });
+ var id = Assert.Single(g.State.Cohorts.Keys);
+ g.Step(new Command[] { new CancelTraining(id), new Train("tel_aviv", "recruit", 3) });
+ g.Step(new Command[0]);
+ var text = g.Save.Write();
+ Assert.Contains("\ntrain tel_aviv halutz 2\n", text);
+ Assert.Contains($"\nuntrain {id}\n", text);
+ Assert.Contains("\ntrain tel_aviv recruit 3\n", text);
+ var loaded = GameSession.Load(Mvp, text, out _).State;
+ Assert.Equal(g.State.Hash(), loaded.Hash());
+ Assert.Single(loaded.Cohorts);
+ }
+
+ // ---- progress in the resolver (R-TRAIN-003, step 4 of section 2.3) ----
+
+ // R-TRAIN-003
+ [Fact]
+ public void ARecruitCohortCompletesAfterExactlyItsTrainingTurns()
+ {
+ var turns = Mvp.UnitTypes.Single(t => t.Id == "recruit").TrainingTurns;
+ Assert.Equal(3, turns);
+ var s = Step(Mvp, Simulation.NewGame(Mvp, GoldenRun.Seed, Mode.Historical), new Train("tel_aviv", "recruit", 3)).State;
+ for (int turn = 1; turn < turns; turn++)
+ {
+ Assert.Equal(turns - turn, Assert.Single(s.Cohorts.Values).TurnsLeft);
+ Assert.Equal(0, s.Cities["tel_aviv"].Recruits);
+ s = Step(Mvp, s).State;
+ }
+ Assert.Empty(s.Cohorts);
+ Assert.Equal(3, s.Cities["tel_aviv"].Recruits);
+ Assert.Empty(s.Units); // a recruit is a count until Phase 5
+ }
+
+ /// <summary>The timing rule, the plan's reading of D-A6 (Task 4.3) and not part of the owner's ruling: the turn a cohort is ordered in is its first training turn, so a cohort
+ /// ordered on turn T with training_turns 3 is done at the end of turn T+2. The other reading (done at the end of T+3) is a
+ /// one-line change: the TurnsLeft a cohort opens with in Training.Start.</summary>
+ // R-TRAIN-001, R-TRAIN-003
+ [Fact]
+ public void ACohortOrderedOnTurnTWithThreeTurnsFinishesAtTheEndOfTurnTPlusTwo()
+ {
+ Assert.Equal(3, Mvp.UnitTypes.Single(t => t.Id == "recruit").TrainingTurns);
+ var start = Simulation.NewGame(Mvp, GoldenRun.Seed, Mode.Historical);
+ var t0 = Step(Mvp, start, new Train("tel_aviv", "recruit", 2)).State; // the end of turn T
+ var t1 = Step(Mvp, t0).State; // the end of turn T+1
+ var t2 = Step(Mvp, t1).State; // the end of turn T+2
+ Assert.Single(t1.Cohorts);
+ Assert.Equal(0, t1.Cities["tel_aviv"].Recruits);
+ Assert.Empty(t2.Cohorts);
+ Assert.Equal(2, t2.Cities["tel_aviv"].Recruits);
+
+ var u0 = Step(Mvp, start, new Train("tel_aviv", "halutz", 2)).State; // halutz: 4 turns, done at the end of T+3
+ var u2 = Step(Mvp, Step(Mvp, u0).State).State;
+ Assert.Empty(u2.Units);
+ Assert.Equal(2, Step(Mvp, u2).State.Units.Count);
+ }
+
+ // R-TRAIN-003
+ [Fact]
+ public void AHalutzCohortBecomesUnitsWithConsecutiveIdsAtTheCitysHex()
+ {
+ var s = Simulation.NewGame(Mvp, GoldenRun.Seed, Mode.Historical);
+ var r = Step(Mvp, s, new Train("tel_aviv", "halutz", 3));
+ s = r.State;
+ var cohort = Assert.Single(s.Cohorts.Keys);
+ for (int turn = 1; turn < Mvp.UnitTypes.Single(t => t.Id == "halutz").TrainingTurns; turn++)
+ {
+ Assert.Empty(s.Units);
+ s = Step(Mvp, s).State;
+ }
+ Assert.Empty(s.Cohorts);
+ Assert.Equal(new[] { cohort + 1, cohort + 2, cohort + 3 }, s.Units.Keys);
+ Assert.All(s.Units.Values, u => Assert.Equal(("halutz", -3, 19), (u.Type, u.Q, u.R))); // Tel Aviv's settlement hex
+ Assert.Equal(cohort + 4, s.NextId);
+ Assert.Equal(0, s.Cities["tel_aviv"].Recruits);
+ }
+
+ // R-TRAIN-003: cohorts end in ascending id, each taking its unit ids in turn. Two cities on different hexes show the order.
+ [Fact]
+ public void CohortsThatEndOnTheSameTurnEndInIdOrder()
+ {
+ var c = ContentLoader.Load(Fixture.Write(Fixture.Gdd(new Dictionary<string, string>
+ {
+ ["map/settlement_hexes.yaml"] = "settlements:\n - { id: town_a, q: 1, r: 0 }\n - { id: town_b, q: 2, r: 1 }\n",
+ ["map/settlements_1948.yaml"] = Fixture.Files["map/settlements_1948.yaml"]
+ + " - { id: town_b, name: Town B, lon: 34.42, lat: 33.28, type: town, founded: 1900, pre_modern: false }\n",
+ ["cities.yaml"] = "cities:\n - { id: town_a, housing_capacity: 12, job_slots: 20, civilians: 10, employed: 6, facilities: [hakhshara] }\n"
+ + " - { id: town_b, housing_capacity: 12, job_slots: 20, civilians: 10, employed: 6, facilities: [hakhshara] }\n",
+ })));
+ var s = Simulation.NewGame(c, 1, Mode.Historical);
+ s.Attention = 10; // two orders on the fixture's first turn
+ var r = Step(c, s, new Train("town_b", "halutz", 1), new Train("town_a", "halutz", 2));
+ Assert.Empty(r.Rejected);
+ s = Step(c, Step(c, r.State).State).State; // the fixture's halutz trains for 3 turns
+ Assert.Empty(s.Cohorts);
+ Assert.Equal(new[] { (2, 1), (1, 0), (1, 0) }, s.Units.Values.Select(u => (u.Q, u.R))); // town_b's cohort first: its id is lower
+ }
+
+ [Fact]
+ public void TheResolverTrainsNothingInTheLegacyLoop()
+ {
+ var c = ContentLoader.Load(RealContentTests.ContentRoot());
+ var s = Step(c, Simulation.NewGame(c, GoldenRun.Seed, Mode.Historical)).State;
+ Assert.Empty(s.Cohorts);
+ Assert.DoesNotContain("train[", s.Describe());
+ }
+}
diff --git a/sim/Statecraft.Sim.Tests/golden/manifest.txt b/sim/Statecraft.Sim.Tests/golden/manifest.txt
index d74142125..04e18d3ed 100644
--- a/sim/Statecraft.Sim.Tests/golden/manifest.txt
+++ b/sim/Statecraft.Sim.Tests/golden/manifest.txt
@@ -7,5 +7,5 @@ hash1952 62f8ec61a14acff4eab503381994a7c94d7a2f786dcfde5c4c19439ac8b4c5e8
smoke5 d3fdd459ddb876bd8d775c20edd1202cf56ca7134a8ad06f873d4d92034aa5b6
scenario-reckless c0bd12bc481a9f2dbeea19aebc981d5347caa1e1cf2e6fd5a5acdf107f2f9045
scenario-cautious 1d5b8d7126160021963537f2a198e377b27d478f522e8c6be63babe9e1b8f482
-mvp-slice f6931e2432b906edffbafb17087add152974645d468ec721b0606f837277446c
+mvp-slice 6343eee818634ebcf60684507d7785251bc8c9ad01648f211202acad795518a2
scenario-mvp-absorb-first 59ea3181e219ef3facbe6b5b76910b96d5c3feced0beeecd29d932295511f9fe
diff --git a/sim/Statecraft.Sim.Tests/golden/mvp-slice.txt b/sim/Statecraft.Sim.Tests/golden/mvp-slice.txt
index a6e585f07..9531f711c 100644
--- a/sim/Statecraft.Sim.Tests/golden/mvp-slice.txt
+++ b/sim/Statecraft.Sim.Tests/golden/mvp-slice.txt
@@ -41,7 +41,7 @@ pop{
veterans=656752.739703733 [41240AE17ABA729C]
sit[
treasury=0 [0000000000000000]
-debt=22.748732976636184 [4036BFACF6E016D2]
+debt=23.248732976636184 [40373FACF6E016D2]
fx=80.85238326859616 [4054368D728D91CC]
rung=5;cf=40;
mob=0.8 [3FE999999999999A]
@@ -80,5 +80,8 @@ map[
mapturn=0001-01-01:0;
over=
city{
- tel_aviv=120,90,120,90,91
-coh=0.6842783505154639 [3FE5E59BB61A644A]
\ No newline at end of file
+ tel_aviv=120,90,120,90,90
+coh=0.685880829015544 [3FE5F2BC5A326776]
+units[
+ 1:halutz@-3,19
+next=2
\ No newline at end of file
diff --git a/sim/Statecraft.Sim/AttentionSystem.cs b/sim/Statecraft.Sim/AttentionSystem.cs
index 77486a23b..1473917bc 100644
--- a/sim/Statecraft.Sim/AttentionSystem.cs
+++ b/sim/Statecraft.Sim/AttentionSystem.cs
@@ -7,11 +7,11 @@ namespace Statecraft.Sim
public static class AttentionSystem
{
static readonly HashSet<string> Kinds = new HashSet<string>
- { "set_policy", "allocate_budget", "choose_event_option", "set_mobilization", "security_order", "appoint", "map_action", "assign_workers" };
+ { "set_policy", "allocate_budget", "choose_event_option", "set_mobilization", "security_order", "appoint", "map_action", "assign_workers", "train", "cancel_training" };
/// <summary>The kinds only the GDD v0.1 loop runs. Rules price them only when systems.loop is gdd, and the legacy loop
/// refuses them before charging Attention.</summary>
- static readonly HashSet<string> GddKinds = new HashSet<string> { "assign_workers" };
+ static readonly HashSet<string> GddKinds = new HashSet<string> { "assign_workers", "train", "cancel_training" };
public static IReadOnlyCollection<string> CommandKinds => Kinds;
diff --git a/sim/Statecraft.Sim/Cities.cs b/sim/Statecraft.Sim/Cities.cs
index 6186739eb..52dfcd40a 100644
--- a/sim/Statecraft.Sim/Cities.cs
+++ b/sim/Statecraft.Sim/Cities.cs
@@ -49,6 +49,7 @@ namespace Statecraft.Sim
/// a placeholder: what happens to people beyond it is D-D1, still open.</summary>
public static void House(Content c, GameState s, List<Cause> why)
{
+ // PLACEHOLDER (owner question, #377): only civilians take housing; people in training and recruits do not.
foreach (var x in s.Cities.Values.ToList())
{
var moved = Math.Min(x.Refugees, Math.Max(0, x.HousingCapacity - x.Civilians));
diff --git a/sim/Statecraft.Sim/Commands.cs b/sim/Statecraft.Sim/Commands.cs
index dfb32fcea..ff9f769e9 100644
--- a/sim/Statecraft.Sim/Commands.cs
+++ b/sim/Statecraft.Sim/Commands.cs
@@ -67,6 +67,24 @@ namespace Statecraft.Sim
public AssignWorkers(string city, string role, int count) { City = city; Role = role; Count = count; }
}
+ /// <summary>Starts <see cref="Count"/> of <see cref="City"/>'s civilians without work training as <see cref="Track"/> (a
+ /// unit type with a facility: recruit or halutz; Training.Start, R-TRAIN-001). GDD v0.1 loop only.</summary>
+ public sealed class Train : Command
+ {
+ public override string Kind => Training.TrainKind;
+ public string City { get; } public string Track { get; } public int Count { get; }
+ public Train(string city, string track, int count) { City = city; Track = track; Count = count; }
+ }
+
+ /// <summary>Ends training cohort <see cref="Cohort"/> early: its people return as civilians and the Money spent is not
+ /// returned (Training.Cancel, R-TRAIN-002, D-A3). GDD v0.1 loop only.</summary>
+ public sealed class CancelTraining : Command
+ {
+ public override string Kind => Training.CancelKind;
+ public int Cohort { get; }
+ public CancelTraining(int cohort) { Cohort = cohort; }
+ }
+
public sealed class Rejection
{
public Command Command { get; } public string Reason { get; }
@@ -96,6 +114,8 @@ namespace Statecraft.Sim
case Appoint a: Text(a.Office, "Office"); Text(a.Person, "Person"); break;
case MapAction m: Text(m.Action, "Action"); break;
case AssignWorkers w: Text(w.City, "City"); Text(w.Role, "Role"); break;
+ case Train t: Text(t.City, "City"); Text(t.Track, "Track"); break;
+ case CancelTraining _: break;
case SetMobilization _: case SecurityOrder _: break;
default: throw new ArgumentException("unknown command type " + cmd.GetType().Name, "commands");
}
diff --git a/sim/Statecraft.Sim/Content.cs b/sim/Statecraft.Sim/Content.cs
index f50d74358..ee861e435 100644
--- a/sim/Statecraft.Sim/Content.cs
+++ b/sim/Statecraft.Sim/Content.cs
@@ -346,6 +346,13 @@ namespace Statecraft.Sim
{
public string Id { get; set; } = "";
public string Kind { get; set; } = "";
+ /// <summary>Where a civilian trains to become this type (military_camp or hakhshara; GDD "Progression"), or "" for a
+ /// type nobody trains into (R-TRAIN-001).</summary>
+ public string Facility { get; set; } = "";
+ /// <summary>Turns a cohort trains, counting the turn it was ordered in (R-TRAIN-003). Only with a facility.</summary>
+ public int TrainingTurns { get; set; }
+ /// <summary>IL millions per population unit trained, paid when training starts (R-TRAIN-001). Only with a facility.</summary>
+ public double TrainingCost { get; set; }
}
/// <summary>One stretch of a budget line's ownership (rules.yaml budget_owners): from this day (inclusive) the office owns the line.</summary>
diff --git a/sim/Statecraft.Sim/ContentLoader.cs b/sim/Statecraft.Sim/ContentLoader.cs
index 5be30b785..3c621735e 100644
--- a/sim/Statecraft.Sim/ContentLoader.cs
+++ b/sim/Statecraft.Sim/ContentLoader.cs
@@ -874,7 +874,22 @@ namespace Statecraft.Sim
}
Unique(uf, "types", c.UnitTypes.Select(x => x.Id));
foreach (var x in c.UnitTypes)
- if (x.Kind != "population" && x.Kind != "unit") throw new ContentException(uf, $"types[{x.Id}].kind", "must be population or unit");
+ {
+ var at = $"types[{x.Id}]";
+ if (x.Kind != "population" && x.Kind != "unit") throw new ContentException(uf, at + ".kind", "must be population or unit");
+ if (x.Facility == "")
+ {
+ // Training (R-TRAIN-001) needs a place to train; values without one would be read by nothing.
+ if (x.TrainingTurns != 0) throw new ContentException(uf, at + ".training_turns", "only a type with a facility trains");
+ if (x.TrainingCost != 0) throw new ContentException(uf, at + ".training_cost", "only a type with a facility trains");
+ continue;
+ }
+ if (!Facilities.Contains(x.Facility)) throw new ContentException(uf, at + ".facility", $"unknown facility '{x.Facility}' (military_camp or hakhshara)");
+ if (x.TrainingTurns < 1) throw new ContentException(uf, at + ".training_turns", "must be >= 1");
+ if (!(x.TrainingCost >= 0 && IsFinite(x.TrainingCost))) throw new ContentException(uf, at + ".training_cost", "must be a finite number >= 0");
+ // A trained count lands in City.Recruits (R-TRAIN-003); other trained counts wait for their decisions (D-D4).
+ if (x.Kind == "population" && x.Id != "recruit") throw new ContentException(uf, at + ".kind", "only recruit is a trained count until Phase 5");
+ }
var cities = new HashSet<string>(c.Cities.Select(x => x.Id));
foreach (var (file, r) in new[] { ("rules.yaml", c.Rules) }.Concat(c.EraRules.OrderBy(kv => kv.Key, StringComparer.Ordinal).Select(kv => ("rules/" + kv.Key + ".yaml", kv.Value))))
{
diff --git a/sim/Statecraft.Sim/GameState.cs b/sim/Statecraft.Sim/GameState.cs
index 7e4ebf980..5fc161ad7 100644
--- a/sim/Statecraft.Sim/GameState.cs
+++ b/sim/Statecraft.Sim/GameState.cs
@@ -63,7 +63,9 @@ namespace Statecraft.Sim
public double Cohesion;
/// <summary>The movable units by id.</summary>
public SortedList<int, Unit> Units = new SortedList<int, Unit>();
- /// <summary>The next id a new unit takes. Ids are never reused.</summary>
+ /// <summary>The groups in training by id (R-TRAIN-001). A cohort leaves when it finishes or is cancelled.</summary>
+ public SortedList<int, Cohort> Cohorts = new SortedList<int, Cohort>();
+ /// <summary>The next id a new unit or training cohort takes (they share it). Ids are never reused.</summary>
public int NextId;
/// <summary>The date each completed objective was completed, by objective id (ordinal).</summary>
public SortedDictionary<string, DateTime> Objectives = new SortedDictionary<string, DateTime>(StringComparer.Ordinal);
@@ -90,6 +92,7 @@ namespace Statecraft.Sim
c.Placements = new List<Placement>(Placements);
c.Cities = new SortedDictionary<string, City>(Cities, StringComparer.Ordinal);
c.Units = new SortedList<int, Unit>(Units);
+ c.Cohorts = new SortedList<int, Cohort>(Cohorts);
c.Objectives = new SortedDictionary<string, DateTime>(Objectives, StringComparer.Ordinal);
return c;
}
@@ -183,6 +186,7 @@ namespace Statecraft.Sim
else sb.Append(bits);
}
if (Units.Count > 0) Section("units", '[', ']', Units.Values.Select(x => x.Canonical()));
+ if (Cohorts.Count > 0) Section("train", '[', ']', Cohorts.Values.Select(x => x.Canonical()));
if (NextId != 0) { Sep(); Nl(); sb.Append("next=").Append(NextId.ToString(CultureInfo.InvariantCulture)); }
if (Objectives.Count > 0)
Section("obj", '{', '}', Objectives.Select(kv => kv.Key + "=" + kv.Value.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)));
diff --git a/sim/Statecraft.Sim/GddState.cs b/sim/Statecraft.Sim/GddState.cs
index 740a7a933..d4afbb1b1 100644
--- a/sim/Statecraft.Sim/GddState.cs
+++ b/sim/Statecraft.Sim/GddState.cs
@@ -5,7 +5,7 @@ namespace Statecraft.Sim
/// <summary>A city in the GDD v0.1 loop (docs/GDD.md "Cities and construction"; owner decision D-A2: civilians and
/// refugees are counts per city). Counts are population units, each a group (D-A1). Immutable, so GameState.Clone can copy
/// the map shallowly; a change replaces the record. Only the attributes approved decisions define are here: housing
- /// condition, craftsmen and recruits arrive with the decisions that define them.</summary>
+ /// condition and craftsmen arrive with the decisions that define them.</summary>
public sealed class City
{
public string Id { get; }
@@ -17,17 +17,27 @@ namespace Statecraft.Sim
/// <summary>The civilians in jobs: part of <see cref="Civilians"/>, not in addition to them.</summary>
public int Employed { get; }
public int Refugees { get; }
+ /// <summary>The recruits who finished basic training here (GDD "Progression"; R-TRAIN-003). A count until Phase 5 makes
+ /// soldiers units.</summary>
+ public int Recruits { get; }
- public City(string id, int housingCapacity, int jobSlots, int civilians, int employed, int refugees)
+ public City(string id, int housingCapacity, int jobSlots, int civilians, int employed, int refugees, int recruits = 0)
{
Id = id; HousingCapacity = housingCapacity; JobSlots = jobSlots; Civilians = civilians; Employed = employed; Refugees = refugees;
+ Recruits = recruits;
}
/// <summary>The same city with new population counts.</summary>
- public City WithCounts(int civilians, int employed, int refugees) => new City(Id, HousingCapacity, JobSlots, civilians, employed, refugees);
+ public City WithCounts(int civilians, int employed, int refugees) => new City(Id, HousingCapacity, JobSlots, civilians, employed, refugees, Recruits);
- /// <summary>The record as the state hash writes it.</summary>
- public string Canonical() => string.Format(CultureInfo.InvariantCulture, "{0}={1},{2},{3},{4},{5}", Id, HousingCapacity, JobSlots, Civilians, Employed, Refugees);
+ /// <summary>The same city with a new number of recruits.</summary>
+ public City WithRecruits(int recruits) => new City(Id, HousingCapacity, JobSlots, Civilians, Employed, Refugees, recruits);
+
+ /// <summary>The record as the state hash writes it. The recruits are written only when there are some, so a city with
+ /// none hashes as it did before training existed (R-LOOP-002's rule).</summary>
+ public string Canonical() =>
+ string.Format(CultureInfo.InvariantCulture, "{0}={1},{2},{3},{4},{5}", Id, HousingCapacity, JobSlots, Civilians, Employed, Refugees)
+ + (Recruits == 0 ? "" : "," + Recruits.ToString(CultureInfo.InvariantCulture));
}
/// <summary>A movable unit in the GDD v0.1 loop (owner decision D-A2: halutzim and soldiers are movable units), a group
@@ -44,4 +54,24 @@ namespace Statecraft.Sim
/// <summary>The record as the state hash writes it.</summary>
public string Canonical() => string.Format(CultureInfo.InvariantCulture, "{0}:{1}@{2},{3}", Id, Type, Q, R);
}
+
+ /// <summary>A group of a city's people in training (GDD "Progression"; R-TRAIN-001): <see cref="Count"/> population units
+ /// becoming <see cref="Type"/> (a unit_types.yaml id with a facility) in <see cref="TurnsLeft"/> more turns. Immutable; a
+ /// change replaces the record.</summary>
+ public sealed class Cohort
+ {
+ public int Id { get; }
+ public string Type { get; }
+ public string City { get; }
+ public int Count { get; }
+ public int TurnsLeft { get; }
+
+ public Cohort(int id, string type, string city, int count, int turnsLeft) { Id = id; Type = type; City = city; Count = count; TurnsLeft = turnsLeft; }
+
+ /// <summary>The same cohort with <paramref name="turnsLeft"/> turns to go.</summary>
+ public Cohort WithTurnsLeft(int turnsLeft) => new Cohort(Id, Type, City, Count, turnsLeft);
+
+ /// <summary>The record as the state hash writes it.</summary>
+ public string Canonical() => string.Format(CultureInfo.InvariantCulture, "{0}:{1}@{2}x{3}/{4}", Id, Type, City, Count, TurnsLeft);
+ }
}
diff --git a/sim/Statecraft.Sim/MvpSlice.cs b/sim/Statecraft.Sim/MvpSlice.cs
index 543d86683..713151087 100644
--- a/sim/Statecraft.Sim/MvpSlice.cs
+++ b/sim/Statecraft.Sim/MvpSlice.cs
@@ -7,7 +7,8 @@ namespace Statecraft.Sim
{
/// <summary>The GDD v0.1 slice before cutover (spec 2026-10-12 section 2.1): the real content with the loop switch on
/// (eras.yaml systems.loop: gdd in every era), monthly turns (rules.yaml turn_lengths all month) and the slice's city data
- /// (cities.yaml, unit_types.yaml, rules.yaml mvp and the GDD command kinds' attention_cost), all placeholders. Tests, the MVP
+ /// (cities.yaml, unit_types.yaml, rules.yaml mvp and the GDD command kinds' attention_cost), all placeholders, and the
+ /// design assumption D-D5 (one military camp and one Hakhshara at the start). Tests, the MVP
/// goldens and the dev flag load it; the real eras.yaml and rules.yaml keep the defaults until cutover. It edits YAML
/// nodes, not text, so a comment or the key order in the real files cannot break it. Balance values the owner has not set
/// may live here, and never under content/ (controller ruling 2, 12 October 2026). R-LOOP-003.</summary>
@@ -25,13 +26,26 @@ cities:
job_slots: 90 # PLACEHOLDER: owner sets
civilians: 100 # PLACEHOLDER: owner sets
employed: 80 # PLACEHOLDER: owner sets
- facilities: [] # PR 4 adds military_camp and hakhshara (D-D5: one of each at start)
+ # PLACEHOLDER: owner sets (D-D5: one of each exists at start; a design assumption, not a claim about 1948).
+ # More are built by pioneers (Phase 4).
+ facilities: [military_camp, hakhshara]
";
- /// <summary>The slice's population types (D-A2: civilians and refugees are counts per city).</summary>
+ /// <summary>The slice's population types (D-A2: civilians and refugees are counts per city; halutzim are movable
+ /// units) and their training (GDD "Progression").</summary>
public const string UnitTypes = @"types:
- { id: civilian, kind: population }
- { id: refugee, kind: population }
+ - id: recruit # civilian to recruit, through basic training (GDD ""Progression"")
+ kind: population # a count per city until Phase 5
+ facility: military_camp
+ training_turns: 3 # PLACEHOLDER: owner sets
+ training_cost: 0.5 # PLACEHOLDER: owner sets (IL millions per group)
+ - id: halutz # civilian to Halutz, through pioneer training in a Hakhshara (GDD ""Progression"")
+ kind: unit # a movable unit (D-A2)
+ facility: hakhshara
+ training_turns: 4 # PLACEHOLDER: owner sets
+ training_cost: 0.5 # PLACEHOLDER: owner sets (IL millions per group)
";
/// <summary>Wraps <paramref name="readFile"/> (the loader's file reader): eras.yaml and rules.yaml come back with the
@@ -71,8 +85,12 @@ cities:
["cohesion_jobs_weight"] = 0.5, // PLACEHOLDER (D-C1 open; the two weights sum to 1)
["arrivals_city"] = "tel_aviv", // Phase 1 has one city: every arrival lands there
};
- if (root.TryGetValue("attention_cost", out var ac) && ac is Dictionary<object, object> costs && !costs.ContainsKey("assign_workers"))
- costs["assign_workers"] = 0.5; // PLACEHOLDER: owner sets
+ if (root.TryGetValue("attention_cost", out var ac) && ac is Dictionary<object, object> costs)
+ {
+ if (!costs.ContainsKey("assign_workers")) costs["assign_workers"] = 0.5; // PLACEHOLDER: owner sets
+ if (!costs.ContainsKey("train")) costs["train"] = 1; // PLACEHOLDER: owner sets
+ if (!costs.ContainsKey("cancel_training")) costs["cancel_training"] = 0.5; // PLACEHOLDER: owner sets
+ }
return Writer.Serialize(root);
}
return text;
diff --git a/sim/Statecraft.Sim/Reference/ReferencePlayer.cs b/sim/Statecraft.Sim/Reference/ReferencePlayer.cs
index 9316ee712..3a9642f46 100644
--- a/sim/Statecraft.Sim/Reference/ReferencePlayer.cs
+++ b/sim/Statecraft.Sim/Reference/ReferencePlayer.cs
@@ -5,8 +5,9 @@ using System.Linq;
namespace Statecraft.Sim.Reference
{
/// <summary>Test policy for the GDD goldens (D-A7): a stated simple policy, not game AI and not historical. It sends
- /// HistoricalAI's orders, then fills each city's jobs with as many civilians as there are jobs, while the turn's Attention
- /// lasts. It lives in Statecraft.Sim only so Unity can replay the MVP goldens (#394); no game mode or UI may reach it
+ /// HistoricalAI's orders, then fills each city's jobs with as many civilians as there are jobs, then, when there is no
+ /// halutz and none in training, trains one halutz group in the first city with a Hakhshara and a civilian left without
+ /// work, while the turn's Attention and the Treasury last. It lives in Statecraft.Sim only so Unity can replay the MVP goldens (#394); no game mode or UI may reach it
/// (ReferencePlayerTests.NoGameModeOrUiReachesIt).</summary>
public static class ReferencePlayer
{
@@ -23,6 +24,17 @@ namespace Statecraft.Sim.Reference
list.Add(new AssignWorkers(city.Id, "job", want));
left -= cost;
}
+ var halutz = c.UnitTypes.FirstOrDefault(t => t.Id == "halutz");
+ if (halutz == null || s.Units.Values.Any(u => u.Type == halutz.Id) || s.Cohorts.Values.Any(k => k.Type == halutz.Id)) return list;
+ var trainCost = AttentionSystem.Cost(c, s, Training.TrainKind);
+ if (trainCost > left + 1e-9 || halutz.TrainingCost > s.Treasury) return list;
+ foreach (var city in s.Cities.Values)
+ {
+ var employed = list.OfType<AssignWorkers>().Where(a => a.City == city.Id).Select(a => a.Count).DefaultIfEmpty(city.Employed).Last();
+ if (city.Civilians - employed < 1 || !c.Cities.First(x => x.Id == city.Id).Facilities.Contains(halutz.Facility)) continue;
+ list.Add(new Train(city.Id, halutz.Id, 1));
+ break;
+ }
return list;
}
}
diff --git a/sim/Statecraft.Sim/SaveGame.cs b/sim/Statecraft.Sim/SaveGame.cs
index 9ec45145c..3de9b4ad5 100644
--- a/sim/Statecraft.Sim/SaveGame.cs
+++ b/sim/Statecraft.Sim/SaveGame.cs
@@ -22,7 +22,8 @@ namespace Statecraft.Sim
/// ruleset legacy|gdd-0.1 the rules it was played under (Content.Ruleset); another ruleset refuses it (R-SAVE-001)
/// turn starts the next turn's command list (one per Simulation.Step)
/// &lt;command&gt; ... policy ID LEVEL | budget OFFICE=SHARE,... | event ID OPTION | mobilize LEVEL |
- /// security DELTA | appoint OFFICE PERSON | map ACTION Q R | work CITY ROLE N
+ /// security DELTA | appoint OFFICE PERSON | map ACTION Q R | work CITY ROLE N |
+ /// train CITY TRACK N | untrain COHORT
/// end &lt;hex&gt; GameState.Hash() after the last turn (checks the replay)
/// Doubles are IEEE bit patterns in hex, so replays are exact; strings are percent-escaped (Uri.EscapeDataString).
/// </summary>
@@ -102,6 +103,8 @@ namespace Statecraft.Sim
Appoint a => $"appoint {Esc(a.Office)} {Esc(a.Person)}",
MapAction m => $"map {Esc(m.Action)} {Int(m.Q)} {Int(m.R)}",
AssignWorkers w => $"work {Esc(w.City)} {Esc(w.Role)} {Int(w.Count)}",
+ Train t => $"train {Esc(t.City)} {Esc(t.Track)} {Int(t.Count)}",
+ CancelTraining t => $"untrain {Int(t.Cohort)}",
_ => throw new ArgumentException($"Cannot save command kind '{cmd.Kind}'", nameof(cmd)),
};
@@ -189,6 +192,8 @@ namespace Statecraft.Sim
case "appoint": Arity(3); return new Appoint(Str(f[1]), Str(f[2]));
case "map": Arity(4); return new MapAction(Str(f[1]), I(f[2]), I(f[3]));
case "work": Arity(4); return new AssignWorkers(Str(f[1]), Str(f[2]), I(f[3]));
+ case "train": Arity(4); return new Train(Str(f[1]), Str(f[2]), I(f[3]));
+ case "untrain": Arity(2); return new CancelTraining(I(f[1]));
default: throw new SaveException(line, $"unknown command '{f[0]}'");
}
}
diff --git a/sim/Statecraft.Sim/Scenario.cs b/sim/Statecraft.Sim/Scenario.cs
index a0a8ac341..1f7dbb174 100644
--- a/sim/Statecraft.Sim/Scenario.cs
+++ b/sim/Statecraft.Sim/Scenario.cs
@@ -22,7 +22,7 @@ namespace Statecraft.Sim
/// </code>
/// Kinds: set_policy (policy, level), allocate_budget (shares: {office: share}), choose_event_option (event, option),
/// set_mobilization (level), security_order (delta), appoint (office, person), map_action (action, q, r), assign_workers
- /// (city, role, count; GDD content only). A turn with no
+ /// (city, role, count), train (city, track, count), cancel_training (cohort; GDD content only). A turn with no
/// scripted command passes; events nobody answered are delegated, as in the game. A command the sim rejects fails the run.</summary>
public sealed class Scenario
{
@@ -67,6 +67,7 @@ namespace Statecraft.Sim
["choose_event_option"] = new[] { "event", "option" }, ["set_mobilization"] = new[] { "level" },
["security_order"] = new[] { "delta" }, ["appoint"] = new[] { "office", "person" },
["map_action"] = new[] { "action", "q", "r" }, ["assign_workers"] = new[] { "city", "role", "count" },
+ ["train"] = new[] { "city", "track", "count" }, ["cancel_training"] = new[] { "cohort" },
};
public static IReadOnlyCollection<string> Kinds => Allowed.Keys;
@@ -92,6 +93,8 @@ namespace Statecraft.Sim
case "appoint": return new Appoint(Str(c, "office"), Str(c, "person"));
case "map_action": return new MapAction(Str(c, "action"), Whole(c, "q"), Whole(c, "r"));
case "assign_workers": return new AssignWorkers(Str(c, "city"), Str(c, "role"), Whole(c, "count"));
+ case "train": return new Train(Str(c, "city"), Str(c, "track"), Whole(c, "count"));
+ case "cancel_training": return new CancelTraining(Whole(c, "cohort"));
default: throw new InvalidDataException($"command kind '{kind}' has no builder");
}
}
@@ -129,7 +132,8 @@ namespace Statecraft.Sim
{
SetPolicy p => $"{p.Policy} {p.Level}", ChooseEventOption e => $"{e.EventId}/{e.OptionId}", SetMobilization m => m.Level.ToString(CultureInfo.InvariantCulture),
SecurityOrder o => o.Delta.ToString(CultureInfo.InvariantCulture), Appoint a => $"{a.Office} {a.Person}", MapAction m => $"{m.Action} {m.Q},{m.R}",
- AssignWorkers w => $"{w.City} {w.Role} {w.Count}", _ => c.Kind,
+ AssignWorkers w => $"{w.City} {w.Role} {w.Count}", Train t => $"{t.City} {t.Track} {t.Count}", CancelTraining t => t.Cohort.ToString(CultureInfo.InvariantCulture),
+ _ => c.Kind,
};
}
diff --git a/sim/Statecraft.Sim/Simulation.cs b/sim/Statecraft.Sim/Simulation.cs
index 87328f16c..f78fe9fdc 100644
--- a/sim/Statecraft.Sim/Simulation.cs
+++ b/sim/Statecraft.Sim/Simulation.cs
@@ -140,6 +140,10 @@ namespace Statecraft.Sim
return MapActions.Apply(c, s, m.Action, m.Q, m.R, why);
case AssignWorkers w:
return Cities.Assign(c, s, w.City, w.Role, w.Count, why);
+ case Train t:
+ return Training.Start(c, s, t.City, t.Track, t.Count, why);
+ case CancelTraining t:
+ return Training.Cancel(c, s, t.Cohort, why);
case SecurityOrder o:
// long arithmetic: an extreme delta clamps to the ladder's end instead of wrapping around.
SecuritySystem.SetRung(c, s, (int)Math.Max(1L, Math.Min(5L, (long)s.Rung + o.Delta)), why);
diff --git a/sim/Statecraft.Sim/Training.cs b/sim/Statecraft.Sim/Training.cs
new file mode 100644
index 000000000..fe251f75e
--- /dev/null
+++ b/sim/Statecraft.Sim/Training.cs
@@ -0,0 +1,99 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace Statecraft.Sim
+{
+ /// <summary>The GDD v0.1 training (docs/GDD.md "Progression"; Phase 1 PR 4): a city's civilians train in a military camp to
+ /// become recruits, or in a Hakhshara to become halutzim, over several turns (D-A3). The facilities are read from
+ /// cities.yaml: one of each exists at the start (D-D5, a design assumption), and pioneers will build more (Phase 4). Runs only
+ /// when eras.yaml systems.loop is gdd. Its causes go to the "city" group of the Why screen: they move a city's people and
+ /// pay for it, like the other city rules.</summary>
+ public static class Training
+ {
+ public const string TrainKind = "train";
+ public const string CancelKind = "cancel_training";
+
+ /// <summary>The facility's name in text the player reads.</summary>
+ static string Place(string facility) => facility == "military_camp" ? "military camp" : "Hakhshara";
+
+ /// <summary>The course the facility gives, in text the player reads.</summary>
+ static string Course(string facility) => facility == "military_camp" ? "basic training" : "pioneer training";
+
+ static string Groups(int n) => n == 1 ? "1 group" : FormattableString.Invariant($"{n} groups");
+
+ /// <summary>R-TRAIN-001: <paramref name="count"/> of the city's civilians without work start training as
+ /// <paramref name="track"/>, a unit type with a facility. The Treasury pays count * training_cost now; training does not
+ /// borrow. 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, it has fewer civilians without work,
+ /// or the Treasury holds less than the cost. Step has already refused it in the legacy loop.</summary>
+ public static string? Start(Content c, GameState s, string city, string track, int count, List<Cause> why)
+ {
+ if (!s.Cities.TryGetValue(city, out var x)) return "There is no such city";
+ var type = c.UnitTypes.FirstOrDefault(t => t.Id == track && t.Facility != "");
+ if (type == null) return "There is no such training";
+ if (count < 1) return "Train at least one group";
+ var name = PlayerText.Settlement(c, city);
+ if (!c.Cities.First(k => k.Id == city).Facilities.Contains(type.Facility)) return $"{name} has no {Place(type.Facility)}";
+ var idle = x.Civilians - x.Employed;
+ if (count > idle) return FormattableString.Invariant($"{name} has {idle} civilians without work");
+ var cost = count * type.TrainingCost;
+ // PLACEHOLDER (owner question, #377): a short Treasury refuses training, where map actions borrow instead.
+ if (cost > s.Treasury)
+ return $"Training costs {PlayerText.Money(c, "treasury", cost)} and the Treasury holds {PlayerText.Money(c, "treasury", s.Treasury)}";
+ s.Treasury -= cost;
+ // PLACEHOLDER (owner question, #377): trainees leave the civilians, and housing (R-CITY-004) counts civilians only,
+ // so their places are free for waiting refugees while they train. Social cohesion (R-CITY-005) also moves: its
+ // employed share is employed over civilians, so it rises when civilians without work leave for training.
+ s.Cities[city] = x.WithCounts(x.Civilians - count, x.Employed, x.Refugees);
+ 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));
+ why.Add(new Cause("city", city, -count, $"{name}: {Groups(count)} began {Course(type.Facility)}, cost {PlayerText.Money(c, "treasury", cost)}"));
+ 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. 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>
+ public static string? Cancel(Content c, GameState s, int cohort, List<Cause> why)
+ {
+ if (!s.Cohorts.TryGetValue(cohort, out var k)) return "There is no such training group";
+ var x = s.Cities[k.City];
+ s.Cities[k.City] = x.WithCounts(x.Civilians + k.Count, x.Employed, x.Refugees);
+ s.Cohorts.Remove(cohort);
+ 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.Facility)}; the Money spent is not returned"));
+ 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: recruits join the city's count, and halutzim become one movable unit
+ /// per group at the city's settlement hex, taking the next ids in turn.</summary>
+ public static void Progress(Content c, GameState s, List<Cause> why)
+ {
+ foreach (var k in s.Cohorts.Values.ToList())
+ {
+ if (k.TurnsLeft > 1) { s.Cohorts[k.Id] = k.WithTurnsLeft(k.TurnsLeft - 1); continue; }
+ s.Cohorts.Remove(k.Id);
+ var type = c.UnitTypes.First(t => t.Id == k.Type);
+ var name = PlayerText.Settlement(c, k.City);
+ 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.Facility)} and are halutzim"));
+ }
+ else
+ {
+ var x = s.Cities[k.City];
+ s.Cities[k.City] = x.WithRecruits(x.Recruits + k.Count);
+ why.Add(new Cause("city", k.City, k.Count, $"{name}: {Groups(k.Count)} finished {Course(type.Facility)} and are recruits"));
+ }
+ }
+ }
+ }
+}
diff --git a/sim/Statecraft.Sim/TurnResolver.cs b/sim/Statecraft.Sim/TurnResolver.cs
index 244735e6b..132b2a43a 100644
--- a/sim/Statecraft.Sim/TurnResolver.cs
+++ b/sim/Statecraft.Sim/TurnResolver.cs
@@ -14,7 +14,9 @@ namespace Statecraft.Sim
{
if (!c.IsGdd) return;
var r = c.RulesAt(s.Date).Mvp!; // the loader requires it in the GDD loop
- // 1-3. Enemy orders, combat, capture: Phase 5. 4. Training: PR 4. 5. Construction: PR 5.
+ // 1-3. Enemy orders, combat, capture: Phase 5.
+ Training.Progress(c, s, why); // 4. training
+ // 5. Construction: PR 5.
Cities.Produce(c, s, r, yearFraction, why); // 6. production
// 7. Consumption: Phase 2.
Cities.House(c, s, why); // 8. housing, then Social cohesion