A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
GDD 0.3: no Attention under gdd-0.3, sim (1/2) (Refs #1688) (#1747)
Eyal Golan01b8eb8ae6da
diff --git a/changelog.d/1688-sim-attention-absence.md b/changelog.d/1688-sim-attention-absence.mdnew file mode 100644index 000000000..1ca95fe1b--- /dev/null+++ b/changelog.d/1688-sim-attention-absence.md@@ -0,0 +1,2 @@+### Changed+- Remove Attention accounting, pricing requirements and state-hash fields only from the opt-in GDD 0.3 simulation. Old rulesets retain their behavior and saves; presentation cutover is a separate step.diff --git a/docs/rules/mvp.md b/docs/rules/mvp.mdindex d11cec47b..a59c4fb91 100644--- a/docs/rules/mvp.md+++ b/docs/rules/mvp.md@@ -20,13 +20,13 @@ R-TURN-004: A move (`Move`) and a unit order (`UnitOrder`) other than Send home## 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`. Optional `systems.ruleset` selects the save identity explicitly: `legacy` requires the legacy loop, while `gdd-0.1` and `gdd-0.3` require the GDD loop. Absent means the original loop-based inference. Every era must resolve to the same identity. Unknown, empty or incompatible selectors are refused at load; `gdd-0.3` also requires a non-null `gdd03-balance.yaml` catalogue. The shared `Content.UsesAttention` predicate describes this identity but changes no behavior until #1688 wires it in. Shipping eras still select GDD 0.1 implicitly (#1687, part 3).+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`. Optional `systems.ruleset` selects the save identity explicitly: `legacy` requires the legacy loop, while `gdd-0.1` and `gdd-0.3` require the GDD loop. Absent means the original loop-based inference. Every era must resolve to the same identity. Unknown, empty or incompatible selectors are refused at load; `gdd-0.3` also requires a non-null `gdd03-balance.yaml` catalogue. The shared `Content.UsesAttention` predicate describes this identity but changes no behavior until #1688 wires it in. Shipping eras still select GDD 0.1 implicitly (#1687, part 3). Since #1688 part 1 the sim reads the predicate: gdd-0.3 has no Attention (R-GOV-002).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.R-LOOP-004: The GDD game ends on the rules key `mvp.end`, 15 January 1952 in the real content (owner, 15 October 2026, D-E5: "End on 15 Jan 1952"), after 44 monthly turns. The end is a boundary the last turn reaches, like the last era's end; the game is then over (`mvp_ended`) and raises no new event. It is the same in every era, after the start and before the last era's end (so the game ends as `mvp_ended`, not `era_ended`). The eras after it stay in the repository and load (G2).-R-LOOP-005: Every balance number of the GDD loop (all of `cities.yaml` and `unit_types.yaml`, the rules' `mvp:` block, and the GDD orders' `attention_cost`) carries the tag `# DESIGN VALUE: owner-set balance, not a historical figure` and its decision row on its own line, and `DesignValuesTests` lists every one of them: a number missing from the list, or a listed one without the tag, fails. For the separately identified gdd-0.3 ruleset, the design catalogue is `content/gdd03-balance.yaml`, transcribed from #1668 `docs/gdd/balance.md` at 605277df: one key per source key (including project and biome rows), with Agreed, Default or Deferred basis and provenance; mixed rows label their parts separately. `DesignValuesTests` checks this inventory and the basis distinctions. Deferred `start.army` remains symbol `A`: the loader refuses any numeric guess or unapproved relabelling, pending #1717 and validation of the full 65-unit partition. The catalogue does not switch either existing loop or supply production defaults; legacy/gdd-0.1 keep the preceding tagged-value contract. See [the catalogue mapping](../gdd03-catalogue.md) for derived/mixed bases and the six owner rulings.+R-LOOP-005: Every balance number of the GDD loop (all of `cities.yaml` and `unit_types.yaml`, the rules' `mvp:` block, and the GDD orders' `attention_cost`) carries the tag `# DESIGN VALUE: owner-set balance, not a historical figure` and its decision row on its own line, and `DesignValuesTests` lists every one of them: a number missing from the list, or a listed one without the tag, fails. For the separately identified gdd-0.3 ruleset, the design catalogue is `content/gdd03-balance.yaml`, transcribed from #1668 `docs/gdd/balance.md` at 605277df: one key per source key (including project and biome rows), with Agreed, Default or Deferred basis and provenance; mixed rows label their parts separately. `DesignValuesTests` checks this inventory and the basis distinctions. Deferred `start.army` remains symbol `A`: the loader refuses any numeric guess or unapproved relabelling, pending #1717 and validation of the full 65-unit partition. The catalogue does not switch either existing loop or supply production defaults; legacy/gdd-0.1 keep the preceding tagged-value contract. See [the catalogue mapping](../gdd03-catalogue.md) for derived/mixed bases and the six owner rulings. Under gdd-0.3, Attention is absent: no pool, price or cost-map requirement; the older tagged Attention contract remains only legacy/gdd-0.1 (#1688, part 1).The ID R-LOOP-003 (the Phase 1 overlay, `MvpSlice.Overlay`) is retired with the overlay at the cutover and is not reused.@@ -402,7 +402,7 @@ D-C5 as decided (12 October 2026): the cabinet and Attention stay, the coalitionR-GOV-001: In the GDD loop the coalition's stability never ends the game: it still moves toward public approval each turn and still weights the coalition votes, but a value below 0.2 (`PoliticsSystem.CollapseBelow`) sets no `coalition_collapse` (D-B5: "Coalition collapse is off in the MVP"). The legacy loop keeps its collapse while the legacy code exists (D-E1).-R-GOV-002: Every GDD order kind has an `attention_cost` in the real rules (a design value, R-LOOP-005), the unit orders `pioneer_work` and `stop_work` cost 0 (D-A6: unit orders are free), and a refused order costs nothing: its Attention is refunded before the next order in the turn is priced.+R-GOV-002: Every GDD order kind has an `attention_cost` in the real rules (a design value, R-LOOP-005), the unit orders `pioneer_work` and `stop_work` cost 0 (D-A6: unit orders are free), and a refused order costs nothing: its Attention is refunded before the next order in the turn is priced. This accounting contract applies to legacy/gdd-0.1. Under gdd-0.3 there is no Attention resource: no refill, charge, refund, affordability query or canonical att field; real order validation/material costs remain, and capture previews express absence (#1688; owner ruling, 25 October 2026, on #1668).D-H3's first slice in the GDD loop (GDD Phase 7 PR 4, #808): each office's competence scales the GDD systems in its remit. Q-MIN-1 and Q-MIN-3 were decided as recommended, Q-MIN-2 as "Output" (owner, 17 and 18 October 2026, #784): competence scales output and progress a turn, and the base price and stated duration stay unchanged. The system-to-office map is `mvp.minister_systems` in `content/rules.yaml`, each entry a labelled design value; the corridors (#870) and military training (#742) join with their own phases. Candidates and appointment stay `Cabinet.Appoint`'s.diff --git a/sim/Statecraft.Sim.Tests/NoAttentionTests.cs b/sim/Statecraft.Sim.Tests/NoAttentionTests.csnew file mode 100644index 000000000..fc607b3c8--- /dev/null+++ b/sim/Statecraft.Sim.Tests/NoAttentionTests.cs@@ -0,0 +1,191 @@+using Statecraft.Sim;+using Statecraft.Sim.Reference;+using System.Text.RegularExpressions;++public class NoAttentionTests+{+ public static IEnumerable<object[]> Kinds() => CommandGuardTests.Samples.Values.Select(c => new object[] { c.Kind });+ static void Select(Dictionary<string,string> files, bool modern)+ {+ if (modern) files["eras.yaml"] = files["eras.yaml"].Replace("loop: gdd", "loop: gdd, ruleset: gdd-0.3");+ files[Gdd03BalanceCatalogue.FileName] = File.ReadAllText(Path.Combine(RealContentTests.ContentRoot(),Gdd03BalanceCatalogue.FileName));+ }+ static Content Load(bool modern = true)+ {+ var files=Fixture.Gdd(); Select(files,modern); return ContentLoader.Load(Fixture.Write(files));+ }+ static void Poison(Content c)+ {+ foreach (var r in c.EraRules.Values.Append(c.Rules)) { r.AttentionCost.Clear(); r.AttentionPerTurn=double.NaN; r.RungAttentionStep=double.NaN; }+ }+ static string WithoutLegacyAccounting(string canonical) =>+ Regex.Replace(canonical.Replace("ruleset=gdd-0.3;", ""), @"\natt=[^\n]*", "");+ static bool Unavailable(string kind) => kind is "map_action" or "set_mobilization" or "security_order";+ static (Content c,GameState s,Command valid,Command invalid) Case(string kind,bool modern)+ {+ var c = kind is "resolve_capture" or "end_occupation"+ ? CaptureTests.Load(files=>Select(files,modern),CaptureTests.AllTargets) : Load(modern);+ var s=Simulation.NewGame(c,1,Mode.Historical); s.Attention=500; s.NextId=1000;+ Command valid=CommandGuardTests.Samples.Values.Single(x=>x.Kind==kind), invalid=valid;+ switch(kind)+ {+ case "set_policy": valid=new SetPolicy("rationing",.5); invalid=new SetPolicy("missing",.5); break;+ case "allocate_budget": valid=new AllocateBudget(new Dictionary<string,double>{{"finance_minister",1}}); invalid=new AllocateBudget(new Dictionary<string,double>{{"missing",1}});break;+ case "choose_event_option":+ c.Events.Add(new GameEvent { Id="test", Office="prime_minister", Options=new List<EventOption>{new EventOption {Id="yes",Text="Test"}} });+ s.PendingEvents.Add("test"); valid=new ChooseEventOption("test","yes"); invalid=new ChooseEventOption("test","missing");break;+ case "appoint": valid=new Appoint("finance_minister","pm_one"); invalid=new Appoint("missing","pm_one");break;+ case "assign_workers":valid=new AssignWorkers("town_a","job",1);invalid=new AssignWorkers("town_a","job",-1);break;+ case "train":valid=new Train("town_a","halutz",1);invalid=new Train("town_a","halutz",0);break;+ case "cancel_training": s.Cohorts[200]=new Cohort(200,"halutz","town_a",1,2);valid=new CancelTraining(200);invalid=new CancelTraining(999);break;+ case "return_craftsmen":s.Cities["town_a"]=s.Cities["town_a"].WithCraftsmen(1);valid=new ReturnCraftsmen("town_a",1);invalid=new ReturnCraftsmen("town_a",0);break;+ case "reassign_craftsmen":s.Cities["town_a"]=s.Cities["town_a"].WithQualified(new Qualified(1,0,Array.Empty<int>()));valid=new ReassignCraftsmen("town_a",1);invalid=new ReassignCraftsmen("town_a",0);break;+ case "reassign_pioneers":s.Cities["town_a"]=s.Cities["town_a"].WithQualified(new Qualified(0,0,new[]{0}));valid=new ReassignPioneers("town_a","halutz",1);invalid=new ReassignPioneers("town_a","halutz",0);break;+ case "reinforce":s.Units[99]=new Unit(99,"recruit",1,0,side:"israel",strength:1,full:2);s.Arms=100;valid=new Reinforce(99,"town_a",1);invalid=new Reinforce(999,"town_a",1);break;+ case "pioneer_work":s.Units[99]=new Unit(99,"halutz",1,0);valid=new PioneerWork(99,Projects.BuildYishuv,"site_a");invalid=new PioneerWork(999,Projects.BuildYishuv,"site_a");break;+ case "stop_work":s.Units[99]=new Unit(99,"halutz",1,0);s.Sites["site_a"]=new SiteWork("site_a",99,3,null);valid=new StopWork(99);invalid=new StopWork(999);break;+ case "start_project":valid=new StartProject("housing","town_a",1,1);invalid=new StartProject("missing","town_a",1,1);break;+ case "cancel_project":s.CityProjects[200]=new CityProject(200,"housing","town_a",1,1,2);valid=new CancelProject(200);invalid=new CancelProject(999);break;+ case "move":s.Units[99]=new Unit(99,"recruit",1,0,side:"israel",strength:1);valid=new Move(99,2,0);invalid=new Move(999,2,0);break;+ case "unit_order":s.Units[99]=new Unit(99,"recruit",1,0,side:"israel",strength:1);valid=new UnitOrder(99,"fortify");invalid=new UnitOrder(999,"fortify");break;+ case "buy_arms":valid=new BuyArms(1);invalid=new BuyArms(0);break;+ case "resolve_capture":s.Units[99]=CaptureTests.Soldier(99,1,0);s.Settlements["town_a"]=new SettlementControl("israel",SettlementControl.AwaitingChoice,s.Date);valid=new ResolveCapture("town_a","raid");invalid=new ResolveCapture("town_a","missing");break;+ case "end_occupation":s.Units[99]=CaptureTests.Soldier(99,1,0);s.Settlements["town_a"]=new SettlementControl("israel",SettlementControl.AwaitingEnd,s.Date);valid=new EndOccupation("town_a","withdraw");invalid=new EndOccupation("town_a","missing");break;+ }+ return(c,s,valid,invalid);+ }+ [Fact] public void CoversEveryConcreteCommand()+ {+ Assert.Equal(23,Kinds().Count());+ Assert.Equal(CommandGuardTests.Samples.Keys.OrderBy(t=>t.Name),typeof(Command).Assembly.GetTypes().Where(t=>t.IsSubclassOf(typeof(Command))&&!t.IsAbstract).OrderBy(t=>t.Name));+ }+ [Theory] [MemberData(nameof(Kinds))]+ public void SetupProvesSuccessfulOldModePathForEveryAvailableKind(string kind)+ {+ var(c,s,valid,invalid)=Case(kind,false);var p=Simulation.Preview(c,s,new[]{valid});+ if(Unavailable(kind)) Assert.Contains("not part of this game",p.Rejected.Single().Reason.Replace("not available in this game","not part of this game"));+ else {Assert.Empty(p.Rejected);Assert.NotEmpty(Simulation.Preview(c,s,new[]{invalid}).Rejected);}+ }+ // R-GOV-002: absence branches before touching legacy accounting, while real validation still runs.+ [Theory] [MemberData(nameof(Kinds))]+ public void EveryKindKeepsRealValidationWithoutReadingOrChangingOldPool(string kind)+ {+ var(c,s,valid,invalid)=Case(kind,true);Poison(c);s.Attention=123.456;+ var good=Simulation.Preview(c,s,new[]{valid});+ if(Unavailable(kind)) Assert.Single(good.Rejected); else Assert.Empty(good.Rejected);+ var bad=Simulation.Preview(c,s,new[]{invalid});Assert.Single(bad.Rejected);+ Assert.DoesNotContain("attention",bad.Rejected[0].Reason,StringComparison.OrdinalIgnoreCase);+ Assert.Equal(123.456,s.Attention);Assert.Equal(123.456,good.State.Attention);Assert.Equal(123.456,bad.State.Attention);+ var step=Simulation.Step(c,s,new[]{valid});Assert.Equal(123.456,step.State.Attention);+ var(oldContent,oldState,oldValid,oldInvalid)=Case(kind,false);+ var oldGood=Simulation.Preview(oldContent,oldState,new[]{oldValid});+ var oldBad=Simulation.Preview(oldContent,oldState,new[]{oldInvalid});+ Assert.Equal(oldBad.Rejected.Single().Reason,bad.Rejected.Single().Reason);+ Assert.Equal(WithoutLegacyAccounting(oldGood.State.Describe()),WithoutLegacyAccounting(good.State.Describe()));+ Assert.Equal(WithoutLegacyAccounting(oldBad.State.Describe()),WithoutLegacyAccounting(bad.State.Describe()));+ Assert.Equal(WithoutLegacyAccounting(Simulation.Step(oldContent,oldState,new[]{oldValid}).State.Describe()),WithoutLegacyAccounting(step.State.Describe()));+ }+ [Fact] public void InitialAndEndTurnRefillAreAbsentAndCanonicalStateIgnoresCompatibilityPool()+ {+ var c=Load();Poison(c);var s=Simulation.NewGame(c,1,Mode.Historical);+ Assert.Equal(c.Ruleset,s.Ruleset);Assert.Equal(c.Ruleset,s.Clone().Ruleset);+ Assert.False(typeof(GameState).GetProperty(nameof(GameState.Ruleset))!.CanWrite);+ Assert.DoesNotContain("att=",s.Describe());Assert.Contains("ruleset=gdd-0.3",s.Describe());+ var hash=s.Hash();s.Attention=double.NaN;Assert.Equal(hash,s.Hash());Assert.Equal(hash,s.Clone().Hash());+ Assert.True(double.IsNaN(Simulation.Step(c,s,Array.Empty<Command>()).State.Attention));+ }+ [Fact] public void LegacyResourceApisRefuseNewModeEvenForEmptyQueuesAndUnknownKinds()+ {+ var c=Load();var s=Simulation.NewGame(c,1,Mode.Historical);Poison(c);+ foreach(var call in new Action[]{()=>AttentionSystem.Refill(c,s),()=>AttentionSystem.Cost(c,s,"missing"),()=>AttentionSystem.Price(c,s,new BuyArms(1)),()=>AttentionSystem.Left(c,s,Array.Empty<Command>()),()=>AttentionSystem.TrySpend(c,s,"buy_arms")})+ Assert.Throws<InvalidOperationException>(call);+ }+ [Fact] public void QueriesCaptureOptionsAndHistoricalAiExpressAbsence()+ {+ var(c,s,_,_)=Case("resolve_capture",true);Poison(c);s.Attention=double.NaN;+ var captures=SettlementControl.CaptureOptions(c,s,"town_a").Where(o=>o.Preview!=null).ToList();Assert.NotEmpty(captures);+ Assert.All(captures,o=>Assert.Null(o.Preview!.Attention));+ var orders=HistoricalAI.Commands(c,s);Assert.Contains(orders,x=>x is ResolveCapture);+ Cabinet.Vacancies(c,s,Array.Empty<Command>());+ Assert.True(EconomySystem.Unsubmitted(c,s,new Dictionary<string,double>{{"defense_minister",1}},Array.Empty<Command>()));+ s.Settlements["town_a"]=new SettlementControl("israel",SettlementControl.AwaitingEnd,s.Date);+ var endings=SettlementControl.EndOptions(c,s,"town_a").Where(o=>o.Preview!=null).ToList();Assert.NotEmpty(endings);+ Assert.All(endings,o=>Assert.Null(o.Preview!.Attention));+ Assert.True(double.IsNaN(s.Attention));+ }+ sealed class UnknownOrder : Command { public override string Kind => "unknown_order"; }+ [Fact] public void UnknownCommandsAndGameOverRemainGuardedWithoutAccounting()+ {+ var c=Load();Poison(c);var s=Simulation.NewGame(c,1,Mode.Historical);s.Attention=12;+ Assert.Throws<ArgumentException>(()=>Simulation.Preview(c,s,new Command[]{new UnknownOrder()}));+ s.GameOver=GameOverCodes.MvpEnded;+ Assert.Contains("game is over",Simulation.Step(c,s,new Command[]{new BuyArms(1)}).Rejected.Single().Reason);+ Assert.Equal(12,Simulation.Preview(c,s,Array.Empty<Command>()).State.Attention);+ }+ [Fact] public void EveryReferenceGoldenEntryPointRefusesBeforeRunningEvenZeroTurns()+ {+ var c=Load();var s=Simulation.NewGame(c,1,Mode.Historical);Poison(c);+ foreach(var call in new Action[]{()=>ReferencePlayer.Commands(c,s),()=>GoldenRun.Orders(c,s),()=>GoldenRun.SmokeOrders(c,s),()=>GoldenRun.SmokeMove(c,s),()=>GoldenRun.Play(c,s.Date),()=>GoldenRun.PlayToEnd(c),()=>GoldenRun.PlayEra(c,c.Eras[0].Id,s.Date.AddDays(1)),()=>GoldenRun.PlaySmoke(c,0),()=>GoldenRun.PlaySmokeOrders(c)})+ Assert.Throws<NotSupportedException>(call);+ }+ [Fact] public void SessionCommitEndTurnAndReplayIgnoreOldPool()+ {+ var c=Load();Poison(c);var g=GameSession.New(c,1,Mode.Historical);g.State.Attention=55;+ g.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);+ // 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()+ {+ 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",+ ["map/unit_anchor_hexes.yaml"]="anchors:\n - { id: test_force, anchor: 0, q: 1, r: 0 }\n"+ });+ Select(files,true);var c=ContentLoader.Load(Fixture.Write(files));Poison(c);+ var g=GameSession.New(c,1,Mode.Historical);var unit=Assert.Single(g.State.Units.Values).Id;+ g.State.Attention=456;+ Assert.Null(g.Commit(new Move(unit,2,0)));var text=g.Save.Write();+ var replay=GameSession.Load(c,text,out var warnings);Assert.Empty(warnings);+ Assert.Equal(g.Now.State.Hash(),replay.Now.State.Hash());Assert.Single(replay.Save.Open);+ var changed=text.Replace($"move {unit} 2 0",$"move {unit} 99 99");Assert.NotEqual(text,changed);+ Assert.Throws<SaveException>(()=>GameSession.Load(c,changed,out _));+ replay.EndTurn(Array.Empty<Command>());Assert.Equal(2,replay.State.Units[unit].Q);+ }+ public static IEnumerable<object[]> OldLoaderCases()+ {+ foreach(string identity in new[]{SaveGame.LegacyRuleset,SaveGame.GddRuleset,SaveGame.Gdd03Ruleset}) foreach(bool over in new[]{false,true})+ foreach(string fragment in new[]{"attention_cost: {}", "attention_per_turn: -1", "rung_attention_step: .nan", "attention_cost: { set_policy: -1 }", "attention_cost: { bogus: 1 }"})+ yield return new object[]{identity,over,fragment};+ }+ [Theory] [MemberData(nameof(OldLoaderCases))]+ public void LoaderPreservesStrictOldValidationAndIgnoresOnlyNewModeAccounting(string identity,bool over,string fragment)+ {+ bool modern=identity==SaveGame.Gdd03Ruleset, gdd=identity!=SaveGame.LegacyRuleset;+ var files=gdd?Fixture.Gdd():new Dictionary<string,string>();+ if(modern)Select(files,true);+ var original=gdd?files["rules.yaml"]:Fixture.Files["rules.yaml"];+ string field=fragment.Split(':')[0];+ var dir=Fixture.Write(files);+ if(over)+ {+ Directory.CreateDirectory(Path.Combine(dir,"rules"));File.WriteAllText(Path.Combine(dir,"rules","founding.yaml"),fragment+"\n");+ }+ else File.WriteAllText(Path.Combine(dir,"rules.yaml"),Regex.Replace(original,@"(?m)^"+field+@":.*$",fragment));+ // Empty override maps merge with the base; this has never removed an old cost.+ if(!modern && !(over && fragment=="attention_cost: {}")) Assert.Throws<ContentException>(()=>ContentLoader.Load(dir));+ else Assert.Equal(identity,ContentLoader.Load(dir).Ruleset);+ }+ [Theory] [InlineData(false)] [InlineData(true)]+ public void LoaderRequiresNoAttentionFieldsForNewModeIncludingEraOverrides(bool eraOverride)+ {+ var files=Fixture.Gdd();Select(files,true);+ files["rules.yaml"]=Regex.Replace(files["rules.yaml"],@"(?m)^(attention_per_turn|rung_attention_step|attention_cost):.*\n","");+ var dir=Fixture.Write(files);+ if(eraOverride){Directory.CreateDirectory(Path.Combine(dir,"rules"));File.WriteAllText(Path.Combine(dir,"rules","founding.yaml"),"attention_per_turn: .nan\nrung_attention_step: -1\nattention_cost: { not_a_command: -99 }\n");}+ Assert.False(ContentLoader.Load(dir).UsesAttention);+ }+}diff --git a/sim/Statecraft.Sim/AttentionSystem.cs b/sim/Statecraft.Sim/AttentionSystem.csindex 129688732..0af35d926 100644--- a/sim/Statecraft.Sim/AttentionSystem.cs+++ b/sim/Statecraft.Sim/AttentionSystem.cs@@ -1,3 +1,4 @@+using System;using System.Collections.Generic;using System.Globalization;using System.Linq;@@ -20,22 +21,30 @@ namespace Statecraft.Simpublic static bool IsGddKind(string kind) => GddKinds.Contains(kind);- public static void Refill(Content c, GameState s) => s.Attention = c.RulesAt(s.Date).AttentionPerTurn;+ static void RequireAttention(Content c)+ {+ if (!c.UsesAttention) throw new InvalidOperationException("Attention is absent in this ruleset; do not query or account for it.");+ }+ public static void Refill(Content c, GameState s)+ { RequireAttention(c); s.Attention = c.RulesAt(s.Date).AttentionPerTurn; }/// <summary>Cost at <paramref name="rung"/> if given, else at the state's current rung.</summary>public static double Cost(Content c, GameState s, string kind, int? rung = null){+ RequireAttention(c);var r = c.RulesAt(s.Date); // the era the turn starts in (docs/determinism.md, "Rules per era")return r.AttentionCost[kind] * (1 + r.RungAttentionStep * ((rung ?? s.Rung) - 1));}/// <summary>The order's Attention price at this turn's prices (0 for a kind Attention does not price): what the UI's/// queue charges for it.</summary>- public static double Price(Content c, GameState s, Command cmd) => IsCommandKind(cmd.Kind) ? Cost(c, s, cmd.Kind) : 0;+ public static double Price(Content c, GameState s, Command cmd)+ { RequireAttention(c); return IsCommandKind(cmd.Kind) ? Cost(c, s, cmd.Kind) : 0; }/// <summary>Attention left after paying for <paramref name="pending"/> (this turn's queue) at this turn's prices: what/// the UI's queue still has to spend (#1110: the Cabinet badge and SimBridge.Queue read the same number).</summary>- public static double Left(Content c, GameState s, IEnumerable<Command> pending) => s.Attention - pending.Sum(x => Price(c, s, x));+ public static double Left(Content c, GameState s, IEnumerable<Command> pending)+ { RequireAttention(c); return s.Attention - pending.Sum(x => Price(c, s, x)); }/// <summary>Returns null and deducts on success, or the reason it could not be afforded./// <paramref name="rung"/> prices the command at that security level (the turn's starting rung).</summary>diff --git a/sim/Statecraft.Sim/Cabinet.cs b/sim/Statecraft.Sim/Cabinet.csindex 1b9601980..6ea0fe172 100644--- a/sim/Statecraft.Sim/Cabinet.cs+++ b/sim/Statecraft.Sim/Cabinet.cs@@ -145,7 +145,7 @@ namespace Statecraft.Simpublic static IReadOnlyList<Office> Vacancies(Content c, GameState s, IEnumerable<Command> pending){var queued = pending.ToList();- if (s.GameOver != null || AttentionSystem.Cost(c, s, "appoint") > AttentionSystem.Left(c, s, queued) + 1e-9)+ if (s.GameOver != null || (c.UsesAttention && AttentionSystem.Cost(c, s, "appoint") > AttentionSystem.Left(c, s, queued) + 1e-9))return new Office[0];var filled = queued.OfType<Appoint>().Select(a => a.Office).ToList();return Lineup(c, s)diff --git a/sim/Statecraft.Sim/Content.cs b/sim/Statecraft.Sim/Content.csindex 689b49212..bc835ef1f 100644--- a/sim/Statecraft.Sim/Content.cs+++ b/sim/Statecraft.Sim/Content.cs@@ -1249,8 +1249,8 @@ namespace Statecraft.Sim/// <summary>The game-wide save identity; an absent selector preserves the loop's original inference.</summary>public string Ruleset => Eras.Count > 0 && Eras[0].Systems.RulesetGiven? Eras[0].Systems.Ruleset : IsGdd ? SaveGame.GddRuleset : SaveGame.LegacyRuleset;- /// <summary>Identity predicate only: legacy and gdd-0.1 have Attention, gdd-0.3 omits it. No rule reads it yet;- /// its callers are wired in #1688 (R-LOOP-001).</summary>+ /// <summary>Identity predicate: legacy and gdd-0.1 have Attention, gdd-0.3 omits it. The sim reads it to leave+ /// Attention out of gdd-0.3 (R-LOOP-001, R-GOV-002, #1688).</summary>public bool UsesAttention => Ruleset != SaveGame.Gdd03Ruleset;/// <summary>The day play ends, a boundary the last turn reaches (Simulation.Step): rules.yaml mvp.end in the GDD loop/// (R-LOOP-004), otherwise the last era's end.</summary>diff --git a/sim/Statecraft.Sim/ContentLoader.cs b/sim/Statecraft.Sim/ContentLoader.csindex d45bf9180..d8c9c7c6c 100644--- a/sim/Statecraft.Sim/ContentLoader.cs+++ b/sim/Statecraft.Sim/ContentLoader.cs@@ -520,15 +520,18 @@ namespace Statecraft.Simstatic void ValidateRules(Content c, Rules r, string file, HashSet<string> indicators, HashSet<string> offices, HashSet<string> historicalOffices){if (r.Start == default) throw new ContentException(file, "start", "required");- if (!(r.AttentionPerTurn >= 0 && !double.IsInfinity(r.AttentionPerTurn))) throw new ContentException(file, "attention_per_turn", "must be a finite non-negative number");- if (!(r.RungAttentionStep >= 0 && !double.IsInfinity(r.RungAttentionStep))) throw new ContentException(file, "rung_attention_step", "must be a finite non-negative number");- foreach (var kv in r.AttentionCost)- if (!(kv.Value >= 0 && !double.IsInfinity(kv.Value))) throw new ContentException(file, $"attention_cost.{kv.Key}", "must be a finite non-negative number");- foreach (var k in r.AttentionCost.Keys)- if (!AttentionSystem.IsCommandKind(k)) throw new ContentException(file, $"attention_cost.{k}", "unknown command kind");- foreach (var k in AttentionSystem.CommandKinds)- if ((c.IsGdd || !AttentionSystem.IsGddKind(k)) && !r.AttentionCost.ContainsKey(k)) // a GDD kind is priced only where it can run- throw new ContentException(file, $"attention_cost.{k}", "missing cost");+ if (c.UsesAttention)+ {+ if (!(r.AttentionPerTurn >= 0 && !double.IsInfinity(r.AttentionPerTurn))) throw new ContentException(file, "attention_per_turn", "must be a finite non-negative number");+ if (!(r.RungAttentionStep >= 0 && !double.IsInfinity(r.RungAttentionStep))) throw new ContentException(file, "rung_attention_step", "must be a finite non-negative number");+ foreach (var kv in r.AttentionCost)+ if (!(kv.Value >= 0 && !double.IsInfinity(kv.Value))) throw new ContentException(file, $"attention_cost.{kv.Key}", "must be a finite non-negative number");+ foreach (var k in r.AttentionCost.Keys)+ if (!AttentionSystem.IsCommandKind(k)) throw new ContentException(file, $"attention_cost.{k}", "unknown command kind");+ foreach (var k in AttentionSystem.CommandKinds)+ if ((c.IsGdd || !AttentionSystem.IsGddKind(k)) && !r.AttentionCost.ContainsKey(k)) // a GDD kind is priced only where it can run+ throw new ContentException(file, $"attention_cost.{k}", "missing cost");+ }if (r.RungMinMobilization.Count != 5) throw new ContentException(file, "rung_min_mobilization", "needs exactly 5 values (rungs 1-5)");for (int i = 0; i < 5; i++){diff --git a/sim/Statecraft.Sim/EconomySystem.cs b/sim/Statecraft.Sim/EconomySystem.csindex aa2626d66..da7fa616c 100644--- a/sim/Statecraft.Sim/EconomySystem.cs+++ b/sim/Statecraft.Sim/EconomySystem.cs@@ -124,7 +124,7 @@ namespace Statecraft.Simvar list = pending.ToList();var queued = list.OfType<AllocateBudget>().LastOrDefault();if (s.GameOver != null || Same(draft, queued?.Shares ?? s.Budget)) return false;- return Same(draft, s.Budget)+ return Same(draft, s.Budget) || !c.UsesAttention|| AttentionSystem.Cost(c, s, "allocate_budget") <= AttentionSystem.Left(c, s, list.Where(x => !(x is AllocateBudget))) + 1e-9;}diff --git a/sim/Statecraft.Sim/GameState.cs b/sim/Statecraft.Sim/GameState.csindex 33dfc8a25..55774935f 100644--- a/sim/Statecraft.Sim/GameState.cs+++ b/sim/Statecraft.Sim/GameState.cs@@ -26,6 +26,11 @@ namespace Statecraft.Sim/// <summary>All mutable game data. Systems never share references between states: Step works on Clone().</summary>public sealed class GameState{+ /// <summary>Immutable replay identity. Old manually constructed states retain their historical hash layout.</summary>+ public string Ruleset { get; } = SaveGame.LegacyRuleset;+ readonly bool usesAttention = true;+ public GameState() { }+ internal GameState(Content c) { Ruleset = c.Ruleset; usesAttention = c.UsesAttention; }public DateTime Date;public ulong RngState;public Mode Mode;@@ -162,6 +167,7 @@ namespace Statecraft.Sim// Hash text: one line, ';'-separated, closing brackets. Readable text: a section label per line, each entry// on its own indented line, no closing brackets. Both are written by the calls below, in the same order.var sb = new StringBuilder();+ if (!usesAttention) sb.Append("ruleset=").Append(Ruleset).Append(';');void Nl() { if (readable) sb.Append('\n'); }void Entry() { if (readable) sb.Append("\n "); }void Close(char c) { if (!readable) sb.Append(c); }@@ -192,7 +198,7 @@ namespace Statecraft.SimList("sit", ActiveSituations);Num("treasury", Treasury); Num("debt", Debt); Num("fx", FxReserves);Nl(); sb.Append("rung=").Append(Rung).Append(";cf=").Append(CeasefireWeeksLeft).Append(';');- Num("mob", Mobilization); Num("stab", CoalitionStability); Num("att", Attention);+ Num("mob", Mobilization); Num("stab", CoalitionStability); if (usesAttention) Num("att", Attention);List("fired", FiredEvents);List("pending", PendingEvents);Nl(); sb.Append("chosen{");diff --git a/sim/Statecraft.Sim/GoldenRun.cs b/sim/Statecraft.Sim/GoldenRun.csindex 97d63dbf6..296600055 100644--- a/sim/Statecraft.Sim/GoldenRun.cs+++ b/sim/Statecraft.Sim/GoldenRun.cs@@ -30,6 +30,7 @@ namespace Statecraft.Simpublic static GameState Play(Content c, DateTime until){if (c == null) throw new ArgumentNullException(nameof(c));+ if (!c.UsesAttention) throw new NotSupportedException("Golden policies are not defined for gdd-0.3.");var s = Simulation.NewGame(c, Seed, Mode.Historical);for (int turn = 0; turn < 1000 && s.Date < until && s.GameOver == null; turn++)s = Simulation.Step(c, s, Orders(c, s)).State;@@ -51,6 +52,7 @@ namespace Statecraft.Simpublic static GameState PlayEra(Content c, string eraId, DateTime until, ulong seed = Seed){if (c == null) throw new ArgumentNullException(nameof(c));+ if (!c.UsesAttention) throw new NotSupportedException("Golden policies are not defined for gdd-0.3.");var era = c.Eras.FirstOrDefault(e => e.Id == eraId) ?? throw new ArgumentException($"no era '{eraId}' (known: {string.Join(", ", c.Eras.Select(e => e.Id))})");if (era.From != c.Rules.Start)throw new NotSupportedException($"era '{eraId}' starts {era.From:yyyy-MM-dd}, but a new game starts {c.Rules.Start:yyyy-MM-dd}: a fresh start of a later era needs that era's start values, which are not read yet (chapters design section 6).");@@ -71,6 +73,7 @@ namespace Statecraft.Simpublic static List<Command> SmokeOrders(Content c, GameState s){if (c == null) throw new ArgumentNullException(nameof(c));+ if (!c.UsesAttention) throw new NotSupportedException("Golden policies are not defined for gdd-0.3.");var answers = new List<Command>();var left = s.Attention;foreach (var e in s.PendingEvents.Select(id => c.Events.First(x => x.Id == id)))@@ -88,6 +91,7 @@ namespace Statecraft.Simpublic static GameState PlaySmoke(Content c, int turns){if (c == null) throw new ArgumentNullException(nameof(c));+ if (!c.UsesAttention) throw new NotSupportedException("Golden policies are not defined for gdd-0.3.");var s = Simulation.NewGame(c, Seed, Mode.Historical);for (int turn = 0; turn < turns && s.Date < Until1952 && s.GameOver == null; turn++)s = Simulation.Step(c, s, SmokeOrders(c, s)).State;@@ -102,6 +106,7 @@ namespace Statecraft.Simpublic static Move SmokeMove(Content c, GameState s){if (c == null) throw new ArgumentNullException(nameof(c));+ if (!c.UsesAttention) throw new NotSupportedException("Golden policies are not defined for gdd-0.3.");var places = Movement.NoEntry(c, s);foreach (var id in s.Units.Keys) // a SortedList: in id orderforeach (var (q, r) in Movement.Reachable(c, s, id).Keys)@@ -114,6 +119,7 @@ namespace Statecraft.Simpublic static GameState PlaySmokeOrders(Content c){if (c == null) throw new ArgumentNullException(nameof(c));+ if (!c.UsesAttention) throw new NotSupportedException("Golden policies are not defined for gdd-0.3.");var s = Simulation.NewGame(c, Seed, Mode.Historical);return Simulation.Step(c, s, new Command[] { SmokeMove(c, s) }).State;}diff --git a/sim/Statecraft.Sim/HistoricalAI.cs b/sim/Statecraft.Sim/HistoricalAI.csindex bdfae3773..007ebd911 100644--- a/sim/Statecraft.Sim/HistoricalAI.cs+++ b/sim/Statecraft.Sim/HistoricalAI.cs@@ -27,6 +27,7 @@ namespace Statecraft.Simwanted.Add(new ResolveCapture(kv.Key, SettlementControl.Raid));var floor = SecuritySystem.MinMobilization(c, s.Date, s.Rung);if (!c.IsGdd && s.Mobilization > floor) wanted.Add(new SetMobilization(floor)); // retired in the GDD loop (R-WAR-002)+ if (!c.UsesAttention) return wanted;var list = new List<Command>();var left = s.Attention;foreach (var cmd in wanted)diff --git a/sim/Statecraft.Sim/Reference/ReferencePlayer.cs b/sim/Statecraft.Sim/Reference/ReferencePlayer.csindex 27b9a0838..5887f4b11 100644--- a/sim/Statecraft.Sim/Reference/ReferencePlayer.cs+++ b/sim/Statecraft.Sim/Reference/ReferencePlayer.cs@@ -21,6 +21,7 @@ namespace Statecraft.Sim.Referencepublic static IReadOnlyList<Command> Commands(Content c, GameState s){+ if (!c.UsesAttention) throw new NotSupportedException("The reference policy is not defined for gdd-0.3.");var list = new List<Command>(HistoricalAI.Commands(c, s));var left = s.Attention - list.Sum(x => AttentionSystem.Cost(c, s, x.Kind));Attack(c, s, list, ref left);diff --git a/sim/Statecraft.Sim/SettlementControl.cs b/sim/Statecraft.Sim/SettlementControl.csindex 28d0e5eb9..9f689683d 100644--- a/sim/Statecraft.Sim/SettlementControl.cs+++ b/sim/Statecraft.Sim/SettlementControl.cs@@ -83,7 +83,7 @@ namespace Statecraft.Sim{var after = s.Clone();var refusal = Spend(c, after, ResolveKind) ?? Resolved(c, after, id, outcome, new List<Cause>());- options.Add(new CaptureOption(outcome, refusal, refusal == null ? Preview(s, after) : null));+ options.Add(new CaptureOption(outcome, refusal, refusal == null ? Preview(c, s, after) : null));}return options;}@@ -92,11 +92,12 @@ namespace Statecraft.Sim/// what it needs and what is left.</summary>static CaptureRefusal? Spend(Content c, GameState s, string kind){+ if (!c.UsesAttention) return null;var need = AttentionSystem.Cost(c, s, kind); var have = s.Attention;return AttentionSystem.TrySpend(c, s, kind) is string no ? new CaptureRefusal(CaptureRefusal.Attention, no, need, have) : null;}- static CapturePreview Preview(GameState s, GameState after) => new CapturePreview(after.Attention - s.Attention,+ static CapturePreview Preview(Content c, GameState s, GameState after) => new CapturePreview(c.UsesAttention ? after.Attention - s.Attention : (double?)null,after.Treasury - s.Treasury, after.Debt - s.Debt, after.Food - s.Food, after.Arms - s.Arms,Indicator(after, "morale") - Indicator(s, "morale"), Indicator(after, "intl_standing") - Indicator(s, "intl_standing"), after.Score - s.Score);@@ -152,7 +153,7 @@ namespace Statecraft.Sim{var after = s.Clone();var refusal = Spend(c, after, EndKind) ?? Ended(c, after, id, outcome, new List<Cause>());- options.Add(new CaptureOption(outcome, refusal, refusal == null ? Preview(s, after) : null));+ options.Add(new CaptureOption(outcome, refusal, refusal == null ? Preview(c, s, after) : null));}return options;}@@ -453,11 +454,12 @@ namespace Statecraft.Sim/// section 4.1's sober cost preview).</summary>public sealed class CapturePreview{- public double Attention { get; } public double Money { get; } public double Debt { get; }+ /// <summary>Delta for legacy accounting; null when this ruleset has no Attention resource.</summary>+ public double? Attention { get; } public double Money { get; } public double Debt { get; }public int Food { get; } public int Arms { get; }public double SocialCohesion { get; } public double InternationalSupport { get; }public int Score { get; }- public CapturePreview(double attention, double money, double debt, int food, int arms, double socialCohesion, double internationalSupport, int score)+ public CapturePreview(double? attention, double money, double debt, int food, int arms, double socialCohesion, double internationalSupport, int score){Attention = attention; Money = money; Debt = debt; Food = food; Arms = arms;SocialCohesion = socialCohesion; InternationalSupport = internationalSupport; Score = score;diff --git a/sim/Statecraft.Sim/Simulation.cs b/sim/Statecraft.Sim/Simulation.csindex 2e460ef4a..598caa186 100644--- a/sim/Statecraft.Sim/Simulation.cs+++ b/sim/Statecraft.Sim/Simulation.cs@@ -11,7 +11,7 @@ namespace Statecraft.Sim{if (c == null) throw new ArgumentNullException(nameof(c));if (mode == Mode.Open) throw new NotSupportedException("Open mode arrives with milestone M4.");- var s = new GameState { Date = c.Rules.Start, RngState = seed, Mode = mode };+ var s = new GameState(c) { Date = c.Rules.Start, RngState = seed, Mode = mode };var why = new List<Cause>();EffectsSystem.Init(c, s);EconomySystem.Init(c, s);@@ -20,7 +20,7 @@ namespace Statecraft.SimPools.Init(c, s);StartingForces.Init(c, s); // R-UNIT-006: before any event can grant a unit, so the forces take ids 0 to n-1SecuritySystem.Init(c, s, why);- AttentionSystem.Refill(c, s);+ if (c.UsesAttention) AttentionSystem.Refill(c, s);EventSystem.Trigger(c, s, why);return s;}@@ -76,7 +76,7 @@ namespace Statecraft.Sim}ContentWindows.Update(c, s, turnStart);Cabinet.ExpireOnGovernmentChange(c, s, why);- AttentionSystem.Refill(c, s);+ if (c.UsesAttention) AttentionSystem.Refill(c, s);if (s.GameOver == null) EventSystem.Trigger(c, s, why, turnStart); // a game that just ended raises no new eventsreturn new StepResult(s, why, rejected);}@@ -143,9 +143,15 @@ namespace Statecraft.Sim// The call-up and the security order are retired in the GDD loop (R-WAR-002): refused the same way,// before charging, so the state and the Attention are unchanged.if (c.IsGdd && (cmd is SetMobilization || cmd is SecurityOrder)) { rejected.Add(new Rejection(cmd, "That order is not available in this game")); continue; }- var before = s.Attention;- var error = AttentionSystem.TrySpend(c, s, cmd.Kind, priceRung) ?? Execute(c, s, cmd, spent, attacked, why);- if (error != null) { s.Attention = before; rejected.Add(new Rejection(cmd, error)); }+ string? error;+ if (c.UsesAttention)+ {+ var before = s.Attention;+ error = AttentionSystem.TrySpend(c, s, cmd.Kind, priceRung) ?? Execute(c, s, cmd, spent, attacked, why);+ if (error != null) s.Attention = before;+ }+ else error = Execute(c, s, cmd, spent, attacked, why);+ if (error != null) rejected.Add(new Rejection(cmd, error));if (c.IsGdd) SettlementControl.CaptureHeld(c, s, why); // R-CTRL-004: only where an order ends}}