Skip to content

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

sim: budget lines owned by office and date (fixes #108) (#303)

Guy Shoham2558cffad9c7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7767b230f..951d563b4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,10 @@ adds a line under **Unreleased**; CI's `Changelog` job checks this (see `CONTRIB
## [Unreleased]
### Added
+- Budget lines owned by office and date (`budget_owners` in `rules.yaml`, issue #108): the Immigration line (its id stays
+ `prime_minister`) belongs to the Minister of Immigration until 7 October 1951 and to the Prime Minister from 8 October
+ 1951. A line scales effects through the owner of the day, and the Budget screen names that office. An office with
+ several holders cannot own a line. The goldens do not move.
- Coalition changes inside a government's term (`coalition_changes` in governments.yaml, each with a date and sources).
Seats, majority, the Cabinet's party rule and the causes use the coalition of the day. Adds Agudat Yisrael and Poalei
Agudat Yisrael leaving the Third Government (18 September 1952, so 60 of 120 seats and no majority until 24 December),
diff --git a/content/rules.yaml b/content/rules.yaml
index 32514719a..d629cf018 100644
--- a/content/rules.yaml
+++ b/content/rules.yaml
@@ -62,12 +62,26 @@ initial_population: { veterans: 649400 }
budget_start:
defense_minister: 0.45
finance_minister: 0.05
- # No Immigration portfolio in the Third Government; absorption is assumed to sit with the Jewish Agency and the Prime
- # Minister (notes, Addendum (a), unverified). The Ministry of Immigration ends on 1951-10-08, so its budget line sits
- # with the Prime Minister (the loader refuses a line for an abolished office).
+ # The Immigration line. Its id stays `prime_minister` (ids are stable: a rename would move every golden hash and break
+ # the replay of saved budget orders), but it was the Ministry of Immigration's line until 8 October 1951:
+ # budget_owners below says which office owns it on each date, and the Budget screen shows that office.
prime_minister: 0.15
labour_minister: 0.10
health_minister: 0.07
education_minister: 0.06
agriculture_minister: 0.07
interior_minister: 0.05
+# Who owns a budget line, by date (issue #108). A line with no entry here belongs to the office with its own id for the
+# whole era. The first owner starts on the era's first day; each later owner starts on its `from`; every owner's office
+# must exist on its dates (the loader checks). The Ministry of Aliyah (immigration_minister) ends on 8 October 1951: the
+# Knesset's government-positions table (KNS_PersonToPosition, GovernmentNum 2, read 2026-10-12) lists "Minister of
+# Aliyah" (GovMinistryID 784) for Haim-Moshe Shapira (PersonID 2661) from 1 November 1950 to 8 October 1951, and
+# GovernmentNum 3 (from 8 October 1951) lists no such ministry. The same table lists no immigration or absorption
+# portfolio for the Prime Minister (Ben-Gurion, PersonID 2198) in the Third Government. That the line then sits with the
+# Prime Minister is an assumption (research notes M3 1950-51, Addendum (a), unverified), as in M3: absorption is
+# assumed to stay with the Jewish Agency and the Prime Minister. Re-point the second owner if a source shows otherwise.
+# Source: https://knesset.gov.il/Odata/ParliamentInfo.svc/KNS_PersonToPosition?$filter=GovernmentNum%20eq%202 (and eq 3).
+budget_owners:
+ prime_minister:
+ - { from: 1948-05-15, office: immigration_minister }
+ - { from: 1951-10-08, office: prime_minister }
diff --git a/docs/WRITING_EVENTS.md b/docs/WRITING_EVENTS.md
index dab39433f..71fceb4e2 100644
--- a/docs/WRITING_EVENTS.md
+++ b/docs/WRITING_EVENTS.md
@@ -268,3 +268,22 @@ including entries carried in an older save.
`from` (the day an office was established) and `until` (the day it was abolished) limit when an office is a Cabinet seat
and can be filled. Terms in `people.yaml` must fall between them. A budget line may run before `from`: the Budget
screen then names the date the ministry begins instead of calling it vacant.
+
+### Budget lines owned by office and date
+
+A line in `rules.yaml` `budget_start` is keyed by its own id. With no `budget_owners` entry, the office with that id owns it
+for the whole era (and must not be abolished). A line can have a dated list of owners instead:
+
+```yaml
+budget_start:
+ prime_minister: 0.15 # the Immigration line; its id stays as it was, the owner changes
+budget_owners:
+ prime_minister:
+ - { from: 1948-05-15, office: immigration_minister }
+ - { from: 1951-10-08, office: prime_minister }
+```
+
+The first owner starts on the first day of the era (no gap). Each `from` is inside the era and after the one before. Each
+owner's office must exist from its `from` to the next `from` (or the end of the era), and one office may own only one line on
+any day. The loader refuses anything else. `Offices.BudgetOwner(content, line, date)` and `Offices.BudgetLineOf(content,
+office, date)` are the only readers. Lines that change across an era boundary are the carry rules' job (#59).
diff --git a/docs/determinism.md b/docs/determinism.md
index 8266ebcf3..b5f92a0ad 100644
--- a/docs/determinism.md
+++ b/docs/determinism.md
@@ -63,7 +63,7 @@ change only at era boundaries (chapters spec section 3.3). Spec section 4.1 will
on it, so every turn then lies in one era; until that lands, only the last era's end is a boundary turn, and a turn that
starts in one era and ends in the next uses the starting era's rules for its whole length
(`EraRulesSwitchTests.ARunPicksUpTheOverrideFromTheFirstTurnThatStartsInTheNewEra`). Start
-values (`start`, `treasury_start`, `fx_start`, `start_rung`, `initial_population`, `budget_start`) are read once by `NewGame`
+values (`start`, `treasury_start`, `fx_start`, `start_rung`, `initial_population`, `budget_start`, `budget_owners`) are read once by `NewGame`
from the base `rules.yaml`: an era override cannot set them. A map action's display name is also read from the base rules,
because an override cannot remove an action. `EraRulesSwitchTests.OnlyStartValuesAndMapActionNamesReadTheBaseRulesDirectly`
fails if a file in `sim/Statecraft.Sim` reads `Rules` directly for anything else, including a bare `var r = c.Rules;`.
diff --git a/docs/m3-rulings.md b/docs/m3-rulings.md
index b60e4030f..e1fe3794d 100644
--- a/docs/m3-rulings.md
+++ b/docs/m3-rulings.md
@@ -49,7 +49,7 @@ These are the decisions made while building M3 where the spec or plan was silent
- **Historical choices have halved security and stability deltas.** Alternatives are halved too, which keeps the shape of each trade-off. The elections event has a single option.
- **Sensitive tags stay honest.** The war-casualties and terror tags were kept, because they already sit in the loader's sensitive list. The sensitivity review of 7 events is an owner step, not a self-approval.
- **Event timing is fitted to the facts, not to the plan.** For example, `hula_drainage` waits for 7 March 1951, and the forex event waits for 1951-10-19. The Bonds window starts at the 10 May launch. Clothing rationing has no food effects. Education concede costs morale 0.03, because the model has no coalition target. Reparations refuse has no penalty (no moral judgement). Maabarot text says "transit camps" before 21 April 1950. Event effects on coalition or support are a Deferred M4 row.
-- **Dated budget ownership is deferred.** The Immigration budget stays on the PM from game start, not Shapira. Cost if wrong: absorption spending is scaled by the PM, not Shapira, for 1948–51.
+- **Dated budget ownership is deferred.** The Immigration budget stays on the PM from game start, not Shapira. Cost if wrong: absorption spending is scaled by the PM, not Shapira, for 1948–51. Update (#108): dated budget ownership landed (`budget_owners` in `content/rules.yaml`): the line keeps its id `prime_minister` and belongs to Shapira's ministry until 8 October 1951.
## UI and input
diff --git a/sim/Statecraft.Sim.Tests/BudgetOwnersTests.cs b/sim/Statecraft.Sim.Tests/BudgetOwnersTests.cs
new file mode 100644
index 000000000..44d8f1158
--- /dev/null
+++ b/sim/Statecraft.Sim.Tests/BudgetOwnersTests.cs
@@ -0,0 +1,250 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using Statecraft.Sim;
+
+/// <summary>Budget lines owned by an office and a date (#108): rules.yaml budget_owners, read through
+/// Offices.BudgetOwner and Offices.BudgetLineOf, and the factor and competence the owner of the day gives.</summary>
+public class BudgetOwnersTests
+{
+ // A supply ministry ends on 1 January 1950; its line then passes to the Prime Minister (pm_one, competence 8).
+ // sup_one (competence 2) holds supply until then. def_two (competence 4) holds defense and finance.
+ const string SupplyOffice = " - id: supply_minister\n title: Minister of Supply\n until: 1950-01-01\n";
+ const string SupplyPerson = @"
+ - id: sup_one
+ name: Sup One
+ living: false
+ competence: 2
+ loyalty: 5
+ offices:
+ - office: supply_minister
+ from: 1948-05-14
+ to: 1950-01-01
+";
+ const string Shares = "budget_start: { finance_minister: 0.4, defense_minister: 0.4, supply: 0.2 }\n";
+ const string Owners = "budget_owners:\n supply:\n - { from: 1948-05-15, office: supply_minister }\n - { from: 1950-01-01, office: prime_minister }\n";
+
+ static Dictionary<string, string> Files(string owners = Owners, string shares = Shares, string? offices = null) => new Dictionary<string, string>
+ {
+ ["offices.yaml"] = offices ?? Fixture.Files["offices.yaml"] + SupplyOffice,
+ ["people.yaml"] = Fixture.Files["people.yaml"] + SupplyPerson,
+ ["rules.yaml"] = Fixture.Files["rules.yaml"].Replace("budget_start: { finance_minister: 1.0 }\n", shares + owners),
+ };
+
+ static Content Load(string owners = Owners, string shares = Shares, string? offices = null) =>
+ ContentLoader.Load(Fixture.Write(Files(owners, shares, offices)));
+
+ static GameState At(Content c, DateTime date)
+ {
+ var s = Simulation.NewGame(c, 1, Mode.Historical);
+ s.Date = date;
+ return s;
+ }
+
+ static readonly DateTime Last = new DateTime(1949, 12, 31);
+ static readonly DateTime Change = new DateTime(1950, 1, 1);
+
+ [Fact]
+ public void TheOwnerChangesOnItsDate()
+ {
+ var c = Load();
+ Assert.Equal("supply_minister", Offices.BudgetOwner(c, "supply", new DateTime(1948, 5, 15)));
+ Assert.Equal("supply_minister", Offices.BudgetOwner(c, "supply", Last));
+ Assert.Equal("prime_minister", Offices.BudgetOwner(c, "supply", Change));
+ Assert.Equal("prime_minister", Offices.BudgetOwner(c, "supply", new DateTime(1956, 12, 31)));
+ }
+
+ [Fact]
+ public void ALineWithNoEntryBelongsToTheOfficeOfItsOwnIdAndAnUnknownLineToNobody()
+ {
+ var c = Load();
+ Assert.Equal("finance_minister", Offices.BudgetOwner(c, "finance_minister", Last));
+ Assert.Equal("finance_minister", Offices.BudgetOwner(c, "finance_minister", Change));
+ Assert.Null(Offices.BudgetOwner(c, "nonsense", Last));
+ Assert.Null(Offices.BudgetOwner(c, "prime_minister", Last)); // an office is not a line
+ }
+
+ [Fact]
+ public void AnOfficeFindsTheLineItOwnsOnADate()
+ {
+ var c = Load();
+ Assert.Equal("supply", Offices.BudgetLineOf(c, "supply_minister", Last));
+ Assert.Null(Offices.BudgetLineOf(c, "prime_minister", Last));
+ Assert.Null(Offices.BudgetLineOf(c, "supply_minister", Change));
+ Assert.Equal("supply", Offices.BudgetLineOf(c, "prime_minister", Change));
+ Assert.Equal("finance_minister", Offices.BudgetLineOf(c, "finance_minister", Change));
+ }
+
+ [Fact]
+ public void TheFactorAndTheCompetenceAreTheOwnersOfTheDay()
+ {
+ var c = Load();
+ var line = 0.5 + 0.2 * 3 / 2.0; // 0.8: the supply line's factor
+ var before = At(c, Last);
+ Assert.Equal((0.5 + 2 / 20.0) * line, EffectsSystem.Multiplier(c, before, "supply_minister"), 9); // sup_one
+ Assert.Equal(line, EffectsSystem.BudgetFactor(c, before, "supply_minister"), 9);
+ Assert.Equal(0.5 + 8 / 20.0, EffectsSystem.Multiplier(c, before, "prime_minister"), 9); // no line yet: neutral
+ Assert.Equal(1.0, EffectsSystem.BudgetFactor(c, before, "prime_minister"), 9);
+ var after = At(c, Change);
+ Assert.Equal(0.5, EffectsSystem.Multiplier(c, after, "supply_minister"), 9); // vacant, no line
+ Assert.Equal(1.0, EffectsSystem.BudgetFactor(c, after, "supply_minister"), 9);
+ Assert.Equal((0.5 + 8 / 20.0) * line, EffectsSystem.Multiplier(c, after, "prime_minister"), 9); // pm_one now scales it
+ Assert.Equal(line, EffectsSystem.BudgetFactor(c, after, "prime_minister"), 9);
+ }
+
+ [Fact]
+ public void TheStateKeepsTheLineIdAcrossTheDate()
+ {
+ var c = Load();
+ var s = Simulation.NewGame(c, 1, Mode.Historical);
+ Assert.Equal(0.2, s.Budget["supply"]);
+ Assert.DoesNotContain("supply_minister", s.Budget.Keys);
+ // The player sets the line by its own id on either side of the date.
+ Assert.Null(EconomySystem.Allocate(c, s, new Dictionary<string, double> { ["finance_minister"] = 0.3, ["defense_minister"] = 0.3, ["supply"] = 0.4 }));
+ s.Date = Change;
+ Assert.Null(EconomySystem.Allocate(c, s, new Dictionary<string, double> { ["finance_minister"] = 0.2, ["defense_minister"] = 0.2, ["supply"] = 0.6 }));
+ Assert.NotNull(EconomySystem.Allocate(c, s, new Dictionary<string, double> { ["finance_minister"] = 0.2, ["defense_minister"] = 0.2, ["supply_minister"] = 0.6 }));
+ }
+
+ [Fact]
+ public void ALineNeverPointsAtAnInactiveOfficeInTheRealContent()
+ {
+ var c = ContentLoader.Load(RealContentTests.ContentRoot());
+ var era = c.Eras.First();
+ int checkedLines = 0;
+ foreach (var line in c.Rules.BudgetOwners.Keys)
+ for (var d = era.From; d < era.To; d = d.AddDays(7))
+ {
+ var owner = Offices.BudgetOwner(c, line, d)!;
+ Assert.True(c.Offices.Single(o => o.Id == owner).ExistsOn(d), $"{line} on {d:yyyy-MM-dd} points at inactive {owner}");
+ checkedLines++;
+ }
+ Assert.True(checkedLines > 0);
+ // Every line whose id is an office id is owned by that office, which is not abolished.
+ foreach (var line in c.Rules.BudgetStart.Keys.Where(k => !c.Rules.BudgetOwners.ContainsKey(k)))
+ Assert.Null(c.Offices.Single(o => o.Id == line).Until);
+ }
+
+ [Fact]
+ public void TheRealImmigrationLineMovesToThePrimeMinisterOn8October1951()
+ {
+ var c = ContentLoader.Load(RealContentTests.ContentRoot());
+ Assert.Equal("immigration_minister", Offices.BudgetOwner(c, "prime_minister", c.Rules.Start));
+ Assert.Equal("immigration_minister", Offices.BudgetOwner(c, "prime_minister", new DateTime(1951, 10, 7)));
+ Assert.Equal("prime_minister", Offices.BudgetOwner(c, "prime_minister", new DateTime(1951, 10, 8)));
+ Assert.Equal(c.Offices.Single(o => o.Id == "immigration_minister").Until, c.Rules.BudgetOwners["prime_minister"][1].From); // the date cannot drift from offices.yaml
+ var share = c.Rules.BudgetStart["prime_minister"];
+ var factor = Math.Min(1.5, 0.5 + share * c.Rules.BudgetStart.Count / 2.0);
+
+ var before = At(c, new DateTime(1951, 10, 7));
+ var shapira = Cabinet.Holder(c, before, "immigration_minister")!;
+ Assert.Equal("shapira", shapira.Id);
+ Assert.Equal((0.5 + shapira.Competence / 20.0) * factor, EffectsSystem.Multiplier(c, before, "immigration_minister"), 9);
+ Assert.Equal(1.0, EffectsSystem.BudgetFactor(c, before, "prime_minister"), 9);
+
+ var after = At(c, new DateTime(1951, 10, 8));
+ var pm = Cabinet.Holder(c, after, "prime_minister")!;
+ Assert.Equal((0.5 + pm.Competence / 20.0) * factor, EffectsSystem.Multiplier(c, after, "prime_minister"), 9);
+ Assert.Equal(1.0, EffectsSystem.BudgetFactor(c, after, "immigration_minister"), 9);
+ }
+
+ // ---- the loader ----
+
+ [Theory]
+ [InlineData("budget_owners:\n supply:\n - { from: 1948-05-15, office: supply_minister }\n - { from: 1950-01-01, office: supply_minister }\n", "budget_owners.supply[1].office", "does not exist on 1950-01-01")] // inactive on its dates
+ [InlineData("budget_owners:\n supply:\n - { from: 1948-05-15, office: supply_minister }\n - { from: 1949-06-01, office: prime_minister }\n - { from: 1950-01-01, office: supply_minister }\n", "budget_owners.supply[2].office", "does not exist on 1950-01-01")]
+ [InlineData("budget_owners:\n supply:\n - { from: 1948-05-15, office: supply_minister }\n", "budget_owners.supply[0].office", "is abolished on 1950-01-01")] // the last owner must last to the end of the era
+ [InlineData("budget_owners:\n supply:\n - { from: 1948-05-15, office: supply_ministre }\n", "budget_owners.supply[0].office", "unknown office")] // a typo
+ [InlineData("budget_owners:\n supply:\n - { from: 1948-05-15, office: prime_minister }\n - { from: 1957-01-01, office: prime_minister }\n", "budget_owners.supply[1].from", "must be inside the era")] // on the era's end
+ [InlineData("budget_owners:\n supply:\n - { from: 1948-05-15, office: prime_minister }\n - { from: 1960-01-01, office: prime_minister }\n", "budget_owners.supply[1].from", "must be inside the era")]
+ [InlineData("budget_owners:\n supply:\n - { from: 1948-05-14, office: supply_minister }\n - { from: 1950-01-01, office: prime_minister }\n", "budget_owners.supply[0].from", "must be inside the era")] // before the era
+ [InlineData("budget_owners:\n supply:\n - { from: 1949-01-01, office: supply_minister }\n - { from: 1950-01-01, office: prime_minister }\n", "budget_owners.supply[0].from", "no gap")]
+ [InlineData("budget_owners:\n supply:\n - { from: 1948-05-15, office: supply_minister }\n - { from: 1950-01-01, office: prime_minister }\n - { from: 1949-06-01, office: prime_minister }\n", "budget_owners.supply[2].from", "must be after the previous owner")]
+ [InlineData("budget_owners:\n supply: []\n", "budget_owners.supply", "needs at least one owner")]
+ [InlineData("budget_owners:\n suply:\n - { from: 1948-05-15, office: prime_minister }\n", "budget_owners.suply", "unknown budget line")]
+ [InlineData("budget_owners:\n supply:\n - { office: prime_minister }\n", "budget_owners.supply[0].from", "required")]
+ [InlineData("budget_owners:\n supply:\n - { from: 1948-05-15, office: prime_minister }\n finance_minister:\n - { from: 1948-05-15, office: prime_minister }\n", "budget_start.supply", "would own both")] // two lines, one office, one day
+ public void TheLoaderRefusesABadOwner(string owners, string field, string message)
+ {
+ var e = Assert.Throws<ContentException>(() => Load(owners));
+ Assert.Equal("rules.yaml", e.File);
+ Assert.Equal(field, e.Field);
+ Assert.Contains(message, e.Message);
+ }
+
+ [Fact]
+ public void AHistoricalOnlyOrSeveralHolderOfficeCannotOwnALine()
+ {
+ var offices = Fixture.Files["offices.yaml"] + SupplyOffice
+ + " - id: elder\n title: Elder\n historical_only: true\n"
+ + " - id: without_portfolio\n title: Minister without Portfolio\n several_holders: true\n";
+ foreach (var (office, message) in new[] { ("elder", "historical-only"), ("without_portfolio", "several holders") })
+ {
+ var owned = Assert.Throws<ContentException>(() => Load($"budget_owners:\n supply:\n - {{ from: 1948-05-15, office: supply_minister }}\n - {{ from: 1950-01-01, office: {office} }}\n", offices: offices));
+ Assert.Equal("budget_owners.supply[1].office", owned.Field);
+ Assert.Contains(message, owned.Message);
+ var ownLine = Assert.Throws<ContentException>(() => Load(owners: "", shares: $"budget_start: {{ finance_minister: 0.5, {office}: 0.5 }}\n", offices: offices));
+ Assert.Equal($"budget_start.{office}", ownLine.Field);
+ Assert.Contains(message, ownLine.Message);
+ }
+ }
+
+ [Fact]
+ public void AnOfficeCanHandOneLineOverAndTakeAnotherOnTheSameDay()
+ {
+ // The Prime Minister owns relief until 1 January 1950 and supply from that day: the stretches touch, they do not overlap.
+ var offices = Fixture.Files["offices.yaml"] + SupplyOffice + " - id: relief_minister\n title: Minister of Relief\n";
+ var c = Load(Owners + " relief:\n - { from: 1948-05-15, office: prime_minister }\n - { from: 1950-01-01, office: relief_minister }\n",
+ "budget_start: { finance_minister: 0.4, defense_minister: 0.3, supply: 0.2, relief: 0.1 }\n", offices);
+ Assert.Equal("relief", Offices.BudgetLineOf(c, "prime_minister", Last));
+ Assert.Equal("supply", Offices.BudgetLineOf(c, "prime_minister", Change));
+ Assert.Equal("relief", Offices.BudgetLineOf(c, "relief_minister", Change));
+ }
+
+ [Fact]
+ public void ALineIdWithDatedOwnersIsLowercase()
+ {
+ var e = Assert.Throws<ContentException>(() => Load(Owners.Replace(" supply:", " Supply:"), Shares.Replace("supply:", "Supply:")));
+ Assert.Equal("budget_start.Supply", e.Field);
+ Assert.Contains("lowercase", e.Message);
+ }
+
+ [Fact]
+ public void ATypoInAnOwnerKeyFailsAtTheYamlLevel()
+ {
+ Assert.Throws<ContentException>(() => Load("budget_owners:\n supply:\n - { from: 1948-05-15, ofice: prime_minister }\n"));
+ Assert.Throws<ContentException>(() => Load("budget_owners:\n supply: prime_minister\n")); // a bare id is not a dated list
+ Assert.Throws<ContentException>(() => Load("budget_owners:\n supply:\n - { from: not-a-date, office: prime_minister }\n"));
+ }
+
+ [Fact]
+ public void ALineWithNoOwnerEntryNeedsAnOfficeOfItsOwnId()
+ {
+ var e = Assert.Throws<ContentException>(() => Load(owners: "", shares: Shares));
+ Assert.Equal("budget_start.supply", e.Field);
+ Assert.Contains("unknown office", e.Message);
+ }
+
+ [Fact]
+ public void AnOfficeEndingBeforeTheEraEndStillNeedsADatedOwnerForItsOwnLine()
+ {
+ // The older rule still holds: a line keyed by an abolished office, with no dated owners, is refused.
+ var e = Assert.Throws<ContentException>(() => Load(owners: "", shares: "budget_start: { finance_minister: 0.5, supply_minister: 0.5 }\n"));
+ Assert.Equal("budget_start.supply_minister", e.Field);
+ Assert.Contains("is abolished on 1950-01-01", e.Message);
+ Assert.Contains("budget_owners", e.Message);
+ }
+
+ [Fact]
+ public void AnEraOverrideCannotSetTheOwners()
+ {
+ var eras = "eras:\n - { id: founding, name: The Founding, from: 1948-05-15, to: 1952-01-01 }\n - { id: later, name: A Later Chapter, from: 1952-01-01, to: 1957-01-01 }\n";
+ var files = Files();
+ files["eras.yaml"] = eras;
+ var dir = Fixture.Write(files);
+ System.IO.Directory.CreateDirectory(System.IO.Path.Combine(dir, "rules"));
+ System.IO.File.WriteAllText(System.IO.Path.Combine(dir, "rules", "later.yaml"), "budget_owners:\n supply:\n - { from: 1952-01-01, office: prime_minister }\n");
+ var e = Assert.Throws<ContentException>(() => ContentLoader.Load(dir));
+ Assert.Equal("budget_owners", e.Field);
+ }
+}
diff --git a/sim/Statecraft.Sim.Tests/EconomyM3Tests.cs b/sim/Statecraft.Sim.Tests/EconomyM3Tests.cs
index 31a4eda6b..5d6023cd4 100644
--- a/sim/Statecraft.Sim.Tests/EconomyM3Tests.cs
+++ b/sim/Statecraft.Sim.Tests/EconomyM3Tests.cs
@@ -84,8 +84,6 @@ public class EconomyM3Tests
Assert.Equal(1.25, EffectsSystem.BudgetFactor(draft, "a"), 9); // 0.5 + 0.5 * 3 / 2
Assert.Equal(0.8, EffectsSystem.BudgetFactor(draft, "c"), 9);
Assert.Equal(1.0, EffectsSystem.BudgetFactor(draft, "z"), 9); // no line: neutral
- var s = new GameState { Budget = draft };
- Assert.Equal(EffectsSystem.BudgetFactor(draft, "b"), EffectsSystem.BudgetFactor(s, "b"));
}
[Fact]
diff --git a/sim/Statecraft.Sim.Tests/EconomyTests.cs b/sim/Statecraft.Sim.Tests/EconomyTests.cs
index 77a4ae02b..b256d2672 100644
--- a/sim/Statecraft.Sim.Tests/EconomyTests.cs
+++ b/sim/Statecraft.Sim.Tests/EconomyTests.cs
@@ -66,10 +66,10 @@ public class EconomyTests
public void BudgetShareScalesEffects()
{
var s = Fresh();
- Assert.Equal(1.0, EffectsSystem.BudgetFactor(s, "finance_minister")); // equal split is neutral
+ Assert.Equal(1.0, EffectsSystem.BudgetFactor(C, s, "finance_minister")); // equal split is neutral
s.Budget = new Dictionary<string, double> { ["finance_minister"] = 0.0, ["defense_minister"] = 1.0 };
- Assert.Equal(0.5, EffectsSystem.BudgetFactor(s, "finance_minister"));
- Assert.Equal(1.5, EffectsSystem.BudgetFactor(s, "defense_minister"));
+ Assert.Equal(0.5, EffectsSystem.BudgetFactor(C, s, "finance_minister"));
+ Assert.Equal(1.5, EffectsSystem.BudgetFactor(s.Budget, "defense_minister"));
}
}
diff --git a/sim/Statecraft.Sim.Tests/EraRulesSwitchTests.cs b/sim/Statecraft.Sim.Tests/EraRulesSwitchTests.cs
index b4dcd9bfd..c8ea5fb22 100644
--- a/sim/Statecraft.Sim.Tests/EraRulesSwitchTests.cs
+++ b/sim/Statecraft.Sim.Tests/EraRulesSwitchTests.cs
@@ -184,7 +184,7 @@ eras:
public void OnlyStartValuesAndMapActionNamesReadTheBaseRulesDirectly()
{
var simDir = Path.Combine(Directory.GetParent(RealContentTests.ContentRoot())!.FullName, "sim", "Statecraft.Sim");
- var allowed = new HashSet<string> { "Start", "TreasuryStart", "FxStart", "BudgetStart", "InitialPopulation", "StartRung", "MapActions" };
+ var allowed = new HashSet<string> { "Start", "TreasuryStart", "FxStart", "BudgetStart", "InitialPopulation", "StartRung", "MapActions", "BudgetOwners" };
var bad = new List<string>();
foreach (var f in Directory.GetFiles(simDir, "*.cs", SearchOption.AllDirectories))
{
diff --git a/sim/Statecraft.Sim.Tests/RealContentTests.cs b/sim/Statecraft.Sim.Tests/RealContentTests.cs
index c43e7eeca..7b0df92f0 100644
--- a/sim/Statecraft.Sim.Tests/RealContentTests.cs
+++ b/sim/Statecraft.Sim.Tests/RealContentTests.cs
@@ -132,10 +132,10 @@ public class RealContentTests
var state = Simulation.NewGame(C, 42, Mode.Historical);
state.Date = change.AddDays(-1);
Assert.Equal(0.9, EffectsSystem.Multiplier(C, state, "agriculture_minister") /
- EffectsSystem.BudgetFactor(state, "agriculture_minister"), 10);
+ EffectsSystem.BudgetFactor(C, state, "agriculture_minister"), 10);
state.Date = change;
Assert.Equal(0.85, EffectsSystem.Multiplier(C, state, "agriculture_minister") /
- EffectsSystem.BudgetFactor(state, "agriculture_minister"), 10);
+ EffectsSystem.BudgetFactor(C, state, "agriculture_minister"), 10);
Assert.Equal("kaplan", Cabinet.Holder(C, state, "minister_without_portfolio")?.Id);
Assert.DoesNotContain(Cabinet.Lineup(C, state), seat => seat.Office.Id == "deputy_prime_minister");
state.Date = end;
@@ -206,7 +206,7 @@ public class RealContentTests
{
Assert.DoesNotContain("rationing_minister", C.Rules.BudgetStart.Keys);
var s = Simulation.NewGame(C, 1, Mode.Historical);
- Assert.Equal(1.0, EffectsSystem.BudgetFactor(s, "rationing_minister"));
+ Assert.Equal(1.0, EffectsSystem.BudgetFactor(C, s, "rationing_minister"));
}
[Fact]
@@ -281,7 +281,7 @@ public class RealContentTests
Assert.Equal(new DateTime(1951, 10, 8), C.Offices.Single(o => o.Id == "immigration_minister").Until);
Assert.Equal(new DateTime(1951, 10, 8), C.Offices.Single(o => o.Id == "war_victims_minister").Until);
Assert.Equal("shapira", Who("immigration_minister", 1951, 10, 7));
- Assert.Equal(0.15, C.Rules.BudgetStart["prime_minister"]);
+ Assert.Equal(0.15, C.Rules.BudgetStart["prime_minister"]); // the Immigration line keeps its id (#108)
var sheetrit = C.People.Single(p => p.Id == "sheetrit");
Assert.Equal("sephardim", Offices.PartyOf(C, sheetrit, new DateTime(1951, 1, 1)));
Assert.Equal("mapai", Offices.PartyOf(C, sheetrit, new DateTime(1951, 10, 8)));
diff --git a/sim/Statecraft.Sim/Content.cs b/sim/Statecraft.Sim/Content.cs
index 3e70f7333..9d8eae0df 100644
--- a/sim/Statecraft.Sim/Content.cs
+++ b/sim/Statecraft.Sim/Content.cs
@@ -226,6 +226,17 @@ namespace Statecraft.Sim
public double NaturalIncreasePerYear { get; set; }
public Dictionary<string, double> InitialPopulation { get; set; } = new Dictionary<string, double>();
public Dictionary<string, double> BudgetStart { get; set; } = new Dictionary<string, double>();
+ /// <summary>Who owns a budget line, by date (#108). A line with no entry here is owned, for the whole era, by the
+ /// office with the line's own id. A listed line is owned by each term's office from that term's day to the next
+ /// term's day. Read through <see cref="Offices.BudgetOwner"/> and <see cref="Offices.BudgetLineOf"/>. Start-only, like budget_start.</summary>
+ public Dictionary<string, List<BudgetOwnerTerm>> BudgetOwners { get; set; } = new Dictionary<string, List<BudgetOwnerTerm>>();
+ }
+
+ /// <summary>One stretch of a budget line's ownership (rules.yaml budget_owners): from this day (inclusive) the office owns the line.</summary>
+ public sealed class BudgetOwnerTerm
+ {
+ public DateTime From { get; set; }
+ public string Office { get; set; } = "";
}
/// <summary>Price and effect of one map action (rules.yaml map_actions).</summary>
diff --git a/sim/Statecraft.Sim/ContentLoader.cs b/sim/Statecraft.Sim/ContentLoader.cs
index 96e23c797..863cfb82a 100644
--- a/sim/Statecraft.Sim/ContentLoader.cs
+++ b/sim/Statecraft.Sim/ContentLoader.cs
@@ -79,7 +79,7 @@ namespace Statecraft.Sim
/// <summary>Keys an era override may not set: the values <c>NewGame</c> reads once. A later era's start values
/// belong in start/&lt;era&gt;.yaml (chapters spec section 6), and the set of budget lines in the carry rules (section 4).</summary>
- static readonly string[] StartOnlyKeys = { "start", "treasury_start", "fx_start", "start_rung", "initial_population", "budget_start" };
+ static readonly string[] StartOnlyKeys = { "start", "treasury_start", "fx_start", "start_rung", "initial_population", "budget_start", "budget_owners" };
/// <summary>Era rules (#58): for each era with a content/rules/&lt;era&gt;.yaml file, rules.yaml with that file's keys
/// merged in at the YAML-node level (maps merge key by key, a list or a value replaces), then read with the strict
@@ -395,17 +395,60 @@ namespace Statecraft.Sim
if (r.FxCrisisFoodPerYear > 0) throw new ContentException(file, "fx_crisis_food_per_year", "must be <= 0 (a crisis cuts food imports)");
if (r.FxCrisisFoodPerYear < 0 && !indicators.Contains("food_supply")) throw new ContentException(file, "fx_crisis_food_per_year", "needs a food_supply indicator in model.yaml");
foreach (var kv in r.InitialPopulation) Count(file, $"initial_population.{kv.Key}", kv.Value);
+ // Budget lines (#108). A line is keyed by its own id. With no budget_owners entry the office of that id owns it for
+ // the whole era; with an entry, a dated list says which office owns it when. Within one era only: a line that
+ // changes across an era boundary is the carry rules' job (chapters spec section 4, #59).
+ var era = c.EraAt(r.Start);
+ var eraEnd = era?.To ?? DateTime.MaxValue;
+ foreach (var kv in r.BudgetOwners)
+ if (!r.BudgetStart.ContainsKey(kv.Key)) throw new ContentException(file, $"budget_owners.{kv.Key}", "unknown budget line: list it in budget_start");
+ var spans = new List<(string line, string office, DateTime from, DateTime to)>();
foreach (var kv in r.BudgetStart)
{
- if (!offices.Contains(kv.Key)) throw new ContentException(file, $"budget_start.{kv.Key}", "unknown office");
- if (historicalOffices.Contains(kv.Key)) throw new ContentException(file, $"budget_start.{kv.Key}", "historical-only titles cannot have a budget line");
- // A budget line must not silently stop mattering when its office is abolished: move it to the office that
- // took over (plan amendment C3).
- var until = c.Offices.First(o => o.Id == kv.Key).Until;
- if (until.HasValue)
- throw new ContentException(file, $"budget_start.{kv.Key}", FormattableString.Invariant($"office '{kv.Key}' is abolished on {until:yyyy-MM-dd}: give its budget line to the office that took over"));
Unit(file, $"budget_start.{kv.Key}", kv.Value);
+ if (!r.BudgetOwners.TryGetValue(kv.Key, out var terms))
+ {
+ if (!offices.Contains(kv.Key)) throw new ContentException(file, $"budget_start.{kv.Key}", "unknown office (or give the line an owner in budget_owners)");
+ if (historicalOffices.Contains(kv.Key)) throw new ContentException(file, $"budget_start.{kv.Key}", "historical-only titles cannot have a budget line");
+ if (c.Offices.Any(o => o.Id == kv.Key && o.SeveralHolders)) throw new ContentException(file, $"budget_start.{kv.Key}", "an office with several holders cannot own a budget line");
+ // A budget line must not silently stop mattering when its office is abolished: give it dated owners (#108).
+ var until = c.Offices.First(o => o.Id == kv.Key).Until;
+ if (until.HasValue)
+ throw new ContentException(file, $"budget_start.{kv.Key}", FormattableString.Invariant($"office '{kv.Key}' is abolished on {until:yyyy-MM-dd}: give its budget line to the office that took over (budget_owners)"));
+ spans.Add((kv.Key, kv.Key, r.Start, eraEnd));
+ continue;
+ }
+ if (!Offices.OfficeId.IsMatch(kv.Key)) throw new ContentException(file, $"budget_start.{kv.Key}", "a budget line id is lowercase letters, digits and underscores");
+ var path = $"budget_owners.{kv.Key}";
+ if (terms.Count == 0) throw new ContentException(file, path, "needs at least one owner");
+ for (int i = 0; i < terms.Count; i++)
+ {
+ var t = terms[i]; var tp = FormattableString.Invariant($"{path}[{i}]");
+ if (t.From == default) throw new ContentException(file, tp + ".from", "required");
+ if (t.From < r.Start || t.From >= eraEnd)
+ throw new ContentException(file, tp + ".from", FormattableString.Invariant($"must be inside the era ({r.Start:yyyy-MM-dd} to {eraEnd:yyyy-MM-dd}); a line that changes across eras is the carry rules' job"));
+ if (i == 0 && t.From != r.Start)
+ throw new ContentException(file, tp + ".from", FormattableString.Invariant($"the first owner must start on {r.Start:yyyy-MM-dd}, the first day of the era (no gap)"));
+ if (i > 0 && t.From <= terms[i - 1].From)
+ throw new ContentException(file, tp + ".from", FormattableString.Invariant($"must be after the previous owner's date ({terms[i - 1].From:yyyy-MM-dd})"));
+ if (t.Office == "" || !offices.Contains(t.Office)) throw new ContentException(file, tp + ".office", "unknown office");
+ if (historicalOffices.Contains(t.Office)) throw new ContentException(file, tp + ".office", "historical-only titles cannot have a budget line");
+ // Like policies and effects (#277): the line's factor scales one minister's competence, so it needs one holder.
+ if (c.Offices.Any(o => o.Id == t.Office && o.SeveralHolders)) throw new ContentException(file, tp + ".office", "an office with several holders cannot own a budget line");
+ var end = i + 1 < terms.Count ? terms[i + 1].From : eraEnd;
+ var office = c.Offices.First(o => o.Id == t.Office);
+ if (!office.ExistsOn(t.From))
+ throw new ContentException(file, tp + ".office", FormattableString.Invariant($"office '{t.Office}' does not exist on {t.From:yyyy-MM-dd}"));
+ if (office.Until.HasValue && office.Until.Value < end)
+ throw new ContentException(file, tp + ".office", FormattableString.Invariant($"office '{t.Office}' is abolished on {office.Until:yyyy-MM-dd}, before this owner's stretch ends ({end:yyyy-MM-dd}): add the office that took over"));
+ spans.Add((kv.Key, t.Office, t.From, end));
+ }
}
+ // One office owns at most one line on any day, so BudgetFactor(office) has one answer.
+ foreach (var a in spans)
+ foreach (var b in spans)
+ if (string.CompareOrdinal(a.line, b.line) < 0 && a.office == b.office && a.from < b.to && b.from < a.to)
+ throw new ContentException(file, $"budget_start.{b.line}", $"office '{a.office}' would own both '{a.line}' and '{b.line}' on the same day");
// The same rule EconomySystem.Allocate applies to every later allocation.
if (r.BudgetStart.Count > 0 && Math.Abs(r.BudgetStart.Values.Sum() - 1.0) > 1e-6) throw new ContentException(file, "budget_start", "shares must sum to 1");
}
diff --git a/sim/Statecraft.Sim/EconomySystem.cs b/sim/Statecraft.Sim/EconomySystem.cs
index f2b957b82..c3511d144 100644
--- a/sim/Statecraft.Sim/EconomySystem.cs
+++ b/sim/Statecraft.Sim/EconomySystem.cs
@@ -73,7 +73,7 @@ namespace Statecraft.Sim
public static string? Allocate(Content c, GameState s, Dictionary<string, double> shares)
{
if (shares == null) return "Budget shares are required";
- var unknown = shares.Keys.OrderBy(k => k, StringComparer.Ordinal).FirstOrDefault(k => c.Offices.All(o => o.Id != k)); // ordinal: play and replay name the same office
+ var unknown = shares.Keys.OrderBy(k => k, StringComparer.Ordinal).FirstOrDefault(k => c.Offices.All(o => o.Id != k) && !c.Rules.BudgetStart.ContainsKey(k)); // ordinal: play and replay name the same office
if (unknown != null) return "The budget names a ministry that does not exist in this game";
if (shares.Values.Any(v => double.IsNaN(v) || double.IsInfinity(v))) return "Budget shares must be finite numbers";
if (!new HashSet<string>(shares.Keys).SetEquals(c.Rules.BudgetStart.Keys))
diff --git a/sim/Statecraft.Sim/EffectsSystem.cs b/sim/Statecraft.Sim/EffectsSystem.cs
index 9a75365f2..2a65f8109 100644
--- a/sim/Statecraft.Sim/EffectsSystem.cs
+++ b/sim/Statecraft.Sim/EffectsSystem.cs
@@ -20,18 +20,23 @@ namespace Statecraft.Sim
if (office == "") return 1.0;
var holder = Cabinet.Holder(c, s, office);
var competence = holder == null ? 0.5 : 0.5 + holder.Competence / 20.0;
- return competence * BudgetFactor(s, office);
+ return competence * BudgetFactor(c, s, office);
}
- /// <summary>An equal split of the budget is neutral (1.0); a ministry's factor runs from 0.5 (no money) to 1.5.
- /// An office with no budget line (not in budget_start, so the player can never fund it) is neutral too:
- /// treating it as unfunded would halve its effects permanently with no way to fix it.</summary>
- public static double BudgetFactor(GameState s, string office) => BudgetFactor(s.Budget, office);
+ /// <summary>The factor of the budget line that <paramref name="office"/> owns on the state's date (#108: a line can
+ /// change owner on a date, see <see cref="Offices.BudgetOwner"/>). An equal split of the budget is neutral (1.0); a
+ /// line's factor runs from 0.5 (no money) to 1.5. An office that owns no line (the player can never fund it) is
+ /// neutral too: treating it as unfunded would halve its effects permanently with no way to fix it.</summary>
+ public static double BudgetFactor(Content c, GameState s, string office)
+ {
+ var line = Offices.BudgetLineOf(c, office, s.Date);
+ return line == null ? 1.0 : BudgetFactor(s.Budget, line);
+ }
- /// <summary>The same rule for any set of shares (the Budget screen shows the factor of a draft budget).</summary>
- public static double BudgetFactor(IReadOnlyDictionary<string, double> budget, string office)
+ /// <summary>The same rule for one budget line of any set of shares (the Budget screen shows the factor of a draft budget).</summary>
+ public static double BudgetFactor(IReadOnlyDictionary<string, double> budget, string line)
{
- if (!budget.TryGetValue(office, out var share)) return 1.0;
+ if (!budget.TryGetValue(line, out var share)) return 1.0;
return Math.Min(1.5, 0.5 + share * budget.Count / 2.0);
}
diff --git a/sim/Statecraft.Sim/Offices.cs b/sim/Statecraft.Sim/Offices.cs
index 4e9669a79..659280249 100644
--- a/sim/Statecraft.Sim/Offices.cs
+++ b/sim/Statecraft.Sim/Offices.cs
@@ -24,6 +24,24 @@ namespace Statecraft.Sim
public static string PartyOf(Content c, Person p, DateTime date) =>
p.Offices.FirstOrDefault(t => t.Party != "" && In(date, t.From, t.To))?.Party ?? p.Party;
+ /// <summary>The office that owns budget line <paramref name="line"/> on date (#108): the last term of rules.yaml
+ /// budget_owners that has begun, or, for a line with no entry, the office with the line's own id. Null when the
+ /// line does not exist or its first term has not begun. Lines are start-only, so this reads the base rules.</summary>
+ public static string? BudgetOwner(Content c, string line, DateTime date)
+ {
+ if (!c.Rules.BudgetStart.ContainsKey(line)) return null;
+ if (!c.Rules.BudgetOwners.TryGetValue(line, out var terms)) return line;
+ string? owner = null;
+ foreach (var t in terms.OrderBy(t => t.From))
+ if (t.From <= date) owner = t.Office;
+ return owner;
+ }
+
+ /// <summary>The budget line that <paramref name="office"/> owns on date, or null when it owns none (the loader allows
+ /// at most one). Lines are searched in ordinal order, so the answer never depends on dictionary order.</summary>
+ public static string? BudgetLineOf(Content c, string office, DateTime date) =>
+ c.Rules.BudgetStart.Keys.OrderBy(k => k, StringComparer.Ordinal).FirstOrDefault(l => BudgetOwner(c, l, date) == office);
+
public static Legislature? Legislature(Content c, DateTime date) =>
c.Legislatures.FirstOrDefault(l => In(date, l.From, l.To));
diff --git a/unity/Assets/Scripts/UI/BudgetPresenter.cs b/unity/Assets/Scripts/UI/BudgetPresenter.cs
index e7e2e15a8..ca75bac5a 100644
--- a/unity/Assets/Scripts/UI/BudgetPresenter.cs
+++ b/unity/Assets/Scripts/UI/BudgetPresenter.cs
@@ -105,15 +105,16 @@ namespace Statecraft.Game.UI
var c = bridge.Content; var s = bridge.State;
var rows = screen.Q<ScrollView>("budget-rows");
rows.Clear();
+ // A budget line is keyed by its own id; the office that owns it today can change (rules.yaml budget_owners, #108).
foreach (var office in c.Rules.BudgetStart.Keys)
{
- var o = c.Offices.First(x => x.Id == office);
+ var o = c.Offices.First(x => x.Id == (Offices.BudgetOwner(c, office, s.Date) ?? office));
var share = draft.TryGetValue(office, out var v) ? v : 0;
var row = new VisualElement { name = "budget-" + office };
row.AddToClassList("row");
// A budget line can run before its ministry exists (Education from 10 March 1949): say so, not "vacant".
var who = o.From.HasValue && s.Date < o.From.Value ? text.Format("budget.not_established", PlayerText.Date(o.From.Value))
- : Cabinet.Holder(c, s, office)?.Name ?? text["budget.vacant"];
+ : Cabinet.Holder(c, s, o.Id)?.Name ?? text["budget.vacant"];
row.Add(new Label(text.Format("budget.office", o.Title, who)) { name = "budget-" + office + "-name" });
row[0].AddToClassList("grow");
row.Add(new Button(() => Change(office, -Step)) { name = "budget-" + office + "-down", text = "-" });
diff --git a/unity/Assets/Tests/EditMode/BudgetScreenTests.cs b/unity/Assets/Tests/EditMode/BudgetScreenTests.cs
index ed515a164..dc5b148e1 100644
--- a/unity/Assets/Tests/EditMode/BudgetScreenTests.cs
+++ b/unity/Assets/Tests/EditMode/BudgetScreenTests.cs
@@ -26,6 +26,22 @@ public class BudgetScreenTests
Assert.AreEqual(1.0, floor.Values.Sum(), 1e-12);
}
+ [Test]
+ public void TheImmigrationLineNamesTheOwnerOfTheDay()
+ {
+ // rules.yaml budget_owners (#108): the Minister of Immigration until 7 October 1951, the Prime Minister from 8 October.
+ using var ui = new UiTestKit();
+ var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), Text);
+ var budget = new BudgetPresenter(ui.Root, bridge, Text);
+ bridge.State.Date = new System.DateTime(1951, 10, 7);
+ budget.Render();
+ Assert.AreEqual("Minister of Immigration (Haim-Moshe Shapira)", ui.Q<Label>("budget-prime_minister-name").text);
+ bridge.State.Date = new System.DateTime(1951, 10, 8);
+ budget.Render();
+ Assert.AreEqual("Prime Minister (David Ben-Gurion)", ui.Q<Label>("budget-prime_minister-name").text);
+ Assert.AreEqual("15%", ui.Q<Label>("budget-prime_minister-share").text); // the line keeps its id; only the owner changes
+ }
+
[Test]
public void TheScreenListsTheMinistriesAndSubmitsTheDraft()
{