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 craftsman work XP and apprentice promotion, fixture-only (Fixes #2472) (#2709)
Berib3e5274fbd84
diff --git a/changelog.d/2472-craftsman-work-xp.md b/changelog.d/2472-craftsman-work-xp.mdnew file mode 100644index 000000000..2b244eea5--- /dev/null+++ b/changelog.d/2472-craftsman-work-xp.md@@ -0,0 +1,7 @@+### Changed++- GDD 0.3: an apprentice craftsman now earns one work turn for each month spent working in Industry or an arms+ workshop, whatever the output or pay, and becomes an expert at the 36th; the expert level counts from the next month,+ and the same person keeps their job, place, equipment and military record. Idle, travel, course, teaching, service,+ farming and building months earn nothing, and a month can only count once (Fixes #2472). No game uses it yet, so+ play is unchanged.diff --git a/docs/rules/mvp.md b/docs/rules/mvp.mdindex 1d5364813..12762274a 100644--- a/docs/rules/mvp.md+++ b/docs/rules/mvp.md@@ -190,9 +190,9 @@ R-TRAIN-008: The fixture refuses, with a "Deferred:" reason and the state unchanR-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). Under `gdd-0.3`, the craftsman course on the population ledger is R-CRAFT-003 (fixture only).-R-CRAFT-002: A craftsman fills an ordinary job slot (Q-CRAFT-2, owner, 15 October 2026). Of a city's employed, its craftsmen are counted first, and each employed craftsman earns `craftsman_income_multiple` (2, a labelled design value) times `income_per_job_per_year`; every other employed unit earns the R-CITY-002 rate. Under `gdd-0.3`, a craftsman is a novice from the course start, then an apprentice or an expert (R-CRAFT-003); the course's Industry slot and income stay with #1692.+R-CRAFT-002: A craftsman fills an ordinary job slot (Q-CRAFT-2, owner, 15 October 2026). Of a city's employed, its craftsmen are counted first, and each employed craftsman earns `craftsman_income_multiple` (2, a labelled design value) times `income_per_job_per_year`; every other employed unit earns the R-CITY-002 rate. Under `gdd-0.3`, a craftsman is a novice from the course start, then an apprentice or an expert (R-CRAFT-003); the course's Industry slot and income stay with #1692. Work XP under `gdd-0.3`, in synthetic fixtures only (#2472, `Gdd03CraftWorkFixture`; nothing in the game calls it): `docs/gdd/training.md` records "Apprentices become experts after `craft.expert_work_turns` actual turns in Industry or an arms workshop. Each turn counts once, regardless of output/work rate." Each apprentice or expert craftsman the month's snapshot (#1716) has working an Industry or arms-workshop slot gives one work receipt for that population id and month; idle, travel, course, teaching, service, farming and building months give none, and a novice craftsman's workshop month changes no qualification (Q55). Receipts are deduplicated by id and month, within a batch and against those already applied, before any XP, so a repeated receipt adds nothing and cannot promote twice. Each receipt adds one tick whatever the output or pay, and an apprentice whose tick reaches `craft.expert_work_turns` (36) becomes an expert: the month's snapshot keeps the apprentice tier for that month's output, and the expert tier counts from the next snapshot. Only the tier and work XP change; the id, assignment, location, equipment and military history stay. An expert's work XP keeps counting past 36 (maintainer reading: `Gdd03CraftArithmetic.WorkTick` already counts it, and no ruling stops it). The detached `Gdd03CraftArithmetic` no longer counts a building turn as work XP; it still quotes the builder's work.-R-CRAFT-003: In `gdd-0.3` synthetic fixtures only (#1698, `Gdd03CraftCourseFixture`; nothing in the game calls it), a craftsman course on the #1689 population ledger. A free civilian with no profession, whatever their reception progress, which is not read (`docs/GDD.md:374`: "Refugees cannot train until they become civilians"), or a novice farmer or pioneer, starts the course and becomes a novice craftsman under the same population id, as a trainee on the course (#1698 follow-up and 27M-3, in the 1 November 2026 answers the owner approved, [answers](https://github.com/eyalgolan/statecraft-israel/pull/1668#issuecomment-6553884547): "When the craftsman course starts." and "The course replaces the novice profession, and paid tools are not refunded."). Work XP restarts at 0 because the course replaces the novice profession, a maintainer call; tools and their paid fact are kept. A person with a job may start: the job is released in the same change, and what they held at the month's opening is no bar. This is a maintainer reading of `docs/gdd/cities.md:42` ("Reassignment releases old capacity atomically.") with `docs/GDD.md:372` Q43(b)/(c), not an owner ruling. A person on a course, teaching or in reception, and a refugee are refused. Course turns follow R-TRAIN-006's Q43 timing: the enrolment month is course turn 1, a later month counts only when its opening snapshot holds the course, and each month ordinal counts once. The turn that reaches Agreed `craft.course_turns` (currently 3) makes an apprentice craftsman with the same id and every other field, released in that turn as a civilian without a job; they cannot start a course that month (Q43(b), R-TRAIN-008), and work starts the next month. Cancelling before that makes an ordinary civilian again: profession and tier none, work XP 0, released at once, same id, tools and their paid fact kept and nothing refunded (#1698 follow-up: "On cancelling before qualifying they are an ordinary civilian again."; 27M-4; Q44). No teacher is read or created and the population count does not change (#1698: "The course adds no mentor population unit"); a teaching record at a craftsman course is refused. The ledger accepts a novice craftsman outside a course too, a maintainer reading of Q55 ("workshop work by a novice craftsman"). A trained or veteran farmer or pioneer may start the course and loses that level, as a qualified civilian a Train order takes does (R-QUAL-006; `docs/GDD.md:349`, D3): they become a novice craftsman with work XP 0, keep their tools and the paid fact, graduate as an apprentice, and on cancelling are an ordinary civilian, not the old level (owner, 4 November 2026, on "#1698: may a trained or veteran farmer or pioneer start the craftsman course?": "Yes, lose old level (Recommended)"). An apprentice or expert craftsman may take the course again (27M-5, `docs/gdd/training.md:66`: "graduates may re-enrol at any time") and keeps their tier on the course, after graduating and after cancelling; the course never lowers a qualification (owner, 4 November 2026, on "#1698: what level does a craftsman hold when they take the craftsman course again?": "Keep their level (Recommended)"). That they keep their work XP too is a maintainer reading, not the owner's: the recorded answer covers only the level. Not built here, refused with a "Deferred:" reason and the state unchanged: a novice craftsman outside a course starting it (the 4 November 2026 answer names an apprentice or expert), and a course turn when the course is not available at the month's freeze (Q52). Out of this rule, with #1692: the Industry slot, its capacity and the course income; and with their owners: the 0.5 Money course cost, apprentice-to-expert work turns, live `Train` orders and saves. Every refusal leaves the state unchanged; legacy and `gdd-0.1` states are refused.+R-CRAFT-003: In `gdd-0.3` synthetic fixtures only (#1698, `Gdd03CraftCourseFixture`; nothing in the game calls it), a craftsman course on the #1689 population ledger. A free civilian with no profession, whatever their reception progress, which is not read (`docs/GDD.md:374`: "Refugees cannot train until they become civilians"), or a novice farmer or pioneer, starts the course and becomes a novice craftsman under the same population id, as a trainee on the course (#1698 follow-up and 27M-3, in the 1 November 2026 answers the owner approved, [answers](https://github.com/eyalgolan/statecraft-israel/pull/1668#issuecomment-6553884547): "When the craftsman course starts." and "The course replaces the novice profession, and paid tools are not refunded."). Work XP restarts at 0 because the course replaces the novice profession, a maintainer call; tools and their paid fact are kept. A person with a job may start: the job is released in the same change, and what they held at the month's opening is no bar. This is a maintainer reading of `docs/gdd/cities.md:42` ("Reassignment releases old capacity atomically.") with `docs/GDD.md:372` Q43(b)/(c), not an owner ruling. A person on a course, teaching or in reception, and a refugee are refused. Course turns follow R-TRAIN-006's Q43 timing: the enrolment month is course turn 1, a later month counts only when its opening snapshot holds the course, and each month ordinal counts once. The turn that reaches Agreed `craft.course_turns` (currently 3) makes an apprentice craftsman with the same id and every other field, released in that turn as a civilian without a job; they cannot start a course that month (Q43(b), R-TRAIN-008), and work starts the next month. Cancelling before that makes an ordinary civilian again: profession and tier none, work XP 0, released at once, same id, tools and their paid fact kept and nothing refunded (#1698 follow-up: "On cancelling before qualifying they are an ordinary civilian again."; 27M-4; Q44). No teacher is read or created and the population count does not change (#1698: "The course adds no mentor population unit"); a teaching record at a craftsman course is refused. The ledger accepts a novice craftsman outside a course too, a maintainer reading of Q55 ("workshop work by a novice craftsman"). A trained or veteran farmer or pioneer may start the course and loses that level, as a qualified civilian a Train order takes does (R-QUAL-006; `docs/GDD.md:349`, D3): they become a novice craftsman with work XP 0, keep their tools and the paid fact, graduate as an apprentice, and on cancelling are an ordinary civilian, not the old level (owner, 4 November 2026, on "#1698: may a trained or veteran farmer or pioneer start the craftsman course?": "Yes, lose old level (Recommended)"). An apprentice or expert craftsman may take the course again (27M-5, `docs/gdd/training.md:66`: "graduates may re-enrol at any time") and keeps their tier on the course, after graduating and after cancelling; the course never lowers a qualification (owner, 4 November 2026, on "#1698: what level does a craftsman hold when they take the craftsman course again?": "Keep their level (Recommended)"). That they keep their work XP too is a maintainer reading, not the owner's: the recorded answer covers only the level. Not built here, refused with a "Deferred:" reason and the state unchanged: a novice craftsman outside a course starting it (the 4 November 2026 answer names an apprentice or expert), and a course turn when the course is not available at the month's freeze (Q52). Out of this rule, with #1692: the Industry slot, its capacity and the course income; and with their owners: the 0.5 Money course cost, apprentice-to-expert work turns (fixture only, R-CRAFT-002), live `Train` orders and saves. Every refusal leaves the state unchanged; legacy and `gdd-0.1` states are refused.## Sitesdiff --git a/sim/Statecraft.Sim.Tests/Gdd03CraftArithmeticTests.cs b/sim/Statecraft.Sim.Tests/Gdd03CraftArithmeticTests.csindex 94a509a3e..4cefef73b 100644--- a/sim/Statecraft.Sim.Tests/Gdd03CraftArithmeticTests.cs+++ b/sim/Statecraft.Sim.Tests/Gdd03CraftArithmeticTests.cs@@ -45,7 +45,6 @@ public class Gdd03CraftArithmeticTests[Theory][InlineData("Industry")][InlineData("Workshop")]- [InlineData("Construction")]public void ActualWorkCrossesThresholdAfterOldTierOutput(string activityName){var activity = Enum.Parse<CraftTickActivity>(activityName);@@ -56,24 +55,26 @@ public class Gdd03CraftArithmeticTestsAssert.Equal(17, crossing.UnitId); Assert.Equal(36, crossing.WorkXp);Assert.Equal(CivilianTier.Apprentice, crossing.OutputTier); Assert.Equal(CivilianTier.Expert, crossing.TierAfter);Assert.Equal(activity == CraftTickActivity.Industry ? 2m : 0m, crossing.IndustryIncome);- Assert.Equal(activity == CraftTickActivity.Construction ? 1.5m : 0m, crossing.BuilderWork);+ Assert.Equal(0m, crossing.BuilderWork);var next = a.WorkTick(17, crossing.TierAfter, crossing.WorkXp, activity, true);Assert.Equal(37, next.WorkXp); Assert.Equal(CivilianTier.Expert, next.OutputTier);Assert.Equal(activity == CraftTickActivity.Industry ? 3m : 0m, next.IndustryIncome);- Assert.Equal(activity == CraftTickActivity.Construction ? 3m : 0m, next.BuilderWork);+ Assert.Equal(0m, next.BuilderWork);// Workshop work has no realized output field: confirmed intermediate/zero-yield turns still count.Assert.Equal(0m, a.WorkTick(17, CivilianTier.Apprentice, 0, CraftTickActivity.Workshop, true).IndustryIncome);}- // R-CRAFT-002: synthetic 12+12+12 participation sequence, no second persisted XP store.+ // R-CRAFT-002: synthetic 18+12+18 participation sequence, no second persisted XP store. The 12 building turns+ // between them quote builder work but add no XP (#2472).[Fact]public void MixedWorkSourcesCountOneTickPerExplicitReceipt(){var a = Arithmetic(); var xp = 0; var tier = CivilianTier.Apprentice;- foreach (var activity in new[] { CraftTickActivity.Industry, CraftTickActivity.Workshop, CraftTickActivity.Construction })- for (var i = 0; i < 12; i++)+ foreach (var activity in new[] { CraftTickActivity.Industry, CraftTickActivity.Construction, CraftTickActivity.Workshop })+ for (var i = 0; i < (activity == CraftTickActivity.Construction ? 12 : 18); i++){var r = a.WorkTick(17, tier, xp, activity, true); xp = r.WorkXp; tier = r.TierAfter;+ if (activity == CraftTickActivity.Construction) Assert.Equal(1.5m, r.BuilderWork);}Assert.Equal(36, xp); Assert.Equal(CivilianTier.Expert, tier);}diff --git a/sim/Statecraft.Sim.Tests/Gdd03CraftWorkFixtureTests.cs b/sim/Statecraft.Sim.Tests/Gdd03CraftWorkFixtureTests.csnew file mode 100644index 000000000..729679e3c--- /dev/null+++ b/sim/Statecraft.Sim.Tests/Gdd03CraftWorkFixtureTests.cs@@ -0,0 +1,158 @@+using Statecraft.Sim;++// #2472, R-CRAFT-002 under gdd-0.3, synthetic fixtures only: craftsman work XP from the month's snapshot. The recorded+// course rule (docs/gdd/training.md): "Apprentices become experts after `craft.expert_work_turns` actual turns in Industry+// or an arms workshop. Each turn counts once, regardless of output/work rate." The catalogue's threshold is 36.+// People, slots and month ordinals below are test data.+public class Gdd03CraftWorkFixtureTests+{+ static readonly Lazy<Gdd03BalanceCatalogue> Real = new(() => ContentLoader.Load(RealContentTests.ContentRoot()).Gdd03Balance!);+ const string Industry = "fixture-industry", Workshop = "fixture-workshop", Builder = "fixture-builder", Field = "fixture-field",+ Course = "fixture-course";+ static readonly Gdd03FixtureSlot[] Slots = {+ new(Industry, Gdd03FixtureWork.Industry, 9, "industry"), new(Workshop, Gdd03FixtureWork.Workshop, 9, "workshop"),+ new(Builder, Gdd03FixtureWork.Builder, 9, "builder"), new(Field, Gdd03FixtureWork.Farm, 9, "field") };++ static Content Content()+ {+ var c = PopulationLedgerTests.Content();+ c.Gdd03Balance = Real.Value;+ return c;+ }++ static PopulationBindings Bindings() => new(+ new[] { new PopulationLocation("north"), new PopulationLocation("south") },+ new[] { new PopulationTarget(Industry, PopulationAssignmentKind.Work, "north"), new PopulationTarget(Workshop, PopulationAssignmentKind.Work, "north"),+ new PopulationTarget(Builder, PopulationAssignmentKind.Work, "north"), new PopulationTarget(Field, PopulationAssignmentKind.Work, "north"),+ new PopulationTarget(Course, PopulationAssignmentKind.Course, "north", 3),+ new PopulationTarget("teacher", PopulationAssignmentKind.Teaching, "north"),+ new PopulationTarget("travel", PopulationAssignmentKind.Travel, "south"),+ new PopulationTarget("service", PopulationAssignmentKind.ActiveService, "north") },+ Array.Empty<string>(), new[] { "basic" });++ static PopulationUnit Craftsman(CivilianTier tier, int xp, PopulationAssignment assignment,+ PopulationStatus status = PopulationStatus.FreeCivilian, CivilianProfession profession = CivilianProfession.Craftsman,+ string region = "north") =>+ new(0, status, 6, new PopulationLocation(region), assignment, profession, tier, xp, "basic", 2, PopulationEquipment.None);+ static PopulationAssignment At(string target) => new(PopulationAssignmentKind.Work, target);++ static GameState State(params PopulationUnit[] people) => PopulationLedger.CreateFixture(Content(), Bindings(),+ people.Select((p, i) => new PopulationInventoryRow("synthetic", i, new PopulationUnit(0, p.Status, p.ReceptionTicks, p.Location,+ p.Assignment, p.Profession, p.Tier, p.WorkXp, p.Qualification, p.CombatXp, new PopulationEquipment($"tools-{i}", true)))));++ static Gdd03SyntheticMonthContext Month(GameState s, int ordinal) => Gdd03SyntheticMonthContext.CreateSynthetic(+ SaveGame.Gdd03Ruleset, ordinal, s.PopulationLedger.Units,+ new[] { Industry, Workshop, Builder, Field, Course, "teacher" }.Select(f => new Gdd03SyntheticFacilitySnapshot(f, true, 9)),+ Array.Empty<int>(), Array.Empty<Gdd03SyntheticHousingSnapshot>(), Array.Empty<Gdd03SyntheticPendingEntry>());++ // R-CRAFT-002: an apprentice at 35 Industry or workshop months reaches 36 and turns expert. That month's output is+ // quoted at the snapshot's apprentice tier (2x); the next month's snapshot holds an expert (3x). Id, assignment,+ // location, equipment and military history are kept.+ [Fact]+ public void AnApprenticeTurnsExpertAtTheThirtySixthWorkMonth_RCraft002()+ {+ var c = Content();+ var s = State(Craftsman(CivilianTier.Apprentice, 35, At(Industry)), Craftsman(CivilianTier.Apprentice, 35, At(Workshop)));+ var before = s.PopulationLedger.Units;+ var f = new Gdd03CraftWorkFixture(c, s, Slots);+ var month = Month(s, 4);+ f.Apply(f.Receipts(month));+ var rates = Gdd03IndustryRates.Read(c);+ Assert.All(month.OpeningPeople, p => Assert.Equal(CivilianTier.Apprentice, p.Tier));+ Assert.Equal(2m, rates.For(month.OpeningPeople[0].Tier)); // this month's output: the snapshot tier+ foreach (var p in before)+ {+ var after = s.PopulationLedger.Get(p.Id);+ Assert.Equal((CivilianTier.Expert, 36), (after.Tier, after.WorkXp));+ Assert.Equal((p.Status, p.Location, p.Assignment, p.Equipment, p.Qualification, p.CombatXp, p.Profession),+ (after.Status, after.Location, after.Assignment, after.Equipment, after.Qualification, after.CombatXp, after.Profession));+ }+ Assert.Equal(3m, rates.For(Month(s, 5).OpeningPeople[0].Tier)); // the next snapshot: expert+ }++ // R-CRAFT-002: at most one tick per population id per month. A repeated receipt in one batch, or the same month applied+ // again, adds nothing and cannot promote twice; the next month ticks once more.+ [Fact]+ public void DuplicateReceiptsAwardOneTick_RCraft002()+ {+ var c = Content();+ var s = State(Craftsman(CivilianTier.Apprentice, 34, At(Industry)));+ var f = new Gdd03CraftWorkFixture(c, s, Slots);+ var receipts = f.Receipts(Month(s, 7));+ Assert.Single(receipts);+ f.Apply(receipts.Concat(receipts));+ Assert.Equal((CivilianTier.Apprentice, 35), (s.PopulationLedger.Get(0).Tier, s.PopulationLedger.Get(0).WorkXp));+ f.Apply(receipts);+ f.Apply(f.Receipts(Month(s, 7)));+ Assert.Equal(35, s.PopulationLedger.Get(0).WorkXp);+ f.Apply(f.Receipts(Month(s, 8)));+ Assert.Equal((CivilianTier.Expert, 36), (s.PopulationLedger.Get(0).Tier, s.PopulationLedger.Get(0).WorkXp));+ }++ // R-CRAFT-002 (#2472): idle, course, teaching, travel, service, building and farming months give no receipt, and a+ // novice craftsman's workshop month changes no qualification (Q55), nor does a civilian with no profession earn+ // craftsman XP in Industry. Nobody's record changes.+ [Fact]+ public void NonIndustryMonthsAwardNoWorkXp_RCraft002()+ {+ var c = Content();+ var s = State(+ Craftsman(CivilianTier.Apprentice, 35, PopulationAssignment.Unassigned),+ Craftsman(CivilianTier.Apprentice, 35, At(Builder)),+ Craftsman(CivilianTier.Apprentice, 35, At(Field)),+ Craftsman(CivilianTier.Apprentice, 35, new PopulationAssignment(PopulationAssignmentKind.Course, Course, 1), PopulationStatus.Trainee),+ Craftsman(CivilianTier.Expert, 40, new PopulationAssignment(PopulationAssignmentKind.Teaching, "teacher")),+ Craftsman(CivilianTier.Apprentice, 35, new PopulationAssignment(PopulationAssignmentKind.Travel, "travel"), PopulationStatus.CivilianInTransit, region: "south"),+ Craftsman(CivilianTier.Apprentice, 35, new PopulationAssignment(PopulationAssignmentKind.ActiveService, "service"), PopulationStatus.ActiveSoldier),+ Craftsman(CivilianTier.Novice, 0, At(Workshop)),+ Craftsman(CivilianTier.None, 0, At(Industry), profession: CivilianProfession.None));+ var before = s.Describe();+ var f = new Gdd03CraftWorkFixture(c, s, Slots);+ var receipts = f.Receipts(Month(s, 0));+ Assert.Empty(receipts);+ f.Apply(receipts);+ Assert.Equal(before, s.Describe());+ }++ // A batch with a bad receipt (building work, a person who is not a craftsman) is refused whole: no record changes and+ // the good receipt in it is not used up, so it still ticks once on its own.+ [Fact]+ public void ABadReceiptRefusesTheWholeBatch()+ {+ var c = Content();+ var s = State(Craftsman(CivilianTier.Apprentice, 10, At(Industry)), Craftsman(CivilianTier.None, 0, At(Industry), profession: CivilianProfession.None));+ var f = new Gdd03CraftWorkFixture(c, s, Slots);+ var good = f.Receipts(Month(s, 3));+ var before = s.Describe();+ Assert.Throws<ArgumentException>(() => f.Apply(good.Append(new Gdd03CraftWorkReceipt(0, 4, CraftTickActivity.Construction))));+ Assert.Throws<ArgumentException>(() => f.Apply(good.Append(new Gdd03CraftWorkReceipt(1, 3, CraftTickActivity.Industry))));+ Assert.Equal(before, s.Describe());+ f.Apply(good);+ Assert.Equal(11, s.PopulationLedger.Get(0).WorkXp);+ }++ // A novice craftsman earns no work XP: the tier check in WorkTick refuses the receipt before any change.+ [Fact]+ public void ANoviceCraftsmanReceiptIsRefusedBeforeAnyChange()+ {+ var s = State(Craftsman(CivilianTier.Apprentice, 10, At(Industry)), Craftsman(CivilianTier.Novice, 0, At(Industry)));+ var f = new Gdd03CraftWorkFixture(Content(), s, Slots);+ var before = s.Describe();+ Assert.Throws<ArgumentOutOfRangeException>(() => f.Apply(new[]+ {+ new Gdd03CraftWorkReceipt(0, 3, CraftTickActivity.Industry),+ new Gdd03CraftWorkReceipt(1, 3, CraftTickActivity.Industry),+ }));+ Assert.Equal(before, s.Describe());+ }++ // gdd-0.1 and legacy are unchanged: the fixture refuses a state without an initialized gdd-0.3 ledger.+ [Fact]+ public void Gdd01IsRefused()+ {+ var c = ContentLoader.Load(RealContentTests.ContentRoot());+ var s = new GameState(c); var before = s.Describe();+ Assert.Throws<InvalidOperationException>(() => new Gdd03CraftWorkFixture(c, s, Slots));+ Assert.Equal(before, s.Describe());+ }+}diff --git a/sim/Statecraft.Sim/Gdd03CraftArithmetic.cs b/sim/Statecraft.Sim/Gdd03CraftArithmetic.csindex b842b3cfb..f61bf2e84 100644--- a/sim/Statecraft.Sim/Gdd03CraftArithmetic.cs+++ b/sim/Statecraft.Sim/Gdd03CraftArithmetic.cs@@ -7,7 +7,8 @@ namespace Statecraft.Siminternal enum CraftTickActivity { Idle, Travel, Course, Industry, Workshop, Construction }/// <summary>Detached #1698 arithmetic on explicit synthetic inputs. No GameState/ledger mutation,- /// reservation, payment, receipt deduplication or live promotion. Future owners supply those contracts.</summary>+ /// reservation, payment, receipt deduplication or live promotion. Gdd03CraftWorkFixture supplies the work receipts,+ /// their deduplication and the promotion (#2472).</summary>internal sealed class Gdd03CraftArithmetic{internal decimal CourseCost { get; }@@ -93,8 +94,11 @@ namespace Statecraft.Simif (!Enum.IsDefined(typeof(CraftTickActivity), activity)) throw new ArgumentOutOfRangeException(nameof(activity));var working = activity == CraftTickActivity.Industry || activity == CraftTickActivity.Workshop || activity == CraftTickActivity.Construction;if (actualWork && !working) throw new ArgumentException("A nonwork activity cannot carry an actual-work receipt.", nameof(actualWork));- var xp = actualWork ? checked(workXp + 1) : workXp;- var after = actualWork && tier == CivilianTier.Apprentice && xp >= ExpertWorkTurns ? CivilianTier.Expert : tier;+ // R-CRAFT-002 (#2472): only Industry and arms-workshop turns count (docs/gdd/training.md: "Apprentices become+ // experts after `craft.expert_work_turns` actual turns in Industry or an arms workshop"); building gives no XP.+ var counts = actualWork && (activity == CraftTickActivity.Industry || activity == CraftTickActivity.Workshop);+ var xp = counts ? checked(workXp + 1) : workXp;+ var after = counts && tier == CivilianTier.Apprentice && xp >= ExpertWorkTurns ? CivilianTier.Expert : tier;var income = actualWork && activity == CraftTickActivity.Industry ? (tier == CivilianTier.Apprentice ? apprenticeIncome : expertIncome) : 0m;var work = actualWork && activity == CraftTickActivity.Construction ? (tier == CivilianTier.Apprentice ? apprenticeWork : expertWork) : 0m;return new CraftWorkTick(unitId, tier, after, xp, income, work);diff --git a/sim/Statecraft.Sim/Gdd03CraftWorkFixture.cs b/sim/Statecraft.Sim/Gdd03CraftWorkFixture.csnew file mode 100644index 000000000..f6fa9f2b9--- /dev/null+++ b/sim/Statecraft.Sim/Gdd03CraftWorkFixture.cs@@ -0,0 +1,102 @@+using System;+using System.Collections.Generic;+using System.Linq;++namespace Statecraft.Sim+{+ /// <summary>One craftsman's actual work in a month (#2472): the population id, the month ordinal and the kind of work.</summary>+ internal sealed class Gdd03CraftWorkReceipt+ {+ internal int PopulationId { get; }+ internal int MonthOrdinal { get; }+ internal CraftTickActivity Activity { get; }+ internal Gdd03CraftWorkReceipt(int populationId, int monthOrdinal, CraftTickActivity activity)+ {+ PopulationId = populationId; MonthOrdinal = monthOrdinal; Activity = activity;+ }+ }++ /// <summary>R-CRAFT-002 under exact gdd-0.3, synthetic fixtures only (#2472): craftsman work XP over the #1689 ledger. No+ /// command, loader, turn or Money hookup. docs/gdd/training.md: "Apprentices become experts after+ /// `craft.expert_work_turns` actual turns in Industry or an arms workshop. Each turn counts once, regardless of+ /// output/work rate." The caller supplies the Work slots; only its Industry and Workshop slots count.</summary>+ internal sealed class Gdd03CraftWorkFixture+ {+ readonly GameState state;+ readonly Gdd03CraftArithmetic arithmetic;+ readonly SortedDictionary<string, CraftTickActivity> counting = new SortedDictionary<string, CraftTickActivity>(StringComparer.Ordinal);+ // Per fixture instance only (not saved), as in Gdd03CraftCourseFixture: the (id, month) receipts already applied.+ readonly SortedSet<(int Id, int Month)> applied = new SortedSet<(int Id, int Month)>();++ internal Gdd03CraftWorkFixture(Content content, GameState state, IEnumerable<Gdd03FixtureSlot> slots)+ {+ if (content == null) throw new ArgumentNullException(nameof(content));+ if (state == null) throw new ArgumentNullException(nameof(state));+ if (slots == null) throw new ArgumentNullException(nameof(slots));+ if (!content.UsesPopulationLedger || !state.UsesPopulationLedger || !state.PopulationLedger.IsInitialized)+ throw new InvalidOperationException("Craftsman work XP requires an initialized gdd-0.3 ledger fixture.");+ arithmetic = Gdd03CraftArithmetic.Read(content.Gdd03Balance+ ?? throw new ContentException(Gdd03BalanceCatalogue.FileName, "values.craft.expert_work_turns", "required under gdd-0.3"));+ this.state = state;+ foreach (var slot in slots)+ if (slot.Work == Gdd03FixtureWork.Industry) counting.Add(slot.Id, CraftTickActivity.Industry);+ else if (slot.Work == Gdd03FixtureWork.Workshop) counting.Add(slot.Id, CraftTickActivity.Workshop);+ }++ /// <summary>One receipt per apprentice or expert craftsman the month's snapshot has working an Industry or workshop+ /// slot (#1716 WorkEligibleIds), in ascending id. Idle, travel, course, teaching, service, building and farming+ /// give none, and so does a novice craftsman's workshop work (Q55: "No. Only the stated apprentice-to-expert+ /// progression counts").</summary>+ internal IReadOnlyList<Gdd03CraftWorkReceipt> Receipts(Gdd03SyntheticMonthContext month)+ {+ if (month == null) throw new ArgumentNullException(nameof(month));+ var working = new HashSet<int>(month.WorkEligibleIds);+ var receipts = new List<Gdd03CraftWorkReceipt>();+ foreach (var p in month.OpeningPeople.OrderBy(p => p.Id))+ if (working.Contains(p.Id) && p.Profession == CivilianProfession.Craftsman+ && (p.Tier == CivilianTier.Apprentice || p.Tier == CivilianTier.Expert)+ && p.Assignment.Target != null && counting.TryGetValue(p.Assignment.Target, out var activity))+ receipts.Add(new Gdd03CraftWorkReceipt(p.Id, month.MonthOrdinal, activity));+ return receipts.AsReadOnly();+ }++ /// <summary>R-CRAFT-002: receipts are deduplicated by population id and month first, against each other and against+ /// those this fixture already applied; then each adds one work-XP tick (<see cref="Gdd03CraftArithmetic.WorkTick"/>),+ /// whatever the output or pay, in ascending id and month. An apprentice whose tick reaches `craft.expert_work_turns`+ /// is an expert from the next snapshot; the month's snapshot keeps the apprentice tier for that month's output. Only+ /// the tier and work XP change. Every receipt is checked before any record changes.</summary>+ internal void Apply(IEnumerable<Gdd03CraftWorkReceipt> receipts)+ {+ if (receipts == null) throw new ArgumentNullException(nameof(receipts));+ var fresh = new SortedDictionary<(int Id, int Month), CraftTickActivity>();+ foreach (var r in receipts)+ {+ if (r == null) throw new ArgumentException("A craftsman work receipt is missing.");+ // Only Industry and workshop months are receipts: any other would take the (id, month) key with no tick.+ if (r.Activity != CraftTickActivity.Industry && r.Activity != CraftTickActivity.Workshop)+ throw new ArgumentException("A craftsman work receipt is for Industry or an arms workshop.");+ var key = (r.PopulationId, r.MonthOrdinal);+ if (!applied.Contains(key) && !fresh.ContainsKey(key)) fresh.Add(key, r.Activity);+ }+ state.PopulationLedger.Reconcile();+ var xp = new SortedDictionary<int, (CivilianTier Tier, int Xp)>();+ foreach (var (key, activity) in fresh) // ascending id, then month+ {+ var p = state.PopulationLedger.Get(key.Id);+ if (p.Profession != CivilianProfession.Craftsman)+ throw new ArgumentException("Only a craftsman earns craftsman work XP.");+ var (tier, workXp) = xp.TryGetValue(key.Id, out var sum) ? sum : (p.Tier, p.WorkXp);+ var tick = arithmetic.WorkTick(key.Id, tier, workXp, activity, true);+ xp[key.Id] = (tick.TierAfter, tick.WorkXp);+ }+ // Each Replace only changes tier and XP on a record Reconcile validated above, so it cannot fail partway.+ foreach (var (id, after) in xp) // ascending id+ {+ var p = state.PopulationLedger.Get(id);+ state.PopulationLedger.Replace(new PopulationUnit(p.Id, p.Status, p.ReceptionTicks, p.Location, p.Assignment,+ p.Profession, after.Tier, after.Xp, p.Qualification, p.CombatXp, p.Equipment, p.Captor, p.Home));+ }+ foreach (var key in fresh.Keys) applied.Add(key);+ }+ }+}