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: training centre course fixture for gdd-0.3 (Refs #1697) (#1880)

Eyal Goland7561e45daaf
diff --git a/changelog.d/1697-training-centre-fixture.md b/changelog.d/1697-training-centre-fixture.md
new file mode 100644
index 000000000..7928a14be
--- /dev/null
+++ b/changelog.d/1697-training-centre-fixture.md
@@ -0,0 +1 @@
+- Refs #1697: add an internal, fixture-only gdd-0.3 training centre course lifecycle (start, counted course turns, cancel) on the population ledger. Graduation timing and the other open design points are refused as Deferred; no real centre, payment or game caller is added, and legacy/gdd-0.1 behaviour and content are unchanged.
diff --git a/docs/rules/mvp.md b/docs/rules/mvp.md
index d57675363..9d77cc302 100644
--- a/docs/rules/mvp.md
+++ b/docs/rules/mvp.md
@@ -142,6 +142,14 @@ R-TRAIN-003: Each turn, in ascending id, every cohort has one turn less to go. A
R-TRAIN-004: `Reinforce(unit, city, n)` (#1510; owner, 23 October 2026: "Replacements cost Arms", https://github.com/eyalgolan/statecraft-israel/issues/1510#issuecomment-6372356139, and "Default (Recommended)") refills a damaged formation of the player's with trained replacements. The unit must be a military unit of the player's side standing on `city`'s settlement hex. Its course is the trained type of the unit's side and class (a type with a `facility`): the recruit's basic training for a recruit or a veteran soldier, the guns' and the armoured cars' own for artillery and armoured cars (R-UNIT-008); a type no course trains (any enemy type) takes none. The cohort then follows R-TRAIN-001: the city's facility, `n` of its civilians without a job, `n * training_cost` with borrowing (R-MONEY-003), and the Arms of R-ARMS-003 for that course; it carries the unit's id, written into the state hash (`|unit=<id>`) only when set. The cap is the strength the unit had before its first loss, `Unit.Full`: combat stores it on a player's unit at its first loss (R-COMBAT-003) and clears it when replacements bring the unit back to it, and it is written into the state hash (`|full=<n>`) only when set, so a unit that has lost nobody, and every enemy unit, hashes as before. The order is refused, the state and Attention unchanged, for an unknown unit ("There is no such unit"), a unit with no side or an enemy unit (R-ORDER-001's wording), an unknown city, a unit off the city's hex ("Unit N is not in <city>"), a type no course trains ("Unit N cannot take replacements"), a unit with nothing to refill ("Unit N has no losses to replace") and `n` past the cap less the unit's strength and the replacements already training for it ("Unit N can take K more groups"), then for R-TRAIN-001's and R-ARMS-003's reasons. A queued `Reinforce` takes its city's civilians as a queued `Train` does (R-CITY-001). In step 4, before a turn is counted, replacements whose unit has left the state (destroyed, captured, sent home) or stands off the city's hex are cancelled as R-TRAIN-002 cancels a cohort: people and Arms back, the Money spent, with a Why line. A cohort that finishes adds its count to the unit's strength and makes no unit and takes no id; the unit keeps its type, service, order and home (a veteran stays a veteran, R-UNIT-004). The people join the unit's home city's housing (R-HOUSE-003). `attention_cost.reinforce` is 1, Train's cost, a design value (owner, 24 October 2026: "1, like Train (Recommended)", https://github.com/eyalgolan/statecraft-israel/issues/1510#issuecomment-6375591436). The save line is `reinforce <unit> <city> <n>` and the scenario form `{ kind: reinforce, unit, city, count }`.
+R-TRAIN-005: In gdd-0.3 synthetic fixtures only (#1697; nothing in the game calls it), a farmer or pioneer course starts at a training centre whose parent reception camp operates and whose upgrade is complete. The teacher is a received free civilian, a veteran of the matching profession, with no other assignment; the trainee is a received, unassigned free civilian who is a novice of that profession with tools. The trainee takes one of the parent camp's own reception beds (Agreed `reception.capacity`, refugee or course-trainee beds per camp); another camp's beds or ordinary work places do not stand in, and the teacher's separate housing is not a reception bed. A teacher takes at most Agreed `profession.trainees_per_teacher` pupils (currently 1), so a busy teacher refuses another pupil. No Money is charged: the tools were paid on entry and a matching course does not charge them again. Teacher and trainee then hold exclusive Teaching and Course assignments, so other assignment paths refuse them. Every refusal leaves the state unchanged. Sources at `605277dfa511dc512562ececeb273b8393b21d35`: `docs/gdd/training.md:15`, "A later matching formal course does not charge tools again."; `:31`, "A training-centre upgrade needs an operating reception camp and a matching veteran teacher. It supplies separate teacher housing. The teacher is fully occupied and cannot work, fight, build, travel or teach another pupil simultaneously. The trainee occupies a reception bed."; `:33`, "A free civilian or matching equipped novice may train." Craftsmen, soldiers and refugees before `reception.turns` cannot enrol. Only exact gdd-0.3 states with an initialized population ledger are accepted; legacy and gdd-0.1 are refused unchanged.
+
+R-TRAIN-006: In the same fixture, a course turn is counted only for a month whose opening snapshot (the #1716 synthetic month context) already holds that course with the same teacher, and at most once per month ordinal: an ordinal not above the last one counted for that pupil is refused. A counted turn keeps the same population id and every record field (work XP, reception progress, equipment, location, military history); no person is created, and teaching and the course earn no work XP (`docs/gdd/training.md:17`, "Travel, idle time, teaching and courses do not count."). Graduation timing is Deferred under #1668 question 43(a): the turn that would bring a course to `profession.course_turns` minus 1 counted turns (currently 2) is the first one where the two answers to "does the enrolment turn count" differ, so it is refused (R-TRAIN-008) and no trained tier is granted in this slice. A unit already trained cannot enrol, because a trained profession is permanent (`:13`, "Once trained, a civilian profession cannot be replaced.").
+
+R-TRAIN-007: In the same fixture, cancelling a course at any turn this slice can reach keeps the population id, profession, novice tier, tools and their payment fact and reception progress. It grants no unfinished trained tier, clears the course progress and releases the teacher and the bed. Nothing is refunded and no one moves. When the released people and bed can be used again is #1668 question 43(b) (R-TRAIN-008). A second cancel, or a cancel of a unit not in a course, is refused unchanged, and a restart is a full new course with no second tools charge (`docs/gdd/training.md:49`, "Cancelled courses retain paid entry costs and earned reception credit but award no unfinished qualification." and "Unfinished course progress clears, and restarting needs a fresh course.").
+
+R-TRAIN-008: The fixture refuses, with a "Deferred:" reason and the state unchanged, every case that needs an open design answer, and chooses no default. #1668 question 42 (teachers per centre and teacher housing): a second teacher at one centre, or a teaching teacher with no pupil. #1668 question 43 (course turn boundaries): counting the enrolment month, including a later snapshot with the enrolment month's ordinal; counting the turn that would bring a course to `profession.course_turns` minus 1 (graduation timing, 43(a)); starting in a month whose opening snapshot shows either participant on another assignment, including a teacher or pupil released by a cancel that month; and starting in a month whose opening snapshot shows the parent camp's beds full, so a bed freed after the opening is not reused that month (43(b), with #1668 question 41). #1668 question 44 and the GDD's novice lock-in decision: a free civilian without a profession, or a novice of another profession, entering a course. #1668, 27 October list, question 9: a course turn or cancellation after the parent camp or the centre stops operating. Same-month availability of a teacher or pupil after a cancel stays Deferred under question 43(b) and (c): the ledger release is not a ruling on it, and the work-assignment fixture (`Gdd03AssignmentFixture.Assign`) takes no month, so it does not enforce it. Real centres, hosts, regions, map bindings, Money and Food settlement, saves and commands remain held with their owners (#1690, #1691, #1696, #1700, #1702, #1713, #1716).
+
## Craftsmen
R-CRAFT-001: A civilian becomes a craftsman by training (D-D4; Q-CRAFT-1, owner, 15 October 2026): `Train(city, craftsman, n)` follows R-TRAIN-001 to R-TRAIN-003, and the city's facility is a completed `industry` project (R-PROJ-003); one still being built does not count. `unit_types.yaml` gives the course's `training_turns` (3) and `training_cost` (IL 0.5m a group), labelled design values (Q-CRAFT-3). A finished cohort adds to the city's count of craftsmen, which is not part of its civilians and is written into the state hash only when not 0. A craftsman can return to civilian life and keep the qualification (R-QUAL-002).
diff --git a/sim/Statecraft.Sim.Tests/Gdd03TrainingCentreFixtureTests.cs b/sim/Statecraft.Sim.Tests/Gdd03TrainingCentreFixtureTests.cs
new file mode 100644
index 000000000..b38fce48d
--- /dev/null
+++ b/sim/Statecraft.Sim.Tests/Gdd03TrainingCentreFixtureTests.cs
@@ -0,0 +1,421 @@
+using Statecraft.Sim;
+
+// #1697 first slice: synthetic fixtures only. No real centre, camp, region, host or game caller is exercised.
+public class Gdd03TrainingCentreFixtureTests
+{
+ static readonly Lazy<Gdd03BalanceCatalogue> Real = new(() => ContentLoader.Load(RealContentTests.ContentRoot()).Gdd03Balance!);
+ const string CentreA = "fixture-centre-a", CampA = "fixture-camp-a", CentreB = "fixture-centre-b", CampB = "fixture-camp-b";
+ const string CentreSouth = "fixture-centre-south", CampSouth = "fixture-camp-south", Field = "fixture-field";
+ const string Service = "fixture-service";
+ static readonly string[] Facilities = { CampA, CampB, CampSouth, CentreA, CentreB, CentreSouth, Field };
+
+ 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(CampA, PopulationAssignmentKind.Reception, "north"),
+ new PopulationTarget(CampB, PopulationAssignmentKind.Reception, "north"),
+ new PopulationTarget(CampSouth, PopulationAssignmentKind.Reception, "south"),
+ new PopulationTarget(CentreA, PopulationAssignmentKind.Course, "north", 3),
+ new PopulationTarget(CentreB, PopulationAssignmentKind.Course, "north", 3),
+ new PopulationTarget(CentreSouth, PopulationAssignmentKind.Course, "south", 3),
+ new PopulationTarget(Field, PopulationAssignmentKind.Work, "north"),
+ new PopulationTarget(Service, PopulationAssignmentKind.ActiveService, "north") },
+ Array.Empty<string>(), Array.Empty<string>());
+
+ static PopulationUnit Person(CivilianProfession profession, CivilianTier tier, string? tools,
+ PopulationStatus status = PopulationStatus.FreeCivilian, int reception = 6, PopulationAssignment? assignment = null,
+ string region = "north")
+ => new(0, status, reception, new PopulationLocation(region), assignment ?? PopulationAssignment.Unassigned,
+ profession, tier, profession == CivilianProfession.None ? 0 : 4, "", 2,
+ new PopulationEquipment(tools, tools != null));
+ static PopulationUnit Teacher(CivilianProfession p, string tools) => Person(p, CivilianTier.Veteran, tools);
+ static PopulationUnit Novice(CivilianProfession p, string tools) => Person(p, CivilianTier.Novice, tools);
+ static PopulationUnit Refugee(string camp = CampA) => Person(CivilianProfession.None, CivilianTier.None, null,
+ PopulationStatus.Refugee, 2, new PopulationAssignment(PopulationAssignmentKind.Reception, camp));
+
+ // Ids follow the row order: 0 farmer teacher, 1 farmer novice, 2 pioneer teacher, 3 pioneer novice,
+ // 4 second farmer teacher, 5 second farmer novice, then any extra rows.
+ static GameState State(Content c, params PopulationUnit[] extra)
+ {
+ var people = new List<PopulationUnit> {
+ Teacher(CivilianProfession.Farmer, "tools-0"), Novice(CivilianProfession.Farmer, "tools-1"),
+ Teacher(CivilianProfession.Pioneer, "tools-2"), Novice(CivilianProfession.Pioneer, "tools-3"),
+ Teacher(CivilianProfession.Farmer, "tools-4"), Novice(CivilianProfession.Farmer, "tools-5") };
+ people.AddRange(extra);
+ return PopulationLedger.CreateFixture(c, Bindings(), people.Select((p, i) => new PopulationInventoryRow("synthetic", i, p)));
+ }
+ static Gdd03FixtureTrainingCentre[] Centres(bool operating = true, bool upgraded = true) => new[] {
+ new Gdd03FixtureTrainingCentre(CentreA, CampA, operating, upgraded),
+ new Gdd03FixtureTrainingCentre(CentreB, CampB, true, true),
+ new Gdd03FixtureTrainingCentre(CentreSouth, CampSouth, true, true) };
+ static Gdd03SyntheticMonthContext Month(GameState s, int ordinal, bool centresAvailable = true)
+ => Gdd03SyntheticMonthContext.CreateSynthetic(SaveGame.Gdd03Ruleset, ordinal, s.PopulationLedger.Units,
+ Facilities.Select(f => new Gdd03SyntheticFacilitySnapshot(f, centresAvailable || !f.Contains("centre", StringComparison.Ordinal), 1)),
+ Array.Empty<int>(), Array.Empty<Gdd03SyntheticHousingSnapshot>(), Array.Empty<Gdd03SyntheticPendingEntry>());
+ static (int teacher, int trainee) Pair(CivilianProfession p) => p == CivilianProfession.Farmer ? (0, 1) : (2, 3);
+
+ static void Unchanged(GameState s, Action act, Type expected, string? deferredPrefix = null)
+ {
+ var before = s.Describe();
+ 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, s.Describe());
+ }
+
+ // R-TRAIN-005, R-TRAIN-006, R-TRAIN-008: a matching equipped novice and veteran teacher start a course; a counted course
+ // turn keeps the same id and every record field, creates no person and earns no work XP. The turn that would bring the
+ // course within one turn of its end (the first one where the two answers to #1668 Q43(a) differ) is Deferred.
+ [Theory]
+ [InlineData(CivilianProfession.Farmer)]
+ [InlineData(CivilianProfession.Pioneer)]
+ public void MatchingNoviceCountsTurnsUntilGraduationTimingIsDeferred(CivilianProfession profession)
+ {
+ var c = Catalogue(); var s = State(c); var f = new Gdd03TrainingCentreFixture(c, s, Centres());
+ var (teacher, trainee) = Pair(profession); var l = s.PopulationLedger;
+ var before = l.Get(trainee); var teacherBefore = l.Get(teacher);
+ int count = l.Units.Count, next = l.NextPopulationId; var people = l.TotalPeople;
+
+ f.Start(trainee, teacher, CentreA, Month(s, 0));
+ var p = l.Get(trainee);
+ Assert.Equal(PopulationStatus.Trainee, p.Status);
+ Assert.Equal(PopulationAssignmentKind.Course, p.Assignment.Kind);
+ Assert.Equal(CentreA, p.Assignment.Target); Assert.Equal(0, p.Assignment.ProgressTicks); Assert.Equal(teacher, p.Assignment.TeacherId);
+ Assert.Equal(PopulationAssignmentKind.Teaching, l.Get(teacher).Assignment.Kind);
+ Assert.Equal(CentreA, l.Get(teacher).Assignment.Target);
+
+ f.Advance(trainee, Month(s, 1));
+ var after = l.Get(trainee); var teacherAfter = l.Get(teacher);
+ Assert.Equal(1, after.Assignment.ProgressTicks); Assert.Equal(PopulationStatus.Trainee, after.Status);
+ Assert.Equal(CivilianTier.Novice, after.Tier); Assert.Equal(profession, after.Profession);
+ Assert.Equal(before.WorkXp, after.WorkXp); Assert.Equal(before.ReceptionTicks, after.ReceptionTicks);
+ Assert.Same(before.Equipment, after.Equipment); Assert.Same(before.Location, after.Location);
+ Assert.Equal(before.CombatXp, after.CombatXp); Assert.Equal(before.Qualification, after.Qualification);
+ Assert.Equal(CivilianTier.Veteran, teacherAfter.Tier); Assert.Equal(teacherBefore.WorkXp, teacherAfter.WorkXp);
+ Assert.Equal(count, l.Units.Count); Assert.Equal(next, l.NextPopulationId); Assert.Equal(people, l.TotalPeople);
+
+ Unchanged(s, () => f.Advance(trainee, Month(s, 2)), typeof(NotSupportedException), "Deferred: #1668 Q43");
+ Assert.Equal(CivilianTier.Novice, l.Get(trainee).Tier);
+ l.Reconcile();
+ }
+
+ // R-TRAIN-006: the Agreed course length is read from the catalogue, not a literal: with a synthetic 4, two turns
+ // count before the Deferred graduation-timing turn.
+ [Fact] public void CourseLengthComesFromTheCatalogue()
+ {
+ var c = Catalogue("profession.course_turns", Agreed(4)); var s = State(c);
+ var f = new Gdd03TrainingCentreFixture(c, s, Centres());
+ f.Start(1, 0, CentreA, Month(s, 0));
+ f.Advance(1, Month(s, 1)); f.Advance(1, Month(s, 2));
+ Assert.Equal(2, s.PopulationLedger.Get(1).Assignment.ProgressTicks);
+ Unchanged(s, () => f.Advance(1, Month(s, 3)), typeof(NotSupportedException), "Deferred: #1668 Q43");
+ }
+
+ // R-TRAIN-006: one month counts once; a stale or repeated snapshot cannot add a second course turn.
+ [Fact] public void AMonthCountsOnceForACourse()
+ {
+ var c = Catalogue("profession.course_turns", Agreed(5)); var s = State(c); var f = new Gdd03TrainingCentreFixture(c, s, Centres());
+ f.Start(1, 0, CentreA, Month(s, 0));
+ var m1 = Month(s, 1); f.Advance(1, m1);
+ Assert.Equal(1, s.PopulationLedger.Get(1).Assignment.ProgressTicks);
+ Unchanged(s, () => f.Advance(1, m1), typeof(ArgumentException));
+ // A fresh snapshot with an ordinal that was already counted, or an earlier one, is refused too.
+ Unchanged(s, () => f.Advance(1, Month(s, 1)), typeof(ArgumentException));
+ f.Advance(1, Month(s, 3));
+ Unchanged(s, () => f.Advance(1, Month(s, 2)), typeof(ArgumentException));
+ Assert.Equal(2, s.PopulationLedger.Get(1).Assignment.ProgressTicks);
+ }
+
+ // R-TRAIN-008: a snapshot taken after enrolment but carrying the enrolment month's ordinal is still the enrolment
+ // month, so it is not counted (#1668 Q43(a)).
+ [Fact] public void TheEnrolmentOrdinalIsNeverCounted()
+ {
+ var c = Catalogue(); var s = State(c); var f = new Gdd03TrainingCentreFixture(c, s, Centres());
+ f.Start(1, 0, CentreA, Month(s, 0));
+ Unchanged(s, () => f.Advance(1, Month(s, 0)), typeof(NotSupportedException), "Deferred: #1668 Q43");
+ }
+
+ // R-TRAIN-005: a busy teacher refuses a second pupil (Agreed profession.trainees_per_teacher = 1).
+ [Fact] public void BusyTeacherRefusesASecondPupil()
+ {
+ var c = Catalogue(); var s = State(c); var f = new Gdd03TrainingCentreFixture(c, s, Centres());
+ f.Start(1, 0, CentreA, Month(s, 0));
+ Unchanged(s, () => f.Start(5, 0, CentreA, Month(s, 1)), typeof(ArgumentException));
+ Unchanged(s, () => f.Start(5, 0, CentreB, Month(s, 1)), typeof(ArgumentException));
+ }
+
+ // R-TRAIN-005: the pupil limit is the catalogue value; a synthetic 2 admits a second pupil for the same teacher.
+ // This only proves the value is read from the catalogue: the GDD allows one pupil per teacher (training.md:31).
+ [Fact] public void PupilLimitComesFromTheCatalogue()
+ {
+ var c = Catalogue("profession.trainees_per_teacher", Agreed(2)); var s = State(c);
+ var f = new Gdd03TrainingCentreFixture(c, s, Centres());
+ f.Start(1, 0, CentreA, Month(s, 0));
+ f.Start(5, 0, CentreA, Month(s, 0));
+ Assert.Equal(0, s.PopulationLedger.Get(5).Assignment.TeacherId);
+ f.Cancel(1);
+ Assert.Equal(PopulationAssignmentKind.Teaching, s.PopulationLedger.Get(0).Assignment.Kind);
+ f.Cancel(5);
+ Assert.Same(PopulationAssignment.Unassigned, s.PopulationLedger.Get(0).Assignment);
+ }
+
+ // R-TRAIN-005: the trainee needs a free bed of the centre's own reception camp (Agreed reception.capacity = 3);
+ // another camp's beds or ordinary work places do not stand in, and the teacher's housing is not a reception bed.
+ [Fact] public void TraineeNeedsTheParentCampsOwnReceptionBed()
+ {
+ var c = Catalogue();
+ var full = State(c, Refugee(), Refugee(), Refugee());
+ var f = new Gdd03TrainingCentreFixture(c, full, Centres());
+ Unchanged(full, () => f.Start(1, 0, CentreA, Month(full, 0)), typeof(ArgumentException));
+
+ var twoTaken = State(c, Refugee(), Refugee(), Refugee(CampB));
+ var g = new Gdd03TrainingCentreFixture(c, twoTaken, Centres());
+ g.Start(1, 0, CentreA, Month(twoTaken, 0)); // 2 refugees + 1 trainee; the teacher takes no bed
+ Assert.Equal(PopulationStatus.Trainee, twoTaken.PopulationLedger.Get(1).Status);
+ g.Start(3, 2, CentreB, Month(twoTaken, 0)); // camp B still has two free beds
+ Assert.Equal(PopulationStatus.Trainee, twoTaken.PopulationLedger.Get(3).Status);
+ }
+
+ // R-TRAIN-005: settled refusals leave the state unchanged and are not reported as Deferred.
+ public static IEnumerable<object[]> SettledRefusals() => new[] {
+ new object[] { "trained trainee", 0, 6, CentreA, true, true },
+ new object[] { "unequipped novice", 0, 7, CentreA, true, true },
+ new object[] { "refugee before reception ends", 0, 8, CentreA, true, true },
+ new object[] { "trainee already working", 0, 9, CentreA, true, true },
+ new object[] { "craftsman", 0, 10, CentreA, true, true },
+ new object[] { "active soldier", 0, 11, CentreA, true, true },
+ new object[] { "trained teacher", 12, 1, CentreA, true, true },
+ new object[] { "teacher busy elsewhere", 13, 1, CentreA, true, true },
+ new object[] { "same person", 1, 1, CentreA, true, true },
+ new object[] { "unknown centre", 0, 1, "fixture-unknown", true, true },
+ new object[] { "parent not operating", 0, 1, CentreA, false, true },
+ new object[] { "upgrade incomplete", 0, 1, CentreA, true, false },
+ // The two region rows are refused by the population ledger's own binding checks, not by a #1697 rule.
+ new object[] { "other region", 0, 1, CentreSouth, true, true },
+ new object[] { "trainee in another region", 0, 14, CentreA, true, true },
+ };
+ [Theory, MemberData(nameof(SettledRefusals))]
+ public void IneligibleStartsAreRefusedWithoutMutation(string why, int teacher, int trainee, string centre, bool operating, bool upgraded)
+ {
+ Assert.False(string.IsNullOrEmpty(why));
+ var c = Catalogue();
+ var s = State(c,
+ Person(CivilianProfession.Farmer, CivilianTier.Trained, "tools-6"), // 6
+ Person(CivilianProfession.Farmer, CivilianTier.Novice, null), // 7
+ Person(CivilianProfession.Farmer, CivilianTier.Novice, "tools-8", PopulationStatus.Refugee, 5), // 8
+ Person(CivilianProfession.Farmer, CivilianTier.Novice, "tools-9", assignment: new PopulationAssignment(PopulationAssignmentKind.Work, Field)), // 9
+ Person(CivilianProfession.Craftsman, CivilianTier.Apprentice, "tools-10"), // 10
+ Person(CivilianProfession.Farmer, CivilianTier.Novice, "tools-11", PopulationStatus.ActiveSoldier, assignment: new PopulationAssignment(PopulationAssignmentKind.ActiveService, Service)), // 11
+ Person(CivilianProfession.Farmer, CivilianTier.Trained, "tools-12"), // 12
+ Person(CivilianProfession.Farmer, CivilianTier.Veteran, "tools-13", assignment: new PopulationAssignment(PopulationAssignmentKind.Work, Field)), // 13
+ Person(CivilianProfession.Farmer, CivilianTier.Novice, "tools-14", region: "south")); // 14
+ var f = new Gdd03TrainingCentreFixture(c, s, Centres(operating, upgraded));
+ Unchanged(s, () => f.Start(trainee, teacher, centre, Month(s, 0)), typeof(ArgumentException));
+ }
+
+ // R-TRAIN-007: cancel at every course turn this slice can reach keeps id, tools, payment fact and reception credit;
+ // grants nothing unfinished; clears progress; releases the teacher and the bed; moves no one.
+ [Theory]
+ [InlineData(CivilianProfession.Farmer, 0)]
+ [InlineData(CivilianProfession.Farmer, 1)]
+ [InlineData(CivilianProfession.Pioneer, 0)]
+ [InlineData(CivilianProfession.Pioneer, 1)]
+ public void CancelAtEveryTurnRetainsPaidStateAndReleasesTeacherAndBed(CivilianProfession profession, int counted)
+ {
+ var c = Catalogue(); var s = State(c, Refugee(), Refugee()); var l = s.PopulationLedger;
+ var f = new Gdd03TrainingCentreFixture(c, s, Centres());
+ var (teacher, trainee) = Pair(profession); var before = l.Get(trainee); int count = l.Units.Count, next = l.NextPopulationId;
+ f.Start(trainee, teacher, CentreA, Month(s, 0));
+ for (int m = 1; m <= counted; m++) f.Advance(trainee, Month(s, m));
+ Assert.Equal(counted, l.Get(trainee).Assignment.ProgressTicks);
+ f.Cancel(trainee);
+ var after = l.Get(trainee);
+ Assert.Equal(PopulationStatus.FreeCivilian, after.Status); Assert.Same(PopulationAssignment.Unassigned, after.Assignment);
+ Assert.Equal(CivilianTier.Novice, after.Tier); Assert.Equal(profession, after.Profession);
+ Assert.Same(before.Equipment, after.Equipment); Assert.True(after.Equipment.ToolsPaid);
+ Assert.Equal(before.ReceptionTicks, after.ReceptionTicks); Assert.Equal(before.WorkXp, after.WorkXp);
+ Assert.Same(PopulationAssignment.Unassigned, l.Get(teacher).Assignment);
+ Assert.Same(before.Location, after.Location);
+ Assert.Equal(count, l.Units.Count); Assert.Equal(next, l.NextPopulationId);
+ // Teacher and bed are free again: the camp's last bed takes a new pupil with another teacher.
+ f.Start(5, 4, CentreA, Month(s, 10));
+ Assert.Equal(PopulationStatus.Trainee, l.Get(5).Status);
+ }
+
+ // R-TRAIN-007: a repeated cancel, or a cancel of someone not in a course, is refused; a restart is a full new course.
+ [Fact] public void CancelIsOnceAndRestartIsAFullNewCourse()
+ {
+ var c = Catalogue(); var s = State(c); var l = s.PopulationLedger;
+ var f = new Gdd03TrainingCentreFixture(c, s, Centres());
+ f.Start(1, 0, CentreA, Month(s, 0)); f.Advance(1, Month(s, 1));
+ f.Cancel(1);
+ Unchanged(s, () => f.Cancel(1), typeof(ArgumentException));
+ Unchanged(s, () => f.Cancel(5), typeof(ArgumentException));
+ f.Start(1, 0, CentreA, Month(s, 2));
+ Assert.Equal(0, l.Get(1).Assignment.ProgressTicks);
+ f.Advance(1, Month(s, 3));
+ Assert.Equal(1, l.Get(1).Assignment.ProgressTicks);
+ Unchanged(s, () => f.Advance(1, Month(s, 4)), typeof(NotSupportedException), "Deferred: #1668 Q43");
+ }
+
+ // R-TRAIN-005: teacher and trainee hold exclusive assignments; other assignment paths refuse them.
+ [Fact] public void TeacherAndTraineeCannotTakeOtherAssignments()
+ {
+ var c = Catalogue(); var s = State(c); var l = s.PopulationLedger;
+ new Gdd03TrainingCentreFixture(c, s, Centres()).Start(1, 0, CentreA, Month(s, 0));
+ var work = new Gdd03AssignmentFixture(c, s, new[] { new Gdd03FixtureSlot(Field, Gdd03FixtureWork.Farm, 5, "fixture") });
+ foreach (var id in new[] { 0, 1 })
+ {
+ Unchanged(s, () => work.Assign(id, Field), typeof(ArgumentException));
+ Unchanged(s, () => l.ChangeAssignment(id, new PopulationAssignment(PopulationAssignmentKind.Work, Field)), typeof(ArgumentException));
+ }
+ }
+
+ // R-TRAIN-008: #1668 Q42 stays open: a second teacher at one centre, or an idle teacher kept at a centre, is refused.
+ [Fact] public void TeachersPerCentreAndIdleTeacherHousingStayDeferred()
+ {
+ var c = Catalogue(); var s = State(c); var f = new Gdd03TrainingCentreFixture(c, s, Centres());
+ f.Start(1, 0, CentreA, Month(s, 0));
+ Unchanged(s, () => f.Start(5, 4, CentreA, Month(s, 0)), typeof(NotSupportedException), "Deferred: #1668 Q42");
+
+ var idle = State(c, new PopulationUnit(0, PopulationStatus.FreeCivilian, 6, new PopulationLocation("north"),
+ new PopulationAssignment(PopulationAssignmentKind.Teaching, CentreB), CivilianProfession.Farmer, CivilianTier.Veteran,
+ 4, "", 2, new PopulationEquipment("tools-6", true)));
+ Unchanged(idle, () => new Gdd03TrainingCentreFixture(c, idle, Centres()), typeof(NotSupportedException), "Deferred: #1668 Q42");
+ }
+
+ // R-TRAIN-008: #1668 Q43 stays open: the enrolment month is not counted, and a participant who held another
+ // assignment at the month's opening cannot start that month.
+ [Fact] public void CourseTurnBoundariesStayDeferred()
+ {
+ var c = Catalogue(); var s = State(c, Person(CivilianProfession.Farmer, CivilianTier.Novice, "tools-6",
+ assignment: new PopulationAssignment(PopulationAssignmentKind.Work, Field)));
+ var f = new Gdd03TrainingCentreFixture(c, s, Centres());
+ var enrolment = Month(s, 0);
+ f.Start(1, 0, CentreA, enrolment);
+ Unchanged(s, () => f.Advance(1, enrolment), typeof(NotSupportedException), "Deferred: #1668 Q43");
+
+ var opening = Month(s, 1);
+ s.PopulationLedger.ChangeAssignment(6, PopulationAssignment.Unassigned);
+ Unchanged(s, () => f.Start(6, 4, CentreB, opening), typeof(NotSupportedException), "Deferred: #1668 Q43");
+
+ f.Cancel(1);
+ Unchanged(s, () => f.Start(1, 0, CentreA, opening), typeof(NotSupportedException), "Deferred: #1668 Q43");
+ // A teacher released by that cancel cannot teach at another centre in the same month.
+ Unchanged(s, () => f.Start(5, 0, CentreB, opening), typeof(NotSupportedException), "Deferred: #1668 Q43");
+ }
+
+ // R-TRAIN-008: #1668 Q43(b): a teacher who worked at the month's opening and was released afterwards cannot start
+ // teaching that month.
+ [Fact] public void TeacherWhoWorkedAtTheOpeningCannotStartThatMonth()
+ {
+ var c = Catalogue(); var s = State(c, Person(CivilianProfession.Farmer, CivilianTier.Veteran, "tools-6",
+ assignment: new PopulationAssignment(PopulationAssignmentKind.Work, Field)));
+ var f = new Gdd03TrainingCentreFixture(c, s, Centres());
+ var opening = Month(s, 0);
+ s.PopulationLedger.ChangeAssignment(6, PopulationAssignment.Unassigned);
+ Unchanged(s, () => f.Start(5, 6, CentreB, opening), typeof(NotSupportedException), "Deferred: #1668 Q43");
+ }
+
+ // R-TRAIN-008: #1668 Q43(b) and Q41: a bed freed after the month's opening (here by a cancel) is not reused that month.
+ [Fact] public void ABedFreedAfterTheOpeningIsNotReusedThatMonth()
+ {
+ var c = Catalogue(); var s = State(c, Refugee(), Refugee()); var f = new Gdd03TrainingCentreFixture(c, s, Centres());
+ f.Start(1, 0, CentreA, Month(s, 0));
+ var m1 = Month(s, 1);
+ f.Cancel(1);
+ Unchanged(s, () => f.Start(5, 4, CentreA, m1), typeof(NotSupportedException), "Deferred: #1668 Q43");
+ f.Start(5, 4, CentreA, Month(s, 2));
+ Assert.Equal(PopulationStatus.Trainee, s.PopulationLedger.Get(5).Status);
+ }
+
+ // R-TRAIN-008: #1668 Q44 and the GDD's novice lock-in stay open: no free entrant becomes a novice here, and no
+ // novice (cancelled or not) changes profession through a course.
+ [Fact] public void LockInAndProfessionChangeStayDeferred()
+ {
+ var c = Catalogue(); var s = State(c, Person(CivilianProfession.None, CivilianTier.None, null));
+ var f = new Gdd03TrainingCentreFixture(c, s, Centres());
+ Unchanged(s, () => f.Start(6, 0, CentreA, Month(s, 0)), typeof(NotSupportedException), "Deferred: #1668 Q44");
+ Unchanged(s, () => f.Start(1, 2, CentreA, Month(s, 0)), typeof(NotSupportedException), "Deferred: #1668 Q44");
+ f.Start(1, 0, CentreA, Month(s, 0)); f.Cancel(1);
+ Unchanged(s, () => f.Start(1, 2, CentreA, Month(s, 1)), typeof(NotSupportedException), "Deferred: #1668 Q44");
+ }
+
+ // R-TRAIN-008: 27 Oct #1668 list question 9 stays open: no course turn or cancellation once the parent camp or
+ // centre stops operating.
+ [Fact] public void CampLossStaysDeferred()
+ {
+ var c = Catalogue(); var s = State(c);
+ new Gdd03TrainingCentreFixture(c, s, Centres()).Start(1, 0, CentreA, Month(s, 0));
+ var closed = new Gdd03TrainingCentreFixture(c, s, Centres(operating: false));
+ Unchanged(s, () => closed.Advance(1, Month(s, 1)), typeof(NotSupportedException), "Deferred: #1668 27 Oct list Q9");
+ Unchanged(s, () => closed.Cancel(1), typeof(NotSupportedException), "Deferred: #1668 27 Oct list Q9");
+ var open = new Gdd03TrainingCentreFixture(c, s, Centres());
+ Unchanged(s, () => open.Advance(1, Month(s, 1, centresAvailable: false)), typeof(NotSupportedException), "Deferred: #1668 27 Oct list Q9");
+ }
+
+ // R-TRAIN-005: exact gdd-0.3 only; legacy and gdd-0.1 states are refused and unchanged in the same run.
+ [Fact] public void OtherIdentitiesAndUninitializedStatesAreRefused()
+ {
+ 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 Gdd03TrainingCentreFixture(c, s, Centres()));
+ Assert.Equal(before, s.Describe());
+ }
+ var g = Catalogue(); var empty = new GameState(g);
+ Assert.Throws<InvalidOperationException>(() => new Gdd03TrainingCentreFixture(g, empty, Centres()));
+ }
+
+ // R-TRAIN-005, R-TRAIN-006: missing or Deferred catalogue values fail closed, with no legacy fallback.
+ [Theory]
+ [InlineData("profession.course_turns")]
+ [InlineData("profession.trainees_per_teacher")]
+ [InlineData("reception.capacity")]
+ public void MissingOrDeferredValuesFailClosed(string key)
+ {
+ foreach (var replacement in new[] { null, Deferred() })
+ {
+ var c = Catalogue(key, replacement); var s = State(Catalogue());
+ Assert.Throws<ContentException>(() => new Gdd03TrainingCentreFixture(c, s, Centres()));
+ }
+ }
+
+ // R-TRAIN-005: centre inputs need explicit distinct ids; one centre upgrade per parent camp in this fixture.
+ [Fact] public void CentreInputsAreValidated()
+ {
+ Assert.Throws<ArgumentException>(() => new Gdd03FixtureTrainingCentre("", CampA, true, true));
+ Assert.Throws<ArgumentException>(() => new Gdd03FixtureTrainingCentre(CentreA, " ", true, true));
+ Assert.Throws<ArgumentException>(() => new Gdd03FixtureTrainingCentre(CampA, CampA, true, true));
+ var c = Catalogue(); var s = State(c);
+ Assert.Throws<ArgumentException>(() => new Gdd03TrainingCentreFixture(c, s, new[] {
+ new Gdd03FixtureTrainingCentre(CentreA, CampA, true, true), new Gdd03FixtureTrainingCentre(CentreB, CampA, true, true) }));
+ Assert.Throws<ArgumentException>(() => new Gdd03TrainingCentreFixture(c, s, new[] {
+ new Gdd03FixtureTrainingCentre(CentreA, CampA, true, true), new Gdd03FixtureTrainingCentre(CentreA, CampB, true, true) }));
+ }
+
+ // R-TRAIN-006: deterministic and isolated: centre input order does not matter and a clone keeps its own course state.
+ [Fact] public void OrderIndependentAndCloneIsolated()
+ {
+ var c = Catalogue(); var a = State(c); var b = State(c);
+ var fa = new Gdd03TrainingCentreFixture(c, a, Centres());
+ var fb = new Gdd03TrainingCentreFixture(c, b, Centres().OrderByDescending(x => x.Id, StringComparer.Ordinal));
+ fa.Start(1, 0, CentreA, Month(a, 0)); fb.Start(1, 0, CentreA, Month(b, 0));
+ fa.Start(3, 2, CentreB, Month(a, 0)); fb.Start(3, 2, CentreB, Month(b, 0));
+ var clone = a.Clone(); var cloned = clone.Describe();
+ fa.Advance(1, Month(a, 1)); fb.Advance(1, Month(b, 1));
+ Assert.Equal(a.Describe(), b.Describe());
+ Assert.Equal(cloned, clone.Describe());
+ Assert.NotEqual(cloned, a.Describe());
+ }
+}
diff --git a/sim/Statecraft.Sim/Gdd03TrainingCentreFixture.cs b/sim/Statecraft.Sim/Gdd03TrainingCentreFixture.cs
new file mode 100644
index 000000000..8beca87ed
--- /dev/null
+++ b/sim/Statecraft.Sim/Gdd03TrainingCentreFixture.cs
@@ -0,0 +1,210 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace Statecraft.Sim
+{
+ /// <summary>Synthetic centre facts supplied by a test. Operating state and upgrade completion are owned by
+ /// #1696 (reception) and #1700/#1713 (construction); this fixture only reads them. No real camp, host or region.</summary>
+ internal sealed class Gdd03FixtureTrainingCentre
+ {
+ internal string Id { get; }
+ internal string ParentCamp { get; }
+ internal bool ParentOperating { get; }
+ internal bool UpgradeComplete { get; }
+ internal Gdd03FixtureTrainingCentre(string id, string parentCamp, bool parentOperating, bool upgradeComplete)
+ {
+ if (string.IsNullOrWhiteSpace(id) || string.IsNullOrWhiteSpace(parentCamp) || string.Equals(id, parentCamp, StringComparison.Ordinal))
+ throw new ArgumentException("A centre needs its own course target id and a distinct parent reception camp id.");
+ PopulationText.ValidateText(id); PopulationText.ValidateText(parentCamp);
+ Id = id; ParentCamp = parentCamp; ParentOperating = parentOperating; UpgradeComplete = upgradeComplete;
+ }
+ }
+
+ /// <summary>R-TRAIN-005 to R-TRAIN-008: gdd-0.3 farmer/pioneer course lifecycle over the #1689 population ledger,
+ /// synthetic fixtures only. No command, save, loader, resolver, Money, Food or UI caller. Graduation is not reachable
+ /// while #1668 Q43(a) is open: no turn that would bring a course within one turn of its end is counted. Open design points
+ /// (#1668 Q42, Q43, Q44 and the 27 Oct list Q9) are refused with a "Deferred:" NotSupportedException.</summary>
+ internal sealed class Gdd03TrainingCentreFixture
+ {
+ readonly GameState state;
+ readonly SortedDictionary<string, Gdd03FixtureTrainingCentre> centres;
+ readonly int courseTurns, pupilsPerTeacher, bedsPerCamp, receptionTurns;
+ // Per fixture instance only (not saved): month ordinals of each pupil's enrolment and last counted course turn.
+ readonly SortedDictionary<int, (int enrolment, int lastCounted)> months = new SortedDictionary<int, (int, int)>();
+
+ internal Gdd03TrainingCentreFixture(Content content, GameState state, IEnumerable<Gdd03FixtureTrainingCentre> centres)
+ {
+ if (!content.UsesPopulationLedger || !state.UsesPopulationLedger || !state.PopulationLedger.IsInitialized)
+ throw new InvalidOperationException("Training centre courses require an initialized gdd-0.3 synthetic fixture.");
+ this.state = state;
+ courseTurns = content.RequirePopulationInteger("profession.course_turns");
+ pupilsPerTeacher = content.RequirePopulationInteger("profession.trainees_per_teacher");
+ bedsPerCamp = content.RequirePopulationInteger("reception.capacity");
+ receptionTurns = content.RequirePopulationInteger("reception.turns");
+ this.centres = new SortedDictionary<string, Gdd03FixtureTrainingCentre>(StringComparer.Ordinal);
+ var parents = new HashSet<string>(StringComparer.Ordinal);
+ foreach (var centre in centres)
+ {
+ this.centres.Add(centre.Id, centre); // a duplicate id throws ArgumentException
+ if (!parents.Add(centre.ParentCamp)) throw new ArgumentException("This fixture supports one centre upgrade per parent camp.");
+ }
+ ValidateInventory();
+ }
+
+ static NotSupportedException Deferred(string question) => new NotSupportedException("Deferred: " + question);
+ const string Q42 = "#1668 Q42 (teachers per centre and an idle centre's teacher housing).";
+ const string Q43 = "#1668 Q43 (course turn boundaries: whether the enrolment turn counts, and in which month's snapshot participants stop or resume other assignments).";
+ const string Q44 = "#1668 Q44 and the GDD novice lock-in decision (when a free entrant becomes a novice; profession change after a cancelled course).";
+ const string Q9 = "#1668 27 Oct list Q9 (return after cancellation or camp loss).";
+
+ bool Received(PopulationUnit p) => p.Status == PopulationStatus.FreeCivilian && p.ReceptionTicks == receptionTurns;
+ static bool FarmerOrPioneer(CivilianProfession p) => p == CivilianProfession.Farmer || p == CivilianProfession.Pioneer;
+ IEnumerable<PopulationUnit> At(PopulationAssignmentKind kind, string target)
+ => state.PopulationLedger.Units.Where(p => p.Assignment.Kind == kind && string.Equals(p.Assignment.Target, target, StringComparison.Ordinal));
+ int Pupils(int teacher) => state.PopulationLedger.Units.Count(p => p.Assignment.Kind == PopulationAssignmentKind.Course
+ && p.Assignment.TeacherId == teacher && centres.ContainsKey(p.Assignment.Target!));
+ // Agreed reception.capacity counts refugee and course-trainee beds per camp; the teacher's housing is separate.
+ int BedsTaken(Gdd03FixtureTrainingCentre centre)
+ => At(PopulationAssignmentKind.Reception, centre.ParentCamp).Count() + At(PopulationAssignmentKind.Course, centre.Id).Count();
+
+ void ValidateInventory()
+ {
+ state.PopulationLedger.Reconcile();
+ foreach (var centre in centres.Values)
+ {
+ var teachers = At(PopulationAssignmentKind.Teaching, centre.Id).ToArray();
+ if (teachers.Length > 1) throw Deferred(Q42);
+ foreach (var t in teachers)
+ {
+ int n = Pupils(t.Id);
+ if (n == 0) throw Deferred(Q42);
+ if (n > pupilsPerTeacher || !FarmerOrPioneer(t.Profession) || t.Tier != CivilianTier.Veteran)
+ throw new ArgumentException("Centre teacher must be a matching veteran within the pupil limit.");
+ }
+ foreach (var p in At(PopulationAssignmentKind.Course, centre.Id))
+ if (p.Assignment.TeacherId is not int teacher || state.PopulationLedger.Get(teacher).Profession != p.Profession
+ || p.Tier != CivilianTier.Novice || p.Assignment.ProgressTicks >= courseTurns)
+ throw new ArgumentException("Centre pupil must be a matching novice with a teacher and an unfinished course.");
+ if (BedsTaken(centre) > bedsPerCamp) throw new ArgumentException("Parent camp reception beds are over capacity.");
+ }
+ }
+
+ Gdd03FixtureTrainingCentre CentreOf(PopulationUnit trainee)
+ {
+ if (trainee.Status != PopulationStatus.Trainee || trainee.Assignment.Kind != PopulationAssignmentKind.Course
+ || trainee.Assignment.Target == null || !centres.TryGetValue(trainee.Assignment.Target, out var centre))
+ throw new ArgumentException("Not a pupil of a fixture training centre course.");
+ return centre;
+ }
+
+ static PopulationUnit Opening(Gdd03SyntheticMonthContext month, int id)
+ => (month ?? throw new ArgumentNullException(nameof(month))).OpeningPeople.FirstOrDefault(p => p.Id == id)
+ ?? throw new ArgumentException("Participant is not in the month's opening snapshot.");
+
+ // Every check runs before the first write; Replace validates each record and a failure restores earlier writes.
+ void Commit(params 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; }
+ }
+ static PopulationUnit Released(PopulationUnit p)
+ => p.WithPlacement(PopulationStatus.FreeCivilian, p.Location, PopulationAssignment.Unassigned, p.Captor, p.Home);
+
+ /// <summary>R-TRAIN-005: enrol a matching equipped novice with a free matching veteran teacher at an operating,
+ /// upgraded centre that has a free bed in its own parent camp. No payment: the tools were paid on entry.</summary>
+ internal void Start(int traineeId, int teacherId, string centreId, Gdd03SyntheticMonthContext month)
+ {
+ ValidateInventory();
+ if (centreId == null || !centres.TryGetValue(centreId, out var centre)) throw new ArgumentException("Unknown fixture centre.");
+ if (!centre.ParentOperating || !centre.UpgradeComplete)
+ throw new ArgumentException("A course needs an operating parent camp and a completed centre upgrade.");
+ if (traineeId == teacherId) throw new ArgumentException("Teacher and trainee must be different population units.");
+ var ledger = state.PopulationLedger; var trainee = ledger.Get(traineeId); var teacher = ledger.Get(teacherId);
+
+ bool teachingHere = teacher.Assignment.Kind == PopulationAssignmentKind.Teaching
+ && string.Equals(teacher.Assignment.Target, centre.Id, StringComparison.Ordinal);
+ if (!Received(teacher) || !FarmerOrPioneer(teacher.Profession) || teacher.Tier != CivilianTier.Veteran)
+ throw new ArgumentException("The teacher must be a received matching veteran farmer or pioneer.");
+ if (teachingHere ? Pupils(teacher.Id) >= pupilsPerTeacher : teacher.Assignment.Kind != PopulationAssignmentKind.Unassigned)
+ throw new ArgumentException("The teacher is occupied and refuses another pupil.");
+
+ if (!Received(trainee) || trainee.Assignment.Kind != PopulationAssignmentKind.Unassigned)
+ throw new ArgumentException("The trainee must be a received, unassigned free civilian.");
+ if (trainee.Profession == CivilianProfession.Craftsman)
+ throw new ArgumentException("A course cannot replace another civilian profession.");
+ if (trainee.Profession != CivilianProfession.None && trainee.Tier != CivilianTier.Novice)
+ throw new ArgumentException("Only a novice can gain the trained tier from a course.");
+ if (trainee.Profession != CivilianProfession.None && trainee.Equipment.ToolsId == null)
+ throw new ArgumentException("A novice needs matching tools to enrol.");
+ if (trainee.Profession != teacher.Profession) throw Deferred(Q44);
+
+ if (At(PopulationAssignmentKind.Teaching, centre.Id).Any(t => t.Id != teacher.Id)) throw Deferred(Q42);
+ if (BedsTaken(centre) >= bedsPerCamp) throw new ArgumentException("No free reception bed in the centre's parent camp.");
+
+ var traineeOpening = Opening(month, trainee.Id); var teacherOpening = Opening(month, teacher.Id);
+ bool teacherOpenedHere = teacherOpening.Assignment.Kind == PopulationAssignmentKind.Teaching && teachingHere
+ && string.Equals(teacherOpening.Assignment.Target, centre.Id, StringComparison.Ordinal);
+ if (traineeOpening.Assignment.Kind != PopulationAssignmentKind.Unassigned
+ || (teacherOpening.Assignment.Kind != PopulationAssignmentKind.Unassigned && !teacherOpenedHere))
+ throw Deferred(Q43);
+ // A bed freed after the month's opening (for example by a cancel) is not reused that month: Q43(b), Q41.
+ if (month.OpeningPeople.Count(p => (p.Assignment.Kind == PopulationAssignmentKind.Reception
+ && string.Equals(p.Assignment.Target, centre.ParentCamp, StringComparison.Ordinal))
+ || (p.Assignment.Kind == PopulationAssignmentKind.Course
+ && string.Equals(p.Assignment.Target, centre.Id, StringComparison.Ordinal))) >= bedsPerCamp)
+ throw Deferred(Q43);
+
+ var course = new PopulationAssignment(PopulationAssignmentKind.Course, centre.Id, 0, teacher.Id);
+ var pupil = trainee.WithPlacement(PopulationStatus.Trainee, trainee.Location, course, trainee.Captor, trainee.Home);
+ if (teachingHere) Commit(pupil);
+ else Commit(teacher.WithPlacement(teacher.Status, teacher.Location,
+ new PopulationAssignment(PopulationAssignmentKind.Teaching, centre.Id), teacher.Captor, teacher.Home), pupil);
+ months[trainee.Id] = (month.MonthOrdinal, month.MonthOrdinal);
+ }
+
+ /// <summary>R-TRAIN-006: count one completed course turn for a course already held at the month's opening, once per
+ /// month ordinal. Counting the turn that would leave one turn or none to go depends on whether the enrolment turn
+ /// counts (#1668 Q43(a)), so it is refused: graduation timing is Deferred and no trained tier is granted here.</summary>
+ internal void Advance(int traineeId, Gdd03SyntheticMonthContext month)
+ {
+ ValidateInventory();
+ var ledger = state.PopulationLedger; var trainee = ledger.Get(traineeId); var centre = CentreOf(trainee);
+ if (!centre.ParentOperating || !centre.UpgradeComplete) throw Deferred(Q9);
+ var opening = Opening(month, trainee.Id);
+ if (opening.Status != PopulationStatus.Trainee || opening.Assignment.Kind != PopulationAssignmentKind.Course
+ || !string.Equals(opening.Assignment.Target, centre.Id, StringComparison.Ordinal)
+ || opening.Assignment.TeacherId != trainee.Assignment.TeacherId)
+ throw Deferred(Q43);
+ bool tracked = months.TryGetValue(trainee.Id, out var known);
+ if (tracked)
+ {
+ if (month.MonthOrdinal == known.enrolment) throw Deferred(Q43);
+ if (month.MonthOrdinal <= known.lastCounted) throw new ArgumentException("This month ordinal was already counted or is earlier.");
+ }
+ if (!month.CourseEligibleIds.Contains(trainee.Id)) throw Deferred(Q9);
+ if (trainee.Assignment.ProgressTicks != opening.Assignment.ProgressTicks)
+ throw new ArgumentException("This month's course turn was already counted.");
+
+ int progress = checked(trainee.Assignment.ProgressTicks + 1);
+ if (progress > courseTurns - 2) throw Deferred(Q43);
+ Commit(trainee.WithPlacement(trainee.Status, trainee.Location, new PopulationAssignment(PopulationAssignmentKind.Course,
+ centre.Id, progress, trainee.Assignment.TeacherId), trainee.Captor, trainee.Home));
+ if (tracked) months[trainee.Id] = (known.enrolment, month.MonthOrdinal);
+ }
+
+ /// <summary>R-TRAIN-007: cancel keeps the id, profession, tier, tools and their payment fact and reception credit;
+ /// it clears the unfinished course and releases the teacher and the bed. Nothing is refunded or granted and no one
+ /// moves. When the released people and bed can be used again is #1668 Q43(b).</summary>
+ internal void Cancel(int traineeId)
+ {
+ ValidateInventory();
+ var ledger = state.PopulationLedger; var trainee = ledger.Get(traineeId); var centre = CentreOf(trainee);
+ if (!centre.ParentOperating || !centre.UpgradeComplete) throw Deferred(Q9);
+ var teacher = ledger.Get(trainee.Assignment.TeacherId!.Value);
+ if (Pupils(teacher.Id) > 1) Commit(Released(trainee)); else Commit(Released(trainee), Released(teacher));
+ months.Remove(trainee.Id);
+ }
+ }
+}