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.

80.1 KB
Raw Blame

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, §2, §3 and §6 "Phase 1". Design of record: docs/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 not built (controller ruling 1, 12 October 2026). AGENTS.md: anything the GDD marks Open, Proposal or TBD needs an owner decision before it is built, and that overrides any brief. Phase 1 needs seven more decisions, now with the owner: D-A5 (who is a refugee, and when one becomes a civilian), D-A6 (the order of resolution), D-A7 (the reference player for the goldens), D-B2 (the timing bonus), D-B6 (point values), D-D5 (whether a camp and a Hakhshara exist at start) and D-D6 (pioneer work: duration, cost, projects at once). PR 2 builds none of them. Decided by the owner on 2026-10-14: all seven as the impact plan recommends (§5), with D-B2's bonus at +5 points per month early, capped at +60, and D-B6 at 100 points per objective (balance values, tunable). PR 3 onward may proceed; each later PR's tasks below are drafts, to be rewritten to the answers before work starts, and its banner names the decisions it waits on.
  • Placeholder values are never under content/ (controller ruling 2, 12 October 2026; the spec's §6 risk line). A balance value the owner has not set lives only in the dev and test overlay (MvpSlice.Overlay, which adds the GDD keys and files as text it supplies) or in a test fixture, marked PLACEHOLDER: owner sets. The loader requires the GDD keys (the mvp: rules block, the GDD command kinds' attention_cost, the city start values) only when systems.loop is gdd, so the real content stays without them until the owner sets the values. Sourced historical facts (the site, its founding date, the card's text and reference date) do belong in content/, with sources. Where a later task below shows a YAML block marked # PLACEHOLDER, that block is the shape of the text the overlay supplies, not a file under content/.
    • 15 October 2026 (owner, Q-CUT-1: "Labelled design values"): from the GDD cutover (Phase 2 PR 1) the balance values are labelled design values in content/, each tagged on its line and listed by DesignValuesTests (R-LOOP-005); this ruling holds only for the work before the cutover, and the overlay is retired.
  • 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 golden mvp-slice (and later 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

Status (14 October 2026): PR 1 merged as #349, PR 2 as #364. The owner answered the seven decisions in Global constraints (#456). PRs 3 and 4's tasks are rewritten to the answers; PRs 5 and 6 are rewritten as each starts.

PR 1 has no dependency. PR 2 needs PR 1 (the overlay sets turn_lengths). PRs 3 to 6 are sequential (each adds to TurnResolver and moves mvp-slice). The site research for PR 5 (Task 5.0) can run while PR 3 or 4 is in review. PR 7 needs PR 6; PR 8 needs PR 7.

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, 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/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

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:

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:

        /// <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:

        /// <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:

            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:

        /// <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 months: TheDefaultReproducesTheLegacyTable must FAIL. Restore.

  • Step 6: Docs. docs/rules/mvp.md:

# 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 in the dev and test overlay (`MvpSlice.Overlay`) or test fixtures, never 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]):

# 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.

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:

    // 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:
        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):

                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:

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:
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 (public, immutable records; counts are population units, D-A1). Only state that approved decisions define; each later PR adds its own section the same way once its decisions are made (cohorts, sites, Social cohesion, housing condition):

    • City(string id, int housingCapacity, int jobSlots, int civilians, int employed, int refugees): the GDD's city attributes and D-A2's counts per city; employed is the part of civilians in jobs.
    • Unit(int id, string type, int q, int r): D-A2's movable units (halutzim, soldiers), by hex.
    • GameState fields: SortedDictionary<string, City> Cities (ordinal), SortedList<int, Unit> Units, int NextId, SortedDictionary<string, DateTime> Objectives (ordinal: the date each objective was completed, GDD "Historical events on objective completion"), int Score (GDD objective 1, "bonus points").
    • Hash sections, appended after over= only when non-empty or non-zero: city{}, units[], next=, obj{}, score=.
  • Step 1: Failing tests:

using System;
using System.Collections.Generic;
using Statecraft.Sim;

public class GddStateTests
{
    // R-LOOP-002
    [Fact]
    public void WithTheSwitchOffTheGoldenSnapshotIsByteIdentical()
    {
        var s = GoldenRun.Play(ContentLoader.Load(RealContentTests.ContentRoot()), GoldenRun.Until1950);
        Assert.Equal(GoldenSnapshot.Read("hash1950"), s.Describe());
    }

    // R-LOOP-002
    [Fact]
    public void EachNewSectionAppearsOnlyWhenSetAndMovesTheHash()
    {
        var s = new GameState();
        var seen = new HashSet<string> { s.Hash() };
        var steps = new List<Action<GameState>>
        {
            x => x.Cities["tel_aviv"] = new City("tel_aviv", 10, 4, 6, 3, 2),
            x => x.Units.Add(1, new Unit(1, "halutz", -3, 19)),
            x => x.NextId = 2,
            x => x.Objectives["first_new_yishuv"] = new DateTime(1949, 3, 15),
            x => x.Score = 5,
        };
        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[", "next=", "obj{", "score=" }) Assert.Contains(label, s.Describe());
    }

    [Fact]
    public void CloneCopiesEveryNewCollection() { /* add one entry to each collection, clone, change the clone's collections, assert the original's are unchanged */ }
}

Write the clone test in full: var a = new GameState(); a.Cities["x"] = new City("x", 1, 1, 1, 0, 0); a.Units.Add(1, new Unit(1, "halutz", 0, 0)); a.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.Objectives.Clear(); Assert.Single(a.Cities); Assert.Single(a.Units); Assert.Single(a.Objectives);. Also a test that every field of each record reaches the hash (change one field at a time, the hash moves).

(GoldenSnapshot.Read(name) is added if missing: the text of golden/<name>.txt, through the existing path helper.)

  • Step 2: Run, expect compile failure.
  • Step 3: Implement GddState.cs: the two records, each with string Canonical() in invariant text (City: id=cap,jobs,civ,emp,ref; Unit: id:type@q,r). GameState: the fields, Clone copying each collection, and in CanonicalText, after the over= line:
            // 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)
            {
                Sep(); 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 (NextId != 0) { Sep(); Nl(); sb.Append("next=").Append(NextId.ToString(CultureInfo.InvariantCulture)); }
            if (Objectives.Count > 0) Section("obj", '{', '}', Objectives.Select(kv => kv.Key + "=" + kv.Value.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)));
            if (Score != 0) { Sep(); Nl(); sb.Append("score=").Append(Score.ToString(CultureInfo.InvariantCulture)); }

The over= line has no trailing separator today, so each new section starts with one; with every section empty, the text is byte-identical.

  • Step 4: Run dotnet test sim/Statecraft.sln (every golden must still pass). Mutate: write city{ unconditionally; the byte-identity test 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:

    // 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:
            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) (a test choice, not a balance value: eight monthly turns) and MvpGolden.Play(Content c) : GameState. The golden covers only what PR 2 builds: the switch and monthly turns under the existing HistoricalAI, which issues no GDD order. It needs no reference player (D-A7) and no resolution order (D-A6).

  • Step 1: Tests. CommandGuardTests:

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:

using System;
using System.Collections.Generic;
using Statecraft.Sim;

/// <summary>The GDD slice's golden (spec 2026-10-12 §3): the overlay content (the loop switch on, monthly turns), the golden
/// seed, Historical mode and HistoricalAI, until Until. A reference player for GDD orders waits on D-A7.</summary>
public static class MvpGolden
{
    public static readonly DateTime Until = new DateTime(1949, 1, 15);   // eight monthly turns

    public static GameState Play(Content c)
    {
        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;
        return s;
    }
}

MvpGoldenTests.TheSliceMatchesItsGolden: var s = MvpGolden.Play(MvpSlice.Load(RealContentTests.ContentRoot())); 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 HistoricalAI 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

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, 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:

# 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
    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, #456)

content/unit_types.yaml (population types only, spec §6):

# 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:

# ---- 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 (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 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.

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).
        /// <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);
            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, 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: 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; 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/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.

/// <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)
    {
        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

Decided by the owner on 2026-10-14 (#456, recorded in the impact plan §5 and in #375): D-D5 and D-A6, each as the impact plan recommends. The tasks below are written to those answers:

  • D-D5: "One of each exists at start (a design assumption, labelled). More are built by pioneers." The slice's Tel Aviv starts with one military camp and one Hakhshara, in the overlay's cities.yaml (ruling 2), labelled PLACEHOLDER: owner sets (D-D5: one of each exists at start; a design assumption, not a claim about 1948). Building more is a pioneer action ("build military training camp", Phase 4), not this PR. Capacity is not part of the answer and the GDD leaves training capacity open, so this PR sets no capacity limit. The facilities are read from the content, not held in the state, until pioneers can build one.
  • D-A6: "The fixed order of §2.3." Training is step 4 of §2.3, after the enemy's orders, combat and capture (Phase 5) and before construction (PR 5) and production. In PR 4 it is therefore the first step TurnResolver runs. The plan reads D-A6 as follows, and this reading is not part of the owner's ruling: a cohort ordered this turn already counts this turn's step, so a cohort ordered on turn T with training_turns 3 is done at the end of turn T+2. The other reading (the end of T+3) is a one-line change in Training.Start.

Placeholder values go in MvpSlice.Overlay or test fixtures, never content/ (ruling 2): the training fields of unit_types.yaml, the facilities in cities.yaml and the two attention_cost kinds below are overlay text, marked PLACEHOLDER: owner sets. scenario-mvp-absorb-first orders no training, so it must not move: the new state (cohorts, recruits) is hashed only when it is set (R-LOOP-002's rule).

Issue #377 (Task form): "GDD Phase 1: training in a military camp and a Hakhshara". Sign-off: placeholders, D-D5 as answered (#456), no borrowing for training, the mvp-slice move.

Task 4.1: the training data (overlay text, ruling 2)

Files: MvpSlice.cs (overlay text), Content.cs (UnitType gains Facility, TrainingTurns, TrainingCost), ContentLoader.cs (ValidateGdd), Fixture.cs (the fixture's town gets both facilities and the two training types), CitiesContentTests.cs (one row per new check).

The overlay's unit_types.yaml gains:

  - id: recruit                  # civilian to recruit, through basic training (GDD "Progression")
    kind: population             # a count per city until Phase 5 (spec §6 item 4)
    facility: military_camp
    training_turns: 3            # PLACEHOLDER: owner sets
    training_cost: 0.5           # PLACEHOLDER: owner sets (IL millions per group)
  - 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)

The overlay's cities.yaml: tel_aviv.facilities: [military_camp, hakhshara] # PLACEHOLDER: owner sets (D-D5: one of each exists at start; a design assumption, not a claim about 1948). attention_cost gains train: 1 and cancel_training: 0.5, both PLACEHOLDER: owner sets. Validation (each a CitiesContentTests row naming file and field): a type with a facility names a known facility and has training_turns ≥ 1 and a finite training_cost ≥ 0; a type without one has neither; a trained population type is recruit (the only trained count until Phase 5).

Task 4.2: Train and CancelTraining (R-TRAIN-001, R-TRAIN-002)

Files: create Training.cs, TrainingTests.cs; GddState.cs (Cohort; City.Recruits), GameState.cs (Cohorts, Clone, the hash), Commands.cs, AttentionSystem.cs (train, cancel_training, both GDD kinds), Simulation.cs (Execute), SaveGame.cs, Scenario.cs, CommandGuardTests.Samples, MvpSliceTests (the slice's costs).

Interfaces:

  • Produces: Train(string city, string track, int count), Kind = "train" (train CITY TRACK N in saves; the track is a unit type id with a facility); CancelTraining(int cohort), Kind = "cancel_training" (untrain ID); Training.Start(c, s, city, track, count, why) : string?; Training.Cancel(c, s, cohort, why) : string?; Cohort { Id, Type, City, Count, TurnsLeft } (immutable); GameState.Cohorts : SortedList<int, Cohort>, hashed as train[...] only when not empty; City.Recruits, written into the city's hash record only when not 0, so a city with none hashes as before.

R-TRAIN-001: Train takes count ≥ 1 civilians without a job (civilians − employed) of a city that has the track's facility, pays count × training_cost from the Treasury (refused if the Treasury holds less; no borrowing for training: flagged in the PR as a choice for the owner), and opens a cohort with TurnsLeft = training_turns and id s.NextId++ (cohorts and units share the id counter, so no id is reused). The trainees leave the city's civilians at once. Refused, state unchanged and Attention refunded: unknown city, unknown track (or a type with no facility), count < 1, no facility, more than the unemployed, Treasury short. The legacy loop refuses it before charging. R-TRAIN-002: CancelTraining returns the cohort's people to the city's civilians, without a job, and refunds nothing (D-A3). An unknown or finished cohort (a finished one has left the state) is refused, state unchanged.

Tests: start; [Theory] of the limits; cancel returns people and not Money; cancelling an unknown or finished cohort; save round trip of both lines; legacy refusal with Attention refunded. Mutation: refund the Money on cancel; CancellingReturnsPeopleNotMoney fails.

Task 4.3: progress in the resolver (R-TRAIN-003)

Training is step 4 of TurnResolver (§2.3, D-A6), the first step PR 4 runs. In ascending cohort id, each cohort's TurnsLeft falls by 1; at 0 the cohort leaves the state and: a population type (recruit) adds count to the city's Recruits; a unit type (halutz) adds count units Unit(s.NextId++, "halutz", q, r) at the city's settlement hex (map/settlement_hexes.yaml; Tel Aviv is (−3, 19)), in order.

Tests: a recruit cohort of 3 groups completes after exactly training_turns turns, counting the turn it was ordered in; a halutz cohort creates units with consecutive ids at Tel Aviv's hex; people in training are not civilians (cohesion and housing read civilians: flagged in the PR, since housing then sees the trainees' places as free while D-D1 and the population role model are open). Reference player (D-A7): after filling the jobs, it trains 1 halutz group when there is none, none in training, a civilian left without a job, and the Treasury and Attention to pay (a stated policy). Re-pin mvp-slice; scenario-mvp-absorb-first does not move. docs/rules/mvp.md R-TRAIN-001 to R-TRAIN-003, docs/gdd/training.md, CHANGELOG, checks, Unity EditMode, web_check, PR, stop.


PR 5: one designated site and "build yishuv"

Decided by the owner on 2026-10-14 (#378): the site is Mefalsim (#459), and every other open question takes the recommendation of the rewritten PR 5 plan posted on #378, which replaces the draft tasks below. D-D6 and D-A6 were decided in #456. Ruling 4 is moot with Mefalsim (its photograph is CC BY 4.0); the recommendation is to refuse the Yeruham photographs as tagged. On 2026-10-15 the owner answered question 13 (and #468's question 1), "Allow borrowing": training and pioneer work borrow what the Treasury lacks, as map actions do.

The site's name, place, date and sources are sourced facts and go in content/sites.yaml; the build turns and cost are overlay text (ruling 2).

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

# 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, waits for the owner). 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

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).

Task 6.1: objectives.yaml and the card event

# 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

As built (15 October 2026, refs #379): the point values are global, as D-B6 and D-B2 read: mvp.objective_points: 100, objective_bonus_per_month: 5, objective_bonus_cap: 60, as rules.yaml design values (the PR was rebased onto the cutover, #600, which retired the overlay), not per objective. The objective also has a name. Months are calendar months (Objectives.MonthsFromHistory, signed), to match the owner's card wording of 14 October 2026 on #379 ("on time" in the same month as history, "n months later" when late), not the whole-months formula of Task 6.2; the owner confirmed calendar months on 15 October 2026 (#653).

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)

Waits for PRs 3 to 6.

  • 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

Waits for PRs 3 to 6.

  • 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.

Carried to the cutover PR (Phase 2)

Found in the review of #364 and left for cutover, when old saves start to be refused for real:

  • N2. A save from a ruleset this build does not know, such as a future gdd-0.2, is reported as "unknown ruleset". It should say the save is from a newer version of the game, the way a newer schema version is reported.
  • N4. The refusal text says "start a new game", and Unity's save.unreadable string adds the same advice again, so the player reads it twice. That string is Hebrew, and it wraps the sim's English reason inside it. Give the refusal a code the UI translates, and say it once.

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.