A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
sim: turn lengths per rung as data, turn_lengths (refs #81) (#349)
Eyal Golanc2e9e86cb418
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d1babdca6..26260fbfb 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,9 @@ adds a line under **Unreleased**; CI's `Changelog` job checks this (see `CONTRIB## [Unreleased]### Added+- Turn lengths per security rung are data: `turn_lengths` in `rules.yaml` or an era override, read in the era the turn+ starts in (R-TURN-001). The default is today's table, so the goldens do not move. GDD v0.1 Phase 1 uses it for monthly+ turns (refs #81).- Indicators, policies, effects, situations, voter groups and actors can carry `from`/`to` dates (chapters spec 3.2, refs#57). The sim reads the records active on the game date; the state gains a record at its start and drops it at its end,and a `set_policy` outside the window is refused. The loader refuses a reference to a record that is not active for thediff --git a/docs/gdd/monthly-turns.md b/docs/gdd/monthly-turns.mdnew file mode 100644index 000000000..4347d76d2--- /dev/null+++ b/docs/gdd/monthly-turns.md@@ -0,0 +1,36 @@+# Monthly turns as data++## Player story++As a player of the MVP, I want every turn to be one month, so that 15 May 1948 to January 1952 plays in about 44 turns (decision D-B1 [S2]; the GDD targets about 48 [S1]).++## Rules++- The turn length on each security rung comes from `turn_lengths` in the rules of the era the turn starts in (R-TURN-001).+- Without the key, the first three rungs have quarter turns, the fourth month turns and the fifth week turns.+- The MVP sets month on every rung. Turns from the start on 15 May 1948 then end on the 15th of each month [S2].+- A turn that reaches an era boundary ends on it, and a turn that would end fewer than 14 days before it is lengthened to it (`SimTime.AdvanceTo`, D-E5, unchanged).++## Data touched++- `content/rules.yaml` and `content/rules/<era>.yaml`: `turn_lengths`. The real content does not set it until the cutover PR.+- `Rules.TurnLengths`, read by `SecuritySystem.TurnLengthFor(c, date, rung)`.++## Done when++- `dotnet test sim/Statecraft.sln --filter TurnLengthsTests` passes.+- The goldens `hash1950`, `hash1952`, `smoke5`, `scenario-cautious` and `scenario-reckless` do not move.++## Out of scope++- Year turns and the `war_mode` switch of issue #81, paused by the plan's §7.2.+- Turning monthly turns on for the real game, which is the cutover PR (the plan's §3).++## Sources++- [S1] The game design of record, docs/GDD.md+- [S2] GDD v0.1 impact analysis and phased plan, decision D-B1, docs/superpowers/specs/2026-10-12-gdd-v0.1-impact-and-plan.md++## Open questions++- None.diff --git a/docs/rules/mvp.md b/docs/rules/mvp.mdnew file mode 100644index 000000000..6dcd46c4f--- /dev/null+++ b/docs/rules/mvp.md@@ -0,0 +1,9 @@+# Rules of the GDD v0.1 MVP++The rules of the 1948–1951 MVP in [docs/GDD.md](../GDD.md), as Phase 1 builds them behind the `systems.loop` switch+([the approved plan](../superpowers/specs/2026-10-12-gdd-v0.1-impact-and-plan.md), §6). Balance values are the owner's.+Until the owner sets them, they are placeholders marked `# PLACEHOLDER: owner sets` in `content/`.++## Turns++R-TURN-001: The turn length on each security rung (1 to 5) is read from the rules key `turn_lengths` of the era the turn starts in. Without the key it is quarter, quarter, quarter, month, week, today's table. The GDD's monthly turns set all five to month.diff --git a/docs/superpowers/plans/2026-10-12-gdd-phase-1.md b/docs/superpowers/plans/2026-10-12-gdd-phase-1.mdnew file mode 100644index 000000000..ef0cd2dc5--- /dev/null+++ b/docs/superpowers/plans/2026-10-12-gdd-phase-1.md@@ -0,0 +1,1045 @@+# GDD v0.1 Phase 1: the vertical slice behind the switch. Implementation plan++> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans (the controller chose inline execution, one PR at a time, no subagents). Steps use checkbox (`- [ ]`) syntax for tracking.++**Goal:** Build GDD v0.1 Phase 1 (one city, training, one pioneer action, one objective card, a minimal UI) behind a data switch, so that `hash1950`, `hash1952`, `smoke5`, `scenario-cautious` and `scenario-reckless` do not move.++**Architecture:** One `systems.loop` switch (`legacy` | `gdd`) in `eras.yaml` and a `turn_lengths` rules key. The real content keeps the defaults until the cutover PR (Phase 2). Tests, the new MVP goldens and a dev URL flag load the real content through `MvpSlice.Overlay`, which turns the switch on and sets monthly turns. New state is hashed only when it is not empty, so with the switch off `GameState.Describe()` is byte-identical to today. The GDD rules run in a new `TurnResolver`, called from `Simulation.Step` only when the loop is `gdd`.++**Tech stack:** C# netstandard2.1 sim (`sim/Statecraft.Sim`), xUnit tests on net10.0 (`sim/Statecraft.Sim.Tests`), YamlDotNet content, Unity 6000.3.25f1 UI Toolkit (`unity/`), Python tools and policy checks under `uv`.++**Spec:** [docs/superpowers/specs/2026-10-12-gdd-v0.1-impact-and-plan.md](../specs/2026-10-12-gdd-v0.1-impact-and-plan.md), §2, §3 and §6 "Phase 1". Design of record: [docs/GDD.md](../../GDD.md). Read both before a task.++## Global constraints++- The GDD wins over every older spec (AGENTS.md). Anything the GDD marks Open is built only as the approved decision or as a labelled placeholder.+- Owner decisions (spec §5, approved 12 October 2026):+ - D-A1: a unit is a group.+ - D-A2: civilians, craftsmen and refugees are counts per city; halutzim and soldiers are movable units.+ - D-A3: work and training take several turns. Cancelling returns the people but not the Money spent.+ - D-A4: Tel Aviv (`tel_aviv`), one 1949–51 yishuv site with a sourced date and photo, and the "first new yishuv" card.+ - D-B1: 15 May 1948 to January 1952, monthly turns.+ - D-C5: keep the cabinet and Attention.+ - D-E1/E4: retire the legacy loop at cutover and refuse old saves.+ - D-E3: the game's English says "War of Independence".+- Not decided, so built as the spec's recommended default and labelled provisional in code comments and PR bodies: D-A5 (refugees become civilians when housed), D-A6 (resolution order of spec §2.3), D-A7 (the reference player is test code), D-B2/D-B6 (score formula and points), D-D5 (one camp and one Hakhshara exist at start), D-D6 (one project per pioneer unit).+- Every balance value is a placeholder in content with the comment `# PLACEHOLDER: owner sets`. The spec's risk line said "never in real content"; the controller's brief (12 October 2026) puts them in content, labelled, so the owner edits one file. They are inert while the switch is off.+- Every historical fact in `content/` has `sources:` with a URL and a `checked:` date (CONTENT_POLICY §2.1). No invented quotes. Dates show as "15 May 1948".+- Event photographs: public domain, CC0, or CC BY 4.0 archival event photographs (for example the Meitar Collection) with a credit line. Never GPO, PD-Israel-only, PD-India or share-alike (CONTENT_POLICY §4, docs/event-images.md).+- Determinism (docs/determinism.md): one RNG, no trigonometry, no unordered iteration into state, invariant culture. Phase 1 adds **no RNG draw**. New collections are ordered by id, hold immutable records, and use integers for counts and timers.+- The goldens `hash1950`, `hash1952`, `smoke5`, `scenario-cautious`, `scenario-reckless` must not move in any Phase 1 PR. The new goldens `mvp-slice` and `scenario-mvp-absorb-first` may move in the PR that changes the rules they cover; the PR says why.+- Every new rule gets an `R-` ID in `docs/rules/mvp.md`, cited by its test (`// R-XXX-NNN`) and in the PR body ("implements R-XXX-NNN"). Each feature gets a `docs/gdd/<feature>.md` section that passes `gdd_lint.py`.+- Each PR: a branch from current `origin/main` in `.worktrees/<branch>`; a claimed issue (Task form style); `CHANGELOG.md` line for `sim/`, `content/` or `unity/`; commits end with `Co-Authored-By: Claude Opus 5.5 <[email protected]>`; the PR body ends with `🤖 Generated with [Claude Code](https://claude.com/claude-code)`.+- Full checks before every PR:+ - `dotnet test sim/Statecraft.sln` (0 warnings);+ - `uv run --with pytest==9.1.1 --with rasterio==1.5.2 --with numpy==2.5.3 --with pyyaml==6.0.3 --with pillow==12.3.0 --with requests==2.32.5 --with pyproj==3.8.0 pytest tools/tests -q`;+ - `uv run --with pytest==9.1.1 --with pyyaml==6.0.3 --with requests==2.32.5 pytest scripts/oss/tests -q`;+ - `uv run scripts/oss/check_repo.py`, `uv run scripts/oss/changelog_check.py --base origin/main`, `uv run scripts/oss/gdd_lint.py`, `uv run scripts/oss/rule_ids.py`.+- Unity, when `unity/` or the sim DLL's use in Unity changes: `tools/build_sim_for_unity.sh`, then EditMode tests under `uv run tools/machine_lock.py --shared --wait-unity --timeout 3000 -- "$UNITY" -batchmode -CI false -GITHUB_ACTIONS false -TF_BUILD false -projectPath unity -buildTarget OSXUniversal -runTests -testPlatform EditMode -testResults "$PWD/unity-editmode.xml" -logFile unity-tests.log`. Never `-nographics` on the editor. Afterwards `git checkout -- unity/Assets/Settings unity/ProjectSettings/ProjectSettings.asset`. Stop only our own Unity process, by PID.+- When the sim changes: a WebGL build (`Build.Web`, compression disabled) and `uv run tools/web_check.py unity/Builds/Web-disabled --query "golden&smoke=5"` with the three `--expect` values from docs/determinism.md.+- In-flight PRs: #329, #332, #335 touch `Content.cs` and `ContentLoader.cs`; #337 and #342 touch `EraTests.cs` and `EventRules.cs`. Build on `origin/main`. Before each PR, run `gh pr view <n> --json state` for them; if one merged, rebase; if a conflict is likely in the same lines, report it before pushing.++## Review focus++1. **A save from the legacy loop loaded into GDD content (and the reverse).** Expect a clear refusal ("made with an earlier version of the game's rules; start a new game"), never a silent replay that drifts. Test in Task 2.4.+2. **The switch off.** With real content, every new section is absent from `Describe()` and every new command is refused with "not available in this game", refunding Attention. Test in Tasks 2.2, 3.2 and every command task.+3. **Counts that would go negative or exceed capacity**: assigning more workers than civilians or job slots, training more than the unemployed, cancelling a cohort that finished. Expect a refusal naming the limit and an unchanged state. Tests in Tasks 3.2, 4.2, 4.3.+4. **Fractional arrivals.** Arrivals are fractions of a person per day; refugees are whole units of `people_per_unit`. The cumulative rule must never lose or double-count a unit across turns of any length. Test in Task 3.3 (sum over the run equals floor of the total).+5. **The objective card fired twice, or before completion, or under the legacy loop.** Expect exactly one card, on the turn after completion, never in legacy. Test in Task 6.3.++## The PR list++| PR | Branch | Issue | What |+|---|---|---|---|+| 1 | `sim/turn-lengths-81` | Refs #81 (re-scoped: months only, spec §7.2) | Monthly turns as data: the `turn_lengths` rules key and `TurnLengthFor(c, date, rung)` |+| 2 | `sim/gdd-switch` | new Task issue | The switch, the overlay, state scaffolding with omit-when-empty hashing, save schema 2 with `ruleset`, the command touch-point guard, the `mvp-slice` golden |+| 3 | `sim/gdd-city` | new Task issue | One city: `cities.yaml`, `unit_types.yaml`, `AssignWorkers`, Money from jobs, arrivals as refugees, housing, Social cohesion, `TurnResolver`, the reference player, `scenario-mvp-absorb-first` |+| 4 | `sim/gdd-training` | new Task issue | Training: camp and Hakhshara, `Train`, `CancelTraining`, recruits as counts, halutzim as units |+| 5 | `sim/gdd-site` | new Task issue (refs #27) | One designated site (`sites.yaml`, sourced), `PioneerWork(build_yishuv)`, `StopWork` |+| 6 | `sim/gdd-objective` | new Task issue | The objective card: `objectives.yaml`, the `objective:` event key, the card event, the score with the timing bonus |+| 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 |++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.++## File map++| File | Responsibility | PRs |+|---|---|---|+| `sim/Statecraft.Sim/SimTime.cs` | `TurnLength` parsing (`SimTime.ParseLength`) | 1 |+| `sim/Statecraft.Sim/SecuritySystem.cs` | `TurnLengthFor(c, date, rung)` reads `turn_lengths`; `TurnLengthFor(rung)` stays as the default table | 1 |+| `sim/Statecraft.Sim/Content.cs` | `Rules.TurnLengths`, `EraSystems.Loop`, `Content.Loop`, `Content.Ruleset`, `MvpRules`, new content records | 1–6 |+| `sim/Statecraft.Sim/ContentLoader.cs` | Read and validate `turn_lengths`, `systems.loop`, `cities.yaml`, `unit_types.yaml`, `sites.yaml`, `objectives.yaml` | 1–6 |+| `sim/Statecraft.Sim/MvpSlice.cs` (new) | `Overlay(readFile)`: real content with the switch on and monthly turns | 2 |+| `sim/Statecraft.Sim/GddState.cs` (new) | Immutable records `City`, `Unit`, `Cohort`, `SiteState` | 2 |+| `sim/Statecraft.Sim/GameState.cs` | New fields, `Clone`, omit-when-empty hash sections | 2 |+| `sim/Statecraft.Sim/SaveGame.cs`, `GameSession.cs` | Schema 2, `ruleset` line, refusal of another ruleset | 2–6 |+| `sim/Statecraft.Sim/Commands.cs`, `AttentionSystem.cs`, `Simulation.cs` | New commands and their touch-points | 3–5 |+| `sim/Statecraft.Sim/Cities.cs` (new) | City rules: assign, production, arrivals, housing, cohesion | 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 provisional) | 3–6 |+| `sim/Statecraft.Sim/EventSystem.cs`, `EventRules.cs` | Objective-triggered events | 6 |+| `content/cities.yaml`, `content/unit_types.yaml`, `content/sites.yaml`, `content/objectives.yaml`, `content/events/first_new_yishuv.yaml`, `content/rules.yaml` (`attention_cost`, `mvp:`), `content/schema/event.schema.json` | Slice content | 3–6 |+| `sim/Statecraft.Sim.Tests/*` | Tests per task; `MvpGolden.cs`, `ReferencePlayer.cs` (new) | 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 |++---++## PR 1: monthly turns as data++Issue: comment on #81 to claim it, re-scoped to months only (spec §7.2): "Taking the `turn_lengths` key and `TurnLengthFor(c, date, rung)` for GDD Phase 1 PR 1, branch `sim/turn-lengths-81`. Year turns and `war_mode` stay paused (spec §7.2). The PR will say Refs #81."++### Task 1.1: the `turn_lengths` key, read per era++**Files:**+- Modify: `sim/Statecraft.Sim/SimTime.cs`, `sim/Statecraft.Sim/SecuritySystem.cs`, `sim/Statecraft.Sim/Simulation.cs:55`, `sim/Statecraft.Sim/Content.cs` (`Rules`), `sim/Statecraft.Sim/ContentLoader.cs` (`ValidateRules`)+- Modify: `sim/Statecraft.Sim.Tests/EconomyCalibrationTests.cs:119` (use the content overload)+- Create: `sim/Statecraft.Sim.Tests/TurnLengthsTests.cs`+- Create: `docs/rules/mvp.md`, `docs/gdd/monthly-turns.md`+- Modify: `CHANGELOG.md`++**Interfaces:**+- Produces: `Rules.TurnLengths : List<string>` (YAML `turn_lengths`, default `[quarter, quarter, quarter, month, week]`); `SimTime.ParseLength(string) : TurnLength` (throws `ArgumentException` on an unknown name); `SimTime.LengthNames : IReadOnlyList<string>`; `SecuritySystem.TurnLengthFor(Content c, DateTime date, int rung) : TurnLength`. `SecuritySystem.TurnLengthFor(int rung)` stays: the default table, used by Unity's Defence screen until cutover.++- [ ] **Step 1: Write the failing tests** in `TurnLengthsTests.cs`:++```csharp+using System;+using System.Collections.Generic;+using System.IO;+using System.Linq;+using Statecraft.Sim;++/// <summary>turn_lengths (GDD Phase 1, refs #81): the turn length on each security rung is data, read in the era the turn starts in.</summary>+public class TurnLengthsTests+{+ static Content Load(string extraRules) => ContentLoader.Load(Fixture.Write(new Dictionary<string, string>+ { ["rules.yaml"] = Fixture.Files["rules.yaml"] + extraRules }));++ // R-TURN-001+ [Theory]+ [InlineData(1, TurnLength.Quarter)] [InlineData(2, TurnLength.Quarter)] [InlineData(3, TurnLength.Quarter)]+ [InlineData(4, TurnLength.Month)] [InlineData(5, TurnLength.Week)]+ public void TheDefaultReproducesTheLegacyTable(int rung, TurnLength expected)+ {+ var c = ContentLoader.Load(RealContentTests.ContentRoot());+ Assert.Equal(expected, SecuritySystem.TurnLengthFor(c, c.Rules.Start, rung));+ Assert.Equal(SecuritySystem.TurnLengthFor(rung), SecuritySystem.TurnLengthFor(c, c.Rules.Start, rung));+ }++ // R-TURN-001+ [Fact]+ public void AllMonthsGivesMonthlyTurnsOnTheFifteenth()+ {+ var c = Load("turn_lengths: [month, month, month, month, month]\n");+ var s = Simulation.NewGame(c, 1, Mode.Historical);+ Assert.Equal(5, s.Rung); // the fixture starts at full war, weekly in the default table+ var dates = new List<DateTime>();+ for (int i = 0; i < 3; i++) { s = Simulation.Step(c, s, new Command[0]).State; dates.Add(s.Date); }+ Assert.Equal(new[] { new DateTime(1948, 6, 15), new DateTime(1948, 7, 15), new DateTime(1948, 8, 15) }, dates);+ }++ // R-TURN-001+ [Fact]+ public void AnEraOverrideChangesTheTableFromItsFirstTurn()+ {+ var dir = Fixture.Write(new Dictionary<string, string> { ["eras.yaml"] = @"+eras:+ - id: founding+ name: The Founding+ from: 1948-05-15+ to: 1948-07-01+ - id: later+ name: A Later Chapter+ from: 1948-07-01+ to: 1957-01-01+" });+ Directory.CreateDirectory(Path.Combine(dir, "rules"));+ File.WriteAllText(Path.Combine(dir, "rules", "later.yaml"), "turn_lengths: [month, month, month, month, month]\n");+ var c = ContentLoader.Load(dir);+ Assert.Equal(TurnLength.Week, SecuritySystem.TurnLengthFor(c, new DateTime(1948, 6, 30), 5));+ Assert.Equal(TurnLength.Month, SecuritySystem.TurnLengthFor(c, new DateTime(1948, 7, 1), 5));+ }++ [Theory]+ [InlineData("turn_lengths: [month, month, month, month]\n", "turn_lengths", "needs exactly 5 values (rungs 1-5)")]+ [InlineData("turn_lengths: [month, month, fortnight, month, month]\n", "turn_lengths[2]", "must be quarter, month or week")]+ public void ABadTableFailsNamingTheField(string rules, string field, string message)+ {+ var ex = Assert.Throws<ContentException>(() => Load(rules));+ Assert.Equal("rules.yaml", ex.File);+ Assert.Equal(field, ex.Field);+ Assert.Contains(message, ex.Message);+ }++ [Fact]+ public void ParseLengthRefusesAnUnknownName() =>+ Assert.Throws<ArgumentException>(() => SimTime.ParseLength("Month")); // names are lowercase, as in YAML+}+```++- [ ] **Step 2: Run, expect a compile failure** (`TurnLengthFor(c, date, rung)` and `ParseLength` do not exist): `dotnet test sim/Statecraft.sln --filter TurnLengthsTests`.++- [ ] **Step 3: Implement.**++`SimTime.cs`, add:++```csharp+ /// <summary>The names `turn_lengths` accepts, in the order of <see cref="TurnLength"/>'s use: quarter, month, week.</summary>+ public static readonly IReadOnlyList<string> LengthNames = new[] { "quarter", "month", "week" };++ /// <summary>The turn length a rules name stands for. Throws on anything else (the loader has already refused it).</summary>+ public static TurnLength ParseLength(string name) => name switch+ {+ "quarter" => TurnLength.Quarter,+ "month" => TurnLength.Month,+ "week" => TurnLength.Week,+ _ => throw new ArgumentException($"unknown turn length '{name}'", nameof(name)),+ };+```++(add `using System.Collections.Generic;`).++`Content.cs`, in `Rules` after `CeasefireWeeks`:++```csharp+ /// <summary>The turn length on each security rung, rungs 1 to 5 (quarter, month or week). The default is the legacy+ /// table; the GDD cutover sets every rung to month (spec 2026-10-12 §3). Read with SecuritySystem.TurnLengthFor(c, date, rung).</summary>+ public List<string> TurnLengths { get; set; } = new List<string> { "quarter", "quarter", "quarter", "month", "week" };+```++`ContentLoader.ValidateRules`, after the `rung_min_mobilization` loop:++```csharp+ if (r.TurnLengths.Count != 5) throw new ContentException(file, "turn_lengths", "needs exactly 5 values (rungs 1-5)");+ for (int i = 0; i < 5; i++)+ if (!SimTime.LengthNames.Contains(r.TurnLengths[i]))+ throw new ContentException(file, FormattableString.Invariant($"turn_lengths[{i}]"), "must be quarter, month or week");+```++`SecuritySystem.cs`, replace the summary on `TurnLengthFor(int)` and add the overload:++```csharp+ /// <summary>The default turn_lengths table (rules.yaml without the key). The game reads+ /// <see cref="TurnLengthFor(Content, DateTime, int)"/>; this stays for the Defence screen's legend until cutover.</summary>+ public static TurnLength TurnLengthFor(int rung) =>+ rung >= 5 ? TurnLength.Week : rung == 4 ? TurnLength.Month : TurnLength.Quarter;++ /// <summary>The length of a turn that starts on <paramref name="date"/> on <paramref name="rung"/>: rules turn_lengths+ /// of the era the date is in (docs/determinism.md, "Rules per era"). R-TURN-001.</summary>+ public static TurnLength TurnLengthFor(Content c, DateTime date, int rung) =>+ SimTime.ParseLength(c.RulesAt(date).TurnLengths[ClampRung(rung) - 1]);+```++`Simulation.cs:55`: `var len = SecuritySystem.TurnLengthFor(c, s.Date, s.Rung);`++`EconomyCalibrationTests.cs:119`: `var yf = SimTime.YearFraction(SecuritySystem.TurnLengthFor(C, a.Date, a.Rung));`++- [ ] **Step 4: Run** `dotnet test sim/Statecraft.sln --filter "TurnLengthsTests|SecurityTests|EraRulesTests"`. Expected: PASS.++- [ ] **Step 5: Prove the test can fail.** Revert `Simulation.cs:55` to `SecuritySystem.TurnLengthFor(s.Rung)` and run `--filter TurnLengthsTests`: `AllMonthsGivesMonthlyTurnsOnTheFifteenth` must FAIL (dates 1948-05-22 ...). Restore. Swap the default list to five `month`s: `TheDefaultReproducesTheLegacyTable` must FAIL. Restore.++- [ ] **Step 6: Docs.** `docs/rules/mvp.md`:++```markdown+# Rules of the GDD v0.1 MVP++Rules of the 1948–1951 MVP ([docs/GDD.md](../GDD.md)), built in Phase 1 behind the `systems.loop` switch+([the plan](../superpowers/plans/2026-10-12-gdd-phase-1.md)). Balance values are the owner's; until set they are+placeholders marked `# PLACEHOLDER: owner sets` in `content/`.++## Turns++R-TURN-001: The turn length on each security rung (1 to 5) is read from the rules key `turn_lengths` of the era the turn starts in. Without the key it is quarter, quarter, quarter, month, week. The GDD's monthly turns set all five to month.+```++`docs/gdd/monthly-turns.md` (follow `docs/gdd/TEMPLATE.md`; every number with a unit, every date with `[S1]`):++```markdown+# Monthly turns as data++## Player story++As a player of the MVP, I want every turn to be one month, so that 15 May 1948 to January 1952 plays in about 44 turns (decision D-B1 [S2]; the GDD targets about 48 [S1]).++## Rules++- The turn length on each security rung comes from `turn_lengths` in the rules of the era the turn starts in (R-TURN-001).+- Without the key, the first three rungs have quarter turns, the fourth month turns and the fifth week turns.+- The MVP sets month on every rung. Turns from the start on 15 May 1948 then end on the 15th of each month [S2].+- A turn that reaches an era boundary ends on it, and a turn that would end fewer than 14 days before it is lengthened to it (`SimTime.AdvanceTo`, D-E5, unchanged).++## Data touched++- `content/rules.yaml` and `content/rules/<era>.yaml`: `turn_lengths` (not set in the real content until cutover).++## Done when++- `dotnet test sim/Statecraft.sln --filter TurnLengthsTests` passes.+- The goldens `hash1950`, `hash1952` and `smoke5` do not move.++## Out of scope++- Year turns and `war_mode` (issue #81, paused by spec §7.2).+- Switching the real game to monthly turns: the cutover PR.++## Sources++- [S1] The game design of record, docs/GDD.md+- [S2] GDD v0.1 impact analysis and phased plan, decision D-B1, docs/superpowers/specs/2026-10-12-gdd-v0.1-impact-and-plan.md++## Open questions++- None.+```++`CHANGELOG.md` under `## [Unreleased]` / `### Added`: "- Turn lengths per security rung are data: `turn_lengths` in `rules.yaml` or an era override, read in the era the turn starts in. The default is today's table, so the goldens do not move (GDD Phase 1, refs #81)."++- [ ] **Step 7: Full checks** (Global constraints). Unity is not needed: no Unity code changes and `TurnLengthFor(int)` keeps its behaviour. The sim changed, so run the WebGL `web_check` (golden&smoke=5) if a build is possible; if not, say so in the PR.++- [ ] **Step 8: Commit and open the PR.**++```bash+git add sim/Statecraft.Sim/SimTime.cs sim/Statecraft.Sim/SecuritySystem.cs sim/Statecraft.Sim/Simulation.cs sim/Statecraft.Sim/Content.cs sim/Statecraft.Sim/ContentLoader.cs sim/Statecraft.Sim.Tests/TurnLengthsTests.cs sim/Statecraft.Sim.Tests/EconomyCalibrationTests.cs docs/rules/mvp.md docs/gdd/monthly-turns.md CHANGELOG.md+git commit -m "sim: turn lengths per rung as data, turn_lengths (refs #81)" -m "GDD Phase 1 PR 1. The default reproduces today's table; goldens unchanged." -m "Co-Authored-By: Claude Opus 5.5 <[email protected]>"+gh pr create --title "sim: turn lengths per rung as data (refs #81)" --body-file <body>+```++Then stop and report.++---++## PR 2: the switch, the overlay, state scaffolding and save schema 2++Issue (Task form): "GDD Phase 1: the loop switch, state scaffolding and save schema 2". Goal, files, done-when as below; sign-off: the save schema bump and the `mvp-slice` golden; Unity: yes (the save format the DLL writes changes).++### Task 2.1: `systems.loop` and `Content.Loop`++**Files:** Modify `Content.cs` (`EraSystems`, `Content`), `ContentLoader.cs` (era validation), `content/eras.yaml` (header comment only: document `loop`), `EraSystemsTests.cs`.++**Interfaces:**+- Produces: `EraSystems.Legacy = "legacy"`, `EraSystems.Gdd = "gdd"`, `EraSystems.Loop : string` (default `legacy`); `Content.Loop : string` (the loop of the first era; the loader requires every era to agree); `Content.IsGdd : bool`; `Content.Ruleset : string` (`"legacy"` or `"gdd-0.1"`).++- [ ] **Step 1: Failing tests** in `EraSystemsTests.cs`:++```csharp+ // R-LOOP-001+ [Fact]+ public void RealContentRunsTheLegacyLoop()+ {+ var c = ContentLoader.Load(RealContentTests.ContentRoot());+ Assert.Equal("legacy", c.Loop);+ Assert.False(c.IsGdd);+ Assert.Equal("legacy", c.Ruleset);+ }++ // R-LOOP-001+ [Fact]+ public void TheGddSwitchSetsTheLoopAndTheRuleset()+ {+ var c = Load(" systems: { loop: gdd }");+ Assert.True(c.IsGdd);+ Assert.Equal("gdd-0.1", c.Ruleset);+ }++ [Theory]+ [InlineData(" systems: { loop: civ }", "eras[founding].systems.loop", "must be legacy or gdd")]+ public void ABadLoopFailsNamingTheField(string systems, string field, string message)+ {+ var ex = Assert.Throws<ContentException>(() => Load(systems));+ Assert.Equal(field, ex.Field);+ Assert.Contains(message, ex.Message);+ }++ [Fact]+ public void EveryEraMustRunTheSameLoop()+ {+ var o = 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+" };+ var ex = Assert.Throws<ContentException>(() => ContentLoader.Load(Fixture.Write(o)));+ Assert.Equal("eras[later].systems.loop", ex.Field);+ Assert.Contains("every era runs the same loop", ex.Message);+ }+```++- [ ] **Step 2: Run, expect compile failure.**+- [ ] **Step 3: Implement.** In `EraSystems`:++```csharp+ public const string Legacy = "legacy";+ public const string Gdd = "gdd";+ /// <summary>`legacy`: today's game. `gdd`: the GDD v0.1 loop (TurnResolver). One value for the whole game: the loader+ /// refuses eras that differ (a save names one ruleset, spec 2026-10-12 §2.4). R-LOOP-001.</summary>+ public string Loop { get; set; } = Legacy;+```++In `Content`: `public string Loop => Eras.Count == 0 ? EraSystems.Legacy : Eras[0].Systems.Loop;`, `public bool IsGdd => Loop == EraSystems.Gdd;`, `public string Ruleset => IsGdd ? "gdd-0.1" : "legacy";`.++In the era validation loop of `ContentLoader` (next to the legislature check):++```csharp+ if (e.Systems.Loop != EraSystems.Legacy && e.Systems.Loop != EraSystems.Gdd)+ throw new ContentException("eras.yaml", at + ".systems.loop", "must be legacy or gdd");+ if (e.Systems.Loop != c.Eras[0].Systems.Loop)+ throw new ContentException("eras.yaml", at + ".systems.loop", "every era runs the same loop (a save names one ruleset)");+```++- [ ] **Step 4: Run** `--filter EraSystemsTests`: PASS. **Mutate:** drop the second check, `EveryEraMustRunTheSameLoop` fails. Restore.+- [ ] **Step 5:** Add R-LOOP-001 to `docs/rules/mvp.md` ("R-LOOP-001: `systems.loop` in eras.yaml is `legacy` (default) or `gdd`, the same in every era. Its ruleset id is `legacy` or `gdd-0.1`."). Commit.++### Task 2.2: the overlay (`MvpSlice.Overlay`)++**Files:** Create `sim/Statecraft.Sim/MvpSlice.cs`, `sim/Statecraft.Sim.Tests/MvpSliceTests.cs`.++**Interfaces:**+- Produces: `MvpSlice.Overlay(Func<string, string?> readFile) : Func<string, string?>` (eras.yaml gets `systems.loop: gdd` on every era; rules.yaml gets `turn_lengths` all `month`; every other file passes through); `MvpSlice.Load(string contentRoot) : Content` (the real content through the overlay, event files listed as `ContentLoader.Load(string)` lists them).++- [ ] **Step 1: Failing tests:**++```csharp+using System;+using System.Linq;+using Statecraft.Sim;++public class MvpSliceTests+{+ static readonly Content Real = ContentLoader.Load(RealContentTests.ContentRoot());+ static readonly Content Mvp = MvpSlice.Load(RealContentTests.ContentRoot());++ [Fact]+ public void TheOverlayTurnsTheSwitchOnAndSetsMonthlyTurns()+ {+ Assert.True(Mvp.IsGdd);+ Assert.All(Mvp.Eras, e => Assert.Equal("gdd", e.Systems.Loop));+ Assert.Equal(new[] { "month", "month", "month", "month", "month" }, Mvp.Rules.TurnLengths);+ Assert.NotEqual(Real.Hash, Mvp.Hash); // a save made on one warns on the other+ }++ [Fact]+ public void TheOverlayChangesNothingElse()+ {+ 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);+ Assert.Equal(Real.Eras.Select(e => (e.Id, e.From, e.To, e.Systems.Legislature)), Mvp.Eras.Select(e => (e.Id, e.From, e.To, e.Systems.Legislature)));+ }++ [Fact]+ public void TheMvpPlaysMonthlyFromTheFifteenthOfMay1948()+ {+ var s = Simulation.NewGame(Mvp, GoldenRun.Seed, Mode.Historical);+ s = Simulation.Step(Mvp, s, HistoricalAI.Commands(Mvp, s)).State;+ Assert.Equal(new DateTime(1948, 6, 15), s.Date);+ }+}+```++- [ ] **Step 2: Run, expect compile failure.**+- [ ] **Step 3: Implement** `MvpSlice.cs`:++```csharp+using System;+using System.Collections.Generic;+using System.IO;+using System.Linq;+using YamlDotNet.Serialization;++namespace Statecraft.Sim+{+ /// <summary>The GDD v0.1 slice before cutover (spec 2026-10-12 §2.1): the real content with the loop switch on and monthly+ /// turns. 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 key order in the real files cannot break it.</summary>+ public static class MvpSlice+ {+ static readonly IDeserializer Reader = new DeserializerBuilder().Build();+ static readonly ISerializer Writer = new SerializerBuilder().Build();++ 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) return null;+ if (rel == "eras.yaml")+ {+ var root = Reader.Deserialize<Dictionary<object, object>>(text);+ foreach (Dictionary<object, object> era in (List<object>)root["eras"])+ {+ var systems = era.TryGetValue("systems", out var x) && x is Dictionary<object, object> d ? d : new Dictionary<object, object>();+ systems["loop"] = EraSystems.Gdd;+ era["systems"] = systems;+ }+ return Writer.Serialize(root);+ }+ if (rel == "rules.yaml")+ {+ var root = Reader.Deserialize<Dictionary<object, object>>(text);+ root["turn_lengths"] = new List<object> { "month", "month", "month", "month", "month" };+ return Writer.Serialize(root);+ }+ return text;+ };+ }++ /// <summary>The real content at <paramref name="contentRoot"/> through <see cref="Overlay"/>.</summary>+ public static Content Load(string contentRoot)+ {+ var eventsDir = Path.Combine(contentRoot, "events");+ var eventFiles = Directory.GetFiles(eventsDir, "*.yaml").Select(f => "events/" + Path.GetFileName(f)).ToList();+ return ContentLoader.Load(Overlay(rel => { var p = Path.Combine(contentRoot, rel); return File.Exists(p) ? File.ReadAllText(p) : null; }), eventFiles);+ }+ }+}+```++- [ ] **Step 4: Run** `--filter MvpSliceTests`: PASS. **Mutate:** remove the `turn_lengths` line; `TheMvpPlaysMonthly...` fails (date 1948-05-22). Restore.+- [ ] **Step 5: Commit.**++### Task 2.3: state scaffolding, omit-when-empty hashing++**Files:** Create `sim/Statecraft.Sim/GddState.cs`; modify `GameState.cs` (fields, `Clone`, `CanonicalText`); create `sim/Statecraft.Sim.Tests/GddStateTests.cs`.++**Interfaces:**+- Produces (all public, immutable records with `With...` copies; counts are population units of `people_per_unit` people, D-A1):+ - `City(string id, int housingCapacity, double housingCondition, int jobSlots, int civilians, int employed, int refugees, int recruits)`; `employed` is the share of `civilians` in jobs.+ - `Unit(int id, string type, string home, int q, int r, string order, string target, int turnsLeft)`; `order` is `idle` or a pioneer action; `target` a site id or `""`.+ - `Cohort(int id, string city, string track, int count, int turnsLeft)`; `track` is `recruit` or `halutz`.+ - `SiteState(string state, int unit, int turnsLeft, DateTime? builtOn)`; `state` is `building` or `built`.+ - `GameState` fields: `SortedDictionary<string, City> Cities`, `SortedList<int, Unit> Units`, `List<Cohort> Cohorts`, `int NextId`, `SortedDictionary<string, SiteState> Sites`, `SortedDictionary<string, DateTime> Objectives`, `int Score`, `double? Cohesion`. All `StringComparer.Ordinal`.+ - Hash sections, appended after `over=` only when non-empty or non-default: `city{}`, `units[]`, `cohorts[]`, `next=`, `site{}`, `obj{}`, `score=`, `coh=`.++- [ ] **Step 1: Failing tests:**++```csharp+using System;+using System.Collections.Generic;+using Statecraft.Sim;++public class GddStateTests+{+ // R-LOOP-002+ [Fact]+ public void WithTheSwitchOffTheGoldenSnapshotsAreByteIdentical()+ {+ var c = ContentLoader.Load(RealContentTests.ContentRoot());+ var s = GoldenRun.Play(c, GoldenRun.Until1950);+ Assert.Equal(GoldenSnapshot.Read("hash1950"), s.Describe());+ Assert.DoesNotContain("city{", s.Describe());+ }++ // R-LOOP-002+ [Fact]+ public void EachNewSectionAppearsOnlyWhenSetAndMovesTheHash()+ {+ var s = new GameState();+ var empty = s.Hash();+ var steps = new List<Action<GameState>>+ {+ x => x.Cities["tel_aviv"] = new City("tel_aviv", 10, 0.5, 4, 6, 3, 2, 0),+ x => x.Units.Add(1, new Unit(1, "halutz", "tel_aviv", -3, 19, "idle", "", 0)),+ x => x.Cohorts.Add(new Cohort(2, "tel_aviv", "recruit", 1, 3)),+ x => x.NextId = 3,+ x => x.Sites["site_a"] = new SiteState("building", 1, 4, null),+ x => x.Objectives["first_new_yishuv"] = new DateTime(1949, 3, 15),+ x => x.Score = 5,+ x => x.Cohesion = 0.5,+ };+ var seen = new HashSet<string> { empty };+ foreach (var step in steps) { step(s); Assert.True(seen.Add(s.Hash()), "a new section did not move the hash"); }+ foreach (var label in new[] { "city{", "units[", "cohorts[", "next=", "site{", "obj{", "score=", "coh=" })+ Assert.Contains(label, s.Describe());+ }++ [Fact]+ public void CloneCopiesEveryNewCollection()+ {+ var a = new GameState();+ a.Cities["x"] = new City("x", 1, 0, 1, 1, 0, 0, 0);+ a.Units.Add(1, new Unit(1, "halutz", "x", 0, 0, "idle", "", 0));+ a.Cohorts.Add(new Cohort(1, "x", "recruit", 1, 1));+ a.Sites["s"] = new SiteState("building", 1, 1, null);+ a.Objectives["o"] = new DateTime(1949, 1, 1);+ var b = a.Clone();+ b.Cities["y"] = a.Cities["x"]; b.Units.Add(2, a.Units[1]); b.Cohorts.Clear(); b.Sites.Clear(); b.Objectives.Clear();+ Assert.Single(a.Cities); Assert.Single(a.Units); Assert.Single(a.Cohorts); Assert.Single(a.Sites); Assert.Single(a.Objectives);+ }+}+```++(`GoldenSnapshot.Read(name)` exists or is added in the same step as a one-line reader of `golden/<name>.txt`; check `GoldenSnapshot.cs` first and reuse its path helper.)++- [ ] **Step 2: Run, expect compile failure.**+- [ ] **Step 3: Implement** `GddState.cs` (records as listed; constructor stores fields; each record gets the `With` methods later tasks need: `City.WithCounts(int civilians, int employed, int refugees, int recruits)`, `Unit.WithOrder(string order, string target, int turnsLeft)`, `Cohort.WithTurnsLeft(int)`, `SiteState.WithTurnsLeft(int)`, `SiteState.Built(DateTime on)`). Each record has `string Canonical()` returning invariant text, for example `City`: `$"{Id}={HousingCapacity},{bits(HousingCondition)},{JobSlots},{Civilians},{Employed},{Refugees},{Recruits}"` with the double as its IEEE bits (`BitConverter.DoubleToInt64Bits(v == 0.0 ? 0.0 : v).ToString("X16", CultureInfo.InvariantCulture)`). In `GameState`: the fields with `new SortedDictionary<string, City>(StringComparer.Ordinal)` etc.; `Clone` copies each collection (`new SortedDictionary<...>(Cities, StringComparer.Ordinal)`, `new SortedList<int, Unit>(Units)`, `new List<Cohort>(Cohorts)`, and the two other dictionaries). In `CanonicalText`, after `sb.Append("over=")...`:++```csharp+ // GDD v0.1 sections (spec 2026-10-12 §2.4): written only when set, so the legacy loop's text is unchanged. R-LOOP-002.+ void Section(string name, char open, char close, IEnumerable<string> items)+ {+ Nl(); sb.Append(name).Append(open);+ 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 (Units.Count > 0) Section("units", '[', ']', Units.Values.Select(x => x.Canonical()));+ if (Cohorts.Count > 0) Section("cohorts", '[', ']', Cohorts.Select(x => x.Canonical()));+ if (NextId != 0) { Nl(); sb.Append("next=").Append(NextId.ToString(CultureInfo.InvariantCulture)).Append(';'); }+ if (Sites.Count > 0) Section("site", '{', '}', Sites.Select(kv => kv.Key + "=" + kv.Value.Canonical()));+ if (Objectives.Count > 0) Section("obj", '{', '}', Objectives.Select(kv => kv.Key + "=" + kv.Value.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)));+ if (Score != 0) { Nl(); sb.Append("score=").Append(Score.ToString(CultureInfo.InvariantCulture)).Append(';'); }+ if (Cohesion.HasValue) Num("coh", Cohesion.Value);+```++Note: the `over=` line today has no trailing `;`; the new sections start after it, so the existing text is a prefix of the new one and unchanged when all are empty.++- [ ] **Step 4: Run** `dotnet test sim/Statecraft.sln` (the whole suite: every golden must still pass). **Mutate:** write `city{` unconditionally; `WithTheSwitchOffTheGoldenSnapshotsAreByteIdentical` and the golden tests fail. Restore.+- [ ] **Step 5:** R-LOOP-002 in `docs/rules/mvp.md`: "The GDD state sections are hashed only when set; with the legacy loop the hash text is unchanged." Commit.++### Task 2.4: save schema 2 and the ruleset line++**Files:** Modify `SaveGame.cs`, `GameSession.cs`, `SaveGameTests.cs` (the three `"statecraft-save 1"` assertions that read a written save become 2; the parse tests of v1 text stay).++**Interfaces:**+- Produces: `SaveGame.SchemaVersion = 2`; `SaveGame.Ruleset : string` (v1 saves read as `legacy`); constructor `SaveGame(string contentHash, ulong seed, Mode mode, string ruleset, string initialHash)`; `GameSession.Load` throws `SaveException(0, ...)` when `saved.Ruleset != c.Ruleset`.++- [ ] **Step 1: Failing tests** in `SaveGameTests.cs`:++```csharp+ // R-SAVE-001+ [Fact]+ public void ASaveNamesItsRulesetAndRoundTrips()+ {+ var c = MvpSlice.Load(RealContentTests.ContentRoot());+ var g = GameSession.New(c, 1, Mode.Historical);+ g.Step(HistoricalAI.Commands(c, g.State));+ var text = g.Save.Write();+ Assert.StartsWith("statecraft-save 2\n", text);+ Assert.Contains("\nruleset gdd-0.1\n", text);+ Assert.Equal("gdd-0.1", SaveGame.Parse(text).Ruleset);+ Assert.Equal(g.State.Hash(), GameSession.Load(c, text, out _).State.Hash());+ }++ // R-SAVE-001+ [Fact]+ public void AVersionOneSaveReadsAsLegacyAndAGddGameRefusesIt()+ {+ var legacy = ContentLoader.Load(RealContentTests.ContentRoot());+ var g = GameSession.New(legacy, 1, Mode.Historical);+ g.Step(new Command[0]);+ var v1 = g.Save.Write().Replace("statecraft-save 2\n", "statecraft-save 1\n").Replace("ruleset legacy\n", "");+ Assert.Equal("legacy", SaveGame.Parse(v1).Ruleset);+ Assert.Equal(g.State.Hash(), GameSession.Load(legacy, v1, out _).State.Hash()); // before cutover a v1 save still loads+ var gdd = MvpSlice.Load(RealContentTests.ContentRoot());+ var ex = Assert.Throws<SaveException>(() => GameSession.Load(gdd, v1, out _));+ Assert.Contains("made with an earlier version of the game's rules; start a new game", ex.Message);+ }++ [Fact]+ public void ALegacyGameRefusesAGddSave()+ {+ var gdd = MvpSlice.Load(RealContentTests.ContentRoot());+ var text = GameSession.New(gdd, 1, Mode.Historical).Save.Write();+ var ex = Assert.Throws<SaveException>(() => GameSession.Load(ContentLoader.Load(RealContentTests.ContentRoot()), text, out _));+ Assert.Contains("made with another version of the game's rules", ex.Message);+ }++ [Theory]+ [InlineData("ruleset chess")]+ [InlineData("ruleset")]+ public void ABadRulesetLineIsRefused(string line) { /* build a v2 save with that line in place of the ruleset line; Assert SaveException on line 5 */ }+```++For the last test, write the body: build the text `"statecraft-save 2\ncontent " + Hex64('a') + "\nseed 1\nmode Historical\n" + line + "\nturn\nend " + Hex64('b') + "\n"` and assert `Assert.Equal(5, Assert.Throws<SaveException>(() => SaveGame.Parse(text)).Line)`.++- [ ] **Step 2: Run, expect failures.**+- [ ] **Step 3: Implement.** In `SaveGame`: `SchemaVersion = 2`; field `public string Ruleset { get; }`; `Write` appends `ruleset <Ruleset>` after `mode`; `Parse`: `if (version < 1)` unchanged; for `version >= 2` read `Head(4, "ruleset", 2)` and require `legacy` or `gdd-0.1`, and start the command loop at line index 5; for version 1 the ruleset is `legacy` and the loop starts at 4; the minimum line count is 6 for v2. Update the header doc comment (`ruleset legacy|gdd-0.1` line). `GameSession.New` passes `c.Ruleset`. `GameSession.Load`, right after `Parse`:++```csharp+ if (saved.Ruleset != c.Ruleset)+ throw new SaveException(0, saved.Ruleset == "legacy"+ ? "This save was made with an earlier version of the game's rules; start a new game."+ : "This save was made with another version of the game's rules; start a new game.");+```++- [ ] **Step 4: Run** `--filter SaveGameTests`, then the whole suite. **Mutate:** remove the ruleset check; the two refusal tests fail. Restore.+- [ ] **Step 5:** R-SAVE-001 in `docs/rules/mvp.md` ("A save names its ruleset; a game refuses a save made under another ruleset. A schema 1 save is legacy."). Commit.++### Task 2.5: the command touch-point guard, and the `mvp-slice` golden++**Files:** Create `sim/Statecraft.Sim.Tests/CommandGuardTests.cs`, `sim/Statecraft.Sim.Tests/MvpGolden.cs`, `sim/Statecraft.Sim.Tests/MvpGoldenTests.cs`, `sim/Statecraft.Sim.Tests/golden/mvp-slice.txt` (written by the update run); modify `GoldenManifestTests.TheManifestHoldsExactlyTheKnownGoldens` (add `mvp-slice`), `golden/manifest.txt`, `docs/determinism.md` (a "MVP goldens" paragraph), `CHANGELOG.md`, `docs/gdd/loop-switch.md`.++**Interfaces:**+- Produces: `CommandGuardTests.Samples : Dictionary<Type, Command>` (one instance per concrete `Command` type; later PRs add theirs); `MvpGolden.Until = new DateTime(1949, 1, 15)` (PLACEHOLDER: the slice golden's end, eight monthly turns; moved later as the slice grows) and `MvpGolden.Play(Content c, Func<Content, GameState, IReadOnlyList<Command>> player) : GameState`.++- [ ] **Step 1: Tests.** `CommandGuardTests`:++```csharp+using System;+using System.Collections.Generic;+using System.Linq;+using Statecraft.Sim;++/// <summary>Every command kind has its five touch-points (spec 2026-10-12 §2.3): an Attention kind and cost, CommandText,+/// the save format, the scenario runner, and (in Unity, SimBridgeGuardTests) the order queue.</summary>+public class CommandGuardTests+{+ public static readonly Dictionary<Type, Command> Samples = new Dictionary<Type, Command>+ {+ [typeof(SetPolicy)] = new SetPolicy("rationing", 0.5),+ [typeof(AllocateBudget)] = new AllocateBudget(new Dictionary<string, double> { ["finance_minister"] = 1.0 }),+ [typeof(ChooseEventOption)] = new ChooseEventOption("e", "o"),+ [typeof(SetMobilization)] = new SetMobilization(0.5),+ [typeof(SecurityOrder)] = new SecurityOrder(1),+ [typeof(Appoint)] = new Appoint("prime_minister", "p"),+ [typeof(MapAction)] = new MapAction("housing", 1, 2),+ };++ static IEnumerable<Type> CommandTypes() => typeof(Command).Assembly.GetTypes().Where(t => t.IsSubclassOf(typeof(Command)) && !t.IsAbstract);++ [Fact]+ public void EveryCommandTypeHasASample() =>+ Assert.Empty(CommandTypes().Where(t => !Samples.ContainsKey(t)).Select(t => t.Name));++ [Fact]+ public void EveryCommandHasAnAttentionKindAndACostInTheRealRules()+ {+ var c = ContentLoader.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);+ }+ }++ [Fact]+ public void EveryCommandPassesCommandTextAndRoundTripsThroughASave()+ {+ foreach (var cmd in Samples.Values)+ {+ Simulation.Step(ContentLoader.Load(Fixture.Write()), new GameState { Date = new DateTime(1948, 5, 15) }, new[] { cmd }); // throws on an unknown type+ Assert.Equal(SaveRoundTrip.Line(cmd), SaveRoundTrip.Line(SaveRoundTrip.Parse(SaveRoundTrip.Line(cmd))));+ }+ }++ [Fact]+ public void TheScenarioRunnerKnowsEveryKind() =>+ Assert.Empty(Samples.Values.Select(c => c.Kind).Where(k => !Scenario.Kinds.Contains(k)));+}+```++`SaveRoundTrip` needs the save's line format from outside the assembly: make `SaveGame.Format(Command)` and `SaveGame.ParseCommand(int, string)` `internal` and add `[assembly: InternalsVisibleTo("Statecraft.Sim.Tests")]` if not already present (check `sim/Statecraft.Sim/` for an existing `InternalsVisibleTo`; `GameState.Describe` is public, so this is the only new internal access). Then `SaveRoundTrip.Line(cmd) => SaveGame.Format(cmd)` and `Parse(line) => SaveGame.ParseCommand(0, line)`. `Scenario.Kinds` is the `allowed` dictionary's keys, made a `public static readonly IReadOnlyCollection<string>` (move the dictionary to a static field).++`MvpGolden.cs`:++```csharp+using System;+using System.Collections.Generic;+using Statecraft.Sim;++/// <summary>The GDD slice's golden (spec 2026-10-12 §3): the overlay content, the golden seed, Historical mode, a reference+/// player (D-A7: test code with a stated policy, not "history"), monthly turns until Until.</summary>+public static class MvpGolden+{+ public static readonly DateTime Until = new DateTime(1949, 1, 15); // PLACEHOLDER: grows with the slice; mvp-end at cutover++ public static GameState Play(Content c, Func<Content, GameState, IReadOnlyList<Command>> player)+ {+ 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, player(c, s)).State;+ return s;+ }+}+```++`MvpGoldenTests.TheSliceMatchesItsGolden`: `var s = MvpGolden.Play(MvpSlice.Load(RealContentTests.ContentRoot()), HistoricalAI.Commands); GoldenSnapshot.Check("mvp-slice", s, GoldenManifest.UpdateRequested ? GoldenManifest.Read().GetValueOrDefault("mvp-slice", "") : GoldenManifest.Expected("mvp-slice"));` plus `Assert.Equal(new DateTime(1949, 1, 15), s.Date)`.++- [ ] **Step 2: Run, expect failures** (no `mvp-slice` line; `Scenario.Kinds` missing).+- [ ] **Step 3:** make the members above accessible, then `STATECRAFT_UPDATE_GOLDEN=1 dotnet test sim/Statecraft.sln --filter MvpGoldenTests`, then a plain full run. Check that `hash1950`, `hash1952`, `smoke5` and the two scenarios are unchanged in `golden/manifest.txt` (`git diff` shows one added line only).+- [ ] **Step 4: Mutate:** remove `MapAction` from `Samples`; `EveryCommandTypeHasASample` fails. Restore.+- [ ] **Step 5: Docs.** determinism.md: under "Scenario goldens" add "**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 §2.1) with the reference player until `MvpGolden.Until`. It moves with each Phase 1 PR that adds a GDD rule; that PR re-pins it and says why. The legacy goldens never move for it." `docs/gdd/loop-switch.md` (template: R-LOOP-001, R-LOOP-002, R-SAVE-001). CHANGELOG: "- The GDD v0.1 loop switch (`systems.loop` in eras.yaml, default `legacy`), its state sections (hashed only when set) and save schema 2 with a `ruleset` line: a game refuses a save made under another ruleset. The real game is unchanged and the goldens do not move."+- [ ] **Step 6: Full checks; Unity EditMode** (the DLL now writes schema 2 saves; `SimSmokeTests` and the save tests in Unity must pass); WebGL `web_check` golden&smoke=5. Revert Unity churn. Commit, open the PR, stop and report.++---++## PR 3: one city++Issue (Task form): "GDD Phase 1: one city (Tel Aviv): housing, jobs, refugees, Money from jobs, Social cohesion". Sign-off: placeholders, the provisional D-A5 and D-A6 defaults, the `mvp-slice` move.++### Task 3.1: content: `cities.yaml`, `unit_types.yaml`, the `mvp:` rules block++**Files:** Create `content/cities.yaml`, `content/unit_types.yaml`; modify `content/rules.yaml` (an `mvp:` block and the new `attention_cost` kinds), `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`.++`content/cities.yaml`:++```yaml+# GDD v0.1 cities (docs/GDD.md "Cities and construction"; spec 2026-10-12 §2.2). Phase 1 has one city, Tel Aviv (owner+# decision D-A4). Counts are population units of rules.yaml mvp.people_per_unit people (D-A1). These are design values,+# not historical figures, until the owner sets them; none is a claim about Tel Aviv in 1948.+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, provisional)+```++`content/unit_types.yaml` (population types only, spec §6):++```yaml+# GDD v0.1 population types (docs/GDD.md "Population and units"). Phase 1: civilians and refugees are counts per city+# (owner decision D-A2). Training types arrive in PR 4.+types:+ - { id: civilian, kind: population }+ - { id: refugee, kind: population }+```++`rules.yaml` additions:++```yaml+# ---- GDD v0.1 MVP (docs/rules/mvp.md). Read only when eras.yaml systems.loop is gdd. ----+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)+ 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`.++- [ ] 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.++### Task 3.2: `AssignWorkers` (R-CITY-001)++**Files:** Commands.cs, AttentionSystem.cs (`assign_workers`), Simulation.cs (`Execute`), SaveGame.cs (`work CITY ROLE N`), Scenario.cs (`assign_workers: city, role, n`), create `Cities.cs`, `CitiesTests.cs`; `CommandGuardTests.Samples` gains `new AssignWorkers("tel_aviv", "job", 1)`.++**Interfaces:**+- Produces: `AssignWorkers(string city, string role, int count)`, `Kind = "assign_workers"`; `Cities.Assign(Content c, GameState s, string city, string role, int count, List<Cause> why) : string?`; `Cities.Init(Content c, GameState s)` (fills `s.Cities` from `cities.yaml` when `c.IsGdd`; called by `NewGame`).++```csharp+ /// <summary>R-CITY-001: sets the number of the city's civilians in jobs (a standing order). Refused, state untouched, when the+ /// loop is legacy, the city or role is unknown, or the count is negative, above the job slots or above the civilians.</summary>+ public static string? Assign(Content c, GameState s, string city, string role, int count, List<Cause> why)+ {+ if (!c.IsGdd) return "That order is not available in this game";+ 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+ 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);+ why.Add(new Cause("city", city, count - x.Employed, FormattableString.Invariant($"{PlayerText.Settlement(c, city)}: {count} groups in work")));+ return null;+ }+```++(`PlayerText.Settlement` is added if it does not exist: the settlement's display name from `settlements_1948.yaml`. The sim reads only ids from that file today, so add the name to `ReadSettlementIds` as a `(id, name)` pair and store `Content.SettlementNames`; the player never sees an id, CONTRIBUTING rule 4.)++Tests (`CitiesTests`, on `MvpSlice.Load` and on the fixture with `systems: { loop: gdd }` plus `cities.yaml`): `AssigningWorkersSetsEmployed`, `[Theory] TheLimitsAreRefusedAndChangeNothing` (−1, slots+1, civilians+1, unknown city, role `craftsman`), `TheLegacyLoopRefusesTheOrderAndRefundsAttention` (real content: the rejection reason and `Attention` equal before and after), `AnAssignOrderSurvivesASave`. Mutation: drop the job-slot check; its row fails.++### Task 3.3: arrivals, housing, production, cohesion in `TurnResolver` (R-CITY-002 to R-CITY-005)++**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, provisional, spec §2.3 steps kept for Phase 1): training (PR 4), construction (PR 5), production, arrivals, housing, cohesion, objectives (PR 6). `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, provisional): `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)`.++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.++### 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`.++```csharp+/// <summary>The reference player for the GDD goldens (D-A7, provisional): 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>+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);+ var cost = AttentionSystem.Cost(c, s, "assign_workers");+ if (want != city.Employed && cost <= left + 1e-9) { list.Add(new AssignWorkers(city.Id, "job", want)); left -= cost; }+ }+ return list;+ }+}+```++`mvp-absorb-first.yaml`: `content: mvp`, `until: 1949-06-15`, steps that assign workers each time refugees are housed (dates chosen from the run, written after a dry run prints the city counts). It must end elsewhere than the bare run (existing `ScenarioTests` check).++- [ ] Steps per task as in PR 2 (failing test, run, implement, run, mutate, commit). Then: `docs/rules/mvp.md` R-CITY-001 to R-CITY-005; `docs/gdd/one-city.md`; CHANGELOG; full checks; legacy goldens unchanged; `mvp-slice` moved (the PR says why: the city rules now run in the slice); WebGL `web_check`. Unity EditMode: run it, because the DLL gains a command that the Unity queue's default branch refuses (PR 7 adds it properly). Open, stop, report.++---++## PR 4: training++Issue: "GDD Phase 1: training in a military camp and a Hakhshara". Sign-off: placeholders, D-D5 provisional.++### Task 4.1: content++`unit_types.yaml` gains:++```yaml+ - id: recruit # civilian to recruit, through basic training (GDD "Progression")+ kind: population # a count until Phase 5 (spec §6 item 4)+ facility: military_camp+ training_turns: 3 # PLACEHOLDER: owner sets+ training_cost: 0.5 # PLACEHOLDER: owner sets (IL millions per group)+ - id: halutz # civilian to Halutz, through pioneer training in a Hakhshara (GDD "Progression")+ kind: unit # a movable unit (D-A2)+ facility: hakhshara+ training_turns: 4 # PLACEHOLDER: owner sets+ training_cost: 0.5 # PLACEHOLDER: owner sets (IL millions per group)+```++`cities.yaml` `tel_aviv.facilities: [military_camp, hakhshara]` with `# PLACEHOLDER: owner sets (D-D5: one of each exists at start; a design assumption, not a claim about 1948)`. `attention_cost`: `train: 1`, `cancel_training: 0.5`, both `# PLACEHOLDER: owner sets`. Validation: a type with `facility` needs `training_turns ≥ 1` and `training_cost ≥ 0`; facility known.++### Task 4.2: `Train` and `CancelTraining` (R-TRAIN-001, R-TRAIN-002)++**Interfaces:**+- Produces: `Train(string city, string track, int count)` (`train CITY TRACK N` in saves); `CancelTraining(int cohort)` (`untrain ID`); `Training.Start(c, s, city, track, count, why) : string?`; `Training.Cancel(c, s, cohort, why) : string?`.++R-TRAIN-001: `Train` takes `count ≥ 1` unemployed civilians (`civilians − employed`) of a city that has the track's facility, pays `count × training_cost` from the Treasury (refused if the Treasury is short; no borrowing for training: flag in the PR as a choice for the owner), and opens a cohort with `turnsLeft = training_turns`, id `s.NextId++`.+R-TRAIN-002: `CancelTraining` returns the cohort's people to the city's civilians and refunds nothing (D-A3).++Tests: start, the limits (no facility, more than the unemployed, `count 0`, unknown track, Treasury short), cancel returns people and not money, cancelling an unknown or finished cohort is refused, save round-trip, legacy refusal. Mutation: refund the money on cancel; `CancellingReturnsPeopleNotMoney` fails.++### Task 4.3: progress in the resolver (R-TRAIN-003)++Training runs first in `TurnResolver`. Each cohort's `turnsLeft` falls by 1 a turn; at 0 the cohort ends: `recruit` adds `count` to the city's `recruits`; `halutz` adds `count` units `Unit(id = s.NextId++, "halutz", city, q, r of the city's settlement hex, "idle", "", 0)` in cohort order. Cohorts are processed in list order (ascending id).++Tests: a recruit cohort of 3 groups completes after exactly `training_turns` steps; halutz cohort creates units with consecutive ids at Tel Aviv's hex (−3, 19); trained people are not counted as civilians while training (cohesion uses civilians). Reference player: after filling jobs, trains 1 halutz group when it has none and none in training (stated policy). Re-pin `mvp-slice`. Docs, CHANGELOG, checks, Unity EditMode, web_check, PR, stop.++---++## PR 5: one designated site and "build yishuv"++### Task 5.0: choose and source the site (before any code)++Criteria (D-A4, CONTENT_POLICY):+1. A Jewish settlement founded between 15 May 1948 and 31 December 1951 (a kibbutz, moshav or development town), inside the 1949 armistice lines, on a land hex of `content/map/hexes.json` that owns no 1948 settlement.+2. A founding date to the day from two independent sources (for example the Hebrew or English Wikipedia article and a municipal, JNF, kibbutz-movement or Knesset/Ministry page), each with a checked date. Where sources disagree, use the rule of CONTENT_POLICY §1 and say so in a comment.+3. A photograph of the founding or of the place in 1949–51 that is CC BY 4.0 from the Meitar Collection (or PD/CC0 with a valid US basis), read through the Commons API (licence, artist, SHA-1). Never GPO, PD-Israel-only or share-alike.+4. Not built on the site of a depopulated Arab locality unless the card can state that factually from mainstream Israeli sources and the owner has seen it (D-F1 sensitivity; prefer a site where the question does not arise).++Search: issues #27 and #97 and their comments, `research_notes/`, then Commons categories of Meitar Collection photographers (Benno Rothenberg, Boris Carmi, Moshe Marlin Levin) for 1949–1951 settlement foundings. Record the candidates with links in the PR 5 issue. **If no candidate meets all four, stop and report the candidates and what each lacks; do not pick one.** The research brief contains no owner email or other identifier in any request.++### Task 5.1: `sites.yaml` and validation++```yaml+# GDD v0.1 designated sites (docs/GDD.md "Pioneer work": building only at designated spots; a new yishuv takes its+# site's name). Phase 1 has one site (owner decision D-A4). Name, place and date are historical and sourced.+sites:+ - id: <site_id>+ name: <English name>+ name_he: <Hebrew name>+ q: <q>+ r: <r>+ kinds: [yishuv]+ founded: <yyyy-mm-dd> # the historical founding date: the objective card's reference date+ sources:+ - { url: <url 1>, checked: 2026-10-<dd> }+ - { url: <url 2>, checked: 2026-10-<dd> }+ status: fact-checked+```++(The values come from Task 5.0; nothing is written until it passes.) `rules.yaml` `mvp:` gains `build_yishuv_turns: 6` and `build_yishuv_cost: 2` (`# PLACEHOLDER: owner sets`). Validation tests: id unique; hex is land; hex owns no 1948 settlement; kinds ⊆ {yishuv}; `founded` required and inside 1948-05-15..1951-12-31; sources non-empty with checked dates; status known.++### Task 5.2: `PioneerWork` and `StopWork` (R-SITE-001 to R-SITE-003)++**Interfaces:** `PioneerWork(int unit, string action, string site)` (`pioneer ID ACTION SITE`); `StopWork(int unit)` (`stop ID`); `Projects.Start`, `Projects.Stop`, `Projects.Advance(c, s, next, why)`.++- R-SITE-001: a halutz unit that is idle may start `build_yishuv` at a site of kind `yishuv` that is neither building nor built; it pays `build_yishuv_cost` (refused if short); the site becomes `building` with `turnsLeft = build_yishuv_turns`; the unit's order becomes `build_yishuv` at that site. One project per unit and one unit per site (D-D6, provisional). The unit is committed without moving (movement is Phase 5); the PR states this.+- R-SITE-002: `StopWork` sets the unit idle and the site back to available; progress and Money are lost (D-A3).+- R-SITE-003: each turn a building site's `turnsLeft` falls by 1; at 0 the site is `built` on the turn's end date, and the unit becomes idle.++Tests: start, every refusal (not a halutz, busy unit, unknown site, site building or built, short Treasury, legacy), stop, completion on the exact turn with `builtOn` equal to the turn's end date, save round-trip. Reference player: sends its idle halutz to the first available site. Re-pin `mvp-slice` (extend `MvpGolden.Until` if the build does not complete inside it, and say so). Docs, CHANGELOG, checks, Unity, web_check, PR (Refs #27), stop.++---++## PR 6: the objective card and the score++### Task 6.1: `objectives.yaml` and the card event++```yaml+# GDD v0.1 objectives (docs/GDD.md "Historical events on objective completion"). Phase 1: the first new yishuv (D-A4).+objectives:+ - id: first_new_yishuv+ completes_when: { site_built: <site_id> }+ reference_date: <the site's founded date> # must equal sites.yaml founded (the loader checks)+ card: first_new_yishuv # content/events/first_new_yishuv.yaml+ points: 100 # PLACEHOLDER: owner sets (D-B6)+ bonus_per_month_early: 10 # PLACEHOLDER: owner sets (D-B2)+ bonus_cap: 120 # PLACEHOLDER: owner sets (D-B2)+```++`content/events/first_new_yishuv.yaml`: `objective: first_new_yishuv`, `anchor: soft`, a window from 1948-05-15 to 1957-01-01, one option (`id: continue`, `historical: true`, no effects), a title naming the place, text of two or three sourced sentences in the house tone (what was founded, by whom, on what date, from the Task 5.0 sources; no quotes), tags `[]`, `sources` and `status: fact-checked`. The English says "War of Independence" if the war is named (D-E3). `content/schema/event.schema.json` gains `objective` (string). The loader checks the event's `objective` names an objective whose `card` is this event, and that an objective's `card` event has exactly one option.++### Task 6.2: completion and score (R-OBJ-001, R-OBJ-002)++- R-OBJ-001: in the resolver's last step, an objective whose condition holds and that is not yet in `s.Objectives` is recorded with the turn's end date.+- R-OBJ-002: it adds `points + min(bonus_cap, bonus_per_month_early × monthsEarly)` to `Score`, where `monthsEarly = max(0, whole months from the completion date to the reference date)`, whole months counted as `(y2 − y1) × 12 + (m2 − m1) − (d2 < d1 ? 1 : 0)`. Provisional formula (D-B2 recommendation, not yet approved); the PR says so.++`Objectives.MonthsEarly(DateTime done, DateTime reference) : int` is public, so the card can show it (spec §2.6). Tests: the formula at the edges (same day: 0; one day early: 0; one month early to the day: 1; the cap); completion records once and scores once.++### Task 6.3: the card fires once, the turn after completion (R-OBJ-003)++`GameEvent.Objective : string` (default `""`). In `EventSystem.Trigger`, add `.Where(e => e.Objective == "" || s.Objectives.ContainsKey(e.Objective))`. Under the legacy loop no objective is ever recorded, so the event never fires and the legacy goldens hold. Tests: Review focus 5 (not before completion, exactly once, never in legacy); the existing event-rule tests still pass with the new key. Re-pin `mvp-slice`. Docs (`docs/gdd/objective-card.md`, R-OBJ-001 to R-OBJ-003), CHANGELOG, `docs/WRITING_EVENTS.md` (the `objective` key), checks, Unity, web_check, PR, stop.++---++## PR 7: Unity core (bridge, dev flag, score, card photograph)++- `SimBridge.Key`: `AssignWorkers` → `"work:" + city`, `Train` → `"train:" + city + ":" + track`, `CancelTraining` → `"untrain:" + id`, `PioneerWork`/`StopWork` → `"unit:" + id`. `SimBridge.Validate`: ids checked against `Content.Cities`, `Content.UnitTypes`, `Content.Sites`, `State.Units`, `State.Cohorts`.+- `SimBridgeGuardTests` (EditMode): every concrete `Command` type in the sim assembly has a `Validate` branch other than the default `order.invalid` (reflection over sample instances, mirroring `CommandGuardTests.Samples`).+- `?mvp=1` URL flag (`UrlFlags`, `GameBoot`): load content through `MvpSlice.Overlay(readFile)` for the controller's playtests. Default off; the golden and smoke flags ignore it.+- HUD: the score (`HudModel.Score`, shown only when `Content.IsGdd`) and Social cohesion as a 0–100% bar.+- Event card: for an objective card, a line under the body "Completed on {date}; historically {date}; {n} months early" from `Objectives.MonthsEarly` and `PlayerText.Date`. The photograph: the Task 5.0 picture as `unity/Assets/UI/EventImages/first_new_yishuv.jpg` through `tools/event_images.py`, its `event-images.yaml` row, `ASSETS.yaml` (`status: owner-verify`), `NOTICE`, `EventImageImport.Run`.+- `strings.en.yaml`: every new label. EditMode tests for each element; WebGL build with `?mvp=1` checked by hand and `golden&smoke=5` unchanged.++## PR 8: Unity city panel and site++- `InfoPanelPresenter`: on a city hex (GDD loop), housing used/capacity, condition, jobs filled/slots, refugees waiting, recruits, training cohorts with turns left; buttons Assign (stepper), Train recruit, Train halutz, Cancel. Every number from the sim (`State.Cities`, `Content.UnitTypes`).+- On the site hex: the site's name, and Build with the halutz units that can start it, their cost and turns from the sim rules; Stop while building.+- `SiteLayer` (new, map): a built site draws a rural kit and its name label at its hex; a building site draws a scaffold marker.+- EditMode tests for the panel states and the layer; screenshots in the PR; WebGL `?mvp=1` playthrough to the card.++---++## Self-review notes++- Spec §6 Phase 1 items 1–7 map to PRs 1, 2, 3, 4, 5, 6 and 7–8. The tests listed in §6 (one test per rule with its R- ID, save round-trip of every new command, clone independence, omit-at-default, unchanged legacy goldens, `mvp-slice`, `scenario-mvp-absorb-first`, Unity EditMode) are in Tasks 2.3, 2.4, 2.5, 3.2–3.4 and each command task.+- Names used across tasks: `Content.IsGdd`, `Content.Ruleset`, `MvpSlice.Load`, `MvpGolden.Play`, `ReferencePlayer.Commands`, `CommandGuardTests.Samples`, `TurnResolver.Resolve`, `City.WithCounts`, `s.NextId`.+- Values written as `<...>` in Tasks 5.1 and 6.1 are research outputs of Task 5.0, not placeholders to invent; the task stops if research fails.diff --git a/sim/Statecraft.Sim.Tests/EconomyCalibrationTests.cs b/sim/Statecraft.Sim.Tests/EconomyCalibrationTests.csindex 23f164a1f..9b8d605a2 100644--- a/sim/Statecraft.Sim.Tests/EconomyCalibrationTests.cs+++ b/sim/Statecraft.Sim.Tests/EconomyCalibrationTests.cs@@ -116,7 +116,7 @@ public class EconomyCalibrationTests{var (a, b) = (History[i - 1], History[i]);if (a.Date < new DateTime(1950, 1, 1) || a.Date >= new DateTime(1952, 1, 1)) continue;- var yf = SimTime.YearFraction(SecuritySystem.TurnLengthFor(a.Rung));+ var yf = SimTime.YearFraction(SecuritySystem.TurnLengthFor(C, a.Date, a.Rung));var trade = C.Rules.ExportsPerYear * yf - C.Rules.ImportsPerCapitaPerYear * a.TotalPopulation * yf;inflow += (b.FxReserves - a.FxReserves) - trade; // everything that reached the reserves except trade}diff --git a/sim/Statecraft.Sim.Tests/TurnLengthsTests.cs b/sim/Statecraft.Sim.Tests/TurnLengthsTests.csnew file mode 100644index 000000000..2c6a4cf33--- /dev/null+++ b/sim/Statecraft.Sim.Tests/TurnLengthsTests.cs@@ -0,0 +1,120 @@+using System;+using System.Collections.Generic;+using System.IO;+using Statecraft.Sim;++/// <summary>turn_lengths (GDD v0.1 Phase 1, refs #81): the turn length on each security rung is data, read in the era the+/// turn starts in. The default is the legacy table, so the goldens do not move.</summary>+public class TurnLengthsTests+{+ static Content Load(string extraRules) => ContentLoader.Load(Fixture.Write(new Dictionary<string, string>+ { ["rules.yaml"] = Fixture.Files["rules.yaml"] + extraRules }));++ // R-TURN-001+ [Theory]+ [InlineData(1, TurnLength.Quarter)] [InlineData(2, TurnLength.Quarter)] [InlineData(3, TurnLength.Quarter)]+ [InlineData(4, TurnLength.Month)] [InlineData(5, TurnLength.Week)]+ public void TheDefaultReproducesTheLegacyTable(int rung, TurnLength expected)+ {+ var c = ContentLoader.Load(RealContentTests.ContentRoot());+ Assert.Equal(expected, SecuritySystem.TurnLengthFor(c, c.Rules.Start, rung));+ Assert.Equal(SecuritySystem.TurnLengthFor(rung), SecuritySystem.TurnLengthFor(c, c.Rules.Start, rung));+ }++ // R-TURN-001+ [Fact]+ public void AllMonthsGivesMonthlyTurnsOnTheFifteenth()+ {+ var c = Load("turn_lengths: [month, month, month, month, month]\n");+ var s = Simulation.NewGame(c, 1, Mode.Historical);+ Assert.Equal(5, s.Rung); // the fixture starts at full war: weekly turns in the default table+ var dates = new List<DateTime>();+ for (int i = 0; i < 3; i++) { s = Simulation.Step(c, s, new Command[0]).State; dates.Add(s.Date); }+ Assert.Equal(new[] { new DateTime(1948, 6, 15), new DateTime(1948, 7, 15), new DateTime(1948, 8, 15) }, dates);+ }++ // R-TURN-001+ [Fact]+ public void AnEraOverrideChangesTheTableFromItsFirstDay()+ {+ var dir = Fixture.Write(new Dictionary<string, string> { ["eras.yaml"] = @"+eras:+ - id: founding+ name: The Founding+ from: 1948-05-15+ to: 1948-07-01+ - id: later+ name: A Later Chapter+ from: 1948-07-01+ to: 1957-01-01+" });+ Directory.CreateDirectory(Path.Combine(dir, "rules"));+ File.WriteAllText(Path.Combine(dir, "rules", "later.yaml"), "turn_lengths: [month, month, month, month, month]\n");+ var c = ContentLoader.Load(dir);+ Assert.Equal(TurnLength.Week, SecuritySystem.TurnLengthFor(c, new DateTime(1948, 6, 30), 5));+ Assert.Equal(TurnLength.Month, SecuritySystem.TurnLengthFor(c, new DateTime(1948, 7, 1), 5));+ Assert.Equal(TurnLength.Quarter, SecuritySystem.TurnLengthFor(c, new DateTime(1948, 6, 30), 1));+ }++ // R-TURN-001+ [Fact]+ public void ARunReadsTheTableOfTheEraTheTurnStartsIn()+ {+ var dir = Fixture.Write(new Dictionary<string, string> { ["eras.yaml"] = @"+eras:+ - id: founding+ name: The Founding+ from: 1948-05-15+ to: 1948-07-01+ - id: later+ name: A Later Chapter+ from: 1948-07-01+ to: 1957-01-01+" });+ Directory.CreateDirectory(Path.Combine(dir, "rules"));+ File.WriteAllText(Path.Combine(dir, "rules", "later.yaml"), "turn_lengths: [month, month, month, month, month]\n");+ var c = ContentLoader.Load(dir);+ var s = Simulation.NewGame(c, 1, Mode.Historical);+ while (s.Date < new DateTime(1948, 7, 1)) s = Simulation.Step(c, s, new Command[0]).State;+ Assert.Equal(new DateTime(1948, 7, 1), s.Date); // the founding era's turns end on the boundary+ s = Simulation.Step(c, s, new Command[0]).State;+ Assert.Equal(new DateTime(1948, 8, 1), s.Date); // the first turn in the later era is a month+ }++ [Theory]+ [InlineData("turn_lengths: [month, month, month, month]\n", "turn_lengths", "needs exactly 5 values (rungs 1-5)")]+ [InlineData("turn_lengths: [month, month, fortnight, month, month]\n", "turn_lengths[2]", "must be quarter, month or week")]+ [InlineData("turn_lengths: [month, month, Month, month, month]\n", "turn_lengths[2]", "must be quarter, month or week")]+ public void ABadTableFailsNamingTheField(string rules, string field, string message)+ {+ var ex = Assert.Throws<ContentException>(() => Load(rules));+ Assert.Equal("rules.yaml", ex.File);+ Assert.Equal(field, ex.Field);+ Assert.Contains(message, ex.Message);+ }++ [Fact]+ public void ABadTableInAnEraOverrideFailsNamingTheEraFile()+ {+ var dir = Fixture.Write(new Dictionary<string, string> { ["eras.yaml"] = @"+eras:+ - id: founding+ name: The Founding+ from: 1948-05-15+ to: 1948-07-01+ - id: later+ name: A Later Chapter+ from: 1948-07-01+ to: 1957-01-01+" });+ Directory.CreateDirectory(Path.Combine(dir, "rules"));+ File.WriteAllText(Path.Combine(dir, "rules", "later.yaml"), "turn_lengths: [month]\n");+ var ex = Assert.Throws<ContentException>(() => ContentLoader.Load(dir));+ Assert.Equal("rules/later.yaml", ex.File);+ Assert.Equal("turn_lengths", ex.Field);+ }++ [Fact]+ public void ParseLengthRefusesAnUnknownName() =>+ Assert.Throws<ArgumentException>(() => SimTime.ParseLength("Month")); // names are lowercase, as in YAML+}diff --git a/sim/Statecraft.Sim/Content.cs b/sim/Statecraft.Sim/Content.csindex 17bdef307..97a060edb 100644--- a/sim/Statecraft.Sim/Content.cs+++ b/sim/Statecraft.Sim/Content.cs@@ -266,6 +266,10 @@ namespace Statecraft.Simpublic Dictionary<string, double> AttentionCost { get; set; } = new Dictionary<string, double>();public double RungAttentionStep { get; set; }public int CeasefireWeeks { get; set; }+ /// <summary>The turn length on each security rung, rungs 1 to 5: quarter, month or week. The default is the legacy+ /// table; the GDD v0.1 cutover sets all five to month (spec 2026-10-12 section 3). Read through+ /// SecuritySystem.TurnLengthFor(c, date, rung). R-TURN-001.</summary>+ public List<string> TurnLengths { get; set; } = new List<string> { "quarter", "quarter", "quarter", "month", "week" };public List<double> RungMinMobilization { get; set; } = new List<double>();public double TreasuryStart { get; set; }public double FxStart { get; set; }diff --git a/sim/Statecraft.Sim/ContentLoader.cs b/sim/Statecraft.Sim/ContentLoader.csindex 1de345277..3241d75d7 100644--- a/sim/Statecraft.Sim/ContentLoader.cs+++ b/sim/Statecraft.Sim/ContentLoader.cs@@ -371,6 +371,10 @@ namespace Statecraft.Simif (i > 0 && r.RungMinMobilization[i] < r.RungMinMobilization[i - 1])throw new ContentException(file, field, "must not be below the previous rung's floor");}+ if (r.TurnLengths.Count != 5) throw new ContentException(file, "turn_lengths", "needs exactly 5 values (rungs 1-5)");+ for (int i = 0; i < 5; i++)+ if (!SimTime.LengthNames.Contains(r.TurnLengths[i]))+ throw new ContentException(file, FormattableString.Invariant($"turn_lengths[{i}]"), "must be quarter, month or week");if (r.StartRung < 1 || r.StartRung > 5) throw new ContentException(file, "start_rung", "must be 1-5");if (r.CeasefireWeeks <= 0) throw new ContentException(file, "ceasefire_weeks", "must be > 0");foreach (var (key, v) in new[] { ("treasury_start", r.TreasuryStart), ("fx_start", r.FxStart), ("tax_per_capita_per_year", r.TaxPerCapitaPerYear),diff --git a/sim/Statecraft.Sim/SecuritySystem.cs b/sim/Statecraft.Sim/SecuritySystem.csindex 64a955762..2d896b935 100644--- a/sim/Statecraft.Sim/SecuritySystem.cs+++ b/sim/Statecraft.Sim/SecuritySystem.cs@@ -6,9 +6,17 @@ namespace Statecraft.Sim/// <summary>The always-on escalation ladder: 1 routine, 2 wave, 3 limited operation, 4 prolonged conflict, 5 full war.</summary>public static class SecuritySystem{+ /// <summary>The default `turn_lengths` table (rules without the key): quarter on rungs 1-3, month on 4, week on 5. The+ /// game reads <see cref="TurnLengthFor(Content, DateTime, int)"/>; this stays for the Defence screen's legend until the+ /// GDD cutover (spec 2026-10-12 section 3).</summary>public static TurnLength TurnLengthFor(int rung) =>rung >= 5 ? TurnLength.Week : rung == 4 ? TurnLength.Month : TurnLength.Quarter;+ /// <summary>The length of a turn that starts on <paramref name="date"/> on <paramref name="rung"/>: rules `turn_lengths` of+ /// the era the date is in (docs/determinism.md, "Rules per era"). R-TURN-001.</summary>+ public static TurnLength TurnLengthFor(Content c, DateTime date, int rung) =>+ SimTime.ParseLength(c.RulesAt(date).TurnLengths[ClampRung(rung) - 1]);+static int Weeks(TurnLength len) => len == TurnLength.Week ? 1 : len == TurnLength.Month ? 4 : 13;/// <summary>The ladder has rungs 1..5; anything outside is clamped (a bad save or a large order delta).</summary>diff --git a/sim/Statecraft.Sim/SimTime.cs b/sim/Statecraft.Sim/SimTime.csindex 70714e612..5fe60ee97 100644--- a/sim/Statecraft.Sim/SimTime.cs+++ b/sim/Statecraft.Sim/SimTime.cs@@ -1,4 +1,5 @@using System;+using System.Collections.Generic;namespace Statecraft.Sim{@@ -23,6 +24,18 @@ namespace Statecraft.Simreturn next >= boundary || (boundary - next).TotalDays < 14 ? boundary : next;}+ /// <summary>The names rules.yaml `turn_lengths` accepts.</summary>+ public static readonly IReadOnlyList<string> LengthNames = new[] { "quarter", "month", "week" };++ /// <summary>The turn length a `turn_lengths` name stands for. Throws on anything else (the loader refuses it first).</summary>+ public static TurnLength ParseLength(string name) => name switch+ {+ "quarter" => TurnLength.Quarter,+ "month" => TurnLength.Month,+ "week" => TurnLength.Week,+ _ => throw new ArgumentException($"unknown turn length '{name}'", nameof(name)),+ };+/// <summary>Share of a year one turn represents (used to scale yearly rates).</summary>public static double YearFraction(TurnLength len) => len switch{diff --git a/sim/Statecraft.Sim/Simulation.cs b/sim/Statecraft.Sim/Simulation.csindex a73755963..7e22d946a 100644--- a/sim/Statecraft.Sim/Simulation.cs+++ b/sim/Statecraft.Sim/Simulation.cs@@ -52,7 +52,7 @@ namespace Statecraft.Sim}EventSystem.Delegate(c, s, why);- var len = SecuritySystem.TurnLengthFor(s.Rung);+ var len = SecuritySystem.TurnLengthFor(c, s.Date, s.Rung);// The next era's start, or the last era's end, is a boundary: the turn that reaches it ends on it, with that turn's real days (spec 4.1, 4.5).var end = c.Eras[c.Eras.Count - 1].To;var boundary = c.Eras.Select(e => e.From).Where(f => f > s.Date).DefaultIfEmpty(end).Min();