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: gdd-0.3 basic training fixture starts recruits with issued Arms (Refs #1699) (#2390)

Eyal Golan40794572bb7e
diff --git a/changelog.d/1699-basic-training-arms.md b/changelog.d/1699-basic-training-arms.md
new file mode 100644
index 000000000..a15606066
--- /dev/null
+++ b/changelog.d/1699-basic-training-arms.md
@@ -0,0 +1,5 @@
+### Added
+- Under the gdd-0.3 rules only, a sim test fixture starts a recruit's basic training on the population ledger: each
+ unequipped recruit takes one spare Arms as its own issued item, a short stock refuses the whole order, an already
+ equipped recruit takes none, a qualified soldier is refused, and each course costs 0.5 Money, borrowing any shortfall
+ (Refs #1699). It is not in the game yet; the game players play (gdd-0.1) is unchanged.
diff --git a/sim/Statecraft.Sim.Tests/Gdd03BasicTrainingFixtureTests.cs b/sim/Statecraft.Sim.Tests/Gdd03BasicTrainingFixtureTests.cs
new file mode 100644
index 000000000..7442e57d1
--- /dev/null
+++ b/sim/Statecraft.Sim.Tests/Gdd03BasicTrainingFixtureTests.cs
@@ -0,0 +1,365 @@
+using System.Globalization;
+using Statecraft.Sim;
+
+// #1699 first slice: a recruit's basic training starts on the population ledger and holds its issued Arms. Synthetic camps
+// only; no real camp (#1719), region, Food or game caller is exercised. Rules quoted below, at main aa29a9b11:
+// - docs/GDD.md:375 (ARMS-1/ARMS-2): "Arms equip new soldiers in training and replacements; attacks and artillery spend
+// none. A recruit course cannot start without its Arms, and all training stays in 0.3 (ARMS-1 to ARMS-3)."
+// - docs/GDD.md:374 (27M-7): "Training is ordered in the camp's city, with no travel (27M-7)."
+// - docs/rules/mvp.md:167 (R-TRAIN-001): "for the type's `training_turns`, counting the turn it was ordered in. The Treasury
+// pays `n * training_cost` at once. When the Treasury holds less, the shortfall is borrowed, as for map actions: it is
+// added to the debt and the Treasury stops at 0"
+// - docs/rules/mvp.md:433 (R-ARMS-003): "Recruit training (R-TRAIN-001) takes `arms_per_recruit_group` (1) Arms for each
+// group when it starts, after its other checks and before it pays. A stock short of that refuses the order with a
+// reason naming the need and the stock"
+// - docs/rules/mvp.md:572 (R-POP-002): "distinct issued civilian/military equipment and paid facts. ... duplicate
+// issued-item ownership are refused before mutation. ... Ledger changes never touch resources, causes, RNG or Attention."
+public class Gdd03BasicTrainingFixtureTests
+{
+ static readonly Lazy<Gdd03BalanceCatalogue> Real = new(() => ContentLoader.Load(RealContentTests.ContentRoot()).Gdd03Balance!);
+ const string CampNorth = "fixture-camp-north", CampSouth = "fixture-camp-south", Field = "fixture-field", Service = "fixture-service";
+ const string Infantry = "infantry", Carried = "fixture-carried-item";
+
+ static Content Catalogue(string? key = null, Gdd03DesignValue? replacement = null, string ruleset = SaveGame.Gdd03Ruleset)
+ {
+ var c = PopulationLedgerTests.Content(ruleset);
+ var values = new Dictionary<string, Gdd03DesignValue>(Real.Value.Values, StringComparer.Ordinal);
+ if (key != null) { if (replacement == null) values.Remove(key); else values[key] = replacement; }
+ c.Gdd03Balance = new Gdd03BalanceCatalogue { Ruleset = Real.Value.Ruleset, Values = values };
+ return c;
+ }
+ static Gdd03DesignValue Agreed(decimal v) => new() { Basis = "Agreed", Values = new() { v }, Note = "synthetic test value" };
+ static Gdd03DesignValue Deferred() => new() { Basis = "Deferred", Expression = "X", Note = "synthetic deferred value" };
+
+ static PopulationBindings Bindings() => new(
+ new[] { new PopulationLocation("north"), new PopulationLocation("south") },
+ new[] { new PopulationTarget(CampNorth, PopulationAssignmentKind.Course, "north", 3),
+ new PopulationTarget(CampSouth, PopulationAssignmentKind.Course, "south", 3),
+ new PopulationTarget(Field, PopulationAssignmentKind.Work, "north"),
+ new PopulationTarget(Service, PopulationAssignmentKind.ActiveService, "north") },
+ Array.Empty<string>(), new[] { Infantry });
+
+ static PopulationUnit Person(PopulationStatus status = PopulationStatus.FreeCivilian, string region = "north",
+ PopulationAssignment? assignment = null, string qualification = "", string? military = null, string? tools = null)
+ => new(0, status, 0, new PopulationLocation(region), assignment ?? PopulationAssignment.Unassigned,
+ CivilianProfession.None, CivilianTier.None, 0, qualification, 0, new PopulationEquipment(tools, tools != null, military, military != null));
+
+ // Ids follow the row order: 0, 1, 2 unequipped civilians in the north (2 holds tools); 3 a civilian carrying an Arms item;
+ // 4 a qualified (demobilised) soldier; 5 a civilian in the south; 6 a refugee; 7 a worker; 8 an active soldier.
+ static GameState State(Content c, params PopulationUnit[] extra)
+ {
+ var people = new List<PopulationUnit> {
+ Person(), Person(), Person(tools: "fixture-tools"), Person(military: Carried),
+ Person(qualification: Infantry), Person(region: "south"), Person(PopulationStatus.Refugee),
+ Person(assignment: new PopulationAssignment(PopulationAssignmentKind.Work, Field)),
+ Person(PopulationStatus.ActiveSoldier, assignment: new PopulationAssignment(PopulationAssignmentKind.ActiveService, Service),
+ qualification: Infantry, military: "fixture-soldier-item") };
+ people.AddRange(extra);
+ return PopulationLedger.CreateFixture(c, Bindings(), people.Select((p, i) => new PopulationInventoryRow("synthetic", i, p)));
+ }
+ static Gdd03FixtureMilitaryCamp[] Camps(bool northOperating = true) => new[] {
+ new Gdd03FixtureMilitaryCamp(CampNorth, "north", northOperating), new Gdd03FixtureMilitaryCamp(CampSouth, "south", true) };
+ static Gdd03BasicTrainingFixture Fixture(Content c, GameState s, int spare = 10, decimal money = 10m, bool northOperating = true)
+ => new(c, s, Camps(northOperating), spare, money);
+
+ static int Issued(GameState s) => s.PopulationLedger.Units.Count(p => p.Equipment.MilitaryId != null);
+ static string Snapshot(GameState s, Gdd03BasicTrainingFixture f)
+ => s.Describe() + "|spare=" + f.SpareArms.ToString(CultureInfo.InvariantCulture)
+ + "|money=" + f.Money.ToString(CultureInfo.InvariantCulture) + "|debt=" + f.Debt.ToString(CultureInfo.InvariantCulture);
+ static Exception Unchanged(GameState s, Gdd03BasicTrainingFixture f, Action act, Type expected, string? deferredPrefix = null)
+ {
+ var before = Snapshot(s, f);
+ var ex = Assert.Throws(expected, act);
+ if (deferredPrefix != null) Assert.StartsWith(deferredPrefix, ex.Message, StringComparison.Ordinal);
+ else Assert.False(ex.Message.StartsWith("Deferred:", StringComparison.Ordinal), ex.Message);
+ Assert.Equal(before, Snapshot(s, f));
+ return ex;
+ }
+
+ // ARMS-1 (docs/GDD.md:375, "Arms equip new soldiers in training"); R-ARMS-003 (docs/rules/mvp.md:433, "takes
+ // `arms_per_recruit_group` (1) Arms for each group when it starts"); content/gdd03-balance.yaml:315-318
+ // `military.issue_arms` [1], "Arms issued once to an unequipped unit". Each unequipped record takes one distinct item
+ // from the fixture's spare Arms; the same ids keep every other field; no person is created.
+ [Fact] public void ARecruitCourseTakesOneArmsPerUnequippedUnit()
+ {
+ var c = Catalogue(); var s = State(c); var f = Fixture(c, s, spare: 5); var l = s.PopulationLedger;
+ var before = new[] { l.Get(0), l.Get(1), l.Get(2) }; int count = l.Units.Count, next = l.NextPopulationId;
+
+ f.Start(new[] { 2, 0, 1 }, CampNorth, 0);
+
+ Assert.Equal(2, f.SpareArms);
+ var items = new HashSet<string>(StringComparer.Ordinal);
+ foreach (var b in before)
+ {
+ var p = l.Get(b.Id);
+ Assert.Equal(PopulationStatus.Trainee, p.Status);
+ Assert.Equal(PopulationAssignmentKind.Course, p.Assignment.Kind);
+ Assert.Equal(CampNorth, p.Assignment.Target); Assert.Equal(0, p.Assignment.ProgressTicks); Assert.Null(p.Assignment.TeacherId);
+ Assert.NotNull(p.Equipment.MilitaryId); Assert.True(items.Add(p.Equipment.MilitaryId!));
+ Assert.True(p.Equipment.MilitaryPaid);
+ Assert.Equal(b.Equipment.ToolsId, p.Equipment.ToolsId); Assert.Equal(b.Equipment.ToolsPaid, p.Equipment.ToolsPaid);
+ Assert.Same(b.Location, p.Location); Assert.Equal(b.Qualification, p.Qualification); Assert.Equal(b.CombatXp, p.CombatXp);
+ Assert.Equal(b.ReceptionTicks, p.ReceptionTicks); Assert.Equal(b.Profession, p.Profession); Assert.Equal(b.WorkXp, p.WorkXp);
+ }
+ Assert.Equal(count, l.Units.Count); Assert.Equal(next, l.NextPopulationId);
+ l.Reconcile();
+ }
+
+ // ARMS-2 (docs/GDD.md:375): "A recruit course cannot start without its Arms"; R-ARMS-003 (docs/rules/mvp.md:433): "A
+ // stock short of that refuses the order with a reason naming the need and the stock". The WHOLE order is refused, not
+ // the part the stock covers; issuing the last spare then succeeds (#1699 comment of 28 October 2026: "Issue of the last
+ // spare succeeds; a further unavailable issue refuses atomically").
+ [Fact] public void ShortArmsRefusesTheWholeOrderWithAReason()
+ {
+ var c = Catalogue(); var s = State(c); var f = Fixture(c, s, spare: 2, money: 10m);
+ var ex = Unchanged(s, f, () => f.Start(new[] { 0, 1, 2 }, CampNorth, 0), typeof(ArgumentException));
+ Assert.Contains("need 3, have 2", ex.Message, StringComparison.Ordinal);
+ Assert.All(new[] { 0, 1, 2 }, id => Assert.Equal(PopulationStatus.FreeCivilian, s.PopulationLedger.Get(id).Status));
+
+ f.Start(new[] { 0, 1 }, CampNorth, 0);
+ Assert.Equal(0, f.SpareArms);
+ var after = Unchanged(s, f, () => f.Start(new[] { 2 }, CampNorth, 0), typeof(ArgumentException));
+ Assert.Contains("need 1, have 0", after.Message, StringComparison.Ordinal);
+ }
+
+ // #1699 What to do: "Arms: issue once to an unequipped unit; never a second issue"; content/gdd03-balance.yaml:339-342
+ // `military.repeat_issue` [0]. A record that already carries an item keeps it and takes none, even from an empty stock.
+ [Fact] public void AnEquippedRecordIsNeverIssuedASecondItem()
+ {
+ var c = Catalogue(); var s = State(c); var f = Fixture(c, s, spare: 0);
+ f.Start(new[] { 3 }, CampNorth, 0);
+ var p = s.PopulationLedger.Get(3);
+ Assert.Equal(PopulationStatus.Trainee, p.Status);
+ Assert.Equal(Carried, p.Equipment.MilitaryId); Assert.True(p.Equipment.MilitaryPaid);
+ Assert.Equal(0, f.SpareArms);
+
+ // A mixed order needs Arms only for its unequipped records.
+ var s2 = State(c); var f2 = Fixture(c, s2, spare: 1);
+ f2.Start(new[] { 0, 3 }, CampNorth, 0);
+ Assert.Equal(0, f2.SpareArms);
+ Assert.Equal(Carried, s2.PopulationLedger.Get(3).Equipment.MilitaryId);
+ }
+
+ // #1699 Done when: "a basic-training order for an already qualified soldier is refused (it cannot be used to avoid
+ // active upkeep)". A qualified civilian, or an active soldier, refuses the whole order.
+ [Fact] public void AQualifiedSoldierIsRefusedBasicTraining()
+ {
+ var c = Catalogue(); var s = State(c); var f = Fixture(c, s);
+ Unchanged(s, f, () => f.Start(new[] { 4 }, CampNorth, 0), typeof(ArgumentException));
+ Unchanged(s, f, () => f.Start(new[] { 8 }, CampNorth, 0), typeof(ArgumentException));
+ Unchanged(s, f, () => f.Start(new[] { 0, 4 }, CampNorth, 0), typeof(ArgumentException));
+ Assert.Equal(PopulationStatus.FreeCivilian, s.PopulationLedger.Get(0).Status);
+ }
+
+ // 27M-7 (docs/GDD.md:374): "Training is ordered in the camp's city, with no travel (27M-7)." A civilian in another region
+ // is refused, never moved; a camp that is not operating refuses the order.
+ [Fact] public void TrainingIsOrderedInTheCampsRegion()
+ {
+ var c = Catalogue(); var s = State(c); var f = Fixture(c, s, northOperating: false);
+ Unchanged(s, f, () => f.Start(new[] { 5 }, CampNorth, 0), typeof(ArgumentException));
+ Unchanged(s, f, () => f.Start(new[] { 0 }, CampNorth, 0), typeof(ArgumentException));
+ Unchanged(s, f, () => f.Start(new[] { 0 }, "fixture-unknown-camp", 0), typeof(ArgumentException));
+ f.Start(new[] { 5 }, CampSouth, 0);
+ var p = s.PopulationLedger.Get(5);
+ Assert.Equal(CampSouth, p.Assignment.Target); Assert.Equal("south", p.Location!.Region);
+ }
+
+ // 27M-7 (docs/GDD.md:374): "Training is ordered in the camp's city, with no travel (27M-7)." With both camps operating,
+ // stock and room to spare, a recruit from another region is refused by the region rule alone, with the fixture's own
+ // reason before any write (the ledger's later target-region check, PopulationLedger.cs:242, is only a backstop), and
+ // nothing changes.
+ [Fact] public void AWrongRegionIsRefusedAtAnOperatingCampWithStock()
+ {
+ var c = Catalogue(); var s = State(c); var f = Fixture(c, s, spare: 10, money: 10m);
+ var ex = Unchanged(s, f, () => f.Start(new[] { 5 }, CampNorth, 0), typeof(ArgumentException));
+ Assert.Equal("Unit 5 is not in the camp's region.", ex.Message);
+ ex = Unchanged(s, f, () => f.Start(new[] { 0, 5 }, CampSouth, 0), typeof(ArgumentException));
+ Assert.Equal("Unit 0 is not in the camp's region.", ex.Message);
+ Assert.Equal("south", s.PopulationLedger.Get(5).Location!.Region);
+ }
+
+ // R-TRAIN-001 (docs/rules/mvp.md:167): takes "the city's civilians without a job"; docs/GDD.md:374: "Refugees cannot
+ // train until they become civilians". A refugee or a worker refuses the whole order, as do a repeated id and an empty order.
+ [Fact] public void RefugeesWorkersAndMalformedOrdersAreRefused()
+ {
+ var c = Catalogue(); var s = State(c); var f = Fixture(c, s);
+ Unchanged(s, f, () => f.Start(new[] { 6 }, CampNorth, 0), typeof(ArgumentException));
+ Unchanged(s, f, () => f.Start(new[] { 0, 7 }, CampNorth, 0), typeof(ArgumentException));
+ Unchanged(s, f, () => f.Start(new[] { 0, 0 }, CampNorth, 0), typeof(ArgumentException));
+ Unchanged(s, f, () => f.Start(Array.Empty<int>(), CampNorth, 0), typeof(ArgumentException));
+ Unchanged(s, f, () => f.Start(new[] { 99 }, CampNorth, 0), typeof(ArgumentException));
+ }
+
+ // content/gdd03-balance.yaml:307-310 `military.camp_capacity` [50], "simultaneous trainee population units per camp".
+ // Read from the catalogue, not a literal: with a synthetic 2, a third trainee in the camp refuses its whole order.
+ [Fact] public void CampCapacityComesFromTheCatalogue()
+ {
+ var c = Catalogue("military.camp_capacity", Agreed(2)); var s = State(c); var f = Fixture(c, s);
+ f.Start(new[] { 0 }, CampNorth, 0);
+ Unchanged(s, f, () => f.Start(new[] { 1, 2 }, CampNorth, 0), typeof(ArgumentException));
+ f.Start(new[] { 1 }, CampNorth, 0);
+ Unchanged(s, f, () => f.Start(new[] { 2 }, CampNorth, 0), typeof(ArgumentException));
+ // The cap is per camp: the south camp is still free.
+ f.Start(new[] { 5 }, CampSouth, 0);
+
+ var real = Catalogue(); var s2 = State(real); var f2 = Fixture(real, s2);
+ f2.Start(new[] { 0, 1, 2, 3 }, CampNorth, 0); // 4 of the real 50
+ }
+
+ // content/gdd03-balance.yaml:347-350 `military.training_money` [0.5], "Money per basic course. Owner ruling, 30 October
+ // 2026 ... "Keep the set values (Recommended)""; docs/gdd/training.md:15 "Basic military training costs 0.5 per course
+ // in Money". R-TRAIN-001 (docs/rules/mvp.md:167): "The Treasury pays `n * training_cost` at once. When the Treasury holds
+ // less, the shortfall is borrowed"; R-MONEY-003 (docs/rules/mvp.md:409): "the Treasury stops at 0". One record is one
+ // course; an equipped record pays the course too. The fixture owns its Money and Debt, as Gdd03ProjectBuildFixture does,
+ // because R-POP-002 says "Ledger changes never touch resources".
+ [Fact] public void EachRecruitPaysTheCatalogueMoneyAndTheShortfallIsBorrowed()
+ {
+ Assert.Equal(0.5m, Gdd03MilitaryCatalogue.Read(Real.Value).TrainingMoney);
+ var c = Catalogue(); var s = State(c); var f = Fixture(c, s, money: 10m);
+ f.Start(new[] { 0, 1, 3 }, CampNorth, 0);
+ Assert.Equal(8.5m, f.Money); Assert.Equal(0m, f.Debt);
+
+ var s2 = State(c); var f2 = Fixture(c, s2, money: 1m);
+ f2.Start(new[] { 0, 1, 2 }, CampNorth, 0);
+ Assert.Equal(0m, f2.Money); Assert.Equal(0.5m, f2.Debt);
+
+ var two = Catalogue("military.training_money", Agreed(2m)); var s3 = State(two); var f3 = Fixture(two, s3, money: 10m);
+ f3.Start(new[] { 0, 1 }, CampNorth, 0);
+ Assert.Equal(6m, f3.Money);
+ }
+
+ // R-TRAIN-001 (docs/rules/mvp.md:167): "counting the turn it was ordered in"; content/gdd03-balance.yaml:311-314
+ // `military.basic_turns` [3]. The enrolment month is course turn 1, each month ordinal counts once, and the turn that
+ // would complete the course is Deferred (completion into a formation is not in this slice). The issued item stays on the
+ // record throughout.
+ [Fact] public void TheEnrolmentMonthCountsAndCompletionIsDeferred()
+ {
+ var c = Catalogue(); var s = State(c); var f = Fixture(c, s); var l = s.PopulationLedger;
+ f.Start(new[] { 0 }, CampNorth, 4);
+ var item = l.Get(0).Equipment.MilitaryId;
+ f.Advance(0, 4);
+ Assert.Equal(1, l.Get(0).Assignment.ProgressTicks);
+ Unchanged(s, f, () => f.Advance(0, 4), typeof(ArgumentException));
+ Unchanged(s, f, () => f.Advance(0, 3), typeof(ArgumentException));
+ f.Advance(0, 5);
+ Assert.Equal(2, l.Get(0).Assignment.ProgressTicks);
+ Unchanged(s, f, () => f.Advance(0, 6), typeof(NotSupportedException), "Deferred:");
+ Assert.Equal(PopulationStatus.Trainee, l.Get(0).Status);
+ Assert.Equal(item, l.Get(0).Equipment.MilitaryId);
+ Unchanged(s, f, () => f.Advance(1, 6), typeof(ArgumentException)); // never started
+ l.Reconcile();
+ }
+
+ // content/gdd03-balance.yaml:311-314 `military.basic_turns` [3], read from the catalogue, not a literal: with a synthetic
+ // 2 or 4, the enrolment month and every later month count until the turn that would reach that value, which is Deferred.
+ [Theory, InlineData(2), InlineData(4)]
+ public void TheCompletionTurnComesFromTheCatalogue(int turns)
+ {
+ var c = Catalogue("military.basic_turns", Agreed(turns)); var s = State(c); var f = Fixture(c, s); var l = s.PopulationLedger;
+ f.Start(new[] { 0 }, CampNorth, 0);
+ for (int month = 0; month < turns - 1; month++) f.Advance(0, month);
+ Assert.Equal(turns - 1, l.Get(0).Assignment.ProgressTicks);
+ Unchanged(s, f, () => f.Advance(0, turns - 1), typeof(NotSupportedException), "Deferred:");
+ }
+
+ // R-MONEY-003 (docs/rules/mvp.md:409): "A shortfall changes nothing but the Treasury and the debt, and a refused order
+ // changes nothing". The order's Money is computed before anything is written, so a cost that
+ // cannot be represented throws with the ledger, spare Arms, Money and Debt all unchanged, not a half-applied order.
+ [Fact] public void ACostThatOverflowsChangesNothing()
+ {
+ var c = Catalogue("military.training_money", Agreed(decimal.MaxValue)); var s = State(c); var f = Fixture(c, s, spare: 5);
+ Unchanged(s, f, () => f.Start(new[] { 0, 1 }, CampNorth, 0), typeof(OverflowException));
+ Assert.Equal(PopulationStatus.FreeCivilian, s.PopulationLedger.Get(0).Status);
+ Assert.Equal(5, f.SpareArms);
+ }
+
+ // #1699 Done when: "Draft, train, cancel and demobilise in any order never change total units or total Arms (spare +
+ // issued)" and "The conservation test runs on a fixture with no arrivals, combat losses, imports or workshop output",
+ // restricted to this slice's start and advance. Accepted and refused steps alike keep spare + issued and the record
+ // count constant, in en-US and he-IL.
+ [Theory, InlineData("en-US"), InlineData("he-IL")]
+ public void SpareAndIssuedArmsAreConservedAfterEveryStep(string culture)
+ {
+ var saved = CultureInfo.CurrentCulture;
+ try
+ {
+ CultureInfo.CurrentCulture = new CultureInfo(culture);
+ var c = Catalogue("military.camp_capacity", Agreed(3)); var s = State(c); var f = Fixture(c, s, spare: 3, money: 0.75m);
+ int total = f.SpareArms + Issued(s), units = s.PopulationLedger.Units.Count;
+ var steps = new Action[] {
+ () => f.Start(new[] { 0, 1, 2, 3 }, CampNorth, 0), // over capacity: refused
+ () => f.Start(new[] { 0, 4 }, CampNorth, 0), // qualified: refused
+ () => f.Start(new[] { 0, 3 }, CampNorth, 0), // one issue, one carried item
+ () => f.Start(new[] { 1, 2 }, CampNorth, 0), // capacity 3: refused
+ () => f.Start(new[] { 5 }, CampSouth, 0), // one issue
+ () => f.Start(new[] { 1 }, CampNorth, 0), // one issue, the last spare
+ () => f.Start(new[] { 2 }, CampSouth, 1), // wrong region: refused
+ () => f.Advance(0, 0), () => f.Advance(0, 0), // second count refused
+ () => f.Advance(0, 1), () => f.Advance(0, 2), // completion Deferred
+ () => f.Advance(3, 1),
+ };
+ int accepted = 0;
+ foreach (var step in steps)
+ {
+ try { step(); accepted++; } catch (ArgumentException) { } catch (NotSupportedException) { }
+ Assert.Equal(total, f.SpareArms + Issued(s));
+ Assert.Equal(units, s.PopulationLedger.Units.Count);
+ s.PopulationLedger.Reconcile();
+ }
+ Assert.Equal(6, accepted);
+ Assert.Equal(0, f.SpareArms);
+ Assert.Equal(1.25m, f.Debt); // 4 courses x 0.5 = 2, of which 0.75 was in hand
+ }
+ finally { CultureInfo.CurrentCulture = saved; }
+ }
+
+ // Item ids: PR #2383 (open) gives starting formation records `units_1948/<row>/<ordinal>` (HistoricalPopulation.FormationPrefix
+ // on main, sim/Statecraft.Sim/HistoricalPopulation.cs:32). This fixture's ids use a disjoint prefix, so no issued id can
+ // equal one of those or a census source; and R-POP-002's "duplicate issued-item ownership are refused before mutation"
+ // still guards a clash with an item already in the ledger: the whole order is refused and nothing is written.
+ [Fact] public void IssuedItemIdsCannotCollideWithStartingFormationItems()
+ {
+ foreach (var other in new[] { HistoricalPopulation.FormationPrefix, HistoricalPopulation.CensusPrefix })
+ {
+ Assert.False(Gdd03BasicTrainingFixture.IssuedPrefix.StartsWith(other, StringComparison.Ordinal));
+ Assert.False(other.StartsWith(Gdd03BasicTrainingFixture.IssuedPrefix, StringComparison.Ordinal));
+ }
+ var c = Catalogue(); var s = State(c); var f = Fixture(c, s);
+ f.Start(new[] { 0, 1 }, CampNorth, 0);
+ Assert.Equal(Gdd03BasicTrainingFixture.IssuedPrefix + "0", s.PopulationLedger.Get(0).Equipment.MilitaryId);
+ Assert.Equal(Gdd03BasicTrainingFixture.IssuedPrefix + "1", s.PopulationLedger.Get(1).Equipment.MilitaryId);
+ Assert.All(s.PopulationLedger.Units.Select(p => p.Equipment.MilitaryId).Where(m => m != null && m != Carried),
+ m => Assert.False(m!.StartsWith(HistoricalPopulation.FormationPrefix, StringComparison.Ordinal)));
+
+ // A record (id 9) already holding the id record 2 would get: the order with 2 is refused whole and rolled back.
+ var clash = State(c, Person(military: Gdd03BasicTrainingFixture.IssuedPrefix + "2"));
+ var g = Fixture(c, clash);
+ Unchanged(clash, g, () => g.Start(new[] { 0, 2 }, CampNorth, 0), typeof(ArgumentException));
+ Assert.Equal(PopulationStatus.FreeCivilian, clash.PopulationLedger.Get(0).Status);
+ }
+
+ // Exact gdd-0.3 only, on an initialized ledger; the catalogue terms fail closed with no fallback; issue_arms other than 1
+ // or repeat_issue other than 0 cannot be represented by one item per record and are refused.
+ [Fact] public void OtherIdentitiesUninitializedStatesAndBadTermsAreRefused()
+ {
+ foreach (var identity in new[] { SaveGame.LegacyRuleset, SaveGame.GddRuleset })
+ {
+ var c = Catalogue(ruleset: identity); var s = new GameState(c); var before = s.Describe();
+ Assert.Throws<InvalidOperationException>(() => new Gdd03BasicTrainingFixture(c, s, Camps(), 1, 1m));
+ Assert.Equal(before, s.Describe());
+ }
+ var g = Catalogue();
+ Assert.Throws<InvalidOperationException>(() => new Gdd03BasicTrainingFixture(g, new GameState(g), Camps(), 1, 1m));
+ var state = State(g);
+ foreach (var key in new[] { "military.camp_capacity", "military.basic_turns", "military.issue_arms", "military.training_money" })
+ foreach (var replacement in new[] { null, Deferred() })
+ Assert.Throws<ContentException>(() => new Gdd03BasicTrainingFixture(Catalogue(key, replacement), state, Camps(), 1, 1m));
+ Assert.Throws<ContentException>(() => new Gdd03BasicTrainingFixture(Catalogue("military.issue_arms", Agreed(2)), state, Camps(), 1, 1m));
+ Assert.Throws<ContentException>(() => new Gdd03BasicTrainingFixture(Catalogue("military.repeat_issue", Agreed(1)), state, Camps(), 1, 1m));
+ Assert.Throws<ArgumentException>(() => new Gdd03BasicTrainingFixture(g, state, Camps(), -1, 1m));
+ Assert.Throws<ArgumentException>(() => new Gdd03BasicTrainingFixture(g, state, Camps(), 1, -1m));
+ Assert.Throws<ArgumentException>(() => new Gdd03BasicTrainingFixture(g, state, Camps().Concat(Camps()), 1, 1m));
+ Assert.Throws<ArgumentException>(() => new Gdd03FixtureMilitaryCamp(" ", "north", true));
+ Assert.Throws<ArgumentException>(() => new Gdd03FixtureMilitaryCamp(CampNorth, "", true));
+ }
+}
diff --git a/sim/Statecraft.Sim/Gdd03BasicTrainingFixture.cs b/sim/Statecraft.Sim/Gdd03BasicTrainingFixture.cs
new file mode 100644
index 000000000..cd66809f9
--- /dev/null
+++ b/sim/Statecraft.Sim/Gdd03BasicTrainingFixture.cs
@@ -0,0 +1,166 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+
+namespace Statecraft.Sim
+{
+ /// <summary>Synthetic military camp facts supplied by a test: the camp's course target id, its region and whether it
+ /// operates. Real camps are #1719's; this fixture only reads these facts.</summary>
+ internal sealed class Gdd03FixtureMilitaryCamp
+ {
+ internal string Id { get; }
+ internal string Region { get; }
+ internal bool Operating { get; }
+ internal Gdd03FixtureMilitaryCamp(string id, string region, bool operating)
+ {
+ if (string.IsNullOrWhiteSpace(id) || string.IsNullOrWhiteSpace(region))
+ throw new ArgumentException("A camp needs its own course target id and a region.");
+ PopulationText.ValidateText(id); PopulationText.ValidateText(region);
+ Id = id; Region = region; Operating = operating;
+ }
+ }
+
+ /// <summary>#1699 first slice: a recruit's basic training starts on the #1689 population ledger and holds its issued
+ /// Arms (ARMS-1, ARMS-2, 27M-7, R-TRAIN-001, R-ARMS-003), synthetic fixtures only. No command, save, loader, resolver,
+ /// Food or UI caller. Like <see cref="Gdd03ProjectBuildFixture"/> it owns its spare Arms, Money and Debt, so the ledger
+ /// never touches resources (R-POP-002). Completion into a formation is refused with a "Deferred:" NotSupportedException.
+ /// Cancel is not built: its Arms refund (R-TRAIN-002, R-ARMS-003 "Refund on cancel") conflicts with #1699's "Cancelling
+ /// basic training leaves the issued Arms on the unit" and waits on an owner ruling.</summary>
+ internal sealed class Gdd03BasicTrainingFixture
+ {
+ /// <summary>Issued item ids are this prefix plus the population id. It is disjoint from the census and units_1948
+ /// source prefixes (<see cref="HistoricalPopulation.CensusPrefix"/>, <see cref="HistoricalPopulation.FormationPrefix"/>),
+ /// so no id can equal a starting formation's item; a record holds at most one military item, so no two records are issued the same id.</summary>
+ internal const string IssuedPrefix = "basic_training/";
+ const string Completion = "Deferred: completing basic training into a formation (#1699; R-TRAIN-003, R-UNIT-003).";
+ const string CampLoss = "Deferred: a camp that stops operating during a course (#1699, 27M-9).";
+
+ readonly GameState state;
+ readonly SortedDictionary<string, Gdd03FixtureMilitaryCamp> camps = new SortedDictionary<string, Gdd03FixtureMilitaryCamp>(StringComparer.Ordinal);
+ readonly int capacity, basicTurns;
+ readonly decimal moneyPerCourse;
+ // Per fixture instance only (not saved): each trainee's enrolment month and last counted month ordinal.
+ readonly SortedDictionary<int, (int enrolment, int lastCounted)> months = new SortedDictionary<int, (int, int)>();
+ internal int SpareArms { get; private set; }
+ internal decimal Money { get; private set; }
+ internal decimal Debt { get; private set; }
+
+ internal Gdd03BasicTrainingFixture(Content content, GameState state, IEnumerable<Gdd03FixtureMilitaryCamp> camps,
+ int spareArms, decimal money)
+ {
+ if (!content.UsesPopulationLedger || !state.UsesPopulationLedger || !state.PopulationLedger.IsInitialized)
+ throw new InvalidOperationException("Basic training requires an initialized gdd-0.3 synthetic fixture.");
+ var terms = Gdd03MilitaryCatalogue.Read(content.Gdd03Balance!);
+ // One issued item per record (R-POP-002): any other issue or repeat count cannot be represented.
+ if (terms.IssueArms != 1)
+ throw new ContentException(Gdd03BalanceCatalogue.FileName, "values.military.issue_arms", "must be 1: one item per population unit");
+ if (terms.RepeatIssueArms != 0)
+ throw new ContentException(Gdd03BalanceCatalogue.FileName, "values.military.repeat_issue", "must be 0: never a second issue");
+ if (spareArms < 0 || money < 0) throw new ArgumentException("Spare Arms and Money must be nonnegative.");
+ this.state = state;
+ capacity = terms.CampCapacity; basicTurns = terms.BasicTurns; moneyPerCourse = terms.TrainingMoney;
+ foreach (var camp in camps) this.camps.Add(camp.Id, camp); // a duplicate id throws ArgumentException
+ SpareArms = spareArms; Money = money;
+ ValidateInventory();
+ }
+
+ IEnumerable<PopulationUnit> Trainees(string campId) => state.PopulationLedger.Units.Where(p
+ => p.Assignment.Kind == PopulationAssignmentKind.Course && string.Equals(p.Assignment.Target, campId, StringComparison.Ordinal));
+
+ void ValidateInventory()
+ {
+ state.PopulationLedger.Reconcile();
+ foreach (var camp in camps.Values)
+ {
+ var trainees = Trainees(camp.Id).ToArray();
+ if (trainees.Length > capacity) throw new ArgumentException("Camp " + camp.Id + " is over its capacity.");
+ if (trainees.Any(p => p.Equipment.MilitaryId == null || p.Assignment.TeacherId != null || p.Assignment.ProgressTicks >= basicTurns))
+ throw new ArgumentException("A basic trainee must hold an issued item, have no teacher and an unfinished course.");
+ }
+ }
+
+ // Every check runs before the first write; Replace validates each record and a failure restores earlier writes.
+ void Commit(IReadOnlyList<PopulationUnit> replacements)
+ {
+ var ledger = state.PopulationLedger; var previous = new List<PopulationUnit>();
+ try { foreach (var r in replacements) { var old = ledger.Get(r.Id); ledger.Replace(r); previous.Add(old); } }
+ catch { for (int i = previous.Count - 1; i >= 0; i--) ledger.Replace(previous[i]); throw; }
+ }
+
+ /// <summary>R-TRAIN-001 and R-ARMS-003 under gdd-0.3: start basic training for the given records at an operating camp,
+ /// all or nothing, ids in ascending order. Each must be a free civilian with no assignment and no military
+ /// qualification, in the camp's region (27M-7, no travel), and the camp's trainees may not pass
+ /// <c>military.camp_capacity</c>. Then, after the other checks and before paying, each unequipped record needs one
+ /// spare Arms (ARMS-2): a short stock refuses the whole order with the need and the stock. An equipped record keeps
+ /// its item and takes none. Each course pays <c>military.training_money</c>, borrowing the shortfall (R-MONEY-003).</summary>
+ internal void Start(IEnumerable<int> ids, string campId, int monthOrdinal)
+ {
+ ValidateInventory();
+ var order = (ids ?? throw new ArgumentNullException(nameof(ids))).OrderBy(id => id).ToArray();
+ if (order.Length == 0 || order.Distinct().Count() != order.Length)
+ throw new ArgumentException("Name at least one population unit, each once.");
+ if (monthOrdinal < 0) throw new ArgumentException("The month ordinal must be nonnegative.");
+ if (campId == null || !camps.TryGetValue(campId, out var camp)) throw new ArgumentException("Unknown fixture camp.");
+ if (!camp.Operating) throw new ArgumentException("Camp " + camp.Id + " is not operating.");
+
+ var ledger = state.PopulationLedger;
+ var recruits = order.Select(ledger.Get).ToArray(); // an unknown id throws ArgumentException
+ foreach (var p in recruits)
+ {
+ if (p.Status != PopulationStatus.FreeCivilian || p.Assignment.Kind != PopulationAssignmentKind.Unassigned)
+ throw new ArgumentException("Unit " + p.Id.ToString(CultureInfo.InvariantCulture) + " is not a civilian without a job.");
+ if (p.Qualification != "")
+ throw new ArgumentException("Unit " + p.Id.ToString(CultureInfo.InvariantCulture) + " is already a qualified soldier.");
+ if (!string.Equals(p.Location!.Region, camp.Region, StringComparison.Ordinal))
+ throw new ArgumentException("Unit " + p.Id.ToString(CultureInfo.InvariantCulture) + " is not in the camp's region.");
+ }
+ int room = capacity - Trainees(camp.Id).Count();
+ if (recruits.Length > room)
+ throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
+ "Camp {0} has room for {1} more trainees (capacity {2}).", camp.Id, room, capacity));
+ int need = recruits.Count(p => p.Equipment.MilitaryId == null);
+ if (need > SpareArms)
+ throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
+ "Basic training: not enough Arms (need {0}, have {1}).", need, SpareArms));
+ // R-MONEY-003: Money stops at 0 and the shortfall moves to debt. The cost and both new balances are computed
+ // before any write, so a cost that cannot be represented (an OverflowException) leaves everything unchanged.
+ decimal cost = moneyPerCourse * recruits.Length;
+ decimal paid = Math.Min(Money, cost), debt = Debt + (cost - paid);
+
+ var course = new PopulationAssignment(PopulationAssignmentKind.Course, camp.Id);
+ Commit(recruits.Select(p =>
+ {
+ var e = p.Equipment;
+ var trainee = e.MilitaryId != null ? p : new PopulationUnit(p.Id, p.Status, p.ReceptionTicks, p.Location, p.Assignment,
+ p.Profession, p.Tier, p.WorkXp, p.Qualification, p.CombatXp,
+ new PopulationEquipment(e.ToolsId, e.ToolsPaid, IssuedPrefix + p.Id.ToString(CultureInfo.InvariantCulture), true),
+ p.Captor, p.Home);
+ return trainee.WithPlacement(PopulationStatus.Trainee, p.Location, course, p.Captor, p.Home);
+ }).ToArray());
+ SpareArms -= need;
+ Money -= paid; Debt = debt;
+ foreach (var p in recruits) months[p.Id] = (monthOrdinal, monthOrdinal - 1);
+ }
+
+ /// <summary>R-TRAIN-001 "counting the turn it was ordered in": count one course turn a month ordinal, the enrolment
+ /// month included, each ordinal once and never an earlier one. The turn that would reach <c>military.basic_turns</c>
+ /// completes the course and is Deferred.</summary>
+ internal void Advance(int traineeId, int monthOrdinal)
+ {
+ ValidateInventory();
+ var trainee = state.PopulationLedger.Get(traineeId);
+ if (trainee.Status != PopulationStatus.Trainee || trainee.Assignment.Target == null
+ || !camps.TryGetValue(trainee.Assignment.Target, out var camp) || !months.TryGetValue(traineeId, out var known))
+ throw new ArgumentException("Not a trainee this fixture started.");
+ if (!camp.Operating) throw new NotSupportedException(CampLoss);
+ if (monthOrdinal < known.enrolment || monthOrdinal <= known.lastCounted)
+ throw new ArgumentException("This month ordinal was already counted or is before enrolment.");
+ int progress = checked(trainee.Assignment.ProgressTicks + 1);
+ if (progress >= basicTurns) throw new NotSupportedException(Completion);
+ Commit(new[] { trainee.WithPlacement(trainee.Status, trainee.Location,
+ new PopulationAssignment(PopulationAssignmentKind.Course, camp.Id, progress), trainee.Captor, trainee.Home) });
+ months[traineeId] = (known.enrolment, monthOrdinal);
+ }
+ }
+}