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 3, one city: TurnResolver, housing, jobs, refugees, Social cohesion (refs #376) (#461)

Eyal Golan04bf7cb438dc
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8e3d10127..98d612c18 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,14 @@ adds a line under **Unreleased**; CI's `Changelog` job checks this (see `CONTRIB
## [Unreleased]
### Added
+- 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
+ the next turn (R-CITY-001 to R-CITY-005); `people_per_unit` must be the same in every era. Every balance value is a placeholder in `MvpSlice.Overlay`, never under
+ `content/`; Social cohesion feeds nothing else and is not shown while D-C1 is open. The reference player for the GDD
+ goldens (`Statecraft.Sim.Reference`, D-A7) is test policy that no game mode or UI reaches. New scenario golden
+ `scenario-mvp-absorb-first`. The real game is unchanged: `hash1950`, `hash1952`, `smoke5` and the two 1948 scenarios do
+ not move.
- Decision videos, phase 2 (#434 follow-up). On 11 decision cards an Illustration switch over the photograph plays a
short, silent AI-generated loop. It is labelled "AI-generated illustration" in place of the credit and carries a small
burned-in bilingual label. The photograph always shows first; nothing plays until the player asks, and the choice holds
@@ -207,6 +215,8 @@ adds a line under **Unreleased**; CI's `Changelog` job checks this (see `CONTRIB
- The map's near (bottom) tilt-shift band is lighter, as on promo 03: gently soft at the play zoom and almost none at the
wide overview, where the foreground is now sharp as on promo 02. On the owner's ruling of 2026-10-14; the far band is
unchanged (#390). Presentation only (#458).
+- The `mvp-slice` golden is re-pinned (`0451920a` to `f6931e24`): the slice now has its city and the GDD turn, and the
+ reference player fills the jobs (GDD Phase 1 PR 3, refs #376). The legacy goldens do not move.
- The trees are warm olive-brown instead of bright green, like the groves in promo 03 (refs #34): citrus groves, olive
crowns, palms and cypresses. Only the leaf colours change; the fruit, meshes and frame cost are the same.
- Map: settlement quick wins (refs #31). The White City's blocks are lime white, with a solid-parapet balcony on each
diff --git a/docs/determinism.md b/docs/determinism.md
index a92ff7b4e..edc80558a 100644
--- a/docs/determinism.md
+++ b/docs/determinism.md
@@ -69,11 +69,14 @@ command; its snapshot diff in the PR shows what moved, and the commit message sa
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 `HistoricalAI` until
-`MvpGolden.Until` (15 January 1949, eight monthly turns). `MvpGoldenTests` checks it against the manifest line `mvp-slice` and the
+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
+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
-exercises moves it, re-pins it and says why; the legacy goldens never move for it.
+exercises moves it, re-pins it and says why; the legacy goldens never move for it. A scenario with `content: mvp` plays the
+same slice instead of the real content: `scenario-mvp-absorb-first` (GDD Phase 1 PR 3) fills Tel Aviv's jobs on the first turn.
`Scenario` and `MvpGolden` live in `Statecraft.Sim` next to `GoldenRun`, so Unity, which gets only `Statecraft.Sim.dll` and
`YamlDotNet.dll` from `tools/build_sim_for_unity.sh`, can play the same runs (#394). The scenario files, the manifest and the
@@ -184,3 +187,4 @@ The hash reads the state keys, so it never sees a record outside its window. An
| playtest 1 E fix 1 | 1950 | `71e9904d` | 1948 war-period events revised after review: windows open on the turn before each decision, Yoav becomes the Hebron-hills decision, follow-ups use `requires`, Bernadotte's shared standing hit, security deltas halved, the elections a one-option card in January, two events added (Jerusalem cease-fire, Rhodes talks); still ends 1950-02-27, turn 35 |
| 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 |
diff --git a/docs/gdd/one-city.md b/docs/gdd/one-city.md
new file mode 100644
index 000000000..9fd8305a4
--- /dev/null
+++ b/docs/gdd/one-city.md
@@ -0,0 +1,42 @@
+# One city: housing, jobs, refugees
+
+## Player story
+
+As a player of the MVP, I want to put Tel Aviv's people to work and house the immigrants who arrive, so that the city earns Money and its people hold together (GDD objective 2, "Absorb immigrants" [S1]; decisions D-A4, D-A5 [S2]).
+
+## Rules
+
+- Civilians and refugees are counts per city, in population units of `people_per_unit` people (D-A1, D-A2 [S2]). The slice has one city, Tel Aviv (D-A4 [S2]).
+- `AssignWorkers(city, job, n)` sets how many of the city's civilians work. It is refused, with the state unchanged, for a negative count, more than the city's jobs or civilians, an unknown city or role, or the legacy loop (R-CITY-001). It costs 0.5 Attention (a placeholder) (unitless).
+- Each turn resolves in the order the owner approved for the plan's resolution phase (D-A6, #456 [S2][S3]): production, then housing and Social cohesion, then arrivals. A turn's arrivals are housed on the next turn.
+- Production: each employed unit earns `income_per_job_per_year` IL millions a year, for the turn's share of a year (R-CITY-002).
+- Arrivals: the CBS series in `content/aliyah.yaml` arrives as refugees in `arrivals_city`, in whole units, counted from the game's start so that no unit is lost or counted twice (R-CITY-003, D-A5 [S2]).
+- Housing: refugees become civilians, without a job, up to the city's housing capacity. The cap is a placeholder while D-D1 is open (R-CITY-004).
+- Social cohesion: a share from 0% to 100%, the weighted housed share and employed share over all cities (R-CITY-005). It is a placeholder while D-C1 is open: no other system reads it and nothing shows it.
+
+## Data touched
+
+- `cities.yaml`, `unit_types.yaml` and `rules.yaml` `mvp:` and `attention_cost.assign_workers`: supplied by `MvpSlice.Overlay` as placeholders, never under `content/` (ruling 2 [S3]).
+- `GameState`: `Cities` (counts), `Cohesion` (hashed as `coh=` when the state has cities), `Treasury`.
+- Save files: the `work CITY ROLE N` line. Scenarios: `assign_workers` and `content: mvp`.
+- `sim/Statecraft.Sim.Tests/golden/manifest.txt`: `mvp-slice` moves; `scenario-mvp-absorb-first` is new.
+
+## Done when
+
+- `dotnet test sim/Statecraft.sln` passes, including `CitiesContentTests`, `CitiesTests` and `ReferencePlayerTests`.
+- `hash1950`, `hash1952`, `smoke5`, `scenario-cautious` and `scenario-reckless` do not move.
+
+## Out of scope
+
+- Training, sites, the objective card and the score (PRs 4 to 6), and any display (PRs 7 and 8).
+- Housing condition (D-D2), overflow beyond capacity (D-D1), craftsmen (D-D4) and Social cohesion's effects (D-C1).
+
+## 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 3, docs/superpowers/plans/2026-10-12-gdd-phase-1.md
+
+## Open questions
+
+- The placeholder values (city start values, people per unit, income per job, the cohesion weights, the Attention cost) wait for the owner.
diff --git a/docs/rules/mvp.md b/docs/rules/mvp.md
index e87c6a8ff..9ab0613e6 100644
--- a/docs/rules/mvp.md
+++ b/docs/rules/mvp.md
@@ -12,10 +12,24 @@ R-TURN-001: The turn length on each security rung (1 to 5) is read from the rule
R-LOOP-001: `systems.loop` in eras.yaml is `legacy` (the default) or `gdd`, and every era has the same value. Its ruleset id, which a save records, is `legacy` or `gdd-0.1`.
-R-LOOP-003: `MvpSlice.Overlay` loads the real content with `systems.loop: gdd` in every era and `turn_lengths` all month, and changes nothing else. Tests, the MVP goldens and the dev flag use it until cutover.
+R-LOOP-003: `MvpSlice.Overlay` loads the real content with `systems.loop: gdd` in every era and `turn_lengths` all month, and adds the slice's placeholder city data (`cities.yaml`, `unit_types.yaml`, the rules' `mvp:` block and the GDD command kinds' `attention_cost`) where the content has none. It changes nothing else. Tests, the MVP goldens and the dev flag use it until cutover.
R-LOOP-002: The GDD state (cities, units, the next unit id, completed objectives, the score) is written into the state hash only when it is set. With the legacy loop the hash text is unchanged, byte for byte.
## Saves
R-SAVE-001: A save names the ruleset it was played under (`ruleset legacy` or `ruleset gdd-0.1`, save schema 2). A game refuses a save made under another ruleset, with a message to start a new game. A schema 1 save has no ruleset line and is legacy.
+
+## Cities
+
+Each GDD turn resolves in the order of the approved plan's section 2.3 (decision D-A6): production, then housing and Social cohesion, then arrivals.
+
+R-CITY-001: `AssignWorkers(city, role, n)` sets how many of the city's civilians work in `role` (only `job` exists). It is refused, with the state unchanged and the Attention refunded, when the city or role is unknown, `n` is negative, or `n` is above the city's jobs or its civilians. The legacy loop refuses it before charging Attention.
+
+R-CITY-002: Each turn every city's employed units add `employed * income_per_job_per_year * the turn's share of a year` to the Treasury.
+
+R-CITY-003: Arrivals from the CBS series (`aliyah.yaml`) become refugees in the rules' `arrivals_city`. Let `P(t)` be the people the series brings from the first era's start to the date `t`, summed over the origin groups in ordinal order. A turn from date `d` to date `e` adds `floor(P(e) / people_per_unit) - floor(P(d) / people_per_unit)` refugees. `people_per_unit` is the same in every era (the loader refuses an era that changes it), so over any run of turns the refugees added are `floor(P(end) / people_per_unit) - floor(P(start) / people_per_unit)`: no unit is lost or counted twice. Before cutover the legacy population (`GameState.Population`) also counts the same arrivals; the two are separate views of the same people until Phase 3 makes arrivals counts.
+
+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.
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 84962eaa6..cda5d894e 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 (12 October 2026):** PR 1 merged as #349. PR 2 is built to this plan. PRs 3 to 8 wait for the owner's answers on the decisions in Global constraints.
+**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.
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.
@@ -81,11 +81,12 @@ PR 1 has no dependency. PR 2 needs PR 1 (the overlay sets `turn_lengths`). PRs 3
| `sim/Statecraft.Sim/Training.cs` (new) | Train, cancel, cohort progress | 4 |
| `sim/Statecraft.Sim/Projects.cs` (new) | Pioneer work at sites | 5 |
| `sim/Statecraft.Sim/Objectives.cs` (new) | Completion, score, timing bonus | 6 |
-| `sim/Statecraft.Sim/TurnResolver.cs` (new) | The fixed resolution order (spec §2.3, D-A6, waits for the owner) | 3–6 |
+| `sim/Statecraft.Sim/TurnResolver.cs` (new) | The fixed resolution order (spec §2.3, D-A6, decided 2026-10-14) | 3–6 |
| `sim/Statecraft.Sim/EventSystem.cs`, `EventRules.cs` | Objective-triggered events | 6 |
| `content/sites.yaml`, `content/objectives.yaml` (sourced facts only), `content/events/first_new_yishuv.yaml`, `content/schema/event.schema.json` | Slice content that is sourced fact | 5–6 |
| `MvpSlice.Overlay` text: the city start values, the population types' balance, the `mvp:` rules block and the GDD command kinds' `attention_cost` (ruling 2: never under `content/` until the owner sets them) | Slice balance placeholders | 3–6 |
-| `sim/Statecraft.Sim.Tests/*` | Tests per task; `MvpGolden.cs`, `ReferencePlayer.cs` (new) | 1–6 |
+| `sim/Statecraft.Sim/Reference/ReferencePlayer.cs` (new) | The GDD goldens' test policy (D-A7), reachable from no game mode or UI | 3–6 |
+| `sim/Statecraft.Sim.Tests/*` | Tests per task | 1–6 |
| `docs/rules/mvp.md` (new), `docs/gdd/*.md` (new) | Rule IDs and feature sections | 1–6 |
| `unity/Assets/Scripts/UI/SimBridge.cs`, `HudModel.cs`, `HudPresenter.cs`, `InfoPanelPresenter.cs`, `EventCardPresenter.cs`, `GameRoot.cs`, `Boot/UrlFlags.cs`, `Boot/GameBoot.cs`, `Resources/strings.en.yaml`, `UI/EventImages/*`, a new `Map/SiteLayer.cs`, EditMode tests | Minimal UI | 7–8 |
@@ -759,17 +760,32 @@ public static class MvpGolden
## PR 3: one city
-> **Waits for the owner (ruling 1):** D-A5, D-A6, D-A7. Placeholder values go in `MvpSlice.Overlay` or test fixtures, never `content/` (ruling 2): the `cities.yaml` start values, the `mvp:` block and `attention_cost` below are overlay text. Rewrite this PR's tasks to the owner's answers before starting.
-
-
-Issue (Task form): "GDD Phase 1: one city (Tel Aviv): housing, jobs, refugees, Money from jobs, Social cohesion". Sign-off: placeholders, D-A5 and D-A6 (wait for the owner), the `mvp-slice` move.
+> **Decided by the owner on 2026-10-14 (#456, recorded in the impact plan §5 and in #375):** D-A5, D-A6 and D-A7, each as the impact plan recommends. The tasks below are written to those answers:
+> - D-A5: "Newly arrived immigrants without housing, from the CBS series (`aliyah.yaml`). They become civilians when housed. Never the residents removed by Deport (§4.1)." (R-CITY-003, R-CITY-004)
+> - D-A6: "The fixed order of §2.3. Actions are capped by Attention, with unit orders free." The resolver follows §2.3 literally: production (6), consumption (7), housing and shortages then Social cohesion (8), arrivals (9), occupation (10), objectives (11). PR 3 builds production, housing, cohesion and arrivals; a turn's arrivals are housed on the next turn. The earlier draft of this PR put arrivals before housing; the owner's answer in #456 supersedes it. (Task 3.3)
+> - D-A7: "Test code with a stated simple policy (§2.3). Not "historical" unless sourced." (Task 3.4)
+>
+> **Controller decisions, 2026-10-14, on how PR 3 is built** (implementation choices, not owner rulings):
+> 1. The order above is §2.3 as written.
+> 2. The reference player ships in `Statecraft.Sim`, so Unity can replay the MVP goldens (#394), as `Statecraft.Sim.Reference.ReferencePlayer`, labelled "Test policy for the GDD goldens (D-A7): a stated simple policy, not game AI and not historical." No game mode or UI path may reach it; a test enforces that.
+> 3. No housing condition in PR 3 (D-D2 open).
+>
+> **Labelled placeholders, pending the owner** (questions on #375, not decisions):
+> - Social cohesion's direct formula (R-CITY-005) and its weights, marked `PLACEHOLDER (D-C1 open)`. Until D-C1 is decided it feeds no other system (no effect, no morale replacement, no threshold, no display); a test checks that its value changes nothing else.
+> - The housing cap of R-CITY-004 (D-D1 open).
+> - `AssignWorkers` changes a city's counts, not a unit's order (D-A2), so D-A6 makes it cost Attention; the cost, 0.5, is a placeholder.
+>
+> PR 3 builds no score: D-B2 (+5 points per month early, capped at +60) and D-B6 (100 points per objective) are PR 6. Placeholder values go in `MvpSlice.Overlay` or test fixtures, never `content/` (ruling 2): the `cities.yaml` start values, the `mvp:` block and `attention_cost` below are overlay text, marked `PLACEHOLDER: owner sets`.
+
+
+Issue (Task form): "GDD Phase 1: one city (Tel Aviv): housing, jobs, refugees, Money from jobs, Social cohesion". Sign-off: placeholders, D-A5 and D-A6 as answered (#456), the `mvp-slice` move.
### Task 3.1: the slice's city data: `cities.yaml`, `unit_types.yaml`, the `mvp:` rules block (overlay text, ruling 2)
**Files:** Modify `sim/Statecraft.Sim/MvpSlice.cs` (the overlay supplies `cities.yaml` and `unit_types.yaml`, and adds the `mvp:` block and the new `attention_cost` kinds to `rules.yaml`, all marked `PLACEHOLDER: owner sets`; nothing under `content/` changes until the owner sets the values; the loader requires these only when the loop is `gdd`), `Content.cs` (`CityStart`, `UnitType`, `MvpRules`, `Content.Cities`, `Content.UnitTypes`, `Rules.Mvp`), `ContentLoader.cs` (read and validate), `Fixture.cs` (the two new files, minimal), `ValidationTests.cs` or a new `CitiesContentTests.cs`.
**Interfaces:**
-- Produces: `CityStart { Id, HousingCapacity, HousingCondition, JobSlots, Civilians, Employed, Facilities : List<string> }`; `UnitType { Id, Kind ("population" | "unit"), TrainingTurns, TrainingCost, Facility }`; `MvpRules { PeoplePerUnit, IncomePerJobPerYear, CohesionHousingWeight, CohesionJobsWeight, ArrivalsCity }`; `Content.Cities : List<CityStart>`; `Content.UnitTypes : List<UnitType>`; `Rules.Mvp : MvpRules`.
+- Produces: `CityStart { Id, HousingCapacity, JobSlots, Civilians, Employed, Facilities : List<string> }`; `UnitType { Id, Kind ("population" | "unit") }` (PR 4 adds the training fields); `MvpRules { PeoplePerUnit, IncomePerJobPerYear, CohesionHousingWeight, CohesionJobsWeight, ArrivalsCity }`; `Content.Cities : List<CityStart>`; `Content.UnitTypes : List<UnitType>`; `Rules.Mvp : MvpRules`.
`content/cities.yaml`:
@@ -780,11 +796,10 @@ Issue (Task form): "GDD Phase 1: one city (Tel Aviv): housing, jobs, refugees, M
cities:
- id: tel_aviv # content/map/settlements_1948.yaml
housing_capacity: 120 # PLACEHOLDER: owner sets
- housing_condition: 0.6 # PLACEHOLDER: owner sets (0 to 1)
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, waits for the owner)
+ facilities: [] # PR 4 adds military_camp and hakhshara (D-D5: one of each at start, #456)
```
`content/unit_types.yaml` (population types only, spec §6):
@@ -804,14 +819,14 @@ types:
mvp:
people_per_unit: 1000 # PLACEHOLDER: owner sets (D-A1 scale)
income_per_job_per_year: 0.06 # PLACEHOLDER: owner sets (IL millions per employed unit per year)
- cohesion_housing_weight: 0.5 # PLACEHOLDER: owner sets
- cohesion_jobs_weight: 0.5 # PLACEHOLDER: owner sets (the two weights sum to 1)
+ cohesion_housing_weight: 0.5 # PLACEHOLDER (D-C1 open)
+ 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
```
and `attention_cost` gains `assign_workers: 0.5 # PLACEHOLDER: owner sets` (written inline in the existing map; the comment goes on the line above).
-Validation (each with a test that names file and field): city id unique and in `settlements_1948.yaml` ids; counts ≥ 0; `employed ≤ civilians`; `housing_condition` in [0, 1]; facility names known (`military_camp`, `hakhshara`); `people_per_unit ≥ 1`; weights in [0, 1] summing to 1 (±1e-9); `arrivals_city` a city in `cities.yaml`; unit type ids unique, kind `population` or `unit`.
+Validation (each with a test that names file and field): city id unique and in `settlements_1948.yaml` ids; counts ≥ 0; `employed ≤ civilians` and `≤ job_slots`; facility names known (`military_camp`, `hakhshara`); `people_per_unit ≥ 1`; weights in [0, 1] summing to 1 (±1e-9); `arrivals_city` a city in `cities.yaml`; unit type ids unique, kind `population` or `unit`.
- [ ] Steps: failing validation tests (`CitiesContentTests`, one `[Theory]` row per rule above, asserting `ex.File` and `ex.Field`), run (fail), implement types and `ReadCities`/`ReadUnitTypes` with `Read<T>`, run (pass), mutate (drop the `employed ≤ civilians` check; its row fails), commit.
@@ -833,7 +848,7 @@ Validation (each with a test that names file and field): city id unique and in `
if (count < 0) return "The number of workers cannot be negative";
if (count > x.JobSlots) return FormattableString.Invariant($"{PlayerText.Settlement(c, city)} has {x.JobSlots} jobs");
if (count > x.Civilians) return FormattableString.Invariant($"{PlayerText.Settlement(c, city)} has {x.Civilians} civilians");
- s.Cities[city] = x.WithCounts(x.Civilians, count, x.Refugees, x.Recruits);
+ s.Cities[city] = x.WithCounts(x.Civilians, count, x.Refugees);
why.Add(new Cause("city", city, count - x.Employed, FormattableString.Invariant($"{PlayerText.Settlement(c, city)}: {count} groups in work")));
return null;
}
@@ -848,23 +863,23 @@ Tests (`CitiesTests`, on `MvpSlice.Load` and on the fixture with `systems: { loo
**Files:** create `TurnResolver.cs`; modify `Cities.cs`, `Simulation.cs` (call), `CitiesTests.cs`.
**Interfaces:**
-- Produces: `TurnResolver.Resolve(Content c, GameState s, DateTime next, double yearFraction, List<Cause> why)`, called in `Step` right after `EventSystem.Delegate` and after `next`/`yf` are computed, only when `c.IsGdd`; order (D-A6, waits for the owner; spec §2.3 recommends): training (PR 4), construction (PR 5), production, arrivals, housing, cohesion, objectives (PR 6). `Cities.ArrivedUnits(Content c, DateTime from, DateTime to) : int`.
+- Produces: `TurnResolver.Resolve(Content c, GameState s, DateTime next, double yearFraction, List<Cause> why)`, called in `Step` right after `EventSystem.Delegate` and after `next`/`yf` are computed, only when `c.IsGdd`; order (D-A6, the fixed order of spec §2.3, #456): training (PR 4), construction (PR 5), production, consumption (Phase 2), housing then cohesion, arrivals, occupation (Phase 6), objectives (PR 6). A turn's arrivals wait as refugees until the next turn's housing step, and the turn's cohesion does not see them yet. (The draft put arrivals before housing; #456 supersedes it.) `Cities.ArrivedUnits(Content c, DateTime from, DateTime to) : int`.
Rules:
- R-CITY-002 production: for each city in id order, `s.Treasury += employed * income_per_job_per_year * yearFraction`.
- R-CITY-003 arrivals: `units(t) = floor(sum over origin ids in ordinal order of Arrivals(c, start, t)) / people_per_unit)`; the turn adds `units(next) - units(s.Date)` refugees to `arrivals_city`. Cumulative, so no unit is lost or counted twice.
-- R-CITY-004 housing (D-A5, waits for the owner): `moved = min(refugees, max(0, housing_capacity - civilians))` refugees become civilians (unemployed).
-- R-CITY-005 cohesion: over all cities, `housed = civilians / (civilians + refugees)` (1 when both 0), `employed = employed / civilians` (1 when 0); `Cohesion = clamp01(w_h * housed + w_j * employed)`.
+- R-CITY-004 housing (D-A5: refugees "become civilians when housed"): `moved = min(refugees, max(0, housing_capacity - civilians))` refugees become civilians (unemployed). The cap is a placeholder: overflow is D-D1, still open.
+- R-CITY-005 cohesion (a placeholder, D-C1 open): over all cities, `housed = civilians / (civilians + refugees)` (1 when both 0), `employed = employed / civilians` (1 when 0); `Cohesion = clamp01(w_h * housed + w_j * employed)`, in `GameState.Cohesion` (hashed as `coh=` when the state has cities). No other system reads it, and nothing shows it.
-Tests: `ProductionPaysPerEmployedGroup` (one step, Treasury delta equals the formula, against a run with 0 employed); `ArrivalsOverTheWholeRunEqualTheFloorOfTheTotal` (Review focus 4: sum of refugee additions over 20 monthly turns equals `floor(total/ppu)`); `RefugeesAreHousedOnlyUpToCapacity`; `CohesionFallsWhenRefugeesWaitAndRisesWhenTheyAreHousedAndEmployed`; `TheResolverDoesNotRunInTheLegacyLoop` (the full suite's legacy goldens are the strong check). Mutations: per-turn `floor` instead of cumulative fails the arrivals test; drop the capacity bound fails the housing test.
+Tests: `ProductionPaysPerEmployedGroup` (one step, Treasury delta equals the formula, against a run with 0 employed); `ArrivalsOverTheWholeRunEqualTheFloorOfTheTotal` (Review focus 4: sum of refugee additions over 20 monthly turns equals `floor(total/ppu)`); `RefugeesAreHousedOnlyUpToCapacity`; `CohesionFallsWhenRefugeesWaitAndRisesWhenTheyAreHousedAndEmployed`; `CohesionFeedsNothingElse` (two states that differ only in Cohesion step to the same state, and no sim or Unity file outside the city rules reads it); `TheResolverDoesNotRunInTheLegacyLoop` (the full suite's legacy goldens are the strong check). Mutations: per-turn `floor` instead of cumulative fails the arrivals test; drop the capacity bound fails the housing test.
### Task 3.4: the reference player and the goldens
-**Files:** create `sim/Statecraft.Sim.Tests/ReferencePlayer.cs`; `MvpGoldenTests` uses it; create `sim/Statecraft.Sim.Tests/scenarios/mvp-absorb-first.yaml` with `content: mvp`; `Scenario.cs` reads `content: mvp` (`ScenarioTests` loads `MvpSlice.Load` for it); re-pin `mvp-slice`, add `scenario-mvp-absorb-first`.
+**Files:** create `sim/Statecraft.Sim/Reference/ReferencePlayer.cs` (namespace `Statecraft.Sim.Reference`; controller decision 2 above); `MvpGolden.Play` uses it; create `ReferencePlayerTests.cs` (the policy, and a guard that only the golden runner and tests name `Statecraft.Sim.Reference`: no game mode, CLI or Unity path); create `sim/Statecraft.Sim.Tests/scenarios/mvp-absorb-first.yaml` with `content: mvp`; `Scenario.cs` reads `content: mvp` (`ScenarioTests` loads `MvpSlice.Load` for it); re-pin `mvp-slice`, add `scenario-mvp-absorb-first`.
```csharp
-/// <summary>The reference player for the GDD goldens (D-A7, waits for the owner): HistoricalAI's orders, then each city's jobs filled
-/// with as many civilians as there are slots. Test code with a stated policy; it is not "history".</summary>
+/// <summary>Test policy for the GDD goldens (D-A7): a stated simple policy, not game AI and not historical. HistoricalAI's
+/// orders, then each city's jobs filled with as many civilians as there are slots.</summary>
public static class ReferencePlayer
{
public static IReadOnlyList<Command> Commands(Content c, GameState s)
@@ -982,6 +997,8 @@ Tests: start, every refusal (not a halutz, busy unit, unknown site, site buildin
## PR 6: the objective card and the score
+> **Note (#456):** when PR 6 starts, its numbers become 100 points per objective (D-B6) and +5 points per month early, capped at +60 (D-B2).
+>
> **Waits for the owner (ruling 1):** D-B2 and D-B6 (the formula and the points), and D-A6. The card event, its text and its reference date are sourced content; `points`, `bonus_per_month_early` and `bonus_cap` are overlay text (ruling 2).
diff --git a/sim/Statecraft.Sim.Tests/CitiesContentTests.cs b/sim/Statecraft.Sim.Tests/CitiesContentTests.cs
new file mode 100644
index 000000000..a4dd24019
--- /dev/null
+++ b/sim/Statecraft.Sim.Tests/CitiesContentTests.cs
@@ -0,0 +1,145 @@
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using Statecraft.Sim;
+
+/// <summary>The GDD slice's city data (Phase 1 PR 3, Task 3.1): cities.yaml, unit_types.yaml and the mvp: rules block. The
+/// loader reads and requires them only when systems.loop is gdd; their values are placeholders in MvpSlice.Overlay or test
+/// fixtures, never under content/ (controller ruling 2).</summary>
+public class CitiesContentTests
+{
+ static Content Load(Dictionary<string, string>? extra = null) => ContentLoader.Load(Fixture.Write(Fixture.Gdd(extra)));
+
+ [Fact]
+ public void TheGddFixtureLoadsItsCityTypesAndRules()
+ {
+ 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));
+ 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"]);
+ }
+
+ [Fact]
+ public void TheLegacyLoopReadsNoCityData()
+ {
+ var c = ContentLoader.Load(RealContentTests.ContentRoot());
+ Assert.Empty(c.Cities);
+ Assert.Empty(c.UnitTypes);
+ Assert.Null(c.RulesAt(c.Eras[0].From).Mvp);
+ Assert.Equal("Tel Aviv", c.SettlementNames["tel_aviv"]); // names are read in both loops: refusals and causes name places
+ }
+
+ [Fact]
+ public void TheSliceHasTelAvivFromTheOverlay()
+ {
+ var c = MvpSlice.Load(RealContentTests.ContentRoot());
+ 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"));
+ }
+
+ [Fact]
+ public void NoBalanceValueIsUnderContent()
+ {
+ var root = RealContentTests.ContentRoot();
+ Assert.False(File.Exists(Path.Combine(root, "cities.yaml")));
+ Assert.False(File.Exists(Path.Combine(root, "unit_types.yaml")));
+ var overrides = Directory.Exists(Path.Combine(root, "rules")) ? Directory.GetFiles(Path.Combine(root, "rules"), "*.yaml") : new string[0];
+ foreach (var f in new[] { "rules.yaml" }.Concat(overrides.Select(x => "rules/" + Path.GetFileName(x))))
+ {
+ var text = File.ReadAllText(Path.Combine(root, f));
+ Assert.DoesNotContain("mvp:", text);
+ Assert.DoesNotContain("assign_workers", 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;
+
+ public static IEnumerable<object[]> BadRows() => new List<object[]>
+ {
+ new object[] { "cities.yaml", Cities(City + City), "cities[town_a].id", "duplicate id" },
+ new object[] { "cities.yaml", Cities(City.Replace("town_a", "nowhere")), "cities[nowhere].id", "is not in map/settlements_1948.yaml" },
+ new object[] { "cities.yaml", Cities(City.Replace("civilians: 10", "civilians: -1")), "cities[town_a].civilians", "must be >= 0" },
+ new object[] { "cities.yaml", Cities(City.Replace("housing_capacity: 12", "housing_capacity: -1")), "cities[town_a].housing_capacity", "must be >= 0" },
+ new object[] { "cities.yaml", Cities(City.Replace("job_slots: 8", "job_slots: -1")), "cities[town_a].job_slots", "must be >= 0" },
+ new object[] { "cities.yaml", Cities(City.Replace("employed: 6", "employed: -1")), "cities[town_a].employed", "must be >= 0" },
+ new object[] { "cities.yaml", Cities(City.Replace("employed: 6", "employed: 11").Replace("job_slots: 8", "job_slots: 20")), "cities[town_a].employed", "cannot be more than civilians" },
+ new object[] { "cities.yaml", Cities(City.Replace("employed: 6", "employed: 9")), "cities[town_a].employed", "cannot be more than job_slots" },
+ new object[] { "cities.yaml", Cities(City.Replace("facilities: []", "facilities: [winery]")), "cities[town_a].facilities", "unknown facility 'winery'" },
+ new object[] { "cities.yaml", "cities: []\n", "mvp.arrivals_city", "is not a city in cities.yaml" },
+ new object[] { "unit_types.yaml", "types:\n - { id: civilian, kind: population }\n - { id: civilian, kind: population }\n", "types[civilian].id", "duplicate id" },
+ new object[] { "unit_types.yaml", "types:\n - { id: civilian, kind: crowd }\n", "types[civilian].kind", "must be population or unit" },
+ new object[] { "rules.yaml", Rules(Fixture.GddRules.Replace("people_per_unit: 10", "people_per_unit: 0")), "mvp.people_per_unit", "must be >= 1" },
+ new object[] { "rules.yaml", Rules(Fixture.GddRules.Replace("income_per_job_per_year: 1.2", "income_per_job_per_year: -1")), "mvp.income_per_job_per_year", "must be a finite number >= 0" },
+ new object[] { "rules.yaml", Rules(Fixture.GddRules.Replace("cohesion_housing_weight: 0.5", "cohesion_housing_weight: 1.5")), "mvp.cohesion_housing_weight", "must be a number from 0 to 1" },
+ new object[] { "rules.yaml", Rules(Fixture.GddRules.Replace("cohesion_jobs_weight: 0.5", "cohesion_jobs_weight: 0.4")), "mvp.cohesion_jobs_weight", "the two cohesion weights must sum to 1" },
+ 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" },
+ };
+
+ [Theory]
+ [MemberData(nameof(BadRows))]
+ public void ABadValueFailsNamingTheFileAndField(string file, string text, string field, string message)
+ {
+ var ex = Assert.Throws<ContentException>(() => Load(new Dictionary<string, string> { [file] = text }));
+ Assert.Equal(field == "mvp.arrivals_city" ? "rules.yaml" : file, ex.File);
+ Assert.Equal(field, ex.Field);
+ Assert.Contains(message, ex.Message);
+ }
+
+ [Theory]
+ [InlineData("cities.yaml")]
+ [InlineData("unit_types.yaml")]
+ public void TheGddLoopNeedsTheCityFiles(string file)
+ {
+ var o = Fixture.Gdd();
+ o.Remove(file);
+ var ex = Assert.Throws<ContentException>(() => ContentLoader.Load(Fixture.Write(o)));
+ Assert.Equal(file, ex.File);
+ Assert.Contains("missing file", ex.Message);
+ }
+
+ /// <summary>Arrivals are counted from the game's start in units of one size (R-CITY-003), so an era may not change it.</summary>
+ [Fact]
+ public void PeoplePerUnitIsTheSameInEveryEra()
+ {
+ var o = Fixture.Gdd(new Dictionary<string, string> { ["eras.yaml"] = @"
+eras:
+ - id: founding
+ name: The Founding
+ from: 1948-05-15
+ to: 1950-01-01
+ systems: { loop: gdd }
+ - id: later
+ name: Later
+ from: 1950-01-01
+ to: 1957-01-01
+ systems: { loop: gdd }
+" });
+ var dir = Fixture.Write(o);
+ Directory.CreateDirectory(Path.Combine(dir, "rules"));
+ File.WriteAllText(Path.Combine(dir, "rules", "later.yaml"), "mvp: { income_per_job_per_year: 2.4 }\n");
+ Assert.Equal(2.4, ContentLoader.Load(dir).EraRules["later"].Mvp!.IncomePerJobPerYear); // other mvp values may change by era
+ File.WriteAllText(Path.Combine(dir, "rules", "later.yaml"), "mvp: { people_per_unit: 20 }\n");
+ var ex = Assert.Throws<ContentException>(() => ContentLoader.Load(dir));
+ Assert.Equal("rules/later.yaml", ex.File);
+ Assert.Equal("mvp.people_per_unit", ex.Field);
+ Assert.Contains("must be the same in every era", ex.Message);
+ }
+
+ [Fact]
+ public void ASettlementWithoutANameIsALoadError()
+ {
+ var bad = Fixture.Files["map/settlements_1948.yaml"].Replace("name: Town A, ", "");
+ var ex = Assert.Throws<ContentException>(() => ContentLoader.Load(Fixture.Write(new Dictionary<string, string> { ["map/settlements_1948.yaml"] = bad })));
+ Assert.Equal("map/settlements_1948.yaml", ex.File);
+ Assert.Equal("settlements[0].name", ex.Field);
+ }
+}
diff --git a/sim/Statecraft.Sim.Tests/CitiesTests.cs b/sim/Statecraft.Sim.Tests/CitiesTests.cs
new file mode 100644
index 000000000..ed64a8a03
--- /dev/null
+++ b/sim/Statecraft.Sim.Tests/CitiesTests.cs
@@ -0,0 +1,233 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using Statecraft.Sim;
+
+/// <summary>The GDD slice's city (Phase 1 PR 3): AssignWorkers (R-CITY-001), and the turn's production, housing, Social
+/// cohesion and arrivals in TurnResolver (R-CITY-002 to R-CITY-005, in the order of spec 2026-10-12 section 2.3, D-A6).</summary>
+public class CitiesTests
+{
+ static readonly Content Mvp = MvpSlice.Load(RealContentTests.ContentRoot());
+
+ /// <summary>The GDD fixture with one city: 20 jobs, 10 civilians, 6 of them employed, housing for 12.</summary>
+ static Content Town(string city = " - { id: town_a, housing_capacity: 12, job_slots: 20, civilians: 10, employed: 6, facilities: [] }\n") =>
+ ContentLoader.Load(Fixture.Write(Fixture.Gdd(new Dictionary<string, string> { ["cities.yaml"] = "cities:\n" + city })));
+
+ static StepResult Step(Content c, GameState s, params Command[] commands) => Simulation.Step(c, s, commands);
+
+ [Fact]
+ public void ANewGddGameStartsWithItsCities()
+ {
+ var s = Simulation.NewGame(Mvp, GoldenRun.Seed, Mode.Historical);
+ var city = Assert.Single(s.Cities.Values);
+ Assert.Equal(("tel_aviv", 120, 90, 100, 80, 0), (city.Id, city.HousingCapacity, city.JobSlots, city.Civilians, city.Employed, city.Refugees));
+ }
+
+ [Fact]
+ public void ALegacyGameHasNoCities() =>
+ Assert.Empty(Simulation.NewGame(ContentLoader.Load(RealContentTests.ContentRoot()), GoldenRun.Seed, Mode.Historical).Cities);
+
+ // R-CITY-001
+ [Fact]
+ public void AssigningWorkersSetsEmployed()
+ {
+ var s = Simulation.NewGame(Mvp, GoldenRun.Seed, Mode.Historical);
+ var r = Step(Mvp, s, new AssignWorkers("tel_aviv", "job", 90));
+ Assert.Empty(r.Rejected);
+ Assert.Equal(90, r.State.Cities["tel_aviv"].Employed);
+ Assert.Contains(r.Why, x => x.System == "city" && x.Message == "Tel Aviv: 90 groups in work");
+ }
+
+ // R-CITY-001
+ [Theory]
+ [InlineData("town_a", "job", -1, "The number of workers cannot be negative")]
+ [InlineData("town_a", "job", 21, "Town A has 20 jobs")]
+ [InlineData("town_a", "job", 11, "Town A has 10 civilians")]
+ [InlineData("nowhere", "job", 1, "There is no such city")]
+ [InlineData("town_a", "craftsman", 1, "There is no such role")]
+ public void TheLimitsAreRefusedAndChangeNothing(string city, string role, int count, string reason)
+ {
+ var c = Town();
+ var s = Simulation.NewGame(c, 1, Mode.Historical);
+ var r = Step(c, s, new AssignWorkers(city, role, 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-CITY-001
+ [Fact]
+ public void TheLegacyLoopRefusesTheOrderAndRefundsAttention()
+ {
+ var c = ContentLoader.Load(RealContentTests.ContentRoot());
+ var s = Simulation.NewGame(c, GoldenRun.Seed, Mode.Historical);
+ var r = Step(c, s, new AssignWorkers("tel_aviv", "job", 1));
+ Assert.Equal("That order is not available in this game", Assert.Single(r.Rejected).Reason);
+ Assert.Equal(Step(c, s).State.Hash(), r.State.Hash());
+ }
+
+ // R-CITY-001
+ [Fact]
+ public void AnAssignOrderSurvivesASave()
+ {
+ var g = GameSession.New(Mvp, GoldenRun.Seed, Mode.Historical);
+ g.Step(new Command[] { new AssignWorkers("tel_aviv", "job", 85) });
+ var text = g.Save.Write();
+ Assert.Contains("\nwork tel_aviv job 85\n", text);
+ Assert.Equal(g.State.Hash(), GameSession.Load(Mvp, text, out _).State.Hash());
+ }
+
+ // ---- the turn (TurnResolver): production, housing then Social cohesion, arrivals (spec section 2.3, D-A6) ----
+
+ static GameState With(GameState s, string city, int civilians, int employed, int refugees)
+ {
+ var x = s.Clone();
+ x.Cities[city] = x.Cities[city].WithCounts(civilians, employed, refugees);
+ return x;
+ }
+
+ // R-CITY-002
+ [Fact]
+ public void ProductionPaysPerEmployedGroup()
+ {
+ var c = Town();
+ var s = Simulation.NewGame(c, 1, Mode.Historical);
+ var paid = Step(c, s).State.Treasury - Step(c, With(s, "town_a", 10, 0, 0)).State.Treasury;
+ Assert.Equal(6 * 1.2 * SimTime.YearFraction(TurnLength.Week), paid, 9); // the fixture's first turn is a week
+ }
+
+ // R-CITY-004
+ [Fact]
+ public void RefugeesAreHousedOnlyUpToCapacity()
+ {
+ var c = Town();
+ var s = With(Simulation.NewGame(c, 1, Mode.Historical), "town_a", 10, 6, 5);
+ var city = Step(c, s).State.Cities["town_a"]; // the first week brings under one unit of arrivals
+ Assert.Equal((12, 6, 3), (city.Civilians, city.Employed, city.Refugees));
+ }
+
+ // R-CITY-003, R-CITY-004 (D-A6: arrivals come after housing, so they are housed on the next turn)
+ [Fact]
+ public void ATurnsArrivalsAreHousedOnTheNextTurn()
+ {
+ var s = Simulation.NewGame(Mvp, GoldenRun.Seed, Mode.Historical);
+ var one = Step(Mvp, s).State;
+ var arrived = one.Cities["tel_aviv"].Refugees;
+ Assert.True(arrived > 0);
+ Assert.Equal(100, one.Cities["tel_aviv"].Civilians); // housing for 20 more was free, but it ran before they came
+ var two = Step(Mvp, one).State.Cities["tel_aviv"];
+ Assert.Equal(100 + Math.Min(arrived, 20), two.Civilians);
+ }
+
+ // R-CITY-003
+ [Fact]
+ public void ArrivalsOverTheWholeRunEqualTheFloorOfTheTotal()
+ {
+ var s = Simulation.NewGame(Mvp, GoldenRun.Seed, Mode.Historical);
+ var start = s.Date;
+ int People(GameState x) => x.Cities["tel_aviv"].Civilians + x.Cities["tel_aviv"].Refugees;
+ var before = People(s);
+ for (int i = 0; i < 20; i++)
+ {
+ var next = Step(Mvp, s).State;
+ Assert.Equal(Cities.ArrivedUnits(Mvp, s.Date, next.Date, 1000), People(next) - People(s));
+ s = next;
+ }
+ var total = PopulationSystem.Arrivals(Mvp, start, s.Date).OrderBy(kv => kv.Key, StringComparer.Ordinal).Sum(kv => kv.Value);
+ Assert.Equal((int)Math.Floor(total / 1000), People(s) - before);
+ }
+
+ /// <summary>Before cutover the same arrivals are in two views: the legacy head count by origin (GameState.Population, which
+ /// the legacy economy reads) and the city's refugees. This pins that overlap so Phase 3, which makes arrivals counts, has
+ /// to change it on purpose.</summary>
+ // R-CITY-003
+ [Fact]
+ public void BeforeCutoverArrivalsAreInTheLegacyHeadCountToo()
+ {
+ var c = Town();
+ var s = Simulation.NewGame(c, 1, Mode.Historical);
+ for (int i = 0; i < 20; i++) s = Step(c, s).State;
+ var people = PopulationSystem.Arrivals(c, c.Eras[0].From, s.Date).Values.Sum();
+ Assert.Equal(Cities.ArrivedUnits(c, c.Eras[0].From, s.Date, 10), s.Cities["town_a"].Refugees + s.Cities["town_a"].Civilians - 10);
+ Assert.True(s.Population["europe"] >= people, "the legacy head count also holds every arrival");
+ }
+
+ // R-CITY-005
+ [Fact]
+ public void CohesionFallsWhenRefugeesWaitAndRisesWhenTheyAreHousedAndEmployed()
+ {
+ var c = Town();
+ var s = Simulation.NewGame(c, 1, Mode.Historical);
+ Assert.Equal(0.5 * 1 + 0.5 * 0.6, s.Cohesion, 12); // all housed, 6 of 10 employed
+ var waiting = Step(c, With(s, "town_a", 10, 6, 10)).State; // 2 housed: 12 of 20 housed, 6 of 12 employed
+ Assert.Equal(0.5 * 0.6 + 0.5 * 0.5, waiting.Cohesion, 12);
+ var working = Step(c, waiting, new AssignWorkers("town_a", "job", 12)).State;
+ Assert.Equal(0.5 * 0.6 + 0.5 * 1, working.Cohesion, 12);
+ Assert.True(waiting.Cohesion < s.Cohesion && working.Cohesion > waiting.Cohesion);
+ }
+
+ /// <summary>The GDD fixture's town with cohesion weights 0.8 on housing and 0.2 on jobs (fixture values), so a change in
+ /// either share shows apart from the other.</summary>
+ 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 }")
+ + Fixture.GddRules.Replace("cohesion_housing_weight: 0.5", "cohesion_housing_weight: 0.8").Replace("cohesion_jobs_weight: 0.5", "cohesion_jobs_weight: 0.2"),
+ })));
+
+ // R-CITY-005
+ [Fact]
+ public void UnequalWeightsWeighTheHousedAndEmployedSharesApart()
+ {
+ var c = Unequal();
+ var s = Simulation.NewGame(c, 1, Mode.Historical);
+ Assert.Equal(0.8 * 1 + 0.2 * 0.6, s.Cohesion, 12); // all housed, 6 of 10 employed
+ var working = Step(c, s, new AssignWorkers("town_a", "job", 10)).State; // all housed, all employed
+ Assert.Equal(1.0, working.Cohesion, 12);
+ }
+
+ /// <summary>D-A6: housing comes before Social cohesion in the turn, so cohesion reads the counts after this turn's housing.
+ /// Read before housing, the same state would give 0.8 * 10/20 + 0.2 * 6/10 = 0.52.</summary>
+ // R-CITY-004, R-CITY-005
+ [Fact]
+ public void CohesionReadsTheCountsAfterThisTurnsHousing()
+ {
+ var c = Unequal();
+ var s = With(Simulation.NewGame(c, 1, Mode.Historical), "town_a", 10, 6, 10);
+ var after = Step(c, s).State; // 2 housed: 12 of 20 housed, 6 of 12 employed
+ Assert.Equal((12, 8), (after.Cities["town_a"].Civilians, after.Cities["town_a"].Refugees));
+ Assert.Equal(0.8 * 0.6 + 0.2 * 0.5, after.Cohesion, 12);
+ }
+
+ /// <summary>Social cohesion is a labelled placeholder while D-C1 is open (an owner question on #375): no effect, morale,
+ /// threshold or display reads it. Two states that differ only in it step to the same state, and no code outside the
+ /// city rules and the state names it.</summary>
+ // R-CITY-005
+ [Fact]
+ public void CohesionFeedsNothingElse()
+ {
+ var s = Simulation.NewGame(Mvp, GoldenRun.Seed, Mode.Historical);
+ for (int i = 0; i < 3; i++) s = Step(Mvp, s).State;
+ var other = s.Clone();
+ other.Cohesion = 1 - s.Cohesion;
+ Assert.NotEqual(s.Hash(), other.Hash());
+ Assert.Equal(Step(Mvp, s).State.Describe(), Step(Mvp, other).State.Describe());
+ var repo = System.IO.Directory.GetParent(RealContentTests.ContentRoot())!.FullName;
+ var readers = new[] { "sim/Statecraft.Sim", "sim/Statecraft.Cli", "unity/Assets" }
+ .Select(d => System.IO.Path.Combine(repo, d)).Where(System.IO.Directory.Exists)
+ .SelectMany(d => System.IO.Directory.GetFiles(d, "*.cs", System.IO.SearchOption.AllDirectories))
+ .Where(f => System.Text.RegularExpressions.Regex.IsMatch(System.IO.File.ReadAllText(f), @"\bCohesion\b"))
+ .Select(f => System.IO.Path.GetFileName(f)).OrderBy(f => f, StringComparer.Ordinal);
+ Assert.Equal(new[] { "Cities.cs", "GameState.cs" }, readers);
+ }
+
+ [Fact]
+ public void TheResolverDoesNotRunInTheLegacyLoop()
+ {
+ var c = ContentLoader.Load(RealContentTests.ContentRoot());
+ var s = Simulation.NewGame(c, GoldenRun.Seed, Mode.Historical);
+ s = Step(c, s).State;
+ Assert.Empty(s.Cities);
+ Assert.Equal(0, s.Cohesion);
+ Assert.DoesNotContain("coh=", s.Describe());
+ }
+}
diff --git a/sim/Statecraft.Sim.Tests/CommandGuardTests.cs b/sim/Statecraft.Sim.Tests/CommandGuardTests.cs
index 64a8ca691..508abf219 100644
--- a/sim/Statecraft.Sim.Tests/CommandGuardTests.cs
+++ b/sim/Statecraft.Sim.Tests/CommandGuardTests.cs
@@ -18,6 +18,7 @@ public class CommandGuardTests
[typeof(SecurityOrder)] = new SecurityOrder(1),
[typeof(Appoint)] = new Appoint("prime_minister", "pm_one"),
[typeof(MapAction)] = new MapAction("housing", 1, 2),
+ [typeof(AssignWorkers)] = new AssignWorkers("tel_aviv", "job", 1),
};
static IEnumerable<Type> CommandTypes() =>
@@ -29,14 +30,16 @@ public class CommandGuardTests
foreach (var t in CommandTypes()) Assert.True(Samples.ContainsKey(t), $"{t.Name} has no sample: add it, then its touch-points");
}
+ /// <summary>A GDD kind is priced in the slice (MvpSlice.Overlay, a placeholder), and every other kind in the real rules.</summary>
[Fact]
public void EveryCommandHasAnAttentionKindAndACostInTheRealRules()
{
var c = ContentLoader.Load(RealContentTests.ContentRoot());
+ var mvp = MvpSlice.Load(RealContentTests.ContentRoot());
foreach (var cmd in Samples.Values)
{
Assert.True(AttentionSystem.IsCommandKind(cmd.Kind), cmd.Kind);
- Assert.True(c.Rules.AttentionCost.ContainsKey(cmd.Kind), cmd.Kind);
+ Assert.True((AttentionSystem.IsGddKind(cmd.Kind) ? mvp : c).Rules.AttentionCost.ContainsKey(cmd.Kind), cmd.Kind);
}
}
diff --git a/sim/Statecraft.Sim.Tests/EraSystemsTests.cs b/sim/Statecraft.Sim.Tests/EraSystemsTests.cs
index 1f7223719..8c575dd8a 100644
--- a/sim/Statecraft.Sim.Tests/EraSystemsTests.cs
+++ b/sim/Statecraft.Sim.Tests/EraSystemsTests.cs
@@ -192,7 +192,7 @@ eras:
[Fact]
public void TheGddSwitchSetsTheLoopAndTheRuleset()
{
- var c = Load(" systems: { loop: gdd }");
+ var c = ContentLoader.Load(Fixture.Write(Fixture.Gdd())); // the GDD loop also needs its city data (CitiesContentTests)
Assert.Equal("gdd", c.Loop);
Assert.True(c.IsGdd);
Assert.Equal("gdd-0.1", c.Ruleset);
diff --git a/sim/Statecraft.Sim.Tests/Fixture.cs b/sim/Statecraft.Sim.Tests/Fixture.cs
index 6e0960811..4fd054dda 100644
--- a/sim/Statecraft.Sim.Tests/Fixture.cs
+++ b/sim/Statecraft.Sim.Tests/Fixture.cs
@@ -195,6 +195,42 @@ series:
",
};
+ /// <summary>The fixture with the GDD loop on (eras.yaml systems.loop: gdd) and the files and keys that loop needs: the
+ /// mvp: rules block, the GDD command kinds' attention_cost, cities.yaml and unit_types.yaml. Every value is a fixture
+ /// value (PLACEHOLDER: owner sets). <paramref name="extra"/> replaces or adds files on top.</summary>
+ public static Dictionary<string, string> Gdd(Dictionary<string, string>? extra = null)
+ {
+ 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,
+ ["cities.yaml"] = GddCities,
+ ["unit_types.yaml"] = GddUnitTypes,
+ };
+ if (extra != null) foreach (var kv in extra) o[kv.Key] = kv.Value;
+ return o;
+ }
+
+ public const string GddRules = @"
+mvp:
+ people_per_unit: 10
+ income_per_job_per_year: 1.2
+ cohesion_housing_weight: 0.5
+ cohesion_jobs_weight: 0.5
+ arrivals_city: town_a
+";
+
+ public const string GddCities = @"
+cities:
+ - { id: town_a, housing_capacity: 12, job_slots: 8, civilians: 10, employed: 6, facilities: [] }
+";
+
+ public const string GddUnitTypes = @"
+types:
+ - { id: civilian, kind: population }
+ - { id: refugee, kind: population }
+";
+
public static string Write(Dictionary<string, string>? overrides = null, Dictionary<string, string>? events = null)
{
var dir = Path.Combine(Path.GetTempPath(), "statecraft-fixture-" + Guid.NewGuid().ToString("N"));
@@ -202,6 +238,9 @@ series:
Directory.CreateDirectory(Path.Combine(dir, "map"));
foreach (var kv in Files)
File.WriteAllText(Path.Combine(dir, kv.Key), overrides != null && overrides.TryGetValue(kv.Key, out var o) ? o : kv.Value);
+ if (overrides != null)
+ foreach (var kv in overrides)
+ if (!Files.ContainsKey(kv.Key)) File.WriteAllText(Path.Combine(dir, kv.Key), kv.Value); // a file only some content has (cities.yaml)
if (events != null)
foreach (var kv in events) File.WriteAllText(Path.Combine(dir, "events", kv.Key), kv.Value);
return dir;
diff --git a/sim/Statecraft.Sim.Tests/GddStateTests.cs b/sim/Statecraft.Sim.Tests/GddStateTests.cs
index fb631bb80..1a70141a6 100644
--- a/sim/Statecraft.Sim.Tests/GddStateTests.cs
+++ b/sim/Statecraft.Sim.Tests/GddStateTests.cs
@@ -20,10 +20,23 @@ public class GddStateTests
public void AnEmptyStateWritesNoNewSection()
{
var text = new GameState().Describe();
- foreach (var label in new[] { "city{", "units[", "next=", "obj{", "score=" }) Assert.DoesNotContain(label, text);
+ foreach (var label in new[] { "city{", "coh=", "units[", "next=", "obj{", "score=" }) Assert.DoesNotContain(label, text);
Assert.EndsWith("over=", text);
}
+ // R-LOOP-002, R-CITY-005
+ [Fact]
+ public void CohesionIsHashedWithTheCities()
+ {
+ var s = new GameState { Cohesion = 0.5 };
+ Assert.DoesNotContain("coh=", s.Describe()); // no cities: the legacy loop's text is unchanged whatever the field holds
+ s.Cities["x"] = new City("x", 1, 1, 1, 0, 0);
+ Assert.Contains("coh=0.5 [3FE0000000000000]", s.Describe());
+ var before = s.Hash();
+ s.Cohesion = 0.25;
+ Assert.NotEqual(before, s.Hash());
+ }
+
// R-LOOP-002
[Fact]
public void EachNewSectionAppearsOnlyWhenSetAndMovesTheHash()
diff --git a/sim/Statecraft.Sim.Tests/MvpSliceTests.cs b/sim/Statecraft.Sim.Tests/MvpSliceTests.cs
index 23e417290..0df7689e0 100644
--- a/sim/Statecraft.Sim.Tests/MvpSliceTests.cs
+++ b/sim/Statecraft.Sim.Tests/MvpSliceTests.cs
@@ -1,4 +1,5 @@
using System;
+using System.Collections.Generic;
using System.Linq;
using Statecraft.Sim;
@@ -26,7 +27,9 @@ 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);
- Assert.Equal(Real.Rules.AttentionCost, Mvp.Rules.AttentionCost);
+ // 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),
+ 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);
Assert.Equal(Real.Eras.Select(e => (e.Id, e.Name, e.From, e.To, e.Systems.Legislature, string.Join(",", e.Systems.MapActions))),
@@ -59,7 +62,7 @@ public class MvpSliceTests
[Fact]
public void LoadKeepsTheLoadersDirectoryChecks()
{
- var dir = Fixture.Write();
+ var dir = Fixture.Write(Fixture.Gdd());
System.IO.Directory.CreateDirectory(System.IO.Path.Combine(dir, "rules"));
System.IO.File.WriteAllText(System.IO.Path.Combine(dir, "rules", "nosuchera.yaml"), "attention_per_turn: 5\n");
var ex = Assert.Throws<ContentException>(() => MvpSlice.Load(dir));
diff --git a/sim/Statecraft.Sim.Tests/ReferencePlayerTests.cs b/sim/Statecraft.Sim.Tests/ReferencePlayerTests.cs
new file mode 100644
index 000000000..cee153b6d
--- /dev/null
+++ b/sim/Statecraft.Sim.Tests/ReferencePlayerTests.cs
@@ -0,0 +1,72 @@
+using System;
+using System.IO;
+using System.Linq;
+using System.Text.RegularExpressions;
+using Statecraft.Sim;
+using Statecraft.Sim.Reference;
+
+/// <summary>The reference player (D-A7, #456): the GDD goldens' test policy. It ships in Statecraft.Sim so Unity can replay the
+/// goldens (#394), but no game mode or UI may reach it (controller decision on PR 3, 2026-10-14).</summary>
+public class ReferencePlayerTests
+{
+ static readonly Content Mvp = MvpSlice.Load(RealContentTests.ContentRoot());
+
+ [Fact]
+ public void ItSendsHistoricalAIsOrdersThenFillsTheJobs()
+ {
+ 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(("tel_aviv", "job", 90), (assign.City, assign.Role, assign.Count)); // min(90 jobs, 100 civilians)
+ Assert.Empty(Simulation.Step(Mvp, s, orders).Rejected);
+ }
+
+ [Fact]
+ public void ItSendsNoOrderWhenTheJobsAreFilledOrAttentionIsShort()
+ {
+ var s = Simulation.NewGame(Mvp, GoldenRun.Seed, Mode.Historical);
+ var full = s.Clone();
+ full.Cities["tel_aviv"] = full.Cities["tel_aviv"].WithCounts(100, 90, 0);
+ Assert.DoesNotContain(ReferencePlayer.Commands(Mvp, full), x => x is AssignWorkers);
+ var tired = s.Clone();
+ tired.Attention = 0;
+ Assert.Empty(ReferencePlayer.Commands(Mvp, tired));
+ }
+
+ [Fact]
+ public void ItFillsNoMoreJobsThanThereAreCivilians()
+ {
+ var s = Simulation.NewGame(Mvp, GoldenRun.Seed, Mode.Historical);
+ s.Cities["tel_aviv"] = s.Cities["tel_aviv"].WithCounts(50, 40, 0); // 90 jobs, 50 civilians
+ var assign = Assert.IsType<AssignWorkers>(ReferencePlayer.Commands(Mvp, s).Last());
+ Assert.Equal(50, assign.Count);
+ }
+
+ [Fact]
+ public void ItIssuesNoGddOrderInTheLegacyLoop()
+ {
+ var c = ContentLoader.Load(RealContentTests.ContentRoot());
+ var s = Simulation.NewGame(c, GoldenRun.Seed, Mode.Historical);
+ Assert.Equal(HistoricalAI.Commands(c, s).Select(x => x.Kind), ReferencePlayer.Commands(c, s).Select(x => x.Kind));
+ }
+
+ /// <summary>Only the golden runner (MvpGolden) and tests may name it: no game mode, CLI command or Unity screen.</summary>
+ [Fact]
+ public void NoGameModeOrUiReachesIt()
+ {
+ Assert.Equal(new[] { "Historical", "Open" }, Enum.GetNames(typeof(Mode))); // no mode plays it
+ var repo = Directory.GetParent(RealContentTests.ContentRoot())!.FullName;
+ string Rel(string f) => Path.GetRelativePath(repo, f).Replace('\\', '/');
+ var users = new[] { "sim/Statecraft.Sim", "sim/Statecraft.Cli", "unity/Assets", "tools" }
+ .Select(d => Path.Combine(repo, d)).Where(Directory.Exists)
+ .SelectMany(d => Directory.GetFiles(d, "*.cs", SearchOption.AllDirectories))
+ .Where(f => Regex.IsMatch(File.ReadAllText(f), @"\bReferencePlayer\b|Statecraft\.Sim\.Reference\b"))
+ .Select(Rel)
+ .Where(f => !f.StartsWith("sim/Statecraft.Sim/Reference/", StringComparison.Ordinal) && !f.StartsWith("unity/Assets/Tests/", StringComparison.Ordinal))
+ .OrderBy(f => f, StringComparer.Ordinal);
+ Assert.Equal(new[] { "sim/Statecraft.Sim/MvpGolden.cs" }, users);
+ Assert.Equal("Statecraft.Sim.Reference", typeof(ReferencePlayer).Namespace);
+ }
+}
diff --git a/sim/Statecraft.Sim.Tests/SaveGameTests.cs b/sim/Statecraft.Sim.Tests/SaveGameTests.cs
index 7460fffae..67972e954 100644
--- a/sim/Statecraft.Sim.Tests/SaveGameTests.cs
+++ b/sim/Statecraft.Sim.Tests/SaveGameTests.cs
@@ -27,7 +27,8 @@ public class SaveGameTests
new Command[] { new AllocateBudget(new Dictionary<string, double> { ["finance_minister"] = 0.75, ["defense_minister"] = 0.25 }) },
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[0], new Command[0], new Command[] { new SecurityOrder(1) }, new Command[0], new Command[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],
};
foreach (var o in orders) g.Step(o);
return g;
diff --git a/sim/Statecraft.Sim.Tests/ScenarioTests.cs b/sim/Statecraft.Sim.Tests/ScenarioTests.cs
index 7497b4e1f..7fffb6089 100644
--- a/sim/Statecraft.Sim.Tests/ScenarioTests.cs
+++ b/sim/Statecraft.Sim.Tests/ScenarioTests.cs
@@ -8,6 +8,10 @@ using Statecraft.Sim;
public class ScenarioTests
{
static readonly Content C = ContentLoader.Load(RealContentTests.ContentRoot());
+ static readonly Content Mvp = MvpSlice.Load(RealContentTests.ContentRoot());
+
+ /// <summary>The content a scenario plays on: the real content, or the GDD slice for `content: mvp`.</summary>
+ static Content For(Scenario sc) => sc.Content == Scenario.MvpContent ? Mvp : C;
/// <summary>sim/Statecraft.Sim.Tests/scenarios, where the scenario files live (the runner, Scenario, is in the sim library).</summary>
public static string Dir() =>
@@ -22,7 +26,7 @@ public class ScenarioTests
{
var sc = Scenario.Parse(File.ReadAllText(Path.Combine(Dir(), file + ".yaml")));
Assert.Equal(file, sc.Name);
- var s = sc.Play(C);
+ var s = sc.Play(For(sc));
var name = "scenario-" + sc.Name;
// A new scenario has no manifest line yet: the blessing run (STATECRAFT_UPDATE_GOLDEN=1) adds it with its snapshot.
var expected = GoldenManifest.UpdateRequested ? GoldenManifest.Read().GetValueOrDefault(name, "") : GoldenManifest.Expected(name);
@@ -34,12 +38,12 @@ public class ScenarioTests
{
var scenarios = Directory.GetFiles(Dir(), "*.yaml").OrderBy(f => f, StringComparer.Ordinal).Select(f => Scenario.Parse(File.ReadAllText(f))).ToList();
Assert.True(scenarios.Count >= 2);
- var hashes = scenarios.Select(sc => sc.Play(C).Hash()).ToList();
+ var hashes = scenarios.Select(sc => sc.Play(For(sc)).Hash()).ToList();
Assert.Equal(hashes.Count, hashes.Distinct().Count());
foreach (var (sc, hash) in scenarios.Zip(hashes, (sc, h) => (sc, h)))
{
- var bare = Scenario.Parse($"name: {sc.Name}\nuntil: {sc.Until}\n" + (sc.Seed.HasValue ? $"seed: {sc.Seed}\n" : ""));
- Assert.True(bare.Play(C).Hash() != hash, $"scenario '{sc.Name}' ends where the same run with no scripted command ends: its choices change nothing");
+ var bare = Scenario.Parse($"name: {sc.Name}\nuntil: {sc.Until}\n" + (sc.Seed.HasValue ? $"seed: {sc.Seed}\n" : "") + (sc.Content != "" ? $"content: {sc.Content}\n" : ""));
+ Assert.True(bare.Play(For(bare)).Hash() != hash, $"scenario '{sc.Name}' ends where the same run with no scripted command ends: its choices change nothing");
}
}
@@ -78,6 +82,19 @@ public class ScenarioTests
public void AMalformedCommandIsRefusedWithTheProblemNamed(string command, string expected) =>
Assert.Contains(expected, Assert.Throws<InvalidDataException>(() => Scenario.Parse(Head + command)).Message);
+ [Fact]
+ public void TheMvpScenarioPlaysTheGddSlice()
+ {
+ var sc = Scenario.Parse(File.ReadAllText(Path.Combine(Dir(), "mvp-absorb-first.yaml")));
+ Assert.Equal("mvp", sc.Content);
+ Assert.True(For(sc).IsGdd);
+ Assert.Equal(90, sc.Play(For(sc)).Cities["tel_aviv"].Employed);
+ }
+
+ [Fact]
+ public void AnUnknownContentIsRefused() =>
+ Assert.Contains("'content' must be mvp", Assert.Throws<InvalidDataException>(() => Scenario.Parse("name: t\ncontent: civ\nuntil: 1948-08-01\n")).Message);
+
[Fact]
public void ABadDateIsRefused() =>
Assert.Contains("yyyy-MM-dd", Assert.Throws<InvalidDataException>(() => Scenario.Parse("name: t\nuntil: soon\n")).Message);
diff --git a/sim/Statecraft.Sim.Tests/golden/manifest.txt b/sim/Statecraft.Sim.Tests/golden/manifest.txt
index 81504f46b..d74142125 100644
--- a/sim/Statecraft.Sim.Tests/golden/manifest.txt
+++ b/sim/Statecraft.Sim.Tests/golden/manifest.txt
@@ -7,4 +7,5 @@ hash1952 62f8ec61a14acff4eab503381994a7c94d7a2f786dcfde5c4c19439ac8b4c5e8
smoke5 d3fdd459ddb876bd8d775c20edd1202cf56ca7134a8ad06f873d4d92034aa5b6
scenario-reckless c0bd12bc481a9f2dbeea19aebc981d5347caa1e1cf2e6fd5a5acdf107f2f9045
scenario-cautious 1d5b8d7126160021963537f2a198e377b27d478f522e8c6be63babe9e1b8f482
-mvp-slice 0451920a78852bcff49d435b04bb387543c33064090071195f8210a7bd8dcdc4
+mvp-slice f6931e2432b906edffbafb17087add152974645d468ec721b0606f837277446c
+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 038aa4957..a6e585f07 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=26.348732976636185 [403A59469079B06C]
+debt=22.748732976636184 [4036BFACF6E016D2]
fx=80.85238326859616 [4054368D728D91CC]
rung=5;cf=40;
mob=0.8 [3FE999999999999A]
@@ -78,4 +78,7 @@ appt{
under=;
map[
mapturn=0001-01-01:0;
-over=
\ No newline at end of file
+over=
+city{
+ tel_aviv=120,90,120,90,91
+coh=0.6842783505154639 [3FE5E59BB61A644A]
\ No newline at end of file
diff --git a/sim/Statecraft.Sim.Tests/golden/scenario-mvp-absorb-first.txt b/sim/Statecraft.Sim.Tests/golden/scenario-mvp-absorb-first.txt
new file mode 100644
index 000000000..3af0108b6
--- /dev/null
+++ b/sim/Statecraft.Sim.Tests/golden/scenario-mvp-absorb-first.txt
@@ -0,0 +1,94 @@
+1949-06-15;11400714819323200433;Historical;13;
+ind{
+ food_supply=0.7200000000000001 [3FE70A3D70A3D70B]
+ housing=0.4311483383927494 [3FDB97EF3347C84B]
+ intl_standing=0.7100000000000002 [3FE6B851EB851EBA]
+ morale=0.4449244143453166 [3FDC79A440338690]
+ security=0.510599903035164 [3FE056D59B9C0EC0]
+pol{
+ border_settlement=0.2 [3FC999999999999A]
+ housing_construction=0.3 [3FD3333333333333]
+ maabarot=0 [0000000000000000]
+ rationing=1 [3FF0000000000000]
+eff{
+ border_villages_secure=0.03559990303516388 [3FA23A26868DB8BB]
+ building_houses=0.08114833839274943 [3FB4C62333858794]
+ homes_lift_morale=0.06417065737109631 [3FB06D7CFAC58CD2]
+ rationing_feeds=0.17 [3FC5C28F5C28F5C3]
+ rationing_grates=-0.15 [BFC3333333333333]
+ safety_lifts_morale=0.05075375697422029 [3FA9FC657CB4F1E7]
+shift{
+ food_supply=0.15000000000000002 [3FC3333333333334]
+ housing=0 [0000000000000000]
+ intl_standing=0.2100000000000002 [3FCAE147AE147AE8]
+ morale=-0.07000000000000006 [BFB1EB851EB851F0]
+ security=0.17500000000000016 [3FC666666666666C]
+bud{
+ agriculture_minister=0.07 [3FB1EB851EB851EC]
+ defense_minister=0.45 [3FDCCCCCCCCCCCCD]
+ education_minister=0.06 [3FAEB851EB851EB8]
+ finance_minister=0.05 [3FA999999999999A]
+ health_minister=0.07 [3FB1EB851EB851EC]
+ interior_minister=0.05 [3FA999999999999A]
+ labour_minister=0.1 [3FB999999999999A]
+ prime_minister=0.15 [3FC3333333333333]
+pop{
+ africa=26076.53167905079 [40D97722070791C7]
+ america_oceania=1128.7559880551275 [4091A30621BB93C2]
+ asia=37290.593872499 [40E235530100E626]
+ europe=132807.37455827303 [4100363AFF186869]
+ unknown=14597.23556687349 [40CC829E270E28D5]
+ veterans=661390.4179891739 [41242F1CD602AD50]
+sit[
+treasury=0 [0000000000000000]
+debt=57.82904503222418 [404CEA1E25CA2835]
+fx=94.29191537516759 [405792AEBDD362D7]
+rung=2;cf=0;
+mob=0.8 [3FE999999999999A]
+stab=0.5583883508188896 [3FE1DE513F278112]
+att=4 [4010000000000000]
+fired[
+ altalena
+ armistice_egypt
+ armistice_jordan
+ armistice_lebanon
+ austerity_1949
+ bernadotte_assassination
+ elections_1949
+ first_truce
+ idf_founding
+ jerusalem_ceasefire
+ jerusalem_military_government
+ latrun_proposal
+ operation_hiram
+ operation_horev
+ operation_yoav
+ second_truce
+ ten_days
+pending[
+chosen{
+ altalena=enforce
+ armistice_egypt=sign
+ armistice_jordan=sign
+ armistice_lebanon=sign
+ austerity_1949=impose
+ bernadotte_assassination=outlaw
+ elections_1949=hold
+ first_truce=accept
+ idf_founding=one_army
+ jerusalem_ceasefire=sign
+ jerusalem_military_government=military_government
+ latrun_proposal=accept_vote
+ operation_hiram=launch
+ operation_horev=launch
+ operation_yoav=stop_at_ceasefire
+ second_truce=comply
+ ten_days=central_front
+appt{
+under=;
+map[
+mapturn=0001-01-01:0;
+over=
+city{
+ tel_aviv=120,90,120,90,190
+coh=0.5826124567474048 [3FE2A4C2E0FF1D3B]
\ No newline at end of file
diff --git a/sim/Statecraft.Sim.Tests/scenarios/mvp-absorb-first.yaml b/sim/Statecraft.Sim.Tests/scenarios/mvp-absorb-first.yaml
new file mode 100644
index 000000000..6a6f5d504
--- /dev/null
+++ b/sim/Statecraft.Sim.Tests/scenarios/mvp-absorb-first.yaml
@@ -0,0 +1,10 @@
+# A player who puts the slice's people to work first (GDD Phase 1 PR 3): on the first turn it fills Tel Aviv's 90 jobs, then
+# plays on with no other order; events nobody answered are delegated. It runs on the GDD slice (MvpSlice: the real content
+# with the loop switch on and placeholder city values), so it moves whenever a GDD rule or placeholder it reaches changes.
+name: mvp-absorb-first
+content: mvp
+until: 1949-06-15
+steps:
+ - on: 1948-05-15
+ commands:
+ - { kind: assign_workers, city: tel_aviv, role: job, count: 90 }
diff --git a/sim/Statecraft.Sim/AttentionSystem.cs b/sim/Statecraft.Sim/AttentionSystem.cs
index c88058a01..77486a23b 100644
--- a/sim/Statecraft.Sim/AttentionSystem.cs
+++ b/sim/Statecraft.Sim/AttentionSystem.cs
@@ -7,12 +7,18 @@ 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" };
+ { "set_policy", "allocate_budget", "choose_event_option", "set_mobilization", "security_order", "appoint", "map_action", "assign_workers" };
+
+ /// <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" };
public static IReadOnlyCollection<string> CommandKinds => Kinds;
public static bool IsCommandKind(string kind) => Kinds.Contains(kind);
+ public static bool IsGddKind(string kind) => GddKinds.Contains(kind);
+
public static void Refill(Content c, GameState s) => s.Attention = c.RulesAt(s.Date).AttentionPerTurn;
/// <summary>Cost at <paramref name="rung"/> if given, else at the state's current rung.</summary>
diff --git a/sim/Statecraft.Sim/Cities.cs b/sim/Statecraft.Sim/Cities.cs
new file mode 100644
index 000000000..6186739eb
--- /dev/null
+++ b/sim/Statecraft.Sim/Cities.cs
@@ -0,0 +1,98 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace Statecraft.Sim
+{
+ /// <summary>The GDD v0.1 cities (docs/GDD.md "Cities and construction"; Phase 1 PR 3): civilians and refugees are counts
+ /// per city (D-A2), in population units (D-A1). Runs only when eras.yaml systems.loop is gdd.</summary>
+ public static class Cities
+ {
+ public const string Kind = "assign_workers";
+
+ /// <summary>Fills the state's cities from cities.yaml, with no refugees yet. Does nothing in the legacy loop.</summary>
+ public static void Init(Content c, GameState s)
+ {
+ if (!c.IsGdd) return;
+ foreach (var x in c.Cities) s.Cities[x.Id] = new City(x.Id, x.HousingCapacity, x.JobSlots, x.Civilians, x.Employed, 0);
+ UpdateCohesion(s, c.RulesAt(s.Date).Mvp!);
+ }
+
+ /// <summary>R-CITY-001: sets the number of the city's civilians in jobs (a standing order). Refused, state untouched,
+ /// when the city or role is unknown or the count is negative, above the job slots or above the civilians. Step has
+ /// already refused it in the legacy loop.</summary>
+ public static string? Assign(Content c, GameState s, string city, string role, int count, List<Cause> why)
+ {
+ if (!s.Cities.TryGetValue(city, out var x)) return "There is no such city";
+ if (role != "job") return "There is no such role"; // craftsman: Phase 3 (D-D4)
+ if (count < 0) return "The number of workers cannot be negative";
+ if (count > x.JobSlots) return FormattableString.Invariant($"{PlayerText.Settlement(c, city)} has {x.JobSlots} jobs");
+ if (count > x.Civilians) return FormattableString.Invariant($"{PlayerText.Settlement(c, city)} has {x.Civilians} civilians");
+ s.Cities[city] = x.WithCounts(x.Civilians, count, x.Refugees);
+ why.Add(new Cause("city", city, count - x.Employed, FormattableString.Invariant($"{PlayerText.Settlement(c, city)}: {count} groups in work")));
+ return null;
+ }
+
+ /// <summary>R-CITY-002: each city's employed units earn income_per_job_per_year for the turn's share of a year.</summary>
+ public static void Produce(Content c, GameState s, MvpRules r, double yearFraction, List<Cause> why)
+ {
+ foreach (var x in s.Cities.Values)
+ {
+ if (x.Employed == 0) continue;
+ var paid = x.Employed * r.IncomePerJobPerYear * yearFraction;
+ s.Treasury += paid;
+ why.Add(new Cause("city", x.Id, paid, $"{PlayerText.Settlement(c, x.Id)}: jobs paid {PlayerText.MoneyChange(c, "treasury", paid)}"));
+ }
+ }
+
+ /// <summary>R-CITY-004 (D-A5): refugees become civilians, without a job, as far as the city's free housing goes. The cap is
+ /// 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)
+ {
+ foreach (var x in s.Cities.Values.ToList())
+ {
+ var moved = Math.Min(x.Refugees, Math.Max(0, x.HousingCapacity - x.Civilians));
+ if (moved == 0) continue;
+ s.Cities[x.Id] = x.WithCounts(x.Civilians + moved, x.Employed, x.Refugees - moved);
+ why.Add(new Cause("city", x.Id, moved, FormattableString.Invariant($"{PlayerText.Settlement(c, x.Id)}: {moved} groups of immigrants housed")));
+ }
+ }
+
+ /// <summary>R-CITY-005, a placeholder while D-C1 is open: over all cities, the housed share (civilians of civilians and
+ /// refugees; 1 with nobody) and the employed share (employed of civilians; 1 with no civilians), weighted by the mvp
+ /// cohesion weights, clamped to 0 to 1. Counts are summed as integers, so city order cannot change the result.</summary>
+ public static void UpdateCohesion(GameState s, MvpRules r)
+ {
+ long civilians = 0, employed = 0, refugees = 0;
+ foreach (var x in s.Cities.Values) { civilians += x.Civilians; employed += x.Employed; refugees += x.Refugees; }
+ var housed = civilians + refugees == 0 ? 1.0 : (double)civilians / (civilians + refugees);
+ var working = civilians == 0 ? 1.0 : (double)employed / civilians;
+ s.Cohesion = Math.Max(0, Math.Min(1, r.CohesionHousingWeight * housed + r.CohesionJobsWeight * working));
+ }
+
+ /// <summary>R-CITY-003 (D-A5): the turn's immigrants (the CBS series, aliyah.yaml) arrive as refugees in the mvp
+ /// arrivals_city, in whole units. Before cutover PopulationSystem still adds the same people to GameState.Population,
+ /// the head count the legacy economy reads: two views of one group until Phase 3 makes arrivals counts (spec section 6).</summary>
+ public static void Arrive(Content c, GameState s, MvpRules r, DateTime next, List<Cause> why)
+ {
+ var units = ArrivedUnits(c, s.Date, next, r.PeoplePerUnit);
+ if (units == 0) return;
+ var x = s.Cities[r.ArrivalsCity];
+ s.Cities[x.Id] = x.WithCounts(x.Civilians, x.Employed, x.Refugees + units);
+ why.Add(new Cause("city", x.Id, units, FormattableString.Invariant($"{PlayerText.Settlement(c, x.Id)}: {units} groups of immigrants arrived and wait for housing")));
+ }
+
+ /// <summary>The whole units of <paramref name="peoplePerUnit"/> people that arrive in [from, to). Counted from the game's
+ /// start, floor(people by to) minus floor(people by from), so over any run of turns no unit is lost or counted twice.</summary>
+ public static int ArrivedUnits(Content c, DateTime from, DateTime to, int peoplePerUnit)
+ {
+ int UnitsBy(DateTime t)
+ {
+ var people = 0.0;
+ foreach (var kv in PopulationSystem.Arrivals(c, c.Eras[0].From, t).OrderBy(k => k.Key, StringComparer.Ordinal)) people += kv.Value;
+ return (int)Math.Floor(people / peoplePerUnit);
+ }
+ return UnitsBy(to) - UnitsBy(from);
+ }
+ }
+}
diff --git a/sim/Statecraft.Sim/Commands.cs b/sim/Statecraft.Sim/Commands.cs
index a8f681499..dfb32fcea 100644
--- a/sim/Statecraft.Sim/Commands.cs
+++ b/sim/Statecraft.Sim/Commands.cs
@@ -58,6 +58,15 @@ namespace Statecraft.Sim
public MapAction(string action, int q, int r) { Action = action; Q = q; R = r; }
}
+ /// <summary>Sets how many of <see cref="City"/>'s civilians work in <see cref="Role"/> (`job`), a standing order
+ /// (Cities.Assign, R-CITY-001). GDD v0.1 loop only.</summary>
+ public sealed class AssignWorkers : Command
+ {
+ public override string Kind => Cities.Kind;
+ public string City { get; } public string Role { get; } public int Count { get; }
+ public AssignWorkers(string city, string role, int count) { City = city; Role = role; Count = count; }
+ }
+
public sealed class Rejection
{
public Command Command { get; } public string Reason { get; }
@@ -86,6 +95,7 @@ namespace Statecraft.Sim
case ChooseEventOption e: Text(e.EventId, "EventId"); Text(e.OptionId, "OptionId"); break;
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 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 14a05a88f..f50d74358 100644
--- a/sim/Statecraft.Sim/Content.cs
+++ b/sim/Statecraft.Sim/Content.cs
@@ -306,6 +306,46 @@ namespace Statecraft.Sim
/// office with the line's own id. A listed line is owned by each term's office from that term's day to the next
/// term's day. Read through <see cref="Offices.BudgetOwner"/> and <see cref="Offices.BudgetLineOf"/>. Start-only, like budget_start.</summary>
public Dictionary<string, List<BudgetOwnerTerm>> BudgetOwners { get; set; } = new Dictionary<string, List<BudgetOwnerTerm>>();
+ /// <summary>The GDD v0.1 rules (docs/rules/mvp.md). Required, and read, only when eras.yaml systems.loop is gdd; null
+ /// otherwise. Its values are the owner's to set: until then they live in MvpSlice.Overlay or a test fixture.</summary>
+ public MvpRules? Mvp { get; set; }
+ }
+
+ /// <summary>rules.yaml mvp: the GDD v0.1 slice's city rules (Phase 1 PR 3).</summary>
+ public sealed class MvpRules
+ {
+ /// <summary>People in one population unit (D-A1: a unit is a group).</summary>
+ public int PeoplePerUnit { get; set; }
+ /// <summary>Money each employed unit earns a year, in IL millions (R-CITY-002).</summary>
+ public double IncomePerJobPerYear { get; set; }
+ /// <summary>Social cohesion's weight on the housed share (R-CITY-005). A placeholder while D-C1 is open.</summary>
+ public double CohesionHousingWeight { get; set; }
+ /// <summary>Social cohesion's weight on the employed share (R-CITY-005). A placeholder while D-C1 is open.</summary>
+ public double CohesionJobsWeight { get; set; }
+ /// <summary>The city every arrival lands in (Phase 1 has one city; R-CITY-003).</summary>
+ public string ArrivalsCity { get; set; } = "";
+ }
+
+ /// <summary>A city's start values (cities.yaml, GDD "Cities and construction"). Counts are population units (D-A1).</summary>
+ public sealed class CityStart
+ {
+ /// <summary>A settlement id of map/settlements_1948.yaml.</summary>
+ public string Id { get; set; } = "";
+ public int HousingCapacity { get; set; }
+ public int JobSlots { get; set; }
+ public int Civilians { get; set; }
+ /// <summary>The civilians in jobs at the start: part of <see cref="Civilians"/>.</summary>
+ public int Employed { get; set; }
+ /// <summary>Training facilities in the city (military_camp, hakhshara). PR 4 uses them (D-D5).</summary>
+ public List<string> Facilities { get; set; } = new List<string>();
+ }
+
+ /// <summary>A population or unit type (unit_types.yaml, GDD "Population and units"). `population`: a count per city;
+ /// `unit`: a movable unit (D-A2).</summary>
+ public sealed class UnitType
+ {
+ public string Id { get; set; } = "";
+ public string Kind { 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>
@@ -524,6 +564,12 @@ namespace Statecraft.Sim
}
}
public List<SettlementHex> SettlementHexes = new List<SettlementHex>();
+ /// <summary>The display name of each settlement id (map/settlements_1948.yaml name), for text the player reads.</summary>
+ public Dictionary<string, string> SettlementNames = new Dictionary<string, string>();
+ /// <summary>The GDD cities' start values (cities.yaml), in file order. Empty in the legacy loop.</summary>
+ public List<CityStart> Cities = new List<CityStart>();
+ /// <summary>The GDD population and unit types (unit_types.yaml). Empty in the legacy loop.</summary>
+ public List<UnitType> UnitTypes = new List<UnitType>();
/// <summary>SHA-256 (lowercase hex) over every file the loader read, in read order, with CRLF read as LF. A save
/// records it; loading a save made with other content shows a warning (spec section 7).</summary>
public string Hash = "";
diff --git a/sim/Statecraft.Sim/ContentLoader.cs b/sim/Statecraft.Sim/ContentLoader.cs
index 1d30d3312..5be30b785 100644
--- a/sim/Statecraft.Sim/ContentLoader.cs
+++ b/sim/Statecraft.Sim/ContentLoader.cs
@@ -45,14 +45,16 @@ namespace Statecraft.Sim
public List<MapHex> Hexes { get; set; } = new List<MapHex>();
}
sealed class SettlementHexesFile { public List<SettlementHex> Settlements { get; set; } = new List<SettlementHex>(); }
+ sealed class CitiesFile { public List<CityStart> Cities { get; set; } = new List<CityStart>(); }
+ sealed class UnitTypesFile { public List<UnitType> Types { get; set; } = new List<UnitType>(); }
public const string HexesFile = "map/hexes.json";
public const string SettlementHexesFileName = "map/settlement_hexes.yaml";
public const string SettlementsFileName = "map/settlements_1948.yaml";
- /// <summary>The ids of settlements_1948.yaml, which the tools own (its other keys are not the sim's business), so it is
- /// read as plain maps rather than through the strict content types.</summary>
- static List<string> ReadSettlementIds(Func<string, string?> readFile)
+ /// <summary>The ids and names of settlements_1948.yaml, which the tools own (its other keys are not the sim's business),
+ /// so it is read as plain maps rather than through the strict content types.</summary>
+ static List<(string id, string name)> ReadSettlements(Func<string, string?> readFile)
{
string? text;
try { text = readFile(SettlementsFileName); }
@@ -63,8 +65,11 @@ namespace Statecraft.Sim
{
var file = new DeserializerBuilder().Build().Deserialize<Dictionary<string, List<Dictionary<string, object>>>>(text);
if (file == null || !file.TryGetValue("settlements", out var rows)) throw new ContentException(SettlementsFileName, "settlements", "required");
- return rows.Select((r, i) => r.TryGetValue("id", out var id) && id is string sid && sid != ""
- ? sid : throw new ContentException(SettlementsFileName, $"settlements[{i}].id", "required")).ToList();
+ return rows.Select((r, i) => (
+ r.TryGetValue("id", out var id) && id is string sid && sid != ""
+ ? sid : throw new ContentException(SettlementsFileName, $"settlements[{i}].id", "required"),
+ r.TryGetValue("name", out var name) && name is string sname && !string.IsNullOrWhiteSpace(sname)
+ ? sname : throw new ContentException(SettlementsFileName, $"settlements[{i}].name", "required (the name shown to the player)"))).ToList();
}
catch (YamlException e) { throw new ContentException(SettlementsFileName, $"line {e.Start.Line}", e.InnerException?.Message ?? e.Message); }
}
@@ -224,7 +229,9 @@ namespace Statecraft.Sim
c.PopulationAnchors = Read<PopulationFile>(readFile, "population.yaml").Anchors;
c.Hexes = Read<MapFile>(readFile, HexesFile).Hexes;
c.SettlementHexes = Read<SettlementHexesFile>(readFile, SettlementHexesFileName).Settlements;
- var settlementIds = ReadSettlementIds(readFile);
+ var settlements = ReadSettlements(readFile);
+ var settlementIds = settlements.Select(x => x.id).ToList();
+ foreach (var (id, name) in settlements) c.SettlementNames[id] = name; // a duplicate id fails in ValidateMap
// Event files (content/events/*.yaml), one GameEvent each. Keys, for content authors:
// id, title, text text may name office holders only through {office_id} placeholders, which
// must have a holder on every day of the window
@@ -245,6 +252,14 @@ namespace Statecraft.Sim
c.Events.Add(e);
}
Validate(c, settlementIds);
+ if (c.IsGdd)
+ {
+ // GDD v0.1 city data (Phase 1 PR 3), read once eras.yaml is known to be valid. Only the GDD loop reads it, so
+ // the legacy content needs neither file.
+ c.Cities = Read<CitiesFile>(readFile, "cities.yaml").Cities;
+ c.UnitTypes = Read<UnitTypesFile>(readFile, "unit_types.yaml").Types;
+ ValidateGdd(c, settlementIds);
+ }
c.BuildWindows();
c.Hash = HashOf(read);
return c;
@@ -366,7 +381,8 @@ namespace Statecraft.Sim
foreach (var k in r.AttentionCost.Keys)
if (!AttentionSystem.IsCommandKind(k)) throw new ContentException(file, $"attention_cost.{k}", "unknown command kind");
foreach (var k in AttentionSystem.CommandKinds)
- if (!r.AttentionCost.ContainsKey(k)) throw new ContentException(file, $"attention_cost.{k}", "missing cost");
+ if ((c.IsGdd || !AttentionSystem.IsGddKind(k)) && !r.AttentionCost.ContainsKey(k)) // a GDD kind is priced only where it can run
+ throw new ContentException(file, $"attention_cost.{k}", "missing cost");
if (r.RungMinMobilization.Count != 5) throw new ContentException(file, "rung_min_mobilization", "needs exactly 5 values (rungs 1-5)");
for (int i = 0; i < 5; i++)
{
@@ -829,6 +845,54 @@ namespace Statecraft.Sim
}
}
+ /// <summary>Facilities a city may have (cities.yaml facilities): the GDD's training places (D-D5).</summary>
+ static readonly string[] Facilities = { "military_camp", "hakhshara" };
+
+ static void NotNegative(string file, string field, int v)
+ {
+ if (v < 0) throw new ContentException(file, field, "must be >= 0");
+ }
+
+ /// <summary>The GDD v0.1 city data and rules (Phase 1 PR 3), checked only when systems.loop is gdd.</summary>
+ static void ValidateGdd(Content c, List<string> settlementIds)
+ {
+ const string cf = "cities.yaml", uf = "unit_types.yaml";
+ Unique(cf, "cities", c.Cities.Select(x => x.Id));
+ var known = new HashSet<string>(settlementIds);
+ foreach (var x in c.Cities)
+ {
+ var at = $"cities[{x.Id}]";
+ if (!known.Contains(x.Id)) throw new ContentException(cf, at + ".id", $"is not in {SettlementsFileName}");
+ NotNegative(cf, at + ".housing_capacity", x.HousingCapacity);
+ NotNegative(cf, at + ".job_slots", x.JobSlots);
+ NotNegative(cf, at + ".civilians", x.Civilians);
+ NotNegative(cf, at + ".employed", x.Employed);
+ if (x.Employed > x.Civilians) throw new ContentException(cf, at + ".employed", "cannot be more than civilians");
+ if (x.Employed > x.JobSlots) throw new ContentException(cf, at + ".employed", "cannot be more than job_slots");
+ foreach (var f in x.Facilities)
+ if (!Facilities.Contains(f)) throw new ContentException(cf, at + ".facilities", $"unknown facility '{f}' (military_camp or hakhshara)");
+ }
+ 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 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))))
+ {
+ var m = r.Mvp ?? throw new ContentException(file, "mvp", "required when eras.yaml systems.loop is gdd");
+ if (m.PeoplePerUnit < 1) throw new ContentException(file, "mvp.people_per_unit", "must be >= 1");
+ // Arrivals are counted from the game's start in units of one size (R-CITY-003): another size in a later era
+ // would lose or double-count units at its boundary.
+ if (m.PeoplePerUnit != c.Rules.Mvp!.PeoplePerUnit)
+ throw new ContentException(file, "mvp.people_per_unit", "must be the same in every era (arrivals are counted in one unit size)");
+ if (!(m.IncomePerJobPerYear >= 0 && IsFinite(m.IncomePerJobPerYear))) throw new ContentException(file, "mvp.income_per_job_per_year", "must be a finite number >= 0");
+ Unit(file, "mvp.cohesion_housing_weight", m.CohesionHousingWeight);
+ Unit(file, "mvp.cohesion_jobs_weight", m.CohesionJobsWeight);
+ if (Math.Abs(m.CohesionHousingWeight + m.CohesionJobsWeight - 1) > 1e-9)
+ throw new ContentException(file, "mvp.cohesion_jobs_weight", "the two cohesion weights must sum to 1");
+ if (!cities.Contains(m.ArrivalsCity)) throw new ContentException(file, "mvp.arrivals_city", $"'{m.ArrivalsCity}' is not a city in cities.yaml");
+ }
+ }
+
static void ValidateMap(Content c, List<string> settlementIds)
{
if (c.Hexes.Count == 0) throw new ContentException(HexesFile, "hexes", "no hexes");
diff --git a/sim/Statecraft.Sim/GameState.cs b/sim/Statecraft.Sim/GameState.cs
index e0d82730f..7e4ebf980 100644
--- a/sim/Statecraft.Sim/GameState.cs
+++ b/sim/Statecraft.Sim/GameState.cs
@@ -58,6 +58,9 @@ namespace Statecraft.Sim
// GDD v0.1 state (spec 2026-10-12 section 2.2). Empty in the legacy loop, and then left out of the hash (R-LOOP-002).
/// <summary>The cities by id (ordinal).</summary>
public SortedDictionary<string, City> Cities = new SortedDictionary<string, City>(StringComparer.Ordinal);
+ /// <summary>Social cohesion, 0 to 1, from the cities' housing and jobs (R-CITY-005). A placeholder while D-C1 is open:
+ /// no other system reads it and nothing shows it. Hashed only when the state has cities.</summary>
+ 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>
@@ -170,7 +173,15 @@ namespace Statecraft.Sim
foreach (var i in items) { Entry(); sb.Append(i); Sep(); }
Close(close);
}
- if (Cities.Count > 0) Section("city", '{', '}', Cities.Values.Select(x => x.Canonical()));
+ if (Cities.Count > 0)
+ {
+ Section("city", '{', '}', Cities.Values.Select(x => x.Canonical()));
+ Sep();
+ var bits = BitConverter.DoubleToInt64Bits(Cohesion == 0.0 ? 0.0 : Cohesion).ToString("X16", CultureInfo.InvariantCulture);
+ Nl(); sb.Append("coh=");
+ if (readable) sb.Append((Cohesion == 0.0 ? 0.0 : Cohesion).ToString("R", CultureInfo.InvariantCulture)).Append(" [").Append(bits).Append(']');
+ else sb.Append(bits);
+ }
if (Units.Count > 0) Section("units", '[', ']', Units.Values.Select(x => x.Canonical()));
if (NextId != 0) { Sep(); Nl(); sb.Append("next=").Append(NextId.ToString(CultureInfo.InvariantCulture)); }
if (Objectives.Count > 0)
diff --git a/sim/Statecraft.Sim/GddState.cs b/sim/Statecraft.Sim/GddState.cs
index aece76639..740a7a933 100644
--- a/sim/Statecraft.Sim/GddState.cs
+++ b/sim/Statecraft.Sim/GddState.cs
@@ -23,6 +23,9 @@ namespace Statecraft.Sim
Id = id; HousingCapacity = housingCapacity; JobSlots = jobSlots; Civilians = civilians; Employed = employed; Refugees = refugees;
}
+ /// <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);
+
/// <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);
}
diff --git a/sim/Statecraft.Sim/MvpGolden.cs b/sim/Statecraft.Sim/MvpGolden.cs
index 0461e3be9..5e5f73a30 100644
--- a/sim/Statecraft.Sim/MvpGolden.cs
+++ b/sim/Statecraft.Sim/MvpGolden.cs
@@ -1,11 +1,11 @@
using System;
+using Statecraft.Sim.Reference;
namespace Statecraft.Sim
{
/// <summary>The GDD slice's golden (spec 2026-10-12 section 3; docs/determinism.md, "MVP goldens"): MvpSlice (the real content
- /// with the loop switch on and monthly turns), the golden seed, Historical mode and HistoricalAI, until Until. It covers only
- /// what is built: no GDD order is issued, so it needs no reference player (decision D-A7, with the owner) and no resolution
- /// order (D-A6).</summary>
+ /// with the loop switch on, monthly turns and the slice's placeholder city), the golden seed, Historical mode and the
+ /// reference player (D-A7: HistoricalAI's orders, then the jobs filled), until Until.</summary>
public static class MvpGolden
{
/// <summary>Eight monthly turns from 15 May 1948. A test choice, not a balance value.</summary>
@@ -15,7 +15,7 @@ namespace Statecraft.Sim
{
var s = Simulation.NewGame(c, GoldenRun.Seed, Mode.Historical);
for (int turn = 0; turn < 1000 && s.Date < Until && s.GameOver == null; turn++)
- s = Simulation.Step(c, s, HistoricalAI.Commands(c, s)).State;
+ s = Simulation.Step(c, s, ReferencePlayer.Commands(c, s)).State;
return s;
}
}
diff --git a/sim/Statecraft.Sim/MvpSlice.cs b/sim/Statecraft.Sim/MvpSlice.cs
index c7db5e26c..543d86683 100644
--- a/sim/Statecraft.Sim/MvpSlice.cs
+++ b/sim/Statecraft.Sim/MvpSlice.cs
@@ -6,7 +6,8 @@ using YamlDotNet.Serialization;
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) and monthly turns (rules.yaml turn_lengths all month). Tests, the MVP
+ /// (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
/// 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>
@@ -15,14 +16,35 @@ namespace Statecraft.Sim
static readonly IDeserializer Reader = new DeserializerBuilder().WithDuplicateKeyChecking().Build();
static readonly ISerializer Writer = new SerializerBuilder().Build();
+ /// <summary>The slice's city (D-A4: Tel Aviv). Design values, not historical figures: none is a claim about Tel Aviv
+ /// in 1948. Counts are population units of mvp.people_per_unit people (D-A1).</summary>
+ public const string Cities = @"# PLACEHOLDER: owner sets every value below (MvpSlice.Overlay; never under content/ until the owner sets them).
+cities:
+ - id: tel_aviv
+ housing_capacity: 120 # PLACEHOLDER: owner sets
+ 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)
+";
+
+ /// <summary>The slice's population types (D-A2: civilians and refugees are counts per city).</summary>
+ public const string UnitTypes = @"types:
+ - { id: civilian, kind: population }
+ - { id: refugee, kind: population }
+";
+
/// <summary>Wraps <paramref name="readFile"/> (the loader's file reader): eras.yaml and rules.yaml come back with the
- /// slice's switches, every other file unchanged.</summary>
+ /// slice's switches and its rules, cities.yaml and unit_types.yaml with the slice's city when the content has none, and
+ /// every other file unchanged.</summary>
public static Func<string, string?> Overlay(Func<string, string?> readFile)
{
if (readFile == null) throw new ArgumentNullException(nameof(readFile));
return rel =>
{
var text = readFile(rel);
+ if (text == null && rel == "cities.yaml") return Cities;
+ if (text == null && rel == "unit_types.yaml") return UnitTypes;
if (text == null) return null;
if (rel == "eras.yaml")
{
@@ -40,6 +62,17 @@ namespace Statecraft.Sim
{
var root = Reader.Deserialize<Dictionary<object, object>>(text) ?? new Dictionary<object, object>();
root["turn_lengths"] = new List<object> { "month", "month", "month", "month", "month" };
+ if (!root.ContainsKey("mvp"))
+ root["mvp"] = new Dictionary<object, object>
+ {
+ ["people_per_unit"] = 1000, // PLACEHOLDER: owner sets (D-A1 scale)
+ ["income_per_job_per_year"] = 0.06, // PLACEHOLDER: owner sets (IL millions per employed unit a year; D-C6)
+ ["cohesion_housing_weight"] = 0.5, // PLACEHOLDER (D-C1 open)
+ ["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
return Writer.Serialize(root);
}
return text;
diff --git a/sim/Statecraft.Sim/PlayerText.cs b/sim/Statecraft.Sim/PlayerText.cs
index 6b84d0904..788cd6b32 100644
--- a/sim/Statecraft.Sim/PlayerText.cs
+++ b/sim/Statecraft.Sim/PlayerText.cs
@@ -35,6 +35,9 @@ namespace Statecraft.Sim
/// <summary>The display name of an aliyah origin group (aliyah.yaml regions).</summary>
public static string Region(Content c, string id) => c.Regions.FirstOrDefault(r => r.Id == id)?.Name ?? throw Unknown("region", id);
+ /// <summary>The display name of a settlement (map/settlements_1948.yaml name), such as a GDD city.</summary>
+ public static string Settlement(Content c, string id) => c.SettlementNames.TryGetValue(id, out var name) ? name : throw Unknown("settlement", id);
+
/// <summary>The display name of what a cause changes: an indicator or policy (model.yaml names), or money
/// (model.yaml money).</summary>
public static string Target(Content c, string id) =>
diff --git a/sim/Statecraft.Sim/Reference/ReferencePlayer.cs b/sim/Statecraft.Sim/Reference/ReferencePlayer.cs
new file mode 100644
index 000000000..9316ee712
--- /dev/null
+++ b/sim/Statecraft.Sim/Reference/ReferencePlayer.cs
@@ -0,0 +1,29 @@
+using System;
+using System.Collections.Generic;
+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
+ /// (ReferencePlayerTests.NoGameModeOrUiReachesIt).</summary>
+ public static class ReferencePlayer
+ {
+ public static IReadOnlyList<Command> Commands(Content c, GameState s)
+ {
+ var list = new List<Command>(HistoricalAI.Commands(c, s));
+ var left = s.Attention - list.Sum(x => AttentionSystem.Cost(c, s, x.Kind));
+ foreach (var city in s.Cities.Values)
+ {
+ var want = Math.Min(city.JobSlots, city.Civilians);
+ if (want == city.Employed) continue;
+ var cost = AttentionSystem.Cost(c, s, Cities.Kind);
+ if (cost > left + 1e-9) continue; // AttentionSystem.TrySpend's rule
+ list.Add(new AssignWorkers(city.Id, "job", want));
+ left -= cost;
+ }
+ return list;
+ }
+ }
+}
diff --git a/sim/Statecraft.Sim/SaveGame.cs b/sim/Statecraft.Sim/SaveGame.cs
index 45985a62a..9ec45145c 100644
--- a/sim/Statecraft.Sim/SaveGame.cs
+++ b/sim/Statecraft.Sim/SaveGame.cs
@@ -22,7 +22,7 @@ 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
+ /// security DELTA | appoint OFFICE PERSON | map ACTION Q R | work CITY ROLE N
/// 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>
@@ -101,6 +101,7 @@ namespace Statecraft.Sim
SecurityOrder o => $"security {Int(o.Delta)}",
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)}",
_ => throw new ArgumentException($"Cannot save command kind '{cmd.Kind}'", nameof(cmd)),
};
@@ -187,6 +188,7 @@ namespace Statecraft.Sim
case "security": Arity(2); return new SecurityOrder(I(f[1]));
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]));
default: throw new SaveException(line, $"unknown command '{f[0]}'");
}
}
diff --git a/sim/Statecraft.Sim/Scenario.cs b/sim/Statecraft.Sim/Scenario.cs
index 563631bdf..a0a8ac341 100644
--- a/sim/Statecraft.Sim/Scenario.cs
+++ b/sim/Statecraft.Sim/Scenario.cs
@@ -13,6 +13,7 @@ namespace Statecraft.Sim
/// <code>
/// name: reckless
/// seed: 1948 # optional, default GoldenRun.Seed
+ /// content: mvp # optional: the GDD slice (MvpSlice.Load) instead of the real content
/// until: 1949-01-01 # the run stops when the date reaches it
/// steps:
/// - on: 1948-05-15 # the commands go in on the first turn that starts on or after this date, once
@@ -20,12 +21,16 @@ namespace Statecraft.Sim
/// - { kind: set_policy, policy: rationing, level: 1.0 }
/// </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). A turn with no
+ /// 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
/// 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
{
public string Name { get; set; } = "";
public ulong? Seed { get; set; }
+ /// <summary>"" for the real content, or <see cref="MvpContent"/> for the GDD slice. The caller loads the content it names.</summary>
+ public string Content { get; set; } = "";
+ public const string MvpContent = "mvp";
public string Until { get; set; } = "";
public List<ScenarioStep> Steps { get; set; } = new List<ScenarioStep>();
@@ -34,6 +39,7 @@ namespace Statecraft.Sim
var d = new DeserializerBuilder().WithNamingConvention(UnderscoredNamingConvention.Instance).Build();
var s = d.Deserialize<Scenario>(yaml) ?? throw new InvalidDataException("the scenario file is empty");
if (string.IsNullOrWhiteSpace(s.Name)) throw new InvalidDataException("a scenario needs a name");
+ if (s.Content != "" && s.Content != MvpContent) throw new InvalidDataException($"'content' must be mvp or left out, got '{s.Content}'");
s.UntilDate = Date(s.Until, "until");
foreach (var step in s.Steps)
{
@@ -60,7 +66,7 @@ namespace Statecraft.Sim
["set_policy"] = new[] { "policy", "level" }, ["allocate_budget"] = new[] { "shares" },
["choose_event_option"] = new[] { "event", "option" }, ["set_mobilization"] = new[] { "level" },
["security_order"] = new[] { "delta" }, ["appoint"] = new[] { "office", "person" },
- ["map_action"] = new[] { "action", "q", "r" },
+ ["map_action"] = new[] { "action", "q", "r" }, ["assign_workers"] = new[] { "city", "role", "count" },
};
public static IReadOnlyCollection<string> Kinds => Allowed.Keys;
@@ -85,6 +91,7 @@ namespace Statecraft.Sim
case "security_order": return new SecurityOrder(Whole(c, "delta"));
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"));
default: throw new InvalidDataException($"command kind '{kind}' has no builder");
}
}
@@ -121,7 +128,8 @@ namespace Statecraft.Sim
static string Describe(Command c) => c switch
{
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}", _ => c.Kind,
+ 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,
};
}
diff --git a/sim/Statecraft.Sim/Simulation.cs b/sim/Statecraft.Sim/Simulation.cs
index 7e22d946a..87328f16c 100644
--- a/sim/Statecraft.Sim/Simulation.cs
+++ b/sim/Statecraft.Sim/Simulation.cs
@@ -16,6 +16,7 @@ namespace Statecraft.Sim
EffectsSystem.Init(c, s);
EconomySystem.Init(c, s);
PopulationSystem.Init(c, s);
+ Cities.Init(c, s);
SecuritySystem.Init(c, s, why);
AttentionSystem.Refill(c, s);
EventSystem.Trigger(c, s, why);
@@ -46,6 +47,8 @@ namespace Statecraft.Sim
foreach (var cmd in commands)
{
if (!AttentionSystem.IsCommandKind(cmd.Kind)) { rejected.Add(new Rejection(cmd, "That order is not known")); continue; }
+ // A GDD order has no price in the legacy rules: refuse it before charging (R-CITY-001).
+ if (AttentionSystem.IsGddKind(cmd.Kind) && !c.IsGdd) { rejected.Add(new Rejection(cmd, "That order is not available in this game")); continue; }
var before = s.Attention;
var error = AttentionSystem.TrySpend(c, s, cmd.Kind, priceRung) ?? Execute(c, s, cmd, why);
if (error != null) { s.Attention = before; rejected.Add(new Rejection(cmd, error)); }
@@ -60,6 +63,7 @@ namespace Statecraft.Sim
var adjusted = next != SimTime.Advance(s.Date, len);
var days = (next - s.Date).Days;
var yf = adjusted ? days / 365.0 : SimTime.YearFraction(len);
+ TurnResolver.Resolve(c, s, next, yf, why); // the GDD v0.1 loop only; the legacy loop goes straight on
EffectsSystem.Apply(c, s, why);
PopulationSystem.Apply(c, s, next, yf, why);
EconomySystem.Apply(c, s, yf, why);
@@ -134,6 +138,8 @@ namespace Statecraft.Sim
return Cabinet.Appoint(c, s, a.Office, a.Person, why);
case MapAction m:
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 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/TurnResolver.cs b/sim/Statecraft.Sim/TurnResolver.cs
new file mode 100644
index 000000000..244735e6b
--- /dev/null
+++ b/sim/Statecraft.Sim/TurnResolver.cs
@@ -0,0 +1,26 @@
+using System;
+using System.Collections.Generic;
+
+namespace Statecraft.Sim
+{
+ /// <summary>The GDD v0.1 turn's resolution phase (spec 2026-10-12 section 2.3), in the fixed order the owner approved
+ /// (D-A6, #456). Simulation.Step calls it after the orders and before the legacy systems, only when systems.loop is gdd.
+ /// Steps not built yet are named where they will go.</summary>
+ public static class TurnResolver
+ {
+ /// <summary>Resolves the turn that starts on s.Date and ends on <paramref name="next"/> (<paramref name="yearFraction"/>
+ /// of a year long).</summary>
+ public static void Resolve(Content c, GameState s, DateTime next, double yearFraction, List<Cause> why)
+ {
+ 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.
+ Cities.Produce(c, s, r, yearFraction, why); // 6. production
+ // 7. Consumption: Phase 2.
+ Cities.House(c, s, why); // 8. housing, then Social cohesion
+ Cities.UpdateCohesion(s, r);
+ Cities.Arrive(c, s, r, next, why); // 9. arrivals
+ // 10. Occupation timers: Phase 6. 11. Objectives and score: PR 6.
+ }
+ }
+}
diff --git a/unity/Assets/Scripts/UI/WhyPresenter.cs b/unity/Assets/Scripts/UI/WhyPresenter.cs
index 6fac1bee2..9f540d302 100644
--- a/unity/Assets/Scripts/UI/WhyPresenter.cs
+++ b/unity/Assets/Scripts/UI/WhyPresenter.cs
@@ -9,7 +9,7 @@ namespace Statecraft.Game.UI
/// that produced it, in a fixed order (what was decided first, then its consequences).</summary>
public sealed class WhyPresenter : System.IDisposable
{
- public static readonly string[] Order = { "era", "events", "politics", "cabinet", "security", "economy", "population", "map", "policy", "effects", "situations" };
+ public static readonly string[] Order = { "era", "events", "politics", "cabinet", "security", "economy", "population", "city", "map", "policy", "effects", "situations" };
readonly VisualElement screen; readonly SimBridge bridge; readonly UiText text;
public WhyPresenter(VisualElement root, SimBridge bridge, UiText text)
diff --git a/unity/Assets/UI/strings.en.yaml b/unity/Assets/UI/strings.en.yaml
index fb567208d..e530cb032 100644
--- a/unity/Assets/UI/strings.en.yaml
+++ b/unity/Assets/UI/strings.en.yaml
@@ -58,6 +58,7 @@ why.cabinet: "Cabinet"
why.security: "Security"
why.economy: "Economy"
why.population: "Immigration and population"
+why.city: "Cities"
why.map: "Building"
why.policy: "Policies"
why.effects: "Ongoing effects"
diff --git a/unity/Assets/UI/strings.he.yaml b/unity/Assets/UI/strings.he.yaml
index fbb35cb83..7041407c1 100644
--- a/unity/Assets/UI/strings.he.yaml
+++ b/unity/Assets/UI/strings.he.yaml
@@ -63,6 +63,7 @@ why.cabinet: "ממשלה"
why.security: "ביטחון"
why.economy: "כלכלה"
why.population: "עלייה ואוכלוסייה"
+why.city: "ערים"
why.map: "בנייה"
why.policy: "מדיניות"
why.effects: "השפעות מתמשכות"