Skip to content

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

sim: the GDD loop switch, state scaffolding and save schema 2 (fixes #357) (#364)

Eyal Golan244723ff07ee
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6a7b794f5..d3c769bad 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,10 @@ adds a line under **Unreleased**; CI's `Changelog` job checks this (see `CONTRIB
## [Unreleased]
### Added
+- The GDD v0.1 loop switch (`systems.loop` in eras.yaml, default `legacy`), its state (cities, units, objectives and score,
+ hashed only when set) and save schema 2, which names its ruleset: a game refuses a save made under another ruleset with a
+ message to start a new game. The real game is unchanged and the goldens do not move; a new `mvp-slice` golden pins the
+ switch on with monthly turns (GDD Phase 1, refs #357).
- The loader refuses an event whose window runs past the end of its era (chapters spec 9: an event may not span a boundary;
split it). A `to` on the boundary is fine (it is exclusive); an open window (no `to`) is allowed only in the last era.
No current event is affected (refs #65).
diff --git a/content/eras.yaml b/content/eras.yaml
index d916ca393..4f98d59a1 100644
--- a/content/eras.yaml
+++ b/content/eras.yaml
@@ -4,6 +4,8 @@
# the start of play to 1 January 1957, the spec's "Q2 1948 to Q4 1956". These are game-design dates, not historical facts.
# Optional per era: `systems: { legislature: state | assembly, map_actions: [transit_camp, housing] }` (issue #58). Absent means
# a state legislature and both map actions. A key is added only with the code behind it.
+# `systems.loop: legacy | gdd` (GDD v0.1, docs/rules/mvp.md R-LOOP-001): which game loop runs; the same in every era. Absent
+# means legacy. The real game stays legacy until the GDD cutover.
eras:
- id: founding
name: The Founding
diff --git a/docs/determinism.md b/docs/determinism.md
index e6c8c29cb..fd2d45718 100644
--- a/docs/determinism.md
+++ b/docs/determinism.md
@@ -68,6 +68,13 @@ manifest line and the snapshot), then run the tests plain. A scenario that moves
command; its snapshot diff in the PR shows what moved, and the commit message says why. Two ship: `cautious` and `reckless`. They stay in 1948, before any change a
later era makes, so they move only when a 1948 rule or event does.
+**MVP goldens (GDD v0.1, before cutover).** `mvp-slice` plays `MvpSlice.Load`, the real content with the loop switch on and
+monthly turns (spec 2026-10-12 section 2.1, R-LOOP-003), from the golden seed in Historical mode with `HistoricalAI` until
+`MvpGolden.Until` (15 January 1949, eight monthly turns). `MvpGoldenTests` checks it against the manifest line `mvp-slice` and the
+snapshot `golden/mvp-slice.txt`, and the update command re-pins it like the others. It is not shown in this file's table or in
+`tools/web_check.py`, because the players run only the legacy goldens until cutover. A Phase 1 PR that adds a GDD rule the slice
+exercises moves it, re-pins it and says why; the legacy goldens never move for it.
+
**Invariants.** A hash says something changed; `sim/Statecraft.Sim.Tests/golden/invariants.yaml` says whether it is
still plausible. Each entry names a golden run (`1950` or `1952`), a value (an indicator id, or `treasury`, `debt`,
`fx`, `population`, `stability`), when it is read (`end`, `always`, or a date: the first state on or after it), a `min`
diff --git a/docs/gdd/loop-switch.md b/docs/gdd/loop-switch.md
new file mode 100644
index 000000000..2119d45c8
--- /dev/null
+++ b/docs/gdd/loop-switch.md
@@ -0,0 +1,40 @@
+# The GDD loop switch
+
+## Player story
+
+As the maintainer, I want the GDD v0.1 loop built behind one switch, so that the real game and its goldens do not change until the cutover turns it on, and a save never replays under rules it was not played with [S1].
+
+## Rules
+
+- `systems.loop` in eras.yaml is `legacy` or `gdd`, the same in every era; absent means legacy (R-LOOP-001).
+- The GDD state (cities, units, the next unit id, completed objectives, the score) is hashed only when it is set, so the legacy hash text is unchanged (R-LOOP-002).
+- `MvpSlice.Overlay` gives the real content with the switch on and monthly turns, and changes nothing else (R-LOOP-003).
+- A save names its ruleset, `legacy` or `gdd-0.1`; a game refuses a save from another ruleset (R-SAVE-001, decision D-E4 [S2]).
+- Balance values the owner has not set live only in the overlay or in test fixtures, never under `content/` [S3].
+
+## Data touched
+
+- `content/eras.yaml`: `systems.loop` (the real content keeps the default).
+- `GameState`: `Cities`, `Units`, `NextId`, `Objectives`, `Score`.
+- Save files: schema 2 and the `ruleset` line.
+- `sim/Statecraft.Sim.Tests/golden/manifest.txt`: the `mvp-slice` line.
+
+## Done when
+
+- `dotnet test sim/Statecraft.sln` passes, and `hash1950`, `hash1952`, `smoke5`, `scenario-cautious` and `scenario-reckless` do not move.
+- The WebGL `web_check` with `golden&smoke=5` passes.
+
+## Out of scope
+
+- Any GDD rule: cities, training, sites, objectives and the score are built once the owner rules on the open decisions.
+- Turning the switch on for the real game, which is the cutover PR.
+
+## Sources
+
+- [S1] GDD v0.1 impact analysis and phased plan, section 2.1, docs/superpowers/specs/2026-10-12-gdd-v0.1-impact-and-plan.md
+- [S2] The same plan, section 5, decision D-E4, docs/superpowers/specs/2026-10-12-gdd-v0.1-impact-and-plan.md
+- [S3] GDD Phase 1 implementation plan, Global constraints, docs/superpowers/plans/2026-10-12-gdd-phase-1.md
+
+## Open questions
+
+- None.
diff --git a/docs/rules/mvp.md b/docs/rules/mvp.md
index 6dcd46c4f..e87c6a8ff 100644
--- a/docs/rules/mvp.md
+++ b/docs/rules/mvp.md
@@ -2,8 +2,20 @@
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/`.
+Until the owner sets them, they are placeholders in the dev and test overlay (`MvpSlice.Overlay`) or in 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, today's table. The GDD's monthly turns set all five to month.
+
+## The loop switch
+
+R-LOOP-001: `systems.loop` in eras.yaml is `legacy` (the default) or `gdd`, and every era has the same value. Its ruleset id, which a save records, is `legacy` or `gdd-0.1`.
+
+R-LOOP-003: `MvpSlice.Overlay` loads the real content with `systems.loop: gdd` in every era and `turn_lengths` all month, and changes nothing else. Tests, the MVP goldens and the dev flag use it until cutover.
+
+R-LOOP-002: The GDD state (cities, units, the next unit id, completed objectives, the score) is written into the state hash only when it is set. With the legacy loop the hash text is unchanged, byte for byte.
+
+## Saves
+
+R-SAVE-001: A save names the ruleset it was played under (`ruleset legacy` or `ruleset gdd-0.1`, save schema 2). A game refuses a save made under another ruleset, with a message to start a new game. A schema 1 save has no ruleset line and is legacy.
diff --git a/docs/superpowers/plans/2026-10-12-gdd-phase-1.md b/docs/superpowers/plans/2026-10-12-gdd-phase-1.md
index ef0cd2dc5..ca8e72ea6 100644
--- a/docs/superpowers/plans/2026-10-12-gdd-phase-1.md
+++ b/docs/superpowers/plans/2026-10-12-gdd-phase-1.md
@@ -22,12 +22,12 @@
- 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.
+- **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. **PR 3 onward waits for the owner's answers**; 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/`.
- 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.
+- 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:
@@ -60,6 +60,8 @@
| 7 | `unity/gdd-ui-core` | new Task issue | Unity: `SimBridge` keys and validation with a reflection guard, the `?mvp` dev flag, the score on the HUD, the objective card's photograph |
| 8 | `unity/gdd-ui-city` | new Task issue | Unity: the city panel (assign, train), the site build button, the built yishuv on the map |
+**Status (12 October 2026):** PR 1 merged as #349. PR 2 is built to this plan. PRs 3 to 8 wait for the owner's answers on the decisions in Global constraints.
+
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
@@ -79,9 +81,10 @@ PR 1 has no dependency. PR 2 needs PR 1 (the overlay sets `turn_lengths`). PRs 3
| `sim/Statecraft.Sim/Training.cs` (new) | Train, cancel, cohort progress | 4 |
| `sim/Statecraft.Sim/Projects.cs` (new) | Pioneer work at sites | 5 |
| `sim/Statecraft.Sim/Objectives.cs` (new) | Completion, score, timing bonus | 6 |
-| `sim/Statecraft.Sim/TurnResolver.cs` (new) | The fixed resolution order (spec §2.3, D-A6 provisional) | 3–6 |
+| `sim/Statecraft.Sim/TurnResolver.cs` (new) | The fixed resolution order (spec §2.3, D-A6, waits for the owner) | 3–6 |
| `sim/Statecraft.Sim/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 |
+| `content/sites.yaml`, `content/objectives.yaml` (sourced facts only), `content/events/first_new_yishuv.yaml`, `content/schema/event.schema.json` | Slice content that is sourced fact | 5–6 |
+| `MvpSlice.Overlay` text: the city start values, the population types' balance, the `mvp:` rules block and the GDD command kinds' `attention_cost` (ruling 2: never under `content/` until the owner sets them) | Slice balance placeholders | 3–6 |
| `sim/Statecraft.Sim.Tests/*` | Tests per task; `MvpGolden.cs`, `ReferencePlayer.cs` (new) | 1–6 |
| `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 |
@@ -249,7 +252,7 @@ eras:
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/`.
+placeholders in the dev and test overlay (`MvpSlice.Overlay`) or test fixtures, never in `content/`.
## Turns
@@ -514,13 +517,11 @@ namespace Statecraft.Sim
**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=`.
+- 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:**
@@ -533,12 +534,10 @@ public class GddStateTests
{
// R-LOOP-002
[Fact]
- public void WithTheSwitchOffTheGoldenSnapshotsAreByteIdentical()
+ public void WithTheSwitchOffTheGoldenSnapshotIsByteIdentical()
{
- var c = ContentLoader.Load(RealContentTests.ContentRoot());
- var s = GoldenRun.Play(c, GoldenRun.Until1950);
+ var s = GoldenRun.Play(ContentLoader.Load(RealContentTests.ContentRoot()), GoldenRun.Until1950);
Assert.Equal(GoldenSnapshot.Read("hash1950"), s.Describe());
- Assert.DoesNotContain("city{", s.Describe());
}
// R-LOOP-002
@@ -546,66 +545,49 @@ public class GddStateTests
public void EachNewSectionAppearsOnlyWhenSetAndMovesTheHash()
{
var s = new GameState();
- var empty = s.Hash();
+ var seen = new HashSet<string> { 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.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,
- 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());
+ foreach (var label in new[] { "city{", "units[", "next=", "obj{", "score=" }) 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);
- }
+ public void CloneCopiesEveryNewCollection() { /* add one entry to each collection, clone, change the clone's collections, assert the original's are unchanged */ }
}
```
-(`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.)
+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` (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=")...`:
+- [ ] **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:
```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);
+ 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 (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 (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) { Nl(); sb.Append("score=").Append(Score.ToString(CultureInfo.InvariantCulture)).Append(';'); }
- if (Cohesion.HasValue) Num("coh", Cohesion.Value);
+ if (Score != 0) { Sep(); Nl(); sb.Append("score=").Append(Score.ToString(CultureInfo.InvariantCulture)); }
```
-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.
+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` (the whole suite: every golden must still pass). **Mutate:** write `city{` unconditionally; `WithTheSwitchOffTheGoldenSnapshotsAreByteIdentical` and the golden tests fail. Restore.
+- [ ] **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
@@ -682,7 +664,7 @@ For the last test, write the body: build the text `"statecraft-save 2\ncontent "
**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`.
+- 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`:
@@ -749,39 +731,42 @@ 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>
+/// <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); // PLACEHOLDER: grows with the slice; mvp-end at cutover
+ public static readonly DateTime Until = new DateTime(1949, 1, 15); // eight monthly turns
- public static GameState Play(Content c, Func<Content, GameState, IReadOnlyList<Command>> player)
+ 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, player(c, s)).State;
+ s = Simulation.Step(c, s, HistoricalAI.Commands(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)`.
+`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 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 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
-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.
+> **Waits for the owner (ruling 1):** D-A5, D-A6, D-A7. Placeholder values go in `MvpSlice.Overlay` or test fixtures, never `content/` (ruling 2): the `cities.yaml` start values, the `mvp:` block and `attention_cost` below are overlay text. Rewrite this PR's tasks to the owner's answers before starting.
-### 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`.
+Issue (Task form): "GDD Phase 1: one city (Tel Aviv): housing, jobs, refugees, Money from jobs, Social cohesion". Sign-off: placeholders, D-A5 and D-A6 (wait for the owner), the `mvp-slice` move.
+
+### Task 3.1: the slice's city data: `cities.yaml`, `unit_types.yaml`, the `mvp:` rules block (overlay text, ruling 2)
+
+**Files:** Modify `sim/Statecraft.Sim/MvpSlice.cs` (the overlay supplies `cities.yaml` and `unit_types.yaml`, and adds the `mvp:` block and the new `attention_cost` kinds to `rules.yaml`, all marked `PLACEHOLDER: owner sets`; nothing under `content/` changes until the owner sets the values; the loader requires these only when the loop is `gdd`), `Content.cs` (`CityStart`, `UnitType`, `MvpRules`, `Content.Cities`, `Content.UnitTypes`, `Rules.Mvp`), `ContentLoader.cs` (read and validate), `Fixture.cs` (the two new files, minimal), `ValidationTests.cs` or a new `CitiesContentTests.cs`.
**Interfaces:**
- Produces: `CityStart { Id, HousingCapacity, HousingCondition, JobSlots, Civilians, Employed, Facilities : List<string> }`; `UnitType { Id, Kind ("population" | "unit"), TrainingTurns, TrainingCost, Facility }`; `MvpRules { PeoplePerUnit, IncomePerJobPerYear, CohesionHousingWeight, CohesionJobsWeight, ArrivalsCity }`; `Content.Cities : List<CityStart>`; `Content.UnitTypes : List<UnitType>`; `Rules.Mvp : MvpRules`.
@@ -799,7 +784,7 @@ cities:
job_slots: 90 # PLACEHOLDER: owner sets
civilians: 100 # PLACEHOLDER: owner sets
employed: 80 # PLACEHOLDER: owner sets
- facilities: [] # PR 4 adds military_camp and hakhshara (D-D5, provisional)
+ facilities: [] # PR 4 adds military_camp and hakhshara (D-D5, waits for the owner)
```
`content/unit_types.yaml` (population types only, spec §6):
@@ -863,12 +848,12 @@ Tests (`CitiesTests`, on `MvpSlice.Load` and on the fixture with `systems: { loo
**Files:** create `TurnResolver.cs`; modify `Cities.cs`, `Simulation.cs` (call), `CitiesTests.cs`.
**Interfaces:**
-- Produces: `TurnResolver.Resolve(Content c, GameState s, DateTime next, double yearFraction, List<Cause> why)`, called in `Step` right after `EventSystem.Delegate` and after `next`/`yf` are computed, only when `c.IsGdd`; order (D-A6, 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`.
+- Produces: `TurnResolver.Resolve(Content c, GameState s, DateTime next, double yearFraction, List<Cause> why)`, called in `Step` right after `EventSystem.Delegate` and after `next`/`yf` are computed, only when `c.IsGdd`; order (D-A6, waits for the owner; spec §2.3 recommends): training (PR 4), construction (PR 5), production, arrivals, housing, cohesion, objectives (PR 6). `Cities.ArrivedUnits(Content c, DateTime from, DateTime to) : int`.
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-004 housing (D-A5, waits for the owner): `moved = min(refugees, max(0, housing_capacity - civilians))` refugees become civilians (unemployed).
- R-CITY-005 cohesion: over all cities, `housed = civilians / (civilians + refugees)` (1 when both 0), `employed = employed / civilians` (1 when 0); `Cohesion = clamp01(w_h * housed + w_j * employed)`.
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.
@@ -878,7 +863,7 @@ Tests: `ProductionPaysPerEmployedGroup` (one step, Treasury delta equals the for
**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
+/// <summary>The reference player for the GDD goldens (D-A7, waits for the owner): HistoricalAI's orders, then each city's jobs filled
/// with as many civilians as there are slots. Test code with a stated policy; it is not "history".</summary>
public static class ReferencePlayer
{
@@ -905,7 +890,10 @@ public static class ReferencePlayer
## PR 4: training
-Issue: "GDD Phase 1: training in a military camp and a Hakhshara". Sign-off: placeholders, D-D5 provisional.
+> **Waits for the owner (ruling 1):** D-D5 (and D-A6 for where training runs in the turn). The values below are overlay or fixture text (ruling 2). Rewrite this PR's tasks to the owner's answers before starting.
+
+
+Issue: "GDD Phase 1: training in a military camp and a Hakhshara". Sign-off: placeholders, D-D5 (waits for the owner).
### Task 4.1: content
@@ -946,6 +934,9 @@ Tests: a recruit cohort of 3 groups completes after exactly `training_turns` ste
## PR 5: one designated site and "build yishuv"
+> **Waits for the owner (ruling 1):** D-D6 (and D-A6). 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). Ruling 4: the public-domain question on Yeruham's 1951 PikiWiki photographs (Werner Braun, tagged PD-author) goes to the owner and is recorded in this PR's notes.
+
+
### Task 5.0: choose and source the site (before any code)
Criteria (D-A4, CONTENT_POLICY):
@@ -981,7 +972,7 @@ sites:
**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-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.
@@ -991,6 +982,9 @@ Tests: start, every refusal (not a halutz, busy unit, unknown site, site buildin
## PR 6: the objective card and the score
+> **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
```yaml
@@ -1022,6 +1016,9 @@ objectives:
## 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.
@@ -1031,6 +1028,9 @@ objectives:
## 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.
@@ -1038,6 +1038,12 @@ objectives:
---
+## 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.
diff --git a/sim/Statecraft.Sim.Tests/CommandGuardTests.cs b/sim/Statecraft.Sim.Tests/CommandGuardTests.cs
new file mode 100644
index 000000000..64a8ca691
--- /dev/null
+++ b/sim/Statecraft.Sim.Tests/CommandGuardTests.cs
@@ -0,0 +1,73 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using Statecraft.Sim;
+
+/// <summary>Every command kind has its touch-points (spec 2026-10-12 section 2.3): an Attention kind with a cost in the real
+/// rules, CommandText (Step refuses an unknown type outright), the save format, and the scenario runner. The Unity order
+/// queue is the fifth, guarded in Unity's own tests. A new Command type fails EveryCommandTypeHasASample until it is added
+/// here, and then fails the others until every touch-point knows it.</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("drought", "a"),
+ [typeof(SetMobilization)] = new SetMobilization(0.5),
+ [typeof(SecurityOrder)] = new SecurityOrder(1),
+ [typeof(Appoint)] = new Appoint("prime_minister", "pm_one"),
+ [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()
+ {
+ foreach (var t in CommandTypes()) Assert.True(Samples.ContainsKey(t), $"{t.Name} has no sample: add it, then its touch-points");
+ }
+
+ [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 EveryCommandIsAcceptedByStepAndRoundTripsThroughASave()
+ {
+ var c = ContentLoader.Load(Fixture.Write());
+ foreach (var cmd in Samples.Values)
+ {
+ var g = GameSession.New(c, 1, Mode.Historical);
+ g.Step(new[] { cmd }); // CommandText throws on a type it does not know; the save throws on one it cannot write
+ var text = g.Save.Write();
+ var parsed = SaveGame.Parse(text);
+ Assert.Equal(text, parsed.Write());
+ Assert.Equal(cmd.GetType(), parsed.Turns.Single().Single().GetType());
+ }
+ }
+
+ [Fact]
+ public void TheScenarioRunnerKnowsEveryKind()
+ {
+ foreach (var cmd in Samples.Values)
+ {
+ Assert.Contains(cmd.Kind, Scenario.Kinds);
+ var fields = new Dictionary<string, object> { ["kind"] = cmd.Kind };
+ foreach (var f in Scenario.FieldsOf(cmd.Kind)) fields[f] = f == "shares" ? new Dictionary<object, object> { ["x"] = "1" } : (object)"1";
+ Assert.Equal(cmd.GetType(), Scenario.Build(fields).GetType());
+ }
+ }
+
+ [Fact]
+ public void EveryAttentionKindHasACommand() =>
+ Assert.Equal(AttentionSystem.CommandKinds.OrderBy(k => k, StringComparer.Ordinal), Samples.Values.Select(x => x.Kind).OrderBy(k => k, StringComparer.Ordinal));
+}
diff --git a/sim/Statecraft.Sim.Tests/EraSystemsTests.cs b/sim/Statecraft.Sim.Tests/EraSystemsTests.cs
index 33b9bb17d..1f7223719 100644
--- a/sim/Statecraft.Sim.Tests/EraSystemsTests.cs
+++ b/sim/Statecraft.Sim.Tests/EraSystemsTests.cs
@@ -177,4 +177,57 @@ eras:
var s2 = Simulation.NewGame(all, 1, Mode.Historical);
Assert.NotEqual("That map action is not available in this chapter", MapActions.Check(all, s2, MapActions.TransitCamp, 0, 0));
}
+
+ // 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.Equal("gdd", c.Loop);
+ Assert.True(c.IsGdd);
+ Assert.Equal("gdd-0.1", c.Ruleset);
+ }
+
+ [Fact]
+ public void ABadLoopFailsNamingTheField()
+ {
+ var ex = Assert.Throws<ContentException>(() => Load(" systems: { loop: civ }"));
+ Assert.Equal("eras.yaml", ex.File);
+ Assert.Equal("eras[founding].systems.loop", ex.Field);
+ Assert.Contains("must be legacy or gdd", ex.Message);
+ }
+
+ // R-LOOP-001
+ [Theory]
+ [InlineData(" systems: { loop: gdd }", "")]
+ [InlineData("", " systems: { loop: gdd }")]
+ public void EveryEraMustRunTheSameLoop(string first, string second)
+ {
+ var o = new Dictionary<string, string> { ["eras.yaml"] = $@"
+eras:
+ - id: founding
+ name: The Founding
+ from: 1948-05-15
+ to: 1950-01-01
+{first}
+ - id: later
+ name: Later
+ from: 1950-01-01
+ to: 1957-01-01
+{second}
+" };
+ 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);
+ }
}
diff --git a/sim/Statecraft.Sim.Tests/GddStateTests.cs b/sim/Statecraft.Sim.Tests/GddStateTests.cs
new file mode 100644
index 000000000..fb631bb80
--- /dev/null
+++ b/sim/Statecraft.Sim.Tests/GddStateTests.cs
@@ -0,0 +1,89 @@
+using System;
+using System.Collections.Generic;
+using Statecraft.Sim;
+
+/// <summary>The GDD v0.1 state (spec 2026-10-12 section 2.2): written into the hash only when set, so the legacy loop's
+/// hash text, and every golden, is unchanged.</summary>
+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());
+ Assert.Equal(GoldenRun.Hash1950, s.Hash());
+ }
+
+ // R-LOOP-002
+ [Fact]
+ public void AnEmptyStateWritesNoNewSection()
+ {
+ var text = new GameState().Describe();
+ foreach (var label in new[] { "city{", "units[", "next=", "obj{", "score=" }) Assert.DoesNotContain(label, text);
+ Assert.EndsWith("over=", text);
+ }
+
+ // R-LOOP-002
+ [Fact]
+ public void EachNewSectionAppearsOnlyWhenSetAndMovesTheHash()
+ {
+ var s = new GameState();
+ var seen = new HashSet<string> { s.Hash() };
+ var steps = new List<(string label, Action<GameState> set)>
+ {
+ ("city{", x => x.Cities["tel_aviv"] = new City("tel_aviv", 10, 4, 6, 3, 2)),
+ ("units[", x => x.Units.Add(1, new Unit(1, "halutz", -3, 19))),
+ ("next=", x => x.NextId = 2),
+ ("obj{", x => x.Objectives["first_new_yishuv"] = new DateTime(1949, 3, 15)),
+ ("score=", x => x.Score = 5),
+ };
+ foreach (var (label, set) in steps)
+ {
+ Assert.DoesNotContain(label, s.Describe());
+ set(s);
+ Assert.Contains(label, s.Describe());
+ Assert.True(seen.Add(s.Hash()), $"setting {label} did not move the hash");
+ }
+ }
+
+ // R-LOOP-002
+ [Fact]
+ public void EveryFieldOfARecordReachesTheHash()
+ {
+ string H(City c) { var s = new GameState(); s.Cities[c.Id] = c; return s.Hash(); }
+ string U(Unit u) { var s = new GameState(); s.Units.Add(u.Id, u); return s.Hash(); }
+ var cities = new[] { new City("a", 1, 1, 1, 1, 1), new City("b", 1, 1, 1, 1, 1), new City("a", 2, 1, 1, 1, 1), new City("a", 1, 2, 1, 1, 1),
+ new City("a", 1, 1, 2, 1, 1), new City("a", 1, 1, 1, 2, 1), new City("a", 1, 1, 1, 1, 2) };
+ Assert.Equal(cities.Length, new HashSet<string>(Array.ConvertAll(cities, H)).Count);
+ var units = new[] { new Unit(1, "halutz", 0, 0), new Unit(2, "halutz", 0, 0), new Unit(1, "recruit", 0, 0), new Unit(1, "halutz", 1, 0), new Unit(1, "halutz", 0, 1) };
+ Assert.Equal(units.Length, new HashSet<string>(Array.ConvertAll(units, U)).Count);
+ }
+
+ [Fact]
+ public void CloneCopiesEveryNewCollection()
+ {
+ 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);
+ a.NextId = 2; a.Score = 3;
+ var before = a.Hash();
+ var b = a.Clone();
+ b.Cities["y"] = a.Cities["x"]; b.Units.Add(2, a.Units[1]); b.Objectives.Clear(); b.NextId = 9; b.Score = 9;
+ Assert.Equal(before, a.Hash());
+ Assert.Single(a.Cities); Assert.Single(a.Units); Assert.Single(a.Objectives);
+ }
+
+ [Fact]
+ public void TheNewCollectionsOrderTheirKeysOrdinally()
+ {
+ var s = new GameState();
+ s.Cities["b"] = new City("b", 1, 1, 1, 0, 0);
+ s.Cities["B"] = new City("B", 1, 1, 1, 0, 0);
+ s.Cities["a"] = new City("a", 1, 1, 1, 0, 0);
+ var text = s.Describe();
+ Assert.True(text.IndexOf("\n B=", StringComparison.Ordinal) < text.IndexOf("\n a=", StringComparison.Ordinal));
+ Assert.True(text.IndexOf("\n a=", StringComparison.Ordinal) < text.IndexOf("\n b=", StringComparison.Ordinal));
+ }
+}
diff --git a/sim/Statecraft.Sim.Tests/GoldenManifestTests.cs b/sim/Statecraft.Sim.Tests/GoldenManifestTests.cs
index 01a7e44e8..9486e8984 100644
--- a/sim/Statecraft.Sim.Tests/GoldenManifestTests.cs
+++ b/sim/Statecraft.Sim.Tests/GoldenManifestTests.cs
@@ -15,7 +15,7 @@ public class GoldenManifestTests
{
var m = GoldenManifest.Read();
var scenarios = System.IO.Directory.GetFiles(Scenario.Dir(), "*.yaml").Select(f => "scenario-" + System.IO.Path.GetFileNameWithoutExtension(f));
- var known = new[] { "hash1950", "hash1952", "smoke5" }.Concat(scenarios).OrderBy(k => k, StringComparer.Ordinal).ToArray(); // one line per scenario file (#296)
+ var known = new[] { "hash1950", "hash1952", "smoke5", "mvp-slice" }.Concat(scenarios).OrderBy(k => k, StringComparer.Ordinal).ToArray(); // one line per scenario file (#296)
Assert.Equal(known, m.Keys.OrderBy(k => k, StringComparer.Ordinal).ToArray());
Assert.All(m.Values, h => Assert.Matches("^[0-9a-f]{64}$", h));
}
diff --git a/sim/Statecraft.Sim.Tests/GoldenSnapshot.cs b/sim/Statecraft.Sim.Tests/GoldenSnapshot.cs
index 55464eae1..cc53d065a 100644
--- a/sim/Statecraft.Sim.Tests/GoldenSnapshot.cs
+++ b/sim/Statecraft.Sim.Tests/GoldenSnapshot.cs
@@ -36,6 +36,9 @@ public static class GoldenSnapshot
Assert.Fail(sb.ToString());
}
+ /// <summary>The committed snapshot of <paramref name="name"/>, with CRLF read as LF.</summary>
+ public static string Read(string name) => File.ReadAllText(Path_(name)).Replace("\r\n", "\n");
+
/// <summary>Changed lines between two descriptions, grouped by section (see <see cref="StateDiff"/>).</summary>
public static string Diff(string before, string after) => StateDiff.Lines(before, after);
}
diff --git a/sim/Statecraft.Sim.Tests/MvpGolden.cs b/sim/Statecraft.Sim.Tests/MvpGolden.cs
new file mode 100644
index 000000000..09f313c0d
--- /dev/null
+++ b/sim/Statecraft.Sim.Tests/MvpGolden.cs
@@ -0,0 +1,20 @@
+using System;
+using Statecraft.Sim;
+
+/// <summary>The GDD slice's golden (spec 2026-10-12 section 3; docs/determinism.md, "MVP goldens"): MvpSlice (the real content
+/// with the loop switch on and monthly turns), the golden seed, Historical mode and HistoricalAI, until Until. It covers only
+/// what is built: no GDD order is issued, so it needs no reference player (decision D-A7, with the owner) and no resolution
+/// order (D-A6).</summary>
+public static class MvpGolden
+{
+ /// <summary>Eight monthly turns from 15 May 1948. A test choice, not a balance value.</summary>
+ public static readonly DateTime Until = new DateTime(1949, 1, 15);
+
+ 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;
+ }
+}
diff --git a/sim/Statecraft.Sim.Tests/MvpGoldenTests.cs b/sim/Statecraft.Sim.Tests/MvpGoldenTests.cs
new file mode 100644
index 000000000..33ce219db
--- /dev/null
+++ b/sim/Statecraft.Sim.Tests/MvpGoldenTests.cs
@@ -0,0 +1,27 @@
+using System;
+using Statecraft.Sim;
+
+/// <summary>The mvp-slice golden: pinned in golden/manifest.txt with its snapshot, like the scenario goldens.</summary>
+public class MvpGoldenTests
+{
+ static readonly Content Mvp = MvpSlice.Load(RealContentTests.ContentRoot());
+
+ [Fact]
+ public void TheSliceMatchesItsGolden()
+ {
+ var s = MvpGolden.Play(Mvp);
+ Assert.Equal(new DateTime(1949, 1, 15), s.Date);
+ Assert.Equal(8, s.Turn);
+ var expected = GoldenManifest.UpdateRequested ? GoldenManifest.Read().GetValueOrDefault("mvp-slice", "") : GoldenManifest.Expected("mvp-slice");
+ GoldenSnapshot.Check("mvp-slice", s, expected);
+ }
+
+ [Fact]
+ public void TheSliceIsNotTheLegacyRun()
+ {
+ var legacy = ContentLoader.Load(RealContentTests.ContentRoot());
+ var s = Simulation.NewGame(legacy, GoldenRun.Seed, Mode.Historical);
+ while (s.Date < MvpGolden.Until) s = Simulation.Step(legacy, s, HistoricalAI.Commands(legacy, s)).State;
+ Assert.NotEqual(s.Hash(), MvpGolden.Play(Mvp).Hash());
+ }
+}
diff --git a/sim/Statecraft.Sim.Tests/MvpSliceTests.cs b/sim/Statecraft.Sim.Tests/MvpSliceTests.cs
new file mode 100644
index 000000000..23e417290
--- /dev/null
+++ b/sim/Statecraft.Sim.Tests/MvpSliceTests.cs
@@ -0,0 +1,69 @@
+using System;
+using System.Linq;
+using Statecraft.Sim;
+
+/// <summary>MvpSlice (GDD v0.1 Phase 1): the real content with the loop switch on and monthly turns, for tests, the MVP
+/// goldens and the dev flag. The real eras.yaml and rules.yaml keep the defaults until cutover.</summary>
+public class MvpSliceTests
+{
+ static readonly Content Real = ContentLoader.Load(RealContentTests.ContentRoot());
+ static readonly Content Mvp = MvpSlice.Load(RealContentTests.ContentRoot());
+
+ // R-LOOP-003
+ [Fact]
+ public void TheOverlayTurnsTheSwitchOnAndSetsMonthlyTurns()
+ {
+ Assert.False(Real.IsGdd);
+ 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); // different content: a save made on one warns on the other
+ }
+
+ // R-LOOP-003
+ [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.Rules.BudgetStart, Mvp.Rules.BudgetStart);
+ Assert.Equal(Real.Rules.CapitalInflowPerYear, Mvp.Rules.CapitalInflowPerYear);
+ Assert.Equal(Real.Eras.Select(e => (e.Id, e.Name, e.From, e.To, e.Systems.Legislature, string.Join(",", e.Systems.MapActions))),
+ Mvp.Eras.Select(e => (e.Id, e.Name, e.From, e.To, e.Systems.Legislature, string.Join(",", e.Systems.MapActions))));
+ Assert.Equal(Real.EraRules.Keys.OrderBy(k => k), Mvp.EraRules.Keys.OrderBy(k => k));
+ }
+
+ // R-LOOP-003
+ [Fact]
+ public void TheSlicePlaysMonthlyFromTheFifteenthOfMay1948()
+ {
+ var s = Simulation.NewGame(Mvp, GoldenRun.Seed, Mode.Historical);
+ var dates = new System.Collections.Generic.List<DateTime>();
+ for (int i = 0; i < 3; i++) { s = Simulation.Step(Mvp, s, HistoricalAI.Commands(Mvp, s)).State; dates.Add(s.Date); }
+ Assert.Equal(new[] { new DateTime(1948, 6, 15), new DateTime(1948, 7, 15), new DateTime(1948, 8, 15) }, dates);
+ }
+
+ [Fact]
+ public void TheOverlayKeepsAnEraSwitchAlreadySet()
+ {
+ var read = MvpSlice.Overlay(rel => rel == "eras.yaml"
+ ? "eras:\n - id: founding\n name: F\n from: 1948-05-15\n to: 1957-01-01\n systems: { legislature: assembly }\n"
+ : null);
+ var text = read("eras.yaml")!;
+ Assert.Contains("legislature: assembly", text);
+ Assert.Contains("loop: gdd", text);
+ Assert.Null(read("missing.yaml"));
+ }
+
+ [Fact]
+ public void LoadKeepsTheLoadersDirectoryChecks()
+ {
+ var dir = Fixture.Write();
+ System.IO.Directory.CreateDirectory(System.IO.Path.Combine(dir, "rules"));
+ System.IO.File.WriteAllText(System.IO.Path.Combine(dir, "rules", "nosuchera.yaml"), "attention_per_turn: 5\n");
+ var ex = Assert.Throws<ContentException>(() => MvpSlice.Load(dir));
+ Assert.Equal("rules/nosuchera.yaml", ex.File);
+ Assert.Contains("must be the id of an era", ex.Message);
+ }
+}
diff --git a/sim/Statecraft.Sim.Tests/SaveGameTests.cs b/sim/Statecraft.Sim.Tests/SaveGameTests.cs
index 1be401003..7460fffae 100644
--- a/sim/Statecraft.Sim.Tests/SaveGameTests.cs
+++ b/sim/Statecraft.Sim.Tests/SaveGameTests.cs
@@ -53,10 +53,11 @@ public class SaveGameTests
var c = Fixture1();
var text = Played(c).Save.Write();
var lines = text.Split('\n');
- Assert.Equal("statecraft-save 1", lines[0]);
+ Assert.Equal("statecraft-save 2", lines[0]);
Assert.Equal("content " + c.Hash, lines[1]);
Assert.Equal("seed 99", lines[2]);
Assert.Equal("mode Historical", lines[3]);
+ Assert.Equal("ruleset legacy", lines[4]);
Assert.Contains("policy rationing 3FD5555555555555", lines); // 1/3, bit for bit
Assert.Contains("policy odd%20id%20with%20spaces%25 3FE0000000000000", lines);
Assert.Contains("budget defense_minister=3FD0000000000000,finance_minister=3FE8000000000000", lines);
@@ -98,7 +99,7 @@ public class SaveGameTests
}
[Theory]
- [InlineData("statecraft-save 2", 1, "line 1: save schema version 2 is newer than this game (1)")]
+ [InlineData("statecraft-save 3", 1, "line 1: save schema version 3 is newer than this game (2)")]
[InlineData("statecraft-save x", 1, "line 1: bad schema version")]
[InlineData("chess-save 1", 1, "line 1: expected 'statecraft-save'")]
public void BadHeadersAreRejected(string first, int line, string message)
@@ -119,10 +120,10 @@ public class SaveGameTests
{
var c = Fixture1();
var lines = Played(c).Save.Write().Split('\n').ToList();
- lines.Insert(5, command); // after the first "turn"
+ lines.Insert(6, command); // after the first "turn" (schema 2: the ruleset line is line 5)
var ex = Assert.Throws<SaveException>(() => GameSession.Load(c, string.Join("\n", lines), out _));
- Assert.Equal(6, ex.Line);
- Assert.Equal("line 6: " + message, ex.Message);
+ Assert.Equal(7, ex.Line);
+ Assert.Equal("line 7: " + message, ex.Message);
}
[Fact]
@@ -186,7 +187,7 @@ public class SaveGameTests
Assert.Throws<ArgumentNullException>(() => g.Step(new Command[] { new Appoint(null!, "pm_one") }));
Assert.Throws<ArgumentNullException>(() => g.Step(new Command[] { new MapAction(null!, 1, 1) }));
Assert.Empty(g.Save.Turns); // nothing half-recorded
- Assert.StartsWith("statecraft-save 1", g.Save.Write());
+ Assert.StartsWith("statecraft-save 2\n", g.Save.Write());
}
[Fact]
@@ -282,9 +283,9 @@ public class SaveGameTests
{
var c = Fixture1();
var lines = Played(c).Save.Write().Split('\n').ToList();
- lines.Insert(5, command);
+ lines.Insert(6, command);
var ex = Assert.Throws<SaveException>(() => GameSession.Load(c, string.Join("\n", lines), out _));
- Assert.Equal("line 6: " + message, ex.Message);
+ Assert.Equal("line 7: " + message, ex.Message);
}
[Fact]
@@ -410,7 +411,7 @@ public class SaveGameTests
[Theory]
[InlineData("statecraft-save 0", "unknown save schema version 0")]
- [InlineData("statecraft-save 2", "save schema version 2 is newer than this game (1)")]
+ [InlineData("statecraft-save 3", "save schema version 3 is newer than this game (2)")]
[InlineData("statecraft-save -1", "bad schema version")]
public void SchemaVersionsOutsideOneAreRefused(string first, string message)
{
@@ -438,7 +439,7 @@ public class SaveGameTests
var g = GameSession.New(Fixture1(), 1, Mode.Historical);
Assert.Throws<ArgumentException>(() => g.Step(new Command[] { new Foreign() }));
g.Step(new Command[0]);
- Assert.StartsWith("statecraft-save 1", g.Save.Write());
+ Assert.StartsWith("statecraft-save 2\n", g.Save.Write());
Assert.Single(g.Save.Turns);
}
@@ -469,4 +470,68 @@ public class SaveGameTests
Assert.Equal("The budget names a ministry that does not exist in this game", live); // no id in player text (final review M4)
Assert.Equal(live, GameSession.Load(c, g.Save.Write(), out _).Last!.Rejected.Single().Reason);
}
+
+ // R-SAVE-001
+ [Fact]
+ public void AGddSaveNamesItsRulesetAndRoundTrips()
+ {
+ 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 var warnings).State.Hash());
+ Assert.Empty(warnings);
+ }
+
+ // R-SAVE-001
+ [Fact]
+ public void AVersionOneSaveReadsAsLegacyAndStillLoadsInTheLegacyGame()
+ {
+ var c = Fixture1();
+ var g = Played(c);
+ 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(c, v1, out _).State.Hash());
+ Assert.StartsWith("statecraft-save 2\n", SaveGame.Parse(v1).Write()); // written back as schema 2
+ Assert.Contains("\nruleset legacy\n", SaveGame.Parse(v1).Write());
+ }
+
+ // R-SAVE-001
+ [Fact]
+ public void AGddGameRefusesALegacySave()
+ {
+ var real = ContentLoader.Load(RealContentTests.ContentRoot());
+ var g = GameSession.New(real, 1, Mode.Historical);
+ g.Step(new Command[0]);
+ var gdd = MvpSlice.Load(RealContentTests.ContentRoot());
+ var ex = Assert.Throws<SaveException>(() => GameSession.Load(gdd, g.Save.Write(), out _));
+ Assert.Equal("This save was made with an earlier version of the game's rules; start a new game.", ex.Message);
+ var v1 = g.Save.Write().Replace("statecraft-save 2\n", "statecraft-save 1\n").Replace("ruleset legacy\n", "");
+ Assert.Equal(ex.Message, Assert.Throws<SaveException>(() => GameSession.Load(gdd, v1, out _)).Message);
+ }
+
+ // R-SAVE-001
+ [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.Equal("This save was made with another version of the game's rules; start a new game.", ex.Message);
+ }
+
+ [Theory]
+ [InlineData("ruleset chess", "unknown ruleset 'chess'")]
+ [InlineData("ruleset", "expected 'ruleset'")]
+ [InlineData("turn", "expected 'ruleset'")]
+ public void ABadRulesetLineIsRefused(string line, string message)
+ {
+ var text = "statecraft-save 2\ncontent " + Hex64('a') + "\nseed 1\nmode Historical\n" + line + "\nturn\nend " + Hex64('b') + "\n";
+ var ex = Assert.Throws<SaveException>(() => SaveGame.Parse(text));
+ Assert.Equal(5, ex.Line);
+ Assert.Contains(message, ex.Message);
+ }
}
diff --git a/sim/Statecraft.Sim.Tests/Scenario.cs b/sim/Statecraft.Sim.Tests/Scenario.cs
index 38588454a..9e8a0648f 100644
--- a/sim/Statecraft.Sim.Tests/Scenario.cs
+++ b/sim/Statecraft.Sim.Tests/Scenario.cs
@@ -56,17 +56,23 @@ public sealed class Scenario
static double Num(Dictionary<string, object> c, string key) =>
double.TryParse(Str(c, key), NumberStyles.Float, CultureInfo.InvariantCulture, out var d) ? d : throw new InvalidDataException($"command '{c["kind"]}': '{key}' must be a number");
- static Command Build(Dictionary<string, object> c)
+ /// <summary>The command kinds a scenario can script, with their fields (CommandGuardTests checks every kind is here).</summary>
+ static readonly Dictionary<string, string[]> Allowed = new Dictionary<string, string[]>
+ {
+ ["set_policy"] = new[] { "policy", "level" }, ["allocate_budget"] = new[] { "shares" },
+ ["choose_event_option"] = new[] { "event", "option" }, ["set_mobilization"] = new[] { "level" },
+ ["security_order"] = new[] { "delta" }, ["appoint"] = new[] { "office", "person" },
+ ["map_action"] = new[] { "action", "q", "r" },
+ };
+
+ public static IReadOnlyCollection<string> Kinds => Allowed.Keys;
+ internal static IReadOnlyList<string> FieldsOf(string kind) => Allowed[kind];
+
+ internal static Command Build(Dictionary<string, object> c)
{
if (!c.ContainsKey("kind")) throw new InvalidDataException("a command needs 'kind'");
var kind = Str(c, "kind");
- var allowed = new Dictionary<string, string[]>
- {
- ["set_policy"] = new[] { "policy", "level" }, ["allocate_budget"] = new[] { "shares" },
- ["choose_event_option"] = new[] { "event", "option" }, ["set_mobilization"] = new[] { "level" },
- ["security_order"] = new[] { "delta" }, ["appoint"] = new[] { "office", "person" },
- ["map_action"] = new[] { "action", "q", "r" },
- };
+ var allowed = Allowed;
if (!allowed.TryGetValue(kind, out var keys)) throw new InvalidDataException($"unknown command kind '{kind}' (known: {string.Join(", ", allowed.Keys)})");
var extra = c.Keys.Where(k => k != "kind" && !keys.Contains(k)).ToList();
if (extra.Count > 0) throw new InvalidDataException($"command '{kind}' has unknown field '{extra[0]}'");
@@ -80,7 +86,8 @@ public sealed class Scenario
case "set_mobilization": return new SetMobilization(Num(c, "level"));
case "security_order": return new SecurityOrder(Whole(c, "delta"));
case "appoint": return new Appoint(Str(c, "office"), Str(c, "person"));
- default: return new MapAction(Str(c, "action"), Whole(c, "q"), Whole(c, "r"));
+ case "map_action": return new MapAction(Str(c, "action"), Whole(c, "q"), Whole(c, "r"));
+ default: throw new InvalidDataException($"command kind '{kind}' has no builder");
}
}
diff --git a/sim/Statecraft.Sim.Tests/golden/manifest.txt b/sim/Statecraft.Sim.Tests/golden/manifest.txt
index 7dbc1dbf7..81504f46b 100644
--- a/sim/Statecraft.Sim.Tests/golden/manifest.txt
+++ b/sim/Statecraft.Sim.Tests/golden/manifest.txt
@@ -7,3 +7,4 @@ hash1952 62f8ec61a14acff4eab503381994a7c94d7a2f786dcfde5c4c19439ac8b4c5e8
smoke5 d3fdd459ddb876bd8d775c20edd1202cf56ca7134a8ad06f873d4d92034aa5b6
scenario-reckless c0bd12bc481a9f2dbeea19aebc981d5347caa1e1cf2e6fd5a5acdf107f2f9045
scenario-cautious 1d5b8d7126160021963537f2a198e377b27d478f522e8c6be63babe9e1b8f482
+mvp-slice 0451920a78852bcff49d435b04bb387543c33064090071195f8210a7bd8dcdc4
diff --git a/sim/Statecraft.Sim.Tests/golden/mvp-slice.txt b/sim/Statecraft.Sim.Tests/golden/mvp-slice.txt
new file mode 100644
index 000000000..038aa4957
--- /dev/null
+++ b/sim/Statecraft.Sim.Tests/golden/mvp-slice.txt
@@ -0,0 +1,81 @@
+1949-01-15;1948;Historical;8;
+ind{
+ food_supply=0.4 [3FD999999999999A]
+ housing=0.42228343009948727 [3FDB06B1147AE147]
+ intl_standing=0.53 [3FE0F5C28F5C28F6]
+ morale=0.6085614645767212 [3FE37955E47ECFEA]
+ security=0.48869177246093765 [3FDF46B9DB22D0E8]
+pol{
+ border_settlement=0.2 [3FC999999999999A]
+ housing_construction=0.3 [3FD3333333333333]
+ maabarot=0 [0000000000000000]
+ rationing=0 [0000000000000000]
+eff{
+ border_villages_secure=0.033691772460937505 [3FA1400C49BA5E36]
+ building_houses=0.0722834300994873 [3FB2812AB851EB85]
+ homes_lift_morale=0.06197826633453369 [3FAFBB9D85F06F69]
+ rationing_feeds=0 [0000000000000000]
+ rationing_grates=0 [0000000000000000]
+ safety_lifts_morale=0.04658319824218751 [3FA7D9C0C1FC8F34]
+shift{
+ food_supply=0 [0000000000000000]
+ housing=0 [0000000000000000]
+ intl_standing=0.030000000000000027 [3F9EB851EB851EC0]
+ morale=-0.050000000000000044 [BFA99999999999A0]
+ security=0.15500000000000014 [3FC3D70A3D70A3DC]
+bud{
+ agriculture_minister=0.07 [3FB1EB851EB851EC]
+ defense_minister=0.45 [3FDCCCCCCCCCCCCD]
+ education_minister=0.06 [3FAEB851EB851EB8]
+ finance_minister=0.05 [3FA999999999999A]
+ health_minister=0.07 [3FB1EB851EB851EC]
+ interior_minister=0.05 [3FA999999999999A]
+ labour_minister=0.1 [3FB999999999999A]
+ prime_minister=0.15 [3FC3333333333333]
+pop{
+ africa=9739.110001692712 [40C3058E1489145A]
+ america_oceania=535.0499244151753 [4080B8663EC59399]
+ asia=7512.155402122331 [40BD5827C86EF924]
+ europe=81633.61444656934 [40F3EE19D4C5ED07]
+ unknown=12145.947428858311 [40C7B8F945594CDE]
+ veterans=656752.739703733 [41240AE17ABA729C]
+sit[
+treasury=0 [0000000000000000]
+debt=26.348732976636185 [403A59469079B06C]
+fx=80.85238326859616 [4054368D728D91CC]
+rung=5;cf=40;
+mob=0.8 [3FE999999999999A]
+stab=0.6151384263401847 [3FE3AF36C7F49BA2]
+att=4 [4010000000000000]
+fired[
+ altalena
+ bernadotte_assassination
+ first_truce
+ idf_founding
+ jerusalem_ceasefire
+ jerusalem_military_government
+ latrun_proposal
+ operation_hiram
+ operation_horev
+ operation_yoav
+ second_truce
+ ten_days
+pending[
+ operation_horev
+chosen{
+ altalena=enforce
+ bernadotte_assassination=outlaw
+ first_truce=accept
+ idf_founding=one_army
+ jerusalem_ceasefire=sign
+ jerusalem_military_government=military_government
+ latrun_proposal=accept_vote
+ operation_hiram=launch
+ operation_yoav=stop_at_ceasefire
+ second_truce=comply
+ ten_days=central_front
+appt{
+under=;
+map[
+mapturn=0001-01-01:0;
+over=
\ No newline at end of file
diff --git a/sim/Statecraft.Sim/Content.cs b/sim/Statecraft.Sim/Content.cs
index 8d34df0d7..14a05a88f 100644
--- a/sim/Statecraft.Sim/Content.cs
+++ b/sim/Statecraft.Sim/Content.cs
@@ -51,6 +51,12 @@ namespace Statecraft.Sim
public string Legislature { get; set; } = State;
/// <summary>The map actions allowed in the era (transit_camp, housing). Absent means both. An empty list means none.</summary>
public List<string> MapActions { get; set; } = new List<string> { "transit_camp", "housing" };
+ public const string Legacy = "legacy";
+ public const string Gdd = "gdd";
+ /// <summary>`legacy`: today's game. `gdd`: the GDD v0.1 loop (docs/GDD.md), built behind this switch until cutover
+ /// (spec 2026-10-12 section 2.1). One value for the whole game: the loader refuses eras that differ, because a save
+ /// names one ruleset (section 2.4). R-LOOP-001.</summary>
+ public string Loop { get; set; } = Legacy;
}
public sealed class Party { public string Id { get; set; } = ""; public string Name { get; set; } = ""; }
@@ -437,6 +443,12 @@ namespace Statecraft.Sim
public Era? EraAt(DateTime date) => Eras.FirstOrDefault(e => date >= e.From && date < e.To);
/// <summary>The system switches in force on <paramref name="date"/>; the defaults outside every era.</summary>
public EraSystems SystemsAt(DateTime date) => EraAt(date)?.Systems ?? new EraSystems();
+ /// <summary>The game's loop (eras.yaml systems.loop, the same in every era): legacy or gdd. R-LOOP-001.</summary>
+ public string Loop => Eras.Count == 0 ? EraSystems.Legacy : Eras[0].Systems.Loop;
+ /// <summary>True when the GDD v0.1 loop runs.</summary>
+ public bool IsGdd => Loop == EraSystems.Gdd;
+ /// <summary>The ruleset a save names (SaveGame.Ruleset): "legacy" or "gdd-0.1".</summary>
+ public string Ruleset => IsGdd ? SaveGame.GddRuleset : SaveGame.LegacyRuleset;
public List<Indicator> Indicators = new List<Indicator>();
public List<Policy> Policies = new List<Policy>();
public List<Effect> Effects = new List<Effect>();
diff --git a/sim/Statecraft.Sim/ContentLoader.cs b/sim/Statecraft.Sim/ContentLoader.cs
index 1e2f1fd20..1d30d3312 100644
--- a/sim/Statecraft.Sim/ContentLoader.cs
+++ b/sim/Statecraft.Sim/ContentLoader.cs
@@ -264,17 +264,21 @@ namespace Statecraft.Sim
}
/// <summary>Loads content from a directory: every events/*.yaml file is an event.</summary>
- public static Content Load(string contentRoot)
+ public static Content Load(string contentRoot) => Load(contentRoot, read => read);
+
+ /// <summary>Loads content from a directory through <paramref name="wrap"/>, which may change the text of the files read
+ /// (MvpSlice.Overlay). The directory checks are the same as for <see cref="Load(string)"/>.</summary>
+ internal static Content Load(string contentRoot, Func<Func<string, string?>, Func<string, string?>> wrap)
{
var eventsDir = Path.Combine(contentRoot, "events");
var eventFiles = Directory.Exists(eventsDir)
? Directory.GetFiles(eventsDir, "*.yaml").Select(f => "events/" + Path.GetFileName(f)).ToList()
: new List<string>();
- var content = Load(rel =>
+ var content = Load(wrap(rel =>
{
var path = Path.Combine(contentRoot, rel);
return File.Exists(path) ? File.ReadAllText(path) : null;
- }, eventFiles);
+ }), eventFiles);
// Only this overload can list the directory. The readFile overload (WebGL) cannot, so a misnamed file is caught
// here and by RealContentTests before anything ships.
var rulesDir = Path.Combine(contentRoot, "rules");
@@ -807,6 +811,10 @@ namespace Statecraft.Sim
if (!MapActions.Actions.Contains(a)) throw new ContentException("eras.yaml", at + ".systems.map_actions", $"unknown map action '{a}' (transit_camp or housing)");
if (e.Systems.MapActions.Distinct().Count() != e.Systems.MapActions.Count)
throw new ContentException("eras.yaml", at + ".systems.map_actions", "lists an action twice");
+ 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)");
if (i == 0)
{
if (c.Rules.Start != default && e.From != c.Rules.Start) // a missing start is rules.yaml's own error
diff --git a/sim/Statecraft.Sim/GameSession.cs b/sim/Statecraft.Sim/GameSession.cs
index b5116fa6a..f210248c7 100644
--- a/sim/Statecraft.Sim/GameSession.cs
+++ b/sim/Statecraft.Sim/GameSession.cs
@@ -21,7 +21,7 @@ namespace Statecraft.Sim
{
if (c == null) throw new ArgumentNullException(nameof(c));
var s = Simulation.NewGame(c, seed, mode);
- return new GameSession(c, s, new SaveGame(c.Hash, seed, mode, s.Hash()));
+ return new GameSession(c, s, new SaveGame(c.Hash, seed, mode, c.Ruleset, s.Hash()));
}
/// <summary>Runs one turn and records it in the save.</summary>
@@ -40,6 +40,11 @@ namespace Statecraft.Sim
{
if (c == null) throw new ArgumentNullException(nameof(c));
var saved = SaveGame.Parse(saveText);
+ // R-SAVE-001: a save replays only under the rules it was played with (spec 2026-10-12 section 2.4, decision D-E4).
+ if (saved.Ruleset != c.Ruleset)
+ throw new SaveException(0, saved.Ruleset == SaveGame.LegacyRuleset
+ ? "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.");
var list = new List<string>();
bool sameContent = saved.ContentHash == c.Hash;
if (!sameContent) list.Add("This save was made with different game content; the replayed game may differ.");
diff --git a/sim/Statecraft.Sim/GameState.cs b/sim/Statecraft.Sim/GameState.cs
index fac730ff2..e0d82730f 100644
--- a/sim/Statecraft.Sim/GameState.cs
+++ b/sim/Statecraft.Sim/GameState.cs
@@ -55,6 +55,18 @@ namespace Statecraft.Sim
public int MapActionsThisTurn;
/// <summary>Why the game ended, as one of the <see cref="GameOverCodes"/>; null while it is on. Never display it: use PlayerText.GameOver.</summary>
public string? GameOver;
+ // GDD v0.1 state (spec 2026-10-12 section 2.2). Empty in the legacy loop, and then left out of the hash (R-LOOP-002).
+ /// <summary>The cities by id (ordinal).</summary>
+ public SortedDictionary<string, City> Cities = new SortedDictionary<string, City>(StringComparer.Ordinal);
+ /// <summary>The movable units by id.</summary>
+ public SortedList<int, Unit> Units = new SortedList<int, Unit>();
+ /// <summary>The next id a new unit takes. Ids are never reused.</summary>
+ public int NextId;
+ /// <summary>The date each completed objective was completed, by objective id (ordinal).</summary>
+ public SortedDictionary<string, DateTime> Objectives = new SortedDictionary<string, DateTime>(StringComparer.Ordinal);
+ /// <summary>The player's score (GDD "Objectives": bonus points). An int assumes whole-number points; the point values and
+ /// the timing bonus are open decisions with the owner (D-B2, D-B6), so the type is revisited when they are set.</summary>
+ public int Score;
public double TotalPopulation => Population.Values.Sum();
@@ -73,6 +85,9 @@ namespace Statecraft.Sim
c.ChosenOptions = new Dictionary<string, string>(ChosenOptions);
c.Appointments = new Dictionary<string, Appointment>(Appointments);
c.Placements = new List<Placement>(Placements);
+ c.Cities = new SortedDictionary<string, City>(Cities, StringComparer.Ordinal);
+ c.Units = new SortedList<int, Unit>(Units);
+ c.Objectives = new SortedDictionary<string, DateTime>(Objectives, StringComparer.Ordinal);
return c;
}
@@ -146,6 +161,21 @@ namespace Statecraft.Sim
Close(']');
Nl(); sb.Append("mapturn=").Append(MapActionsTurnDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)).Append(':').Append(MapActionsThisTurn).Append(';');
Nl(); sb.Append("over=").Append(GameOver ?? "");
+ // GDD v0.1 sections (spec 2026-10-12 section 2.4): each written only when set, so with the legacy loop the text
+ // above is the whole text, byte for byte. The over= line has no separator after it, so each section adds one.
+ // 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)); }
return sb.ToString();
}
}
diff --git a/sim/Statecraft.Sim/GddState.cs b/sim/Statecraft.Sim/GddState.cs
new file mode 100644
index 000000000..aece76639
--- /dev/null
+++ b/sim/Statecraft.Sim/GddState.cs
@@ -0,0 +1,44 @@
+using System.Globalization;
+
+namespace Statecraft.Sim
+{
+ /// <summary>A city in the GDD v0.1 loop (docs/GDD.md "Cities and construction"; owner decision D-A2: civilians and
+ /// refugees are counts per city). Counts are population units, each a group (D-A1). Immutable, so GameState.Clone can copy
+ /// the map shallowly; a change replaces the record. Only the attributes approved decisions define are here: housing
+ /// condition, craftsmen and recruits arrive with the decisions that define them.</summary>
+ public sealed class City
+ {
+ public string Id { get; }
+ /// <summary>How much population the city can house (GDD "Housing capacity").</summary>
+ public int HousingCapacity { get; }
+ /// <summary>The number of jobs (GDD "Employment slots").</summary>
+ public int JobSlots { get; }
+ public int Civilians { get; }
+ /// <summary>The civilians in jobs: part of <see cref="Civilians"/>, not in addition to them.</summary>
+ public int Employed { get; }
+ public int Refugees { get; }
+
+ public City(string id, int housingCapacity, int jobSlots, int civilians, int employed, int refugees)
+ {
+ Id = id; HousingCapacity = housingCapacity; JobSlots = jobSlots; Civilians = civilians; Employed = employed; Refugees = refugees;
+ }
+
+ /// <summary>The record as the state hash writes it.</summary>
+ public string Canonical() => string.Format(CultureInfo.InvariantCulture, "{0}={1},{2},{3},{4},{5}", Id, HousingCapacity, JobSlots, Civilians, Employed, Refugees);
+ }
+
+ /// <summary>A movable unit in the GDD v0.1 loop (owner decision D-A2: halutzim and soldiers are movable units), a group
+ /// (D-A1), on hex (Q, R). Immutable; a change replaces the record.</summary>
+ public sealed class Unit
+ {
+ public int Id { get; }
+ public string Type { get; }
+ public int Q { get; }
+ public int R { get; }
+
+ public Unit(int id, string type, int q, int r) { Id = id; Type = type; Q = q; R = r; }
+
+ /// <summary>The record as the state hash writes it.</summary>
+ public string Canonical() => string.Format(CultureInfo.InvariantCulture, "{0}:{1}@{2},{3}", Id, Type, Q, R);
+ }
+}
diff --git a/sim/Statecraft.Sim/MvpSlice.cs b/sim/Statecraft.Sim/MvpSlice.cs
new file mode 100644
index 000000000..c7db5e26c
--- /dev/null
+++ b/sim/Statecraft.Sim/MvpSlice.cs
@@ -0,0 +1,53 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using YamlDotNet.Serialization;
+
+namespace Statecraft.Sim
+{
+ /// <summary>The GDD v0.1 slice before cutover (spec 2026-10-12 section 2.1): the real content with the loop switch on
+ /// (eras.yaml systems.loop: gdd in every era) and monthly turns (rules.yaml turn_lengths all month). Tests, the MVP
+ /// goldens and the dev flag load it; the real eras.yaml and rules.yaml keep the defaults until cutover. It edits YAML
+ /// nodes, not text, so a comment or the key order in the real files cannot break it. Balance values the owner has not set
+ /// may live here, and never under content/ (controller ruling 2, 12 October 2026). R-LOOP-003.</summary>
+ public static class MvpSlice
+ {
+ static readonly IDeserializer Reader = new DeserializerBuilder().WithDuplicateKeyChecking().Build();
+ static readonly ISerializer Writer = new SerializerBuilder().Build();
+
+ /// <summary>Wraps <paramref name="readFile"/> (the loader's file reader): eras.yaml and rules.yaml come back with the
+ /// slice's switches, every other file unchanged.</summary>
+ 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);
+ if (root != null && root.TryGetValue("eras", out var list) && list is List<object> eras)
+ foreach (var item in eras.OfType<Dictionary<object, object>>())
+ {
+ var systems = item.TryGetValue("systems", out var x) && x is Dictionary<object, object> d ? d : new Dictionary<object, object>();
+ systems["loop"] = EraSystems.Gdd;
+ item["systems"] = systems;
+ }
+ return Writer.Serialize(root);
+ }
+ if (rel == "rules.yaml")
+ {
+ var root = Reader.Deserialize<Dictionary<object, object>>(text) ?? new Dictionary<object, object>();
+ root["turn_lengths"] = new List<object> { "month", "month", "month", "month", "month" };
+ return Writer.Serialize(root);
+ }
+ return text;
+ };
+ }
+
+ /// <summary>The content at <paramref name="contentRoot"/> (a directory laid out like content/) through <see cref="Overlay"/>,
+ /// with the same directory checks as ContentLoader.Load(string).</summary>
+ public static Content Load(string contentRoot) => ContentLoader.Load(contentRoot, Overlay);
+ }
+}
diff --git a/sim/Statecraft.Sim/SaveGame.cs b/sim/Statecraft.Sim/SaveGame.cs
index 72fc225e0..45985a62a 100644
--- a/sim/Statecraft.Sim/SaveGame.cs
+++ b/sim/Statecraft.Sim/SaveGame.cs
@@ -16,9 +16,10 @@ namespace Statecraft.Sim
/// <summary>
/// A save is seed + command log + content hash + schema version (spec section 3); loading replays it. Text format,
/// one item per line:
- /// statecraft-save 1 schema version
+ /// statecraft-save 2 schema version (a schema 1 save has no ruleset line and is legacy)
/// content &lt;hex&gt; Content.Hash of the content it was played with
/// seed &lt;ulong&gt; / mode Historical
+ /// ruleset legacy|gdd-0.1 the rules it was played under (Content.Ruleset); another ruleset refuses it (R-SAVE-001)
/// turn starts the next turn's command list (one per Simulation.Step)
/// &lt;command&gt; ... policy ID LEVEL | budget OFFICE=SHARE,... | event ID OPTION | mobilize LEVEL |
/// security DELTA | appoint OFFICE PERSON | map ACTION Q R
@@ -27,7 +28,11 @@ namespace Statecraft.Sim
/// </summary>
public sealed class SaveGame
{
- public const int SchemaVersion = 1;
+ public const int SchemaVersion = 2;
+ /// <summary>The ruleset of the legacy loop (Content.Ruleset).</summary>
+ public const string LegacyRuleset = "legacy";
+ /// <summary>The ruleset of the GDD v0.1 loop (eras.yaml systems.loop: gdd).</summary>
+ public const string GddRuleset = "gdd-0.1";
/// <summary>Turns are at least a week long, so 2000 turns is 38 years, far past any content; a save with more is hostile or damaged.</summary>
public const int MaxTurns = 2000;
const string Magic = "statecraft-save";
@@ -39,16 +44,19 @@ namespace Statecraft.Sim
public string ContentHash { get; }
public ulong Seed { get; }
public Mode Mode { get; }
+ /// <summary>The ruleset the game was played under: <see cref="LegacyRuleset"/> or <see cref="GddRuleset"/> (R-SAVE-001).</summary>
+ public string Ruleset { get; }
/// <summary>The recorded turns as new command objects each time it is read (changing them changes nothing in the save).</summary>
public IReadOnlyList<IReadOnlyList<Command>> Turns =>
turns.Select(t => (IReadOnlyList<Command>)t.Select(l => ParseCommand(0, l)).ToList().AsReadOnly()).ToList().AsReadOnly();
/// <summary>GameState.Hash() after the last recorded turn (the new game's hash before any turn).</summary>
public string FinalHash { get; private set; }
- public SaveGame(string contentHash, ulong seed, Mode mode, string initialHash)
+ public SaveGame(string contentHash, ulong seed, Mode mode, string ruleset, string initialHash)
{
ContentHash = contentHash ?? throw new ArgumentNullException(nameof(contentHash));
- Seed = seed; Mode = mode;
+ if (ruleset != LegacyRuleset && ruleset != GddRuleset) throw new ArgumentException($"unknown ruleset '{ruleset}'", nameof(ruleset));
+ Seed = seed; Mode = mode; Ruleset = ruleset;
FinalHash = initialHash ?? throw new ArgumentNullException(nameof(initialHash));
}
@@ -69,6 +77,7 @@ namespace Statecraft.Sim
sb.Append("content ").Append(ContentHash).Append('\n');
sb.Append("seed ").Append(Seed.ToString(CultureInfo.InvariantCulture)).Append('\n');
sb.Append("mode ").Append(Mode.ToString()).Append('\n');
+ sb.Append("ruleset ").Append(Ruleset).Append('\n');
foreach (var t in turns)
{
sb.Append("turn\n");
@@ -123,11 +132,20 @@ namespace Statecraft.Sim
if (!Enum.GetNames(typeof(Mode)).Contains(modeName)) throw new SaveException(4, "bad mode"); // names only: Enum.TryParse would accept "0"
var mode = (Mode)Enum.Parse(typeof(Mode), modeName);
if (mode == Mode.Open) throw new SaveException(4, "mode Open is not supported"); // Simulation.NewGame cannot start it before M4
+ var first = 4; // the first line after the header
+ var ruleset = LegacyRuleset;
+ if (version >= 2)
+ {
+ if (n < 6) throw new SaveException(0, "Not a Statecraft save (too short)");
+ ruleset = Head(4, "ruleset", 2)[1];
+ if (ruleset != LegacyRuleset && ruleset != GddRuleset) throw new SaveException(5, $"unknown ruleset '{ruleset}'");
+ first = 5;
+ }
var end = Head(n - 1, "end", 2)[1];
if (!IsHash(end)) throw new SaveException(n, "bad end hash");
- var save = new SaveGame(content, seed, mode, end);
+ var save = new SaveGame(content, seed, mode, ruleset, end);
List<string>? current = null;
- for (int i = 4; i < n - 1; i++)
+ for (int i = first; i < n - 1; i++)
{
if (lines[i] == "turn") { current = new List<string>(); save.turns.Add(current); continue; }
if (current == null) throw new SaveException(i + 1, "command before the first 'turn'");