A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Events: a soft event the cap leaves out fires on a later turn; objective cards take no soft slot (Fixes #2605) (#2611)
Eyal Golan95fe77ebd939
diff --git a/changelog.d/2605-soft-cap.md b/changelog.d/2605-soft-cap.mdnew file mode 100644index 000000000..4a70100f5--- /dev/null+++ b/changelog.d/2605-soft-cap.md@@ -0,0 +1,5 @@+### Fixed++- Keep soft events that exceed a turn's three-card cap waiting until a later free slot, and let objective cards fire without taking a slot.+ Saves now record the waiting events and are written as save schema 5. An older save still loads; if its game now plays+ out differently, it loads with the notice that some parts differ from the save, instead of being refused.diff --git a/docs/rules/mvp.md b/docs/rules/mvp.mdindex 5decbc521..7d23dabf4 100644--- a/docs/rules/mvp.md+++ b/docs/rules/mvp.md@@ -80,14 +80,16 @@ R-CTRL-022: `DeportNeverDominates` (impact plan section 4.1 item 5; Q-TECH-4 as## 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. A schema 1 save has no ruleset line and is legacy, so the GDD game refuses it as made under earlier rules. The refusal carries a code (`older_rules`) the UI translates, and the sim's reason does not itself ask for a new game: the player reads that once (N4). GDD 0.3 has its own ruleset, `gdd-0.3`, saved as schema 4 (#1687; owner ruling 26 October 2026: GDD 0.3 is built behind its own ruleset); `legacy` and `gdd-0.1` saves stay schema 3. A gdd-0.3 game refuses a `legacy` or `gdd-0.1` save as made under earlier rules (`older_rules`), before any replay. No content selects `gdd-0.3` yet, so the live game is unchanged.+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. A schema 1 save has no ruleset line and is legacy, so the GDD game refuses it as made under earlier rules. The refusal carries a code (`older_rules`) the UI translates, and the sim's reason does not itself ask for a new game: the player reads that once (N4). GDD 0.3 has its own ruleset, `gdd-0.3`, first saved as schema 4 (#1687; owner ruling 26 October 2026: GDD 0.3 is built behind its own ruleset), while `legacy` and `gdd-0.1` saves were schema 3; every ruleset now writes schema 5 (R-SAVE-005). A gdd-0.3 game refuses a `legacy` or `gdd-0.1` save as made under earlier rules (`older_rules`), before any replay. No content selects `gdd-0.3` yet, so the live game is unchanged.-R-SAVE-002: A save that names a ruleset this build does not know, or a newer save schema, was made by a newer version of the game and is refused with the code `newer_version` (N2). A `legacy` or `gdd-0.1` game refuses a `gdd-0.3` save the same way, and a schema 4 save naming `legacy` or `gdd-0.1` is newer too. A `gdd-0.3` save under schema 2 or 3 was never written by any build, so it is refused as damaged, with no code (#1687).+R-SAVE-002: A save that names a ruleset this build does not know, or a newer save schema, was made by a newer version of the game and is refused with the code `newer_version` (N2). A `legacy` or `gdd-0.1` game refuses a `gdd-0.3` save the same way, A `gdd-0.3` save under schema 2 or 3, and a schema 4 save naming `legacy` or `gdd-0.1`, were never written by any build, so they are refused as damaged, with no code (#1687, #2605).-R-SAVE-003: Save schema 3 adds the open turn: after the last `turn`, a line `open` and the turn in progress's committed orders (R-TURN-004), one a line (a waiting order there is refused: the save was edited); the `end` hash is still the state's after the last finished turn. Loading replays the turns, then commits the open orders again; one refused on the same content means the save is damaged (`SaveException`), and on other content the rest are dropped with the `replay_differs` warning. A schema 2 save has no open turn and loads as before (but see R-SAVE-004).+R-SAVE-003: Save schema 3 adds the open turn: after the last `turn`, a line `open` and the turn in progress's committed orders (R-TURN-004), one a line (a waiting order there is refused: the save was edited); the `end` hash is still the state's after the last finished turn. Loading replays the turns, then commits the open orders again; one refused on the same content means the save is damaged (`SaveException`), and on other content the rest are dropped with the `replay_differs` warning. A schema 2 save has no open turn and loads as before (but see R-SAVE-004). A save older than schema 5 is R-SAVE-005's.R-SAVE-004: A schema 2 save of the GDD game with a player attack (`order <unit> attack <q> <r>`) is refused with the code `older_rules` (R-SAVE-001): its attacks were standing orders, so it would replay differently (the owner, 23 October 2026: "Refuse with a clear message"). So is a schema 2 GDD save whose replay under the current rules does not end on its saved hash (instant capture, the full-points step). Other schema 2 saves load.+R-SAVE-005: Since #2605 the state records the soft events the cap left waiting (R-EVT-001), so every ruleset writes schema 5. An older save of a valid schema for its ruleset (1 to 3 for `legacy`, 2 to 3 for `gdd-0.1`, 4 for `gdd-0.3`; schema 1 has no ruleset line, so it is `legacy`) still loads, and is written back as schema 5. #2536's exception for a finished game without its ending cards applies to such a save only. It was played under the earlier cap, so with the same content a replay that does not end on its saved hash, or an open-turn order the replay now refuses, is the rules' change, not damage: it loads with the `replay_differs` warning. R-SAVE-004's schema 2 refusals come first. A schema 5 save that does either on the same content is damaged (`SaveException`).+## CitiesEach GDD turn resolves in the order of the approved plan's section 2.3 (decision D-A6): production, then housing and Social cohesion, then arrivals.@@ -408,7 +410,7 @@ R-OBJ-001: An objective (`objectives.yaml`) names its condition, `completes_whenR-OBJ-002: Recording a standalone objective adds `objective_points + min(objective_bonus_cap, objective_bonus_per_month * monthsEarly)` to the score, once. `monthsEarly` is `max(0, monthsFromHistory)`, and `monthsFromHistory` counts calendar months from the completion's month to the reference date's month, `(y2 - y1) * 12 + (m2 - m1)`: 0 in the same month ("on time, as in history"), negative when late (owner's card wording, #379, 14 October 2026). Late costs nothing. The owner set 100 points (D-B6) and +5 a month capped at +60 (D-B2) on 14 October 2026 (#456); they are balance values and stay tunable, as `rules.yaml` design values (R-LOOP-005). R-OBJ-006 says when a multipart objective receives the same base. The rules are those of the date the turn starts from (docs/determinism.md, "Rules per era"), so a turn that ends on the next era's first day scores with the era it started in.-R-OBJ-003: An event with `objective:` is that objective's card. It is eligible only once its objective is recorded, so it fires once, at the end of the turn the objective is completed in, and never in the legacy loop. That holds on the turn that ends the game too (the dated end of R-LOOP-004, or a defeat): its objective cards, and the card of any objective recorded earlier that the soft-event cap held back (R-EVT-001), fire then, without the cap, and no other event does; and Unity shows them before the end screen (owner, 4 November 2026, #2536: "Show the card (Recommended)"). Answering one there is no order and changes nothing: the score is the one step 11 recorded. A card has exactly one option, and an objective and its card name each other (the loader checks both). An unanswered card resolves to its option without drawing from the RNG.+R-OBJ-003: An event with `objective:` is that objective's card. It is eligible only once its objective is recorded, so it fires once, at the end of the turn the objective is completed in, and never in the legacy loop. It takes no soft-event slot, like a Deport card (owner, 4 November 2026, #2605: "Always that turn (Recommended)"). That holds on the turn that ends the game too (the dated end of R-LOOP-004, or a defeat): its objective cards, and the card of any objective recorded earlier that has not fired yet, fire then, without the cap, and no other event does; and Unity shows them before the end screen (owner, 4 November 2026, #2536: "Show the card (Recommended)"). Answering one there is no order and changes nothing: the score is the one step 11 recorded. A card has exactly one option, and an objective and its card name each other (the loader checks both). An unanswered card resolves to its option without drawing from the RNG.R-OBJ-004: An objective may instead name `completes_when: { absorbed: { population_at_least, overflow_at_most, employed_at_least } }` (D-B4; owner, 18 October 2026, #738, option (a)). It holds at step 11 once the Jewish population (`GameState.TotalPopulation`, the national count as step 11 reads it, before the turn's population step) is at or above `population_at_least`, and then the cities' overflow (R-HOUSE-002), summed, is at most `overflow_at_most` of their housed people (R-HOUSE-003), summed, and their employed, summed, are at least `employed_at_least` of their civilians and craftsmen, summed (as R-CITY-005 counts them; owner, 3 November 2026, #1714: "Both rulesets (Recommended)", so gdd-0.1 and gdd-0.3 alike). Refugees waiting do not count: each turn's arrivals (step 9) wait at step 11, after housing (step 8). The gate keeps the census start values (41% employed, no overflow) from completing it on the first turn. Sums are integers, compared with the decimal share, so city order cannot change the result. An objective names exactly one kind; all three keys are required (a missing key is never read as 0), the shares are from 0 to 1 and the population above 0 (the loader). Recorded and scored as R-OBJ-001 and R-OBJ-002 say; its card follows R-OBJ-003.@@ -548,7 +550,7 @@ R-EFX-009: Under gdd-0.3 only, an option's `debt_dollars` (US$ millions) also adD-H1 in the GDD loop (GDD Phase 7 PR 1, #805). The owner took the plan's recommendations for Q-EVT-1 to Q-EVT-4 on 17 October 2026 (#784). As the plan's Decided rows record them (`docs/superpowers/plans/2026-10-15-gdd-phase-7.md`), that keeps windows, hard anchors and the cap of 3 soft events a turn, keeps delegation, adds no delayed effects in the MVP, and shows every effect of every option from the sim's preview. These rules state what the code already does; no behaviour changed. On 18 October 2026 the owner added loyalty to delegation (#107: "Yes: minister loyalty changes a delegated event's outcome, with labelled values in the PR"); R-EVT-003 states it, with two design values (`delegation_loyalty_floor`, `disloyal_effect_share`).-R-EVT-001: An event fires on the first turn whose span overlaps its window `[from, to)` (or at the new game, when the start date is in it), once its `requires` is met and its conditions hold; an objective's card also waits for its objective (R-OBJ-003). Every eligible hard anchor fires. At most 3 soft events fire a turn (`EventSystem.MaxSoftEventsPerTurn`); they take the slots the hard anchors leave, `max(0, 3 - hard anchors)`, and the rest wait for a later turn (Q-CUT-6).+R-EVT-001: An event fires on the first turn whose span overlaps its window `[from, to)` (or at the new game, when the start date is in it), once its `requires` is met and its conditions hold; an objective's card also waits for its objective (R-OBJ-003). Every eligible hard anchor fires. At most 3 soft events fire a turn (`EventSystem.MaxSoftEventsPerTurn`), apart from the cards R-OBJ-003 and R-EVT-007 say take no slot; ordinary soft events take the slots the hard anchors leave, `max(0, 3 - hard anchors)`, and the rest wait for the first later turn with a free slot, even after their window has ended (Q-CUT-6; owner, 4 November 2026, #2605: "Show it late (Recommended)"). A waiting event's normal eligibility gates, including its conditions, are evaluated again when it can fire.R-EVT-002: The soft events take the free slots in order: an early armistice first (`front_quiet`, R-WAR-008; Q-EVT-1, Q-OBJ-1), then consequence cards (R-ALT-008), then the rest; within each group by `from`, then `order` (R-EVT-006), then id (ordinal). So two fronts that turn quiet on the same turn come in a stable order, and the cap of 3 still holds. With no early armistice eligible the order is unchanged.diff --git a/sim/Statecraft.Sim.Tests/EventRulesGddTests.cs b/sim/Statecraft.Sim.Tests/EventRulesGddTests.csindex 6f7453e71..ea20e8d58 100644--- a/sim/Statecraft.Sim.Tests/EventRulesGddTests.cs+++ b/sim/Statecraft.Sim.Tests/EventRulesGddTests.cs@@ -52,15 +52,146 @@ public class EventRulesGddTestsAssert.Equal(3, EventSystem.MaxSoftEventsPerTurn);for (int i = 0; i < Run.Count; i++){- var soft = FiredOn(i).Where(e => e.Anchor != "hard").Select(e => e.Id).ToList();- var hard = FiredOn(i).Count(e => e.Anchor == "hard");+ // R-OBJ-003, R-EVT-007: objective and Deport cards take no slot. R-WAR-008: an armistice before its date is soft.+ bool Slotless(GameEvent e) => e.Objective != "" || e.Deported != "";+ bool Hard(GameEvent e) => e.Anchor == "hard" && !(e.FrontQuiet != "" && Run[i].Date < e.From);+ var soft = FiredOn(i).Where(e => !Slotless(e) && !Hard(e)).Select(e => e.Id).ToList();+ var hard = FiredOn(i).Count(e => !Slotless(e) && Hard(e));// the soft events take only the slots the hard anchors leaveAssert.True(soft.Count <= Math.Max(0, EventSystem.MaxSoftEventsPerTurn - hard), $"{Run[i].Date:yyyy-MM-dd}: {hard} hard, soft {string.Join(", ", soft)}");}}- static string Soft(string id, string from) =>- $"id: {id}\ntitle: '{id}'\ntext: Something happens.\nfrom: {from}\noptions:\n - id: ok\n text: Accept\n historical: true\n";+ static string Soft(string id, string from, string? to = null) =>+ $"id: {id}\ntitle: '{id}'\ntext: Something happens.\nfrom: {from}\n" ++ (to == null ? "" : $"to: {to}\n") ++ "options:\n - id: ok\n text: Accept\n historical: true\n";++ // R-EVT-001 (#2605): red before the fix because d's finite window has closed by the second Trigger, so it is lost.+ // Trigger is the shared path: the same wait and once-only result holds for legacy, gdd-0.1 and gdd-0.3 identities.+ [Theory]+ [InlineData(SaveGame.LegacyRuleset)]+ [InlineData(SaveGame.GddRuleset)]+ [InlineData(SaveGame.Gdd03Ruleset)]+ public void CappedFiniteWindowEventWaitsAcrossEveryRuleset(string ruleset)+ {+ var c = ContentLoader.Load(Fixture.Write(events: new Dictionary<string, string>+ {+ ["a.yaml"] = Soft("a", "1948-05-15", "1948-05-22"),+ ["b.yaml"] = Soft("b", "1948-05-15", "1948-05-22"),+ ["c.yaml"] = Soft("c", "1948-05-15", "1948-05-22"),+ ["d.yaml"] = Soft("d", "1948-05-15", "1948-05-22"),+ }));+ c.Eras[0].Systems.Loop = ruleset == SaveGame.LegacyRuleset ? EraSystems.Legacy : EraSystems.Gdd;+ c.Eras[0].Systems.Ruleset = ruleset;+ var s = new GameState(c) { Date = new DateTime(1948, 5, 22) };++ EventSystem.Trigger(c, s, new List<Cause>(), new DateTime(1948, 5, 15));+ Assert.Equal(new[] { "a", "b", "c" }, s.PendingEvents);+ Assert.Equal(new[] { "d" }, s.CappedEvents);++ s.PendingEvents.Clear();+ s.Date = new DateTime(1948, 5, 29);+ EventSystem.Trigger(c, s, new List<Cause>(), new DateTime(1948, 5, 22));+ Assert.Equal(new[] { "d" }, s.PendingEvents);+ Assert.Empty(s.CappedEvents);++ s.PendingEvents.Clear();+ s.Date = new DateTime(1948, 6, 5);+ EventSystem.Trigger(c, s, new List<Cause>(), new DateTime(1948, 5, 29));+ Assert.Empty(s.PendingEvents);+ Assert.Equal(4, s.FiredEvents.Count); // the late event fired once+ }++ // R-EVT-001 (#2605): red before the fix because no capped-out state exists to survive replaying a save.+ [Fact]+ public void SaveRoundTripKeepsTheCappedEventSet()+ {+ var c = ContentLoader.Load(Fixture.Write(events: new Dictionary<string, string>+ {+ ["a.yaml"] = Soft("a", "1948-05-15", "1948-05-16"),+ ["b.yaml"] = Soft("b", "1948-05-15", "1948-05-16"),+ ["c.yaml"] = Soft("c", "1948-05-15", "1948-05-16"),+ ["d.yaml"] = Soft("d", "1948-05-15", "1948-05-16"),+ }));+ var played = GameSession.New(c, 1, Mode.Historical);+ Assert.Equal(new[] { "d" }, played.State.CappedEvents);++ var loaded = GameSession.Load(c, played.Save.Write(), out var warnings);+ Assert.Empty(warnings);+ Assert.Equal(played.State.CappedEvents, loaded.State.CappedEvents);+ Assert.Equal(played.State.Hash(), loaded.State.Hash());+ }++ // R-EVT-001 (#2605): a waiting event is past only the date gate; its conditions still have to hold when it fires.+ [Fact]+ public void CappedEventRechecksItsConditions()+ {+ var conditioned = Soft("d", "1948-05-15", "1948-05-22").Replace("options:", "conditions: [{ indicator: food_supply, max: 0.5 }]\noptions:");+ var c = ContentLoader.Load(Fixture.Write(events: new Dictionary<string, string>+ {+ ["a.yaml"] = Soft("a", "1948-05-15", "1948-05-22"),+ ["b.yaml"] = Soft("b", "1948-05-15", "1948-05-22"),+ ["c.yaml"] = Soft("c", "1948-05-15", "1948-05-22"),+ ["d.yaml"] = conditioned,+ }));+ var s = new GameState { Date = new DateTime(1948, 5, 22) };+ EffectsSystem.Init(c, s);+ EventSystem.Trigger(c, s, new List<Cause>(), new DateTime(1948, 5, 15));+ Assert.Equal(new[] { "d" }, s.CappedEvents);++ s.PendingEvents.Clear(); s.Date = new DateTime(1948, 5, 29); s.Indicators["food_supply"] = 0.9;+ EventSystem.Trigger(c, s, new List<Cause>(), new DateTime(1948, 5, 22));+ Assert.Empty(s.PendingEvents); Assert.Equal(new[] { "d" }, s.CappedEvents);++ s.Date = new DateTime(1948, 6, 5); s.Indicators["food_supply"] = 0.4;+ EventSystem.Trigger(c, s, new List<Cause>(), new DateTime(1948, 5, 29));+ Assert.Equal(new[] { "d" }, s.PendingEvents); Assert.Empty(s.CappedEvents);+ }++ // R-OBJ-003 (#2605): red before the fix because only the three ordinary soft events take the three slots and all+ // four same-turn objective cards are held back. Objective cards are ordered after the ordinary events as before.+ // R-OBJ-003: a hard-anchored objective card takes no soft slot and leaves the three slots to the ordinary soft events.+ [Fact]+ public void AHardObjectiveCardLeavesAllThreeSoftSlots()+ {+ var c = ContentLoader.Load(Fixture.Write());+ var s = Simulation.NewGame(c, 1, Mode.Historical);+ c.Objectives.Add(new Objective { Id = "objective_h", Card = "card_h" });+ c.Events.Add(new GameEvent { Id = "card_h", Title = "objective_h", Text = "Done.", From = s.Date, Objective = "objective_h", Anchor = "hard",+ Options = new List<EventOption> { new EventOption { Id = "ok", Text = "Continue", Historical = true } } });+ s.Objectives["objective_h"] = s.Date;+ for (int i = 0; i < 3; i++)+ c.Events.Add(new GameEvent { Id = "soft_" + i, Title = "soft", Text = "Soft.", From = s.Date,+ Options = new List<EventOption> { new EventOption { Id = "ok", Text = "Continue", Historical = true } } });++ EventSystem.Trigger(c, s, new List<Cause>());++ Assert.Equal(new[] { "soft_0", "soft_1", "soft_2", "card_h" }, s.PendingEvents.OrderBy(x => x == "card_h" ? 1 : 0).ToArray());+ Assert.Empty(s.CappedEvents);+ }+ [Fact]+ public void FourObjectiveCardsDoNotTakeTheThreeSoftSlots()+ {+ var c = ContentLoader.Load(Fixture.Write());+ var s = Simulation.NewGame(c, 1, Mode.Historical);+ for (int i = 0; i < 4; i++)+ {+ var id = "objective_" + i;+ c.Objectives.Add(new Objective { Id = id, Card = "card_" + i });+ c.Events.Add(new GameEvent { Id = "card_" + i, Title = id, Text = "Done.", From = s.Date, Objective = id,+ Options = new List<EventOption> { new EventOption { Id = "ok", Text = "Continue", Historical = true } } });+ s.Objectives[id] = s.Date; // all four completed on this turn+ }+ for (int i = 0; i < 3; i++)+ c.Events.Add(new GameEvent { Id = "soft_" + i, Title = "soft", Text = "Soft.", From = s.Date,+ Options = new List<EventOption> { new EventOption { Id = "ok", Text = "Continue", Historical = true } } });++ EventSystem.Trigger(c, s, new List<Cause>());++ Assert.Equal(new[] { "soft_0", "soft_1", "soft_2", "card_0", "card_1", "card_2", "card_3" }, s.PendingEvents);+ Assert.Empty(s.CappedEvents);+ }// R-EVT-001: the soft events take only the slots the hard anchors leave. With 1 hard anchor and 3 soft events// eligible on one turn, exactly 2 soft events fire (the mvp-end run has no such turn, so a fixture pins it).diff --git a/sim/Statecraft.Sim.Tests/GameSessionTurnTests.cs b/sim/Statecraft.Sim.Tests/GameSessionTurnTests.csindex 1e1d2c336..8b76424c4 100644--- a/sim/Statecraft.Sim.Tests/GameSessionTurnTests.cs+++ b/sim/Statecraft.Sim.Tests/GameSessionTurnTests.cs@@ -121,7 +121,7 @@ public class GameSessionTurnTestspublic void ASchema2SaveWithAnAttackIsRefusedAsOlderRules(){var session = Fresh();- var text = session.Save.Write().Replace("statecraft-save 3", "statecraft-save 2")+ var text = session.Save.Write().Replace("statecraft-save 5", "statecraft-save 2").Replace("end ", "turn\norder 0 attack 10 10\nend ");var e = Assert.Throws<SaveException>(() => GameSession.Load(C, text, out _));Assert.Equal(SaveException.OlderRules, e.Code);@@ -163,15 +163,31 @@ public class GameSessionTurnTeststhrow new InvalidOperationException("precondition: no attack is possible at the start");}- // R-SAVE-004: a schema 2 GDD save that does not replay to its saved hash gets the clear older-rules message; a schema 3- // one that does not is still damaged (no code).+ // R-SAVE-004: a schema 2 GDD save that does not replay to its saved hash gets the clear older-rules message. #2605: a+ // schema 3 one was played before the soft-event cap kept left-out events waiting, so it loads with replay_differs; a+ // current (schema 5) one that does not is still damaged (no code).[Fact]public void ASchema2SaveThatReplaysDifferentlyIsRefusedAsOlderRules(){static string WrongEnd(string text) { var end = text.Substring(text.LastIndexOf("end ", StringComparison.Ordinal) + 4, 64); return text.Replace("end " + end, "end " + new string('0', 64)); }- var two = WrongEnd(Fresh().Save.Write().Replace("statecraft-save 3", "statecraft-save 2"));+ var two = WrongEnd(Fresh().Save.Write().Replace("statecraft-save 5", "statecraft-save 2"));Assert.Equal(SaveException.OlderRules, Assert.Throws<SaveException>(() => GameSession.Load(C, two, out _)).Code);- var three = WrongEnd(Fresh().Save.Write());- Assert.Null(Assert.Throws<SaveException>(() => GameSession.Load(C, three, out _)).Code);+ var three = WrongEnd(Fresh().Save.Write().Replace("statecraft-save 5", "statecraft-save 3"));+ GameSession.Load(C, three, out var warnings);+ Assert.Equal(new[] { GameSession.ReplayDiffers }, warnings);+ var five = WrongEnd(Fresh().Save.Write());+ Assert.StartsWith("statecraft-save 5\n", five);+ Assert.Null(Assert.Throws<SaveException>(() => GameSession.Load(C, five, out _)).Code);+ }++ // #2605: the same for a refused open-turn order. A schema 3 save's open turn follows a replay under the earlier soft-event+ // cap, so an order the new replay refuses loads with replay_differs; in a current save it is damage.+ [Fact]+ public void ASchema3SaveWhoseOpenOrderIsRefusedLoadsWithReplayDiffers()+ {+ var bad = Fresh().Save.Write().Replace("end ", "open\nmove 999 1 1\nend ");+ Assert.Throws<SaveException>(() => GameSession.Load(C, bad, out _));+ GameSession.Load(C, bad.Replace("statecraft-save 5", "statecraft-save 3"), out var warnings);+ Assert.Equal(new[] { GameSession.ReplayDiffers }, warnings);}}diff --git a/sim/Statecraft.Sim.Tests/Gdd03ArmisticeOfferTests.cs b/sim/Statecraft.Sim.Tests/Gdd03ArmisticeOfferTests.csindex 23f73c6d5..efbf55317 100644--- a/sim/Statecraft.Sim.Tests/Gdd03ArmisticeOfferTests.cs+++ b/sim/Statecraft.Sim.Tests/Gdd03ArmisticeOfferTests.cs@@ -151,6 +151,38 @@ options:Assert.Equal(pending, Fire(c, again));}+ // R-EVT-001 (#2605), R-WAR-008: an early armistice is soft, so when hard anchors take every slot it waits with the other+ // soft events left out. It comes on the next turn its front is still quiet, ahead of them, and leaves the wait. If the+ // front was engaged meanwhile it stays out: the wait keeps a card past its window, not past its other gates.+ [Fact]+ public void R_EVT_001_AnEarlyArmisticeTheCapLeavesOutWaitsForItsQuietFront()+ {+ var c = Load();+ foreach (var id in new[] { "h1", "h2", "h3" })+ c.Events.Add(new GameEvent+ {+ Id = id, Title = id, Anchor = "hard", From = new DateTime(1948, 12, 1),+ Options = new List<EventOption> { new EventOption { Id = "ok", Text = "Ok" } },+ });+ var s = At(c, December15, 2, 0);+ Assert.Equal(new[] { "h1", "h2", "h3" }, Fire(c, s));+ Assert.Equal(new[] { "a1", "a2", "a3", "armistice_egypt" }, s.CappedEvents);++ var engaged = s.Clone();+ engaged.PendingEvents.Clear();+ engaged.Date = December15.AddDays(14);+ engaged.QuietTurns["egypt"] = 0;+ Assert.Equal(new[] { "a1", "a2", "a3" }, Fire(c, engaged));+ Assert.Contains("armistice_egypt", engaged.CappedEvents);++ var quiet = s.Clone();+ quiet.PendingEvents.Clear();+ quiet.Date = December15.AddDays(14);+ quiet.QuietTurns["egypt"] = 3;+ Assert.Equal(new[] { "armistice_egypt", "a1", "a2" }, Fire(c, quiet));+ Assert.Equal(new[] { "a3" }, quiet.CappedEvents);+ }+// R-EVT-001, R-WAR-008: the sourced hard-anchor date stays the card's ordinary path: on or after it, a front that is not// quiet still gets its card, as a hard anchor that takes no soft slot.[Fact]diff --git a/sim/Statecraft.Sim.Tests/Gdd03ArmisticeQuietTests.cs b/sim/Statecraft.Sim.Tests/Gdd03ArmisticeQuietTests.csindex fbfecaf87..942148a60 100644--- a/sim/Statecraft.Sim.Tests/Gdd03ArmisticeQuietTests.cs+++ b/sim/Statecraft.Sim.Tests/Gdd03ArmisticeQuietTests.cs@@ -188,7 +188,7 @@ options:Assert.Empty(ended.EngagedFronts);}- // R-WAR-005, R-SAVE-003, plan test 6: a save and reload between an instant attack and End turn, through a real schema-4+ // R-WAR-005, R-SAVE-003, plan test 6: a save and reload between an instant attack and End turn, through a real schema-5// save of the real content, rebuilds the fronts engaged in the open turn and gives the same hash, and End turn from both// gives the same counts and hash (the pattern of NoShotArmsSessionTests).[Fact]@@ -213,7 +213,7 @@ options:Assert.NotEmpty(engaged);var text = game.Save.Write();- Assert.StartsWith("statecraft-save 4", text);+ Assert.StartsWith("statecraft-save 5", text);var replay = GameSession.Load(c, text, out _);Assert.Equal(game.Now.State.EngagedFronts.ToArray(), replay.Now.State.EngagedFronts.ToArray());Assert.Equal(game.Now.State.Hash(), replay.Now.State.Hash());diff --git a/sim/Statecraft.Sim.Tests/Gdd03SaveTests.cs b/sim/Statecraft.Sim.Tests/Gdd03SaveTests.csindex b1ebc094e..e5a62cc66 100644--- a/sim/Statecraft.Sim.Tests/Gdd03SaveTests.cs+++ b/sim/Statecraft.Sim.Tests/Gdd03SaveTests.cs@@ -1,17 +1,18 @@using Statecraft.Sim;-/// <summary>#1687, R-SAVE-001/002: a separate envelope, never a live-loop cutover.</summary>+/// <summary>#1687, R-SAVE-001/002: a separate envelope, never a live-loop cutover. #2605: every ruleset now writes schema 5;+/// gdd-0.3 wrote 4 before, legacy 1 to 3 and gdd-0.1 2 to 3.</summary>public class Gdd03SaveTests{static string Text(int version, string ruleset) =>$"statecraft-save {version}\ncontent {new string('a', 64)}\nseed 1\nmode Historical\nruleset {ruleset}\nend {new string('b', 64)}\n";[Fact]- public void Gdd03WritesSchemaFourAndRoundTrips()+ public void Gdd03WritesSchemaFiveAndRoundTrips(){var save = new SaveGame(new string('a', 64), 1, Mode.Historical, "gdd-0.3", new string('b', 64));- Assert.Equal(4, save.Version);- Assert.StartsWith("statecraft-save 4\n", save.Write());+ Assert.Equal(5, save.Version);+ Assert.StartsWith("statecraft-save 5\n", save.Write());Assert.Equal("gdd-0.3", SaveGame.Parse(save.Write()).Ruleset);Assert.Equal(save.Write(), SaveGame.Parse(save.Write()).Write());}@@ -29,20 +30,41 @@ public class Gdd03SaveTests[Theory][InlineData(4, "gdd-future")]- [InlineData(5, "gdd-0.3")]- [InlineData(4, "legacy")]- [InlineData(4, "gdd-0.1")]+ [InlineData(6, "gdd-0.3")]+ [InlineData(6, "legacy")]+ [InlineData(6, "gdd-0.1")]public void UnknownRulesOrNewerSchemasAreRefused(int schema, string ruleset) =>Assert.Equal(SaveException.NewerVersion, Assert.Throws<SaveException>(() => SaveGame.Parse(Text(schema, ruleset))).Code);+ // #2605: schema 4 was gdd-0.3's alone; no build wrote it for the older rules, so such a save was edited.[Theory][InlineData("legacy")][InlineData("gdd-0.1")]- public void ExistingRulesStillWriteSchemaThree(string ruleset)+ public void OlderRulesUnderSchemaFourAreDamage(string ruleset) =>+ Assert.Null(Assert.Throws<SaveException>(() => SaveGame.Parse(Text(4, ruleset))).Code);++ [Theory]+ [InlineData("legacy")]+ [InlineData("gdd-0.1")]+ [InlineData("gdd-0.3")]+ public void EveryRulesetWritesSchemaFive(string ruleset){var save = new SaveGame(new string('a', 64), 1, Mode.Historical, ruleset, new string('b', 64));- Assert.Equal(3, save.Version);- Assert.StartsWith("statecraft-save 3\n", save.Write());+ Assert.Equal(5, save.Version);+ Assert.StartsWith("statecraft-save 5\n", save.Write());+ }++ // R-SAVE-005 (#2605): the earlier schema of each ruleset still reads, keeps its version, and is written back as schema 5.+ [Theory]+ [InlineData(3, "legacy")]+ [InlineData(3, "gdd-0.1")]+ [InlineData(4, "gdd-0.3")]+ public void AnEarlierSchemaReadsAndIsWrittenBackAsFive(int schema, string ruleset)+ {+ var save = SaveGame.Parse(Text(schema, ruleset));+ Assert.Equal(schema, save.Version);+ Assert.Equal(ruleset, save.Ruleset);+ Assert.StartsWith("statecraft-save 5\n", save.Write());}// R-SAVE-001/002: future gdd-0.3 callers must not replay the live rules' saves.@@ -51,6 +73,8 @@ public class Gdd03SaveTests[InlineData(3, "legacy")][InlineData(2, "gdd-0.1")][InlineData(3, "gdd-0.1")]+ [InlineData(5, "legacy")]+ [InlineData(5, "gdd-0.1")]public void EarlierRulesAreRefusedByGdd03(int schema, string ruleset){var error = Assert.Throws<SaveException>(() => SaveGame.Parse(Text(schema, ruleset), SaveGame.Gdd03Ruleset));@@ -59,18 +83,22 @@ public class Gdd03SaveTests}[Theory]- [InlineData("legacy")]- [InlineData("gdd-0.1")]- public void ExistingGamesRefuseGdd03AsNewer(string ruleset) =>- Assert.Equal(SaveException.NewerVersion, Assert.Throws<SaveException>(() => SaveGame.Parse(Text(4, "gdd-0.3"), ruleset)).Code);+ [InlineData(4, "legacy")]+ [InlineData(4, "gdd-0.1")]+ [InlineData(5, "legacy")]+ [InlineData(5, "gdd-0.1")]+ public void ExistingGamesRefuseGdd03AsNewer(int schema, string ruleset) =>+ Assert.Equal(SaveException.NewerVersion, Assert.Throws<SaveException>(() => SaveGame.Parse(Text(schema, "gdd-0.3"), ruleset)).Code);- [Fact]- public void Gdd03AcceptsItsOwnEnvelope() =>- Assert.Equal("gdd-0.3", SaveGame.Parse(Text(4, "gdd-0.3"), SaveGame.Gdd03Ruleset).Ruleset);+ [Theory]+ [InlineData(4)]+ [InlineData(5)]+ public void Gdd03AcceptsItsOwnEnvelope(int schema) =>+ Assert.Equal("gdd-0.3", SaveGame.Parse(Text(schema, "gdd-0.3"), SaveGame.Gdd03Ruleset).Ruleset);[Theory][InlineData(4, "gdd-future")]- [InlineData(5, "gdd-0.3")]+ [InlineData(6, "gdd-0.3")]public void Gdd03RefusesUnknownRulesAndFutureSchemas(int schema, string ruleset) =>Assert.Equal(SaveException.NewerVersion, Assert.Throws<SaveException>(() => SaveGame.Parse(Text(schema, ruleset), SaveGame.Gdd03Ruleset)).Code);}diff --git a/sim/Statecraft.Sim.Tests/LastTurnObjectiveCardTests.cs b/sim/Statecraft.Sim.Tests/LastTurnObjectiveCardTests.csindex 62c7fdfb8..52fd0016a 100644--- a/sim/Statecraft.Sim.Tests/LastTurnObjectiveCardTests.cs+++ b/sim/Statecraft.Sim.Tests/LastTurnObjectiveCardTests.cs@@ -159,15 +159,20 @@ public class LastTurnObjectiveCardTestsAssert.DoesNotContain(deport.Id, s.PendingEvents);}- // R-OBJ-003, R-EVT-001, R-LOOP-004: an objective recorded on the turn before the end whose card the soft-event cap held- // back (all objective cards are soft, and a hard card takes a slot) shows on the ending turn: there is no later turn for- // it to wait for. Only such cards fire then, uncapped. Fresh content: the test rewrites objectives and events in memory.+ // R-OBJ-003, R-EVT-001, R-LOOP-004: an objective recorded on the turn before the end whose card has not fired yet shows+ // on the ending turn: there is no later turn for it to wait for. Only such cards fire then, uncapped. Objective cards take+ // no soft slot (#2605), so the cap cannot hold one back: here the window does (a `from` the day after that turn's+ // trigger date), and the other objective cards fire on that turn although a hard card takes a slot. Fresh content: the+ // test rewrites objectives and events in memory.[Fact]- public void AnObjectiveCardTheCapHeldBackShowsOnTheEndingTurn()+ public void AnObjectiveCardNotYetFiredShowsOnTheEndingTurn(){var c = ContentLoader.Load(RealContentTests.ContentRoot());var twoBefore = BeforeTheEnd(c, turnsBefore: 2);twoBefore.PendingEvents.Clear();+ // The turn before the end triggers its events on this date (Simulation.Step moves the date, then triggers).+ var penultimateDate = Simulation.Step(c, twoBefore, Array.Empty<Command>()).State.Date;+ Assert.True(c.Objectives.Count >= 3, "precondition: at least three objectives, so two can be held back and one fire");var cards = new List<GameEvent>();foreach (var objective in c.Objectives)@@ -179,7 +184,8 @@ public class LastTurnObjectiveCardTests};twoBefore.Objectives.Remove(objective.Id);var card = c.Events.Single(e => e.Id == objective.Card);- card.From = twoBefore.Date;+ // The first two objectives' cards open the day after the turn before the end triggers; the rest open now.+ card.From = cards.Count < 2 ? penultimateDate.AddDays(1) : twoBefore.Date;card.To = null;card.Anchor = "soft";card.Requires.Clear();@@ -202,7 +208,9 @@ public class LastTurnObjectiveCardTestsAssert.Contains("fixture_penultimate_hard", penultimate.FiredEvents);Assert.All(c.Objectives, objective => Assert.Equal(penultimate.Date, penultimate.Objectives[objective.Id]));var heldBack = cards.Where(card => !penultimate.FiredEvents.Contains(card.Id)).Select(card => card.Id).ToArray();- Assert.True(heldBack.Length >= 2, "precondition: the cap held back at least two objective cards on the turn before the end");+ Assert.Equal(cards.Take(2).Select(card => card.Id).OrderBy(id => id, StringComparer.Ordinal),+ heldBack.OrderBy(id => id, StringComparer.Ordinal));+ Assert.Empty(penultimate.CappedEvents.Intersect(cards.Select(card => card.Id)));// An event open on the last turn that nothing else holds back, made unfired so it would be eligible then.var other = c.Events.First(e => e.Objective == "" && e.Site == "" && e.Prisoners == "" && e.Deported == ""@@ -261,7 +269,8 @@ public class LastTurnObjectiveCardTests/// <summary>#2536: a one-turn game over fresh content that ends on its first turn's boundary with the railway recorded/// then, so its card is the ending card. Returns the save as the new rules write it, and the same save with the final- /// hash the old rules wrote (the ending card neither fired nor pending).</summary>+ /// hash the old rules wrote (the ending card neither fired nor pending) and the schema they wrote it in (3, gdd-0.1;+ /// the current schema came later, #2605).</summary>static (Content c, string newSave, string oldSave) FinishedWithAnEndingCard(){var c = ContentLoader.Load(RealContentTests.ContentRoot());@@ -288,7 +297,8 @@ public class LastTurnObjectiveCardTestsvar newSave = g.Save.Write();var endLine = "end " + g.State.Hash();Assert.Contains(endLine + "\n", newSave);- return (c, newSave, newSave.Replace(endLine, "end " + old.Hash()));+ Assert.StartsWith("statecraft-save 5\n", newSave);+ return (c, newSave, newSave.Replace(endLine, "end " + old.Hash()).Replace("statecraft-save 5\n", "statecraft-save 3\n"));}// #2536: a game finished before the ending turn fired objective cards replays with its ending card added. That is the@@ -318,6 +328,16 @@ public class LastTurnObjectiveCardTestsAssert.Throws<SaveException>(() => GameSession.Load(c, wrong, out _));}+ // #2605 review: a current-schema save was written after #2536, so it always has its ending cards; one without them was+ // edited or damaged, and is refused like any other difference.+ [Fact]+ public void ACurrentSchemaSaveWithoutItsEndingCardIsRefused()+ {+ var (c, _, oldSave) = FinishedWithAnEndingCard();+ var edited = oldSave.Replace("statecraft-save 3\n", "statecraft-save 5\n");+ Assert.Null(Assert.Throws<SaveException>(() => GameSession.Load(c, edited, out _)).Code);+ }+// #2536: with other content the same save gives only content_changed, not replay_differs.[Fact]public void WithOtherContentAFinishedOldSaveGivesOnlyContentChanged()diff --git a/sim/Statecraft.Sim.Tests/NoAttentionTests.cs b/sim/Statecraft.Sim.Tests/NoAttentionTests.csindex 65ac66b60..b1b73bad4 100644--- a/sim/Statecraft.Sim.Tests/NoAttentionTests.cs+++ b/sim/Statecraft.Sim.Tests/NoAttentionTests.cs@@ -140,12 +140,12 @@ public class NoAttentionTestsg.State.Units[99]=new Unit(99,"recruit",1,0,side:"israel",strength:1);g.State.NextId=100;Assert.Null(g.Commit(new Move(99,2,0)));Assert.Equal(55,g.Now.State.Attention);g.EndTurn(Array.Empty<Command>());Assert.Equal(55,g.State.Attention);- var text=g.Save.Write();Assert.Equal(4,SaveGame.Parse(text,c.Ruleset).Version);+ var text=g.Save.Write();Assert.Equal(5,SaveGame.Parse(text,c.Ruleset).Version);// Use a fresh session without injected units for actual replay of an authored deferred command.var clean=GameSession.New(c,1,Mode.Historical);clean.Step(new[]{new AssignWorkers("town_a","job",1)});Assert.Equal(clean.State.Hash(),GameSession.Load(c,clean.Save.Write(),out _).State.Hash());}- [Fact] public void OpenTurnSchema4ReplaysWithoutInjectedStateAndRejectsTampering()+ [Fact] public void OpenTurnSchema5ReplaysWithoutInjectedStateAndRejectsTampering(){var files=Fixture.Gdd(new Dictionary<string,string> {["map/units_1948.yaml"]="units:\n- id: test_force\n service: army\n side: israel\n status: draft\n strength: { value: 1000, as_of: '1948-05-15' }\n anchors:\n - { place: Here, lon: 34.29, lat: 33.35, from: '1948-05-15', to: '1949-01-01' }\n",diff --git a/sim/Statecraft.Sim.Tests/NoShotArmsTests.cs b/sim/Statecraft.Sim.Tests/NoShotArmsTests.csindex 2b8f13eee..5f09eed03 100644--- a/sim/Statecraft.Sim.Tests/NoShotArmsTests.cs+++ b/sim/Statecraft.Sim.Tests/NoShotArmsTests.cs@@ -307,11 +307,11 @@ public class NoShotArmsTests}/// <summary>R-COMBAT-001, R-COMBAT-004 on the real content under gdd-0.3: an attack with an empty stock commits, replays-/// from a schema-4 save and is not fought again at End turn.</summary>+/// from a schema-5 save and is not fought again at End turn.</summary>public class NoShotArmsSessionTests{[Fact]- public void AZeroStockInstantAttackReplaysInSchemaFourAndIsNotRepeatedAtEndTurn()+ public void AZeroStockInstantAttackReplaysInSchemaFiveAndIsNotRepeatedAtEndTurn(){var root = RealContentTests.ContentRoot();var c = ContentLoader.Load(rel =>@@ -333,7 +333,7 @@ public class NoShotArmsSessionTestsAssert.Single(game.Now.Why, w => w.Key == WhyKeys.Engagement);var text = game.Save.Write();- Assert.StartsWith("statecraft-save 4", text);+ Assert.StartsWith("statecraft-save 5", text);var replay = GameSession.Load(c, text, out _);Assert.Equal(game.Now.State.Hash(), replay.Now.State.Hash());Assert.Single(replay.Committed);diff --git a/sim/Statecraft.Sim.Tests/PopulationLedgerTests.cs b/sim/Statecraft.Sim.Tests/PopulationLedgerTests.csindex ea7f6444f..596c45895 100644--- a/sim/Statecraft.Sim.Tests/PopulationLedgerTests.cs+++ b/sim/Statecraft.Sim.Tests/PopulationLedgerTests.cs@@ -131,7 +131,8 @@ public class PopulationLedgerTestsAssert.NotEqual(a.Hash(),b.Hash());}- // R-POP-001, R-POP-003, R-LOOP-002, R-CITY-001, R-CITY-008: old identities neither gain state nor accept helpers.+ // R-POP-001, R-POP-003, R-LOOP-002, R-CITY-001, R-CITY-008: old identities neither gain state nor accept helpers. Their+ // saves differ from gdd-0.3's only by the ruleset line (every ruleset writes schema 5 since #2605).[Theory] [InlineData("legacy")] [InlineData("gdd-0.1")]public void OldIdentitiesKeepCanonicalTextAndSaveBytes(string identity){@@ -140,7 +141,7 @@ public class PopulationLedgerTestsAssert.Throws<InvalidOperationException>(()=>s.PopulationLedger.RegisterArrival("ship",0,Person()));Assert.Equal(before,s.Describe()); Assert.Equal(before,s.Clone().Describe());var save = new SaveGame(new string('a',64),1,Mode.Historical,identity,new string('b',64));- Assert.Equal($"statecraft-save 3\ncontent {new string('a',64)}\nseed 1\nmode Historical\nruleset {identity}\nend {new string('b',64)}\n",save.Write());+ Assert.Equal($"statecraft-save 5\ncontent {new string('a',64)}\nseed 1\nmode Historical\nruleset {identity}\nend {new string('b',64)}\n",save.Write());}// R-POP-001, R-LOOP-005: no numeric fallback from the old common scale or Deferred start.army.diff --git a/sim/Statecraft.Sim.Tests/RulesetSelectorTests.cs b/sim/Statecraft.Sim.Tests/RulesetSelectorTests.csindex 19e6e1a40..748d73e80 100644--- a/sim/Statecraft.Sim.Tests/RulesetSelectorTests.cs+++ b/sim/Statecraft.Sim.Tests/RulesetSelectorTests.cs@@ -94,9 +94,9 @@ public class RulesetSelectorTests}[Theory]- [InlineData("legacy", null, "legacy", 3)]- [InlineData("gdd", null, "gdd-0.1", 3)]- [InlineData("gdd", "gdd-0.3", "gdd-0.3", 4)]+ [InlineData("legacy", null, "legacy", 5)]+ [InlineData("gdd", null, "gdd-0.1", 5)]+ [InlineData("gdd", "gdd-0.3", "gdd-0.3", 5)]public void SessionAndSaveCarrySelectedIdentity(string loop, string? selector, string expected, int schema){var c = Load(loop, selector);diff --git a/sim/Statecraft.Sim.Tests/SaveGameTests.cs b/sim/Statecraft.Sim.Tests/SaveGameTests.csindex afaee1477..06592142b 100644--- a/sim/Statecraft.Sim.Tests/SaveGameTests.cs+++ b/sim/Statecraft.Sim.Tests/SaveGameTests.cs@@ -58,10 +58,10 @@ public class SaveGameTestsvar save = new SaveGame(new string('a', 64), 7, Mode.Historical, SaveGame.GddRuleset, new string('b', 64));save.SetOpen(new Command[] { new Move(1, 2, 3), new UnitOrder(1, Orders.Hold) });var text = save.Write();- Assert.StartsWith("statecraft-save 3\n", text);+ Assert.StartsWith("statecraft-save 5\n", text);Assert.Contains("open\nmove 1 2 3\norder 1 hold\nend ", text);var back = SaveGame.Parse(text);- Assert.Equal(3, back.Version);+ Assert.Equal(5, back.Version);Assert.Equal(new[] { "move", "unit_order" }, back.Open.Select(x => x.Kind));}@@ -169,7 +169,7 @@ public class SaveGameTestsvar c = Fixture1();var text = Played(c).Save.Write();var lines = text.Split('\n');- Assert.Equal("statecraft-save 3", lines[0]);+ Assert.Equal("statecraft-save 5", lines[0]);Assert.Equal("content " + c.Hash, lines[1]);Assert.Equal("seed 99", lines[2]);Assert.Equal("mode Historical", lines[3]);@@ -215,7 +215,8 @@ public class SaveGameTests}[Theory]- [InlineData("statecraft-save 4", 1, "line 1: save schema version 4 is newer than this game (3)")]+ [InlineData("statecraft-save 6", 1, "line 1: save schema version 6 is newer than this game (5)")]+ [InlineData("statecraft-save 4", 1, "line 1: no version of the game wrote a legacy save in schema 4")][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)@@ -313,7 +314,7 @@ public class SaveGameTestsAssert.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 3\n", g.Save.Write());+ Assert.StartsWith("statecraft-save 5\n", g.Save.Write());}[Fact]@@ -572,7 +573,7 @@ public class SaveGameTests[Theory][InlineData("statecraft-save 0", "unknown save schema version 0")]- [InlineData("statecraft-save 4", "save schema version 4 is newer than this game (3)")]+ [InlineData("statecraft-save 6", "save schema version 6 is newer than this game (5)")][InlineData("statecraft-save -1", "bad schema version")]public void SchemaVersionsOutsideOneAreRefused(string first, string message){@@ -600,7 +601,7 @@ public class SaveGameTestsvar 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 3\n", g.Save.Write());+ Assert.StartsWith("statecraft-save 5\n", g.Save.Write());Assert.Single(g.Save.Turns);}@@ -640,7 +641,7 @@ public class SaveGameTestsvar g = GameSession.New(c, 1, Mode.Historical);g.Step(HistoricalAI.Commands(c, g.State));var text = g.Save.Write();- Assert.StartsWith("statecraft-save 3\n", text);+ Assert.StartsWith("statecraft-save 5\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());@@ -653,10 +654,10 @@ public class SaveGameTests{var c = Fixture1();var g = Played(c);- var v1 = g.Save.Write().Replace("statecraft-save 3\n", "statecraft-save 1\n").Replace("ruleset legacy\n", "");+ var v1 = g.Save.Write().Replace("statecraft-save 5\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 3\n", SaveGame.Parse(v1).Write()); // written back as the current schema+ Assert.StartsWith("statecraft-save 5\n", SaveGame.Parse(v1).Write()); // written back as the current schemaAssert.Contains("\nruleset legacy\n", SaveGame.Parse(v1).Write());}@@ -673,7 +674,7 @@ public class SaveGameTestsAssert.Equal(SaveException.OlderRules, ex.Code);Assert.Equal("This save was made with an earlier version of the game's rules.", ex.Message);Assert.DoesNotContain("new game", ex.Message);- var v1 = g.Save.Write().Replace("statecraft-save 3\n", "statecraft-save 1\n").Replace("ruleset legacy\n", "");+ var v1 = g.Save.Write().Replace("statecraft-save 5\n", "statecraft-save 1\n").Replace("ruleset legacy\n", "");var ex1 = Assert.Throws<SaveException>(() => GameSession.Load(real, v1, out _));Assert.Equal((ex.Code, ex.Message), (ex1.Code, ex1.Message));}@@ -691,8 +692,8 @@ public class SaveGameTestsAssert.Contains("This save was made with a newer version of the game", ex.Message);Assert.DoesNotContain("new game", ex.Message);Assert.Equal(SaveException.NewerVersion, Assert.Throws<SaveException>(() => GameSession.Load(real, text, out _)).Code);- var schema4 = text.Replace("statecraft-save 3\n", "statecraft-save 4\n");- Assert.Equal(SaveException.NewerVersion, Assert.Throws<SaveException>(() => SaveGame.Parse(schema4)).Code);+ var schema6 = text.Replace("statecraft-save 5\n", "statecraft-save 6\n");+ Assert.Equal(SaveException.NewerVersion, Assert.Throws<SaveException>(() => SaveGame.Parse(schema6)).Code);}// R-SAVE-001diff --git a/sim/Statecraft.Sim/EventSystem.cs b/sim/Statecraft.Sim/EventSystem.csindex dbff9e020..f2e4e2d92 100644--- a/sim/Statecraft.Sim/EventSystem.cs+++ b/sim/Statecraft.Sim/EventSystem.cs@@ -15,13 +15,13 @@ namespace Statecraft.Sim/// <summary>Fires every unfired event whose `requires` (if any) is met, whose window [From, To) overlaps the turn just played,/// [<paramref name="turnStart"/>, s.Date), or contains s.Date; <paramref name="turnStart"/> defaults to s.Date/// (game start). Every eligible hard anchor fires; MaxSoftEventsPerTurn caps only the non-hard events per turn,- /// which fill the slots that remain (max(0, cap - hard count)) in the usual order (an early armistice first, R-WAR-008, then consequence cards, R-ALT-008, then From, objective cards last in objectives.yaml's order, R-OBJ-007, then id). The fired- /// events keep the usual order.+ /// which fill the slots that remain (max(0, cap - hard count)) in the usual order (an early armistice first, R-WAR-008, then consequence cards, R-ALT-008, then From, objective cards last in objectives.yaml's order, R-OBJ-007, then id). Objective and Deport cards take no soft slot. The fired+ /// events keep the usual order. An eligible soft event left out by the cap waits past its window until it can fire./// Late fire: an event whose window overlapped the turn just played can fire after its window has ended; its/// conditions are evaluated at the end of the turn, and its text is filled at the last in-window day/// (<see cref="FillDate"/>)./// <para>With <paramref name="endingTurn"/> (the turn that ended the game, R-LOOP-004) only the unfired cards of recorded- /// objectives fire (those that turn recorded, and any an earlier turn's soft-event cap held back), all of them, uncapped+ /// objectives fire (those that turn recorded, and any recorded earlier whose card has not fired yet), all of them, uncapped/// (R-OBJ-003; the owner's choice "Show the card (Recommended)", 4 November 2026, #2536); no other event does.</para></summary>public static void Trigger(Content c, GameState s, List<Cause> why, DateTime? turnStart = null, bool endingTurn = false){@@ -32,7 +32,8 @@ namespace Statecraft.Simvar quiet = new HashSet<string>(c.Events.Where(e => e.FrontQuiet != "" && Armistice.MayOfferEarly(c, s, e.FrontQuiet)&& (s.FiredEvents.Contains(e.Id) || s.Date < e.From)).Select(e => e.Id));var eligible = c.Events- .Where(e => (quiet.Contains(e.Id) || !s.FiredEvents.Contains(e.Id) && e.From <= s.Date) && (e.To == null || start < e.To.Value))+ .Where(e => (quiet.Contains(e.Id) || !s.FiredEvents.Contains(e.Id) && e.From <= s.Date)+ && (s.CappedEvents.Contains(e.Id) || e.To == null || start < e.To.Value)).Where(e => !endingTurn || EndingCard(s, e)).Where(e => Timeline.AllMet(c, s, e))// R-OBJ-003: an objective's card waits for the objective. Only the GDD loop records one, so in the legacy loop it never fires.@@ -58,13 +59,19 @@ namespace Statecraft.Sim.ThenBy(e => e.Objective == "" ? -1 : c.Objectives.FindIndex(o => o.Id == e.Objective)).ThenBy(e => e.Order).ThenBy(e => e.Id, StringComparer.Ordinal).ToList();- // R-EVT-007: a Deport card takes no soft slot, so it fires on its Deport's turn however full that turn is.- bool Hard(GameEvent e) => e.Anchor == "hard" && !quiet.Contains(e.Id);+ // R-OBJ-003, R-EVT-007: objective and Deport cards take no soft slot, so they fire however full the turn is.+ // A hard objective or Deport card takes no soft slot either, so it does not shrink the slots the others share.+ // R-WAR-008: an early armistice is soft (it takes a slot and can wait); on its date it is a hard anchor.+ bool Hard(GameEvent e) => e.Anchor == "hard" && !quiet.Contains(e.Id) && e.Objective == "" && e.Deported == "";+ bool TakesSoftSlot(GameEvent e) => !Hard(e) && e.Objective == "" && e.Deported == "";var hardCount = eligible.Count(Hard);- var chosen = new HashSet<string>(eligible.Where(e => Hard(e) || e.Deported != "")- .Concat(eligible.Where(e => !Hard(e) && e.Deported == "").Take(endingTurn ? int.MaxValue : Math.Max(0, MaxSoftEventsPerTurn - hardCount))).Select(e => e.Id));+ var chosen = new HashSet<string>(eligible.Where(e => !TakesSoftSlot(e))+ .Concat(eligible.Where(TakesSoftSlot).Take(endingTurn ? int.MaxValue : Math.Max(0, MaxSoftEventsPerTurn - hardCount))).Select(e => e.Id));+ // R-EVT-001: only events eligible now can newly enter the wait; every other gate is re-evaluated on later turns.+ foreach (var e in eligible.Where(e => TakesSoftSlot(e) && !chosen.Contains(e.Id))) s.CappedEvents.Add(e.Id);foreach (var e in eligible.Where(e => chosen.Contains(e.Id))){+ s.CappedEvents.Remove(e.Id);s.FiredEvents.Add(e.Id);s.PendingEvents.Add(e.Id);why.Add(new Cause("events", e.Id, 0, $"New: {Title(c, s, e)}", key: CauseKeys.EventNew, args: Context(Title(c, s, e), HebrewTitle(c, s, e))));@@ -72,8 +79,8 @@ namespace Statecraft.Sim}/// <summary>Whether <paramref name="e"/> is a card of the turn that ended the game: the card of a recorded objective, in a- /// game that is over (R-OBJ-003, R-LOOP-004; #2536). Not only the objectives that turn recorded: a card the soft-event- /// cap held back on an earlier turn (R-EVT-001) has no later turn to wait for. Unfired ones are the only events that+ /// game that is over (R-OBJ-003, R-LOOP-004; #2536). Not only the objectives that turn recorded: the card of one recorded+ /// earlier that has not fired yet has no later turn to wait for. Unfired ones are the only events that/// fire on that turn; Unity shows them before the end screen.</summary>public static bool EndingCard(GameState s, GameEvent e) =>s.GameOver != null && e.Objective != "" && s.Objectives.ContainsKey(e.Objective);diff --git a/sim/Statecraft.Sim/GameSession.cs b/sim/Statecraft.Sim/GameSession.csindex 1cc7b053f..10d73e1ca 100644--- a/sim/Statecraft.Sim/GameSession.cs+++ b/sim/Statecraft.Sim/GameSession.cs@@ -83,7 +83,9 @@ namespace Statecraft.Sim/// warning (spec section 7), and a second warning if the replay then differs from the saved game. The warnings are/// kinds (<see cref="ContentChanged"/>, <see cref="ReplayDiffers"/>), not display text: the UI says each in the/// player's language, as it does SaveException.Code (#637). A finished game whose replay differs only by the ending- /// turn's objective cards (#2536) is not a difference: it loads with no warning.</summary>+ /// turn's objective cards (#2536) is not a difference: it loads with no warning. A save older than schema 5 was played+ /// before the soft-event cap kept a left-out event waiting (#2605), so with the same content a different replay is+ /// the rules' change, not damage: it loads with <see cref="ReplayDiffers"/>.</summary>public static GameSession Load(Content c, string saveText, out IReadOnlyList<string> warnings){if (c == null) throw new ArgumentNullException(nameof(c));@@ -96,6 +98,8 @@ namespace Statecraft.Simvar list = new List<string>();bool sameContent = saved.ContentHash == c.Hash;if (!sameContent) list.Add(ContentChanged);+ // #2605: only a current-schema save with the same content must replay exactly; an older one may differ.+ bool mustMatch = sameContent && saved.Version >= SaveGame.SchemaVersion;var session = New(c, saved.Seed, saved.Mode);int turnNo = 0;try { foreach (var turn in saved.Turns) { session.Step(turn); turnNo++; } }@@ -103,18 +107,19 @@ namespace Statecraft.Simcatch (Exception e) { throw new SaveException(FormattableString.Invariant($"turn {turnNo + 1}: {e.Message}"), e); }// #2536: a game finished before the ending turn fired objective cards replays with those cards added, and only// them: the same game, so it loads as saved, with no warning, and shows its ending card(s).- if (session.State.Hash() != saved.FinalHash && !OnlyEndingCardsAdded(c, session.State, saved.FinalHash))+ // Only an older save can be from before #2536: a current-schema save always has its ending cards (#2605 review).+ if (session.State.Hash() != saved.FinalHash && !(saved.Version < SaveGame.SchemaVersion && OnlyEndingCardsAdded(c, session.State, saved.FinalHash))){if (saved.Version < 3 && saved.Ruleset == SaveGame.GddRuleset)throw new SaveException(0, "This save was made with an earlier version of the game's rules.", SaveException.OlderRules);- if (sameContent) throw new SaveException(0, "The replay does not match the saved game: the save is damaged or was edited, or the game has a bug.");+ if (mustMatch) throw new SaveException(0, "The replay does not match the saved game: the save is damaged or was edited, or the game has a bug.");list.Add(ReplayDiffers);}foreach (var cmd in saved.Open){var reason = session.Commit(cmd);if (reason == null) continue;- if (sameContent) throw new SaveException(0, $"The open turn's order '{cmd.Kind}' was refused: {reason}");+ if (mustMatch) throw new SaveException(0, $"The open turn's order '{cmd.Kind}' was refused: {reason}");if (!list.Contains(ReplayDiffers)) list.Add(ReplayDiffers);break;}diff --git a/sim/Statecraft.Sim/GameState.cs b/sim/Statecraft.Sim/GameState.csindex b98cef628..5999c76fd 100644--- a/sim/Statecraft.Sim/GameState.cs+++ b/sim/Statecraft.Sim/GameState.cs@@ -70,6 +70,8 @@ namespace Statecraft.Simpublic double Attention;public SortedSet<string> FiredEvents = new SortedSet<string>(StringComparer.Ordinal);public List<string> PendingEvents = new List<string>();+ /// <summary>Soft events that were eligible but found no slot, by id (R-EVT-001). They remain here until they fire.</summary>+ public SortedSet<string> CappedEvents = new SortedSet<string>(StringComparer.Ordinal);/// <summary>The option each resolved event was resolved with (chosen or delegated), for events' `requires`.</summary>public Dictionary<string, string> ChosenOptions = new Dictionary<string, string>();/// <summary>Player appointments by office id; valid while the government in AppointedUnder is in office (Cabinet).</summary>@@ -170,6 +172,7 @@ namespace Statecraft.Simc.playerRegions = new SortedDictionary<string, PlayerRegionPool>(playerRegions, StringComparer.Ordinal);c.FiredEvents = new SortedSet<string>(FiredEvents, StringComparer.Ordinal);c.PendingEvents = new List<string>(PendingEvents);+ c.CappedEvents = new SortedSet<string>(CappedEvents, StringComparer.Ordinal);c.ChosenOptions = new Dictionary<string, string>(ChosenOptions);c.Appointments = new Dictionary<string, Appointment>(Appointments);c.Placements = new List<Placement>(Placements);@@ -246,6 +249,8 @@ namespace Statecraft.SimNum("mob", Mobilization); Num("stab", CoalitionStability); if (usesAttention) Num("att", Attention);List("fired", FiredEvents);List("pending", PendingEvents);+ // R-EVT-001: absent when no event has waited for the cap, so all existing golden hashes stay byte-for-byte stable.+ if (CappedEvents.Count > 0) Section("capped", '[', ']', CappedEvents);Nl(); sb.Append("chosen{");foreach (var kv in ChosenOptions.OrderBy(k => k.Key, StringComparer.Ordinal)) { Entry(); sb.Append(kv.Key).Append('=').Append(kv.Value); Sep(); }Close('}');diff --git a/sim/Statecraft.Sim/SaveGame.cs b/sim/Statecraft.Sim/SaveGame.csindex 228c723d9..fc87f9dd3 100644--- a/sim/Statecraft.Sim/SaveGame.cs+++ b/sim/Statecraft.Sim/SaveGame.cs@@ -30,7 +30,7 @@ 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 4 gdd-0.3; existing rulesets still write schema 3 (a schema 1 save has no ruleset line and is legacy)+ /// statecraft-save 5 every ruleset (#2605); earlier: 3 for legacy and gdd-0.1, 4 for gdd-0.3, 1 with no ruleset line (legacy)/// content <hex> Content.Hash of the content it was played with/// seed <ulong> / mode Historical/// ruleset legacy|gdd-0.1|gdd-0.3 the rules it was played under (Content.Ruleset); another ruleset refuses it (R-SAVE-001),@@ -47,9 +47,11 @@ namespace Statecraft.Sim/// </summary>public sealed class SaveGame{- /// <summary>Newest understood schema, reserved for the separate GDD v0.3 ruleset (#1687).</summary>- public const int SchemaVersion = 4;- const int PreviousSchemaVersion = 3;+ /// <summary>The schema every new save is written in, whatever its ruleset (#2605: the state now records the soft events+ /// the cap left waiting, so a replay of an older save can end elsewhere; GameSession.Load says so instead of refusing).</summary>+ public const int SchemaVersion = 5;+ /// <summary>The last schema written before <see cref="SchemaVersion"/>: legacy and gdd-0.1 wrote 3, gdd-0.3 wrote 4 (#1687).</summary>+ const int LegacyPreviousSchemaVersion = 3, Gdd03PreviousSchemaVersion = 4;/// <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>@@ -58,7 +60,6 @@ namespace Statecraft.Simpublic const string Gdd03Ruleset = "gdd-0.3";static bool KnownRuleset(string ruleset) => ruleset == LegacyRuleset || ruleset == GddRuleset || ruleset == Gdd03Ruleset;- static int WritingSchema(string ruleset) => ruleset == Gdd03Ruleset ? SchemaVersion : PreviousSchemaVersion;/// <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";@@ -68,7 +69,7 @@ namespace Statecraft.Simreadonly List<List<string>> turns = new List<List<string>>();readonly List<string> open = new List<string>();- /// <summary>The schema version parsed from this save; a new save uses its ruleset's writing schema (4 for gdd-0.3, otherwise 3).</summary>+ /// <summary>The schema version parsed from this save; a new save uses <see cref="SchemaVersion"/>.</summary>public int Version { get; private set; }public string ContentHash { get; }public ulong Seed { get; }@@ -87,7 +88,7 @@ namespace Statecraft.Sim{ContentHash = contentHash ?? throw new ArgumentNullException(nameof(contentHash));if (!KnownRuleset(ruleset)) throw new ArgumentException($"unknown ruleset '{ruleset}'", nameof(ruleset));- Version = WritingSchema(ruleset); Seed = seed; Mode = mode; Ruleset = ruleset;+ Version = SchemaVersion; Seed = seed; Mode = mode; Ruleset = ruleset;FinalHash = initialHash ?? throw new ArgumentNullException(nameof(initialHash));}@@ -114,7 +115,7 @@ namespace Statecraft.Simpublic string Write(){var sb = new StringBuilder();- sb.Append(Magic).Append(' ').Append(WritingSchema(Ruleset).ToString(CultureInfo.InvariantCulture)).Append('\n');+ sb.Append(Magic).Append(' ').Append(SchemaVersion.ToString(CultureInfo.InvariantCulture)).Append('\n');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');@@ -208,12 +209,11 @@ namespace Statecraft.Simthrow new SaveException(5, $"This save was made with a newer version of the game (ruleset '{ruleset}').", SaveException.NewerVersion);first = 5;}- // #1687, R-SAVE-001/002: schema 4 belongs only to the isolated gdd-0.3 envelope.- // No build writes gdd-0.3 under an earlier schema, so such a save was edited: damage, not older or newer rules.- if (ruleset == Gdd03Ruleset && version < SchemaVersion)- throw new SaveException(1, FormattableString.Invariant($"a gdd-0.3 save is schema {SchemaVersion}, not {version}"));- if (version > PreviousSchemaVersion && ruleset != Gdd03Ruleset)- throw new SaveException(1, FormattableString.Invariant($"save schema version {version} is newer than this game ({PreviousSchemaVersion})"), SaveException.NewerVersion);+ // #1687, #2605, R-SAVE-001/002: before schema 5, schema 4 belonged only to the isolated gdd-0.3 envelope, legacy+ // wrote 1 to 3 and gdd-0.1 2 to 3 (schema 1 has no ruleset line, so it is legacy). No build wrote another pairing,+ // so such a save was edited: damage, not older or newer rules.+ if (version < SchemaVersion && (ruleset == Gdd03Ruleset ? version != Gdd03PreviousSchemaVersion : version > LegacyPreviousSchemaVersion))+ throw new SaveException(1, FormattableString.Invariant($"no version of the game wrote a {ruleset} save in schema {version}"));// Check compatibility before replay, including gdd-0.1 -> gdd-0.3 as earlier rules.if (expectedRuleset != null && ruleset != expectedRuleset)throw ruleset == LegacyRuleset || (ruleset == GddRuleset && expectedRuleset == Gdd03Ruleset)