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.

feat(sim): the field harvest runs on a Historical ledger game (#1694, #1725 PR 7) (#2972)

Eyal Golan34c639e6d69e
diff --git a/changelog.d/1725-pr7-harvest.md b/changelog.d/1725-pr7-harvest.md
new file mode 100644
index 000000000..9c4694ba1
--- /dev/null
+++ b/changelog.d/1725-pr7-harvest.md
@@ -0,0 +1,5 @@
+- GDD 0.3 starting population (Refs #1725, Refs #1694): the field harvest (R-FIELD-002) can now run on the inactive
+ dark start's Historical ledger. Given the turn's month snapshot, each field whose farmer is still on it and that no
+ enemy unit stands on yields its farmer's tier of Food, with one Why line per field. Plowed site fields yield nothing
+ there until field preparation (#1713), and the harvest gives no work XP. No turn passes it a month yet, so there is
+ no change in the game.
diff --git a/docs/rules/mvp.md b/docs/rules/mvp.md
index 9b159fb3d..8dc4e4427 100644
--- a/docs/rules/mvp.md
+++ b/docs/rules/mvp.md
@@ -208,9 +208,9 @@ R-SITE-003: Each turn, in ordinal site id order, every site being built has one
## Veteran pioneers
-R-VET-001: Under legacy/gdd-0.1, and under gdd-0.3 until the population ledger's work-XP tiers are live, in step 5, after its site's or segment's progress (R-COR-002), a halutz unit whose site or corridor segment is being built gains one turn of service, the turn it is built included; an idle unit gains none. At `veteran_halutz_service` turns of service it becomes a `veteran_halutz` at the end of that turn, keeping its id, hex, service and project, and a cause says so. A veteran gains no more service. A unit's service is written into the state hash only when it is not 0 (D-D9; Q-VET-1, owner, 17 October 2026, #782). A halutz or veteran can return to civilian life and keep its service or its status (R-QUAL-003). In gdd-0.3 synthetic fixtures only, the pure profession helper proposes one actual-work XP increment for a received free civilian with a matching Work assignment and completed staffed-farming evidence regardless of output or advancement, or evidence of advancing an on-site pioneer project. Adopted sources at `605277dfa511dc512562ececeb273b8393b21d35`: `docs/gdd/training.md:17`, "Farmers earn work XP only on staffed farming turns. Pioneers earn it only while advancing an on-site pioneer project."; `docs/gdd/balance.md:70`, "Work XP counts actual qualifying turns, not output or work quantity." Multiple matching results count once per evaluation; zero pioneer advancement, wrong profession/target, generic work, travel, idle, teaching and courses give none. Both novice and trained farmer/pioneer become veteran at the Agreed catalogue `profession.work_to_veteran` threshold (currently 9). Craftsmen do not use this path. The caller must use one turn-start snapshot and commit at most once at turn end; turn scheduling, authoritative evidence production and cross-call deduplication remain held. No game-loop caller is added. The fixture-only pioneer producer (`Gdd03PioneerWorkFixture.ResolveTurnEnd`, #1693) is that caller for pioneers on initialized gdd-0.3 ledger fixtures: from one turn-start state and the pioneer projects being built that turn (yishuv sites and corridor segments alike; owner, 3 November 2026, #1693 answer 5), each pioneer record at Work on one of them gives advancement evidence and its result is committed once, in ascending id, into a new state, except that a veteran's work XP is not advanced (maintainer call, not a ruling, matching the legacy veteran that gains no more service; it still works at its rate); the turn-start state is unchanged, so resolving the same snapshot twice gives one tick. Records off the job (idle, travel, course, teaching) earn nothing and keep their tier and work XP (answer 4). MVP pioneers are course-trained (answer 2). The fixture-only farmer producer (`Gdd03FieldFixture.ResolveWorkXp`, #2468) is the same caller for farmers: from one turn-start state and the month's snapshot (27M-2), each farmer the snapshot has working a field that is still Israeli-held (Q37, the fields R-FIELD-002 pays) gives one staffed-farming receipt, committed the same way, with the same veteran exception; a farmer whose turn-start record is no longer on that field, idle, travelling, teaching or in a course earns nothing. It has no game-loop caller until #1689's integration slice.
+R-VET-001: Under legacy/gdd-0.1, and under gdd-0.3 until the population ledger's work-XP tiers are live, in step 5, after its site's or segment's progress (R-COR-002), a halutz unit whose site or corridor segment is being built gains one turn of service, the turn it is built included; an idle unit gains none. At `veteran_halutz_service` turns of service it becomes a `veteran_halutz` at the end of that turn, keeping its id, hex, service and project, and a cause says so. A veteran gains no more service. A unit's service is written into the state hash only when it is not 0 (D-D9; Q-VET-1, owner, 17 October 2026, #782). A halutz or veteran can return to civilian life and keep its service or its status (R-QUAL-003). In gdd-0.3 synthetic fixtures only, the pure profession helper proposes one actual-work XP increment for a received free civilian with a matching Work assignment and completed staffed-farming evidence regardless of output or advancement, or evidence of advancing an on-site pioneer project. Adopted sources at `605277dfa511dc512562ececeb273b8393b21d35`: `docs/gdd/training.md:17`, "Farmers earn work XP only on staffed farming turns. Pioneers earn it only while advancing an on-site pioneer project."; `docs/gdd/balance.md:70`, "Work XP counts actual qualifying turns, not output or work quantity." Multiple matching results count once per evaluation; zero pioneer advancement, wrong profession/target, generic work, travel, idle, teaching and courses give none. Both novice and trained farmer/pioneer become veteran at the Agreed catalogue `profession.work_to_veteran` threshold (currently 9). Craftsmen do not use this path. The caller must use one turn-start snapshot and commit at most once at turn end; turn scheduling, authoritative evidence production and cross-call deduplication remain held. No game-loop caller is added. The fixture-only pioneer producer (`Gdd03PioneerWorkFixture.ResolveTurnEnd`, #1693) is that caller for pioneers on initialized gdd-0.3 ledger fixtures: from one turn-start state and the pioneer projects being built that turn (yishuv sites and corridor segments alike; owner, 3 November 2026, #1693 answer 5), each pioneer record at Work on one of them gives advancement evidence and its result is committed once, in ascending id, into a new state, except that a veteran's work XP is not advanced (maintainer call, not a ruling, matching the legacy veteran that gains no more service; it still works at its rate); the turn-start state is unchanged, so resolving the same snapshot twice gives one tick. Records off the job (idle, travel, course, teaching) earn nothing and keep their tier and work XP (answer 4). MVP pioneers are course-trained (answer 2). The fixture-only farmer producer (`Gdd03FieldFixture.ResolveWorkXp`, #2468) is the same caller for farmers: from one turn-start state and the month's snapshot (27M-2), each farmer the snapshot has working a field that is still Israeli-held (Q37, the fields R-FIELD-002 pays) gives one staffed-farming receipt, committed the same way, with the same veteran exception; a farmer whose turn-start record is no longer on that field, idle, travelling, teaching or in a course earns nothing. It has no game-loop caller until #1689's integration slice. The ledger harvest (R-FIELD-002, #1694, #1725 PR 7) commits no work XP either (owner, 8 November 2026, on #1725, "Not in this change (Recommended)").
-R-VET-002: Under legacy/gdd-0.1, and under gdd-0.3 until the population ledger's work-XP tiers are live, a veteran's site or corridor segment being built has `veteran_progress` turns less to go each turn, against a halutz's 1; one with that many or fewer left is built that turn. A veteran does the same pioneer work as a halutz (R-SITE-001) (D-D9; Q-VET-2, owner, 17 October 2026, #782). In gdd-0.3 synthetic fixtures only, output quotes read the turn-start tier from Agreed catalogue `pioneer.work_rate` (novice/trained/veteran: 0.75/1/1.5) or `farmer.output` (2/3/5, multiples of `field_food_per_turn`, R-FIELD-002 (owner, 1 November 2026: "Main's base x 0.3's tiers (Recommended)"; #2112); the farmer quote here and in the synthetic field evaluator is that multiple, which equals Food only while `field_food_per_turn` is 1, and `Gdd03FieldRates.FoodPerTurn` converts it). Promotion returns a separate record for the next turn, preserving identity, assignment, placement, equipment and independent military history. No project progress or farming yield is applied by the helper; absent, Deferred or malformed values fail closed without legacy fallback. The #1693 pioneer producer quotes each record's work with this turn-start `pioneer.work_rate`, never `veteran_progress`, and returns the quote per target, summed over the records at Work on an advancing target, without applying it to any project.
+R-VET-002: Under legacy/gdd-0.1, and under gdd-0.3 until the population ledger's work-XP tiers are live, a veteran's site or corridor segment being built has `veteran_progress` turns less to go each turn, against a halutz's 1; one with that many or fewer left is built that turn. A veteran does the same pioneer work as a halutz (R-SITE-001) (D-D9; Q-VET-2, owner, 17 October 2026, #782). In gdd-0.3 synthetic fixtures only, output quotes read the turn-start tier from Agreed catalogue `pioneer.work_rate` (novice/trained/veteran: 0.75/1/1.5) or `farmer.output` (2/3/5, multiples of `field_food_per_turn`, R-FIELD-002 (owner, 1 November 2026: "Main's base x 0.3's tiers (Recommended)"; #2112); the farmer quote here and in the synthetic field evaluator is that multiple, which equals Food only while `field_food_per_turn` is 1, and `Gdd03FieldRates.FoodPerTurn` converts it). Promotion returns a separate record for the next turn, preserving identity, assignment, placement, equipment and independent military history. No project progress or farming yield is applied by the helper; absent, Deferred or malformed values fail closed without legacy fallback. The #1693 pioneer producer quotes each record's work with this turn-start `pioneer.work_rate`, never `veteran_progress`, and returns the quote per target, summed over the records at Work on an advancing target, without applying it to any project. The ledger harvest (R-FIELD-002, #1694, #1725 PR 7) applies the farmer quote: a field that yields adds `farmer.output` at its month-snapshot farmer's tier times `field_food_per_turn` to the Food stock.
### Return to civilian life and reassignment (#1511)
@@ -242,6 +242,8 @@ R-FIELD-002: Each turn in step 6, after the cities' production and in ordinal si
Then changed (3 Nov 2026): under exact `gdd-0.3`, in synthetic fixtures only (R-POP-004), each authored starting field (`regions.yaml` `field_hexes`, Q36) is one Work slot for one farmer (`field.slots` 1; owner, 3 November 2026, "One farmer per field (Recommended)"), staffed only by a farmer located in its region (Q27) while the field is Israeli-held (Q37). Only a farmer may hold a field (owner, 4 November 2026: asked "May only a unit with the Farmer profession staff a field?", the owner answered "yes", [recorded on #1694](https://github.com/eyalgolan/statecraft-israel/issues/1694#issuecomment-6623124984)). A field staffed in the month's snapshot (27M-2) and still Israeli-held yields `farmer.output` (2 / 3 / 5) times `field_food_per_turn` by the snapshot tier, and no Money; an unworked field yields nothing. Then changed (#2471): the fixture's settlement adds that yield to the national Food stock (R-FOOD-001), each field's once and in ordinal field-id order, with one Why line per field that yields. Control is checked again at settlement as well as at the snapshot's freeze, and a field lost by either adds nothing while its farmer keeps the same id, tier and assignment (D6: "its people stay"); once retaken, the next month's snapshot yields again with no new assignment (D6: "On retaking, everything resumes and nothing is deleted."). The caller states which fields are Israeli-held (maintainer reading: the sim has no hex control for fields yet). No game-loop caller is added, and the legacy and gdd-0.1 plowed-field harvest above is unchanged.
+Then changed (#1694, #1725 PR 7): on a game with an initialized Historical ledger (the dark start, R-POP-004), the step-6 harvest (`Pools.Harvest` given a month) reads the turn's one month snapshot (`Gdd03SyntheticMonthContext.CreateLive`; owner, 8 November 2026, on #1725, "One snapshot per turn (Recommended)": the snapshot is taken at the turn's start, after the orders). In ordinal field-id order, each authored field yields `farmer.output` at its snapshot farmer's tier times `field_food_per_turn` only if that farmer's record still exists and still holds Work on the field when the harvest runs ("Yes, recheck (Recommended)"), and the field is held: no enemy military unit stands on its hex at that time, the test `Cities.Held` uses for cities (R-CITY-010; "Held unless enemy on it (Recommended)"). An unworked or enemy-held field adds nothing, and its farmer's record is unchanged. Each field that yields writes one field food Why line (`field_food`, its argument the field id; "Per field, words later (Recommended)"), whose EN and HE wording comes with the dark-turn change. A plowed `sites.yaml` field adds nothing on a ledger game until #1713 ("Nothing until #1713 (Recommended)"). The harvest gives no work XP (R-VET-001). Every check, the checked sum included, comes before the stock changes. No turn passes it a month yet; without one the harvest is the aggregate one above, still refused on any initialized ledger (R-POP-002).
+
R-SWAMP-001: `PioneerWork(unit, dry_swamp, site)` drains a swamp at a site whose kinds include `swamp`, by R-SITE-001 to R-SITE-003's rules, with `dry_swamp_turns` and `dry_swamp_cost` (12 turns and IL 4m, labelled design values, required in the GDD loop; Q-SWAMP-1, decided 17 October 2026). Built, the swamp site is drained, and the field site in its hex becomes ready: before that a `plow_fields` order there is refused with the state unchanged and the Attention refunded, as at an unbuilt yishuv (R-FIELD-001). Drained, the swamp does nothing else. A field site is not also a swamp site, since draining would plow it; the loader refuses a row that gives it both kinds. The MVP's one swamp site is the Hula (Q-SWAMP-1; Q-SWAMP-3, "Allow as planned", owner, 17 October 2026, #789).
R-SWAMP-002: An event with `site: <id>` names a swamp site (the loader checks it in the GDD loop) and, in the GDD loop, can fire only while that site is being worked: it has a record that is not built. With no works, or once the swamp is drained, it waits, and it can still fire later in its window (Q-SWAMP-2, decided 17 October 2026). The legacy loop reads no sites and ignores the key, so the legacy goldens hold. `hula_drainage` carries `site: hula`.
@@ -605,7 +607,7 @@ These contracts cover #1689 steps 1–2 and the Historical start inventory (R-PO
R-POP-001: Only exact `gdd-0.3` enables the population-ledger capability, independently of the broad GDD loop and Attention (R-LOOP-002/005). An immutable own-population record has a dedicated nonnegative ordinal id. Synthetic fixture inventory is ordered by source key (ordinal string comparison), then within-source ordinal. Registered arrivals allocate monotonically; only explicit combat losses remove living ids. Sources remain registered after loss, and ids are never reused. Reconciliation checks the exact created-minus-lost id set against the living ledger, not just equal totals. Status/region counts include every matching record once. The gdd-0.3 scale of a synthetic or Open fixture reads one positive Agreed integer from `population.people_per_unit` in its catalogue (currently 10,000, Open mode's scale under D2); a Historical fixture reads `rules.yaml`'s `people_per_unit` for the start day (1,000), as R-UNIT-006 does (owner, 1 November 2026, D2: "Approve all six (Recommended)", "The Historical MVP keeps main's start: census cities at 1,000 people a unit (`R-CITY-007`)"; R-POP-004); rows with a `census/`, `units_1948/` or `field/` source key are the Historical start's and are refused in any other fixture. Old identities retain the common rules scale. Missing, fractional, nonpositive, overflowing or Deferred values have no fallback, in either source.
-R-POP-002: A ledger record has exactly one typed status and assignment, validated location, home and captor references, whole reception-turn ticks capped by the catalogue requirement, civilian profession-specific tier and actual-work XP, separate military qualification/combat XP, and distinct issued civilian/military equipment and paid facts. Unknown references, unresolved teacher ids, incompatible statuses/assignments, inconsistent region/hex/facility bindings, invalid progress/tiers and duplicate issued-item ownership are refused before mutation. Moves and atomic status/location/assignment transitions retain identity/history. Capture retains home context without inventing a prison hex or refunding equipment. Ledger changes never touch resources, causes, RNG or Attention. Initialization is internal and fixture-only; initialized ledger fixtures refuse aggregate Simulation commands and turns. The dark start (#1725 PR 5) is the internal, fixture-only `Simulation.NewGame` overload that initializes the Historical ledger (R-POP-004) in place before `Pools.Init`: `Pools.Init` then reads the ledger's need, one ration for each living own population id (R-FOOD-001, #2470), after the ledger reconciles, and `StartingForces.Init` places the forces once each own starting formation's strength is its ledger soldiers, refusing otherwise. Both read only a ledger initialized with mode Historical, the dark start's; a synthetic or Open ledger is refused by both, as by the other aggregate systems, with the state unchanged. An aggregate system whose own rule says it runs on that Historical ledger (#1725 PR 7: civilian upkeep, R-MONEY-002, the first, and food_supply's stock term, R-FOOD-003; training, R-TRAIN-001 to R-TRAIN-004; military upkeep, R-UNIT-010; arms workshops, R-ARMS-005 and R-ARMS-006; Send home, R-UNIT-005) also reads only that ledger; a synthetic or Open ledger is still refused by it. Prisoners.Take and Prisoners.Upkeep are such systems (#1710, R-POW-001, R-POW-002, R-POW-005): a capture turns the surrendered formation's serving records into captives with their captor and home, all or nothing, and records no loss. `EventSystem.Trigger` still refuses a ledger, so a dark start fires no opening event; the public `NewGame` is unchanged. The step-7 Food settlement given a month's synthetic context is another exception to that refusal: it reads its need from that month's frozen snapshot (R-FOOD-002, #2470). The live month snapshot (`Gdd03SyntheticMonthContext.CreateLive`, #1725 PR 7; owner, 8 November 2026, "One snapshot per turn (Recommended)") reads only a ledger initialized with mode Historical and changes no record; a synthetic or Open ledger and an aggregate game are refused (R-FOOD-002). Old identities refuse ledger mutation. Prices, progression awards, return destinations, tool lock-in and captive-equipment outcomes remain with their owning issues. A craftsman's tier is novice, apprentice or expert (R-CRAFT-003); a farmer's or pioneer's is novice, trained or veteran.
+R-POP-002: A ledger record has exactly one typed status and assignment, validated location, home and captor references, whole reception-turn ticks capped by the catalogue requirement, civilian profession-specific tier and actual-work XP, separate military qualification/combat XP, and distinct issued civilian/military equipment and paid facts. Unknown references, unresolved teacher ids, incompatible statuses/assignments, inconsistent region/hex/facility bindings, invalid progress/tiers and duplicate issued-item ownership are refused before mutation. Moves and atomic status/location/assignment transitions retain identity/history. Capture retains home context without inventing a prison hex or refunding equipment. Ledger changes never touch resources, causes, RNG or Attention. Initialization is internal and fixture-only; initialized ledger fixtures refuse aggregate Simulation commands and turns. The dark start (#1725 PR 5) is the internal, fixture-only `Simulation.NewGame` overload that initializes the Historical ledger (R-POP-004) in place before `Pools.Init`: `Pools.Init` then reads the ledger's need, one ration for each living own population id (R-FOOD-001, #2470), after the ledger reconciles, and `StartingForces.Init` places the forces once each own starting formation's strength is its ledger soldiers, refusing otherwise. Both read only a ledger initialized with mode Historical, the dark start's; a synthetic or Open ledger is refused by both, as by the other aggregate systems, with the state unchanged. An aggregate system whose own rule says it runs on that Historical ledger (#1725 PR 7: civilian upkeep, R-MONEY-002, the first, and food_supply's stock term, R-FOOD-003; training, R-TRAIN-001 to R-TRAIN-004; military upkeep, R-UNIT-010; arms workshops, R-ARMS-005 and R-ARMS-006; Send home, R-UNIT-005) also reads only that ledger; a synthetic or Open ledger is still refused by it. Prisoners.Take and Prisoners.Upkeep are such systems (#1710, R-POW-001, R-POW-002, R-POW-005): a capture turns the surrendered formation's serving records into captives with their captor and home, all or nothing, and records no loss. `EventSystem.Trigger` still refuses a ledger, so a dark start fires no opening event; the public `NewGame` is unchanged. The step-7 Food settlement given a month's synthetic context is another exception to that refusal: it reads its need from that month's frozen snapshot (R-FOOD-002, #2470). The live month snapshot (`Gdd03SyntheticMonthContext.CreateLive`, #1725 PR 7; owner, 8 November 2026, "One snapshot per turn (Recommended)") reads only a ledger initialized with mode Historical and changes no record; a synthetic or Open ledger and an aggregate game are refused (R-FOOD-002). The step-6 harvest given that live month (`Pools.Harvest`, R-FIELD-002, #1694) also runs on that ledger: it reads only a ledger initialized with mode Historical, a synthetic or Open ledger is still refused by it, and without a month it is refused on any initialized ledger. Old identities refuse ledger mutation. Prices, progression awards, return destinations, tool lock-in and captive-equipment outcomes remain with their owning issues. A craftsman's tier is novice, apprentice or expert (R-CRAFT-003); a farmer's or pioneer's is novice, trained or veteran.
R-POP-003: Clone copies all ledger containers; immutable records and frozen bindings may be shared. The canonical writer emits a gdd-0.3-only section ordered by numeric population id, with fixed field order, stable machine tokens, invariant integer formatting and length-prefixed reference strings. It covers every record/assignment/equipment/reference field, binding, creation/loss provenance and allocator even after the last combat loss. Legacy/gdd-0.1 emit no ledger section or allocator marker. A location's optional city (a `regions.yaml` member location of its region that is a census city of `cities.yaml` or one of that region's field hosts, where R-POP-004 houses own people: a settlement hosts only F19 and F20, owner, 7 November 2026, #1689: "These two only (Recommended)"; any other, including a locality, a `sites.yaml` id or a map location, is refused when a fixture is created, naming the city and the region, R-POP-002) is written after its other fields as `|city=` with a length-prefixed id, only when set, as R-UNIT-002's `|home=` is, so a location without a city keeps its canonical text and hash. R-SAVE-001/002 still govern identity mismatch refusal and replay: no ledger snapshot or new command syntax is added in this foundation, and fixture injection is not replay evidence. Existing unpublished schema-4 draft hashes change; no migration promise is made.
diff --git a/sim/Statecraft.Sim.Tests/LedgerHarvestTests.cs b/sim/Statecraft.Sim.Tests/LedgerHarvestTests.cs
new file mode 100644
index 000000000..24b798781
--- /dev/null
+++ b/sim/Statecraft.Sim.Tests/LedgerHarvestTests.cs
@@ -0,0 +1,285 @@
+using Statecraft.Sim;
+
+/// <summary>#1694, #1725 PR 7: <c>Pools.Harvest</c> on a game with an initialized Historical ledger reads the month
+/// snapshot (#2970's <c>Gdd03SyntheticMonthContext.CreateLive</c>). Owner, 8 November 2026, on #1725: "One snapshot per
+/// turn (Recommended)", the harvest reads the one month snapshot taken at the turn's start; "Held unless enemy on it
+/// (Recommended)", a field is held unless an enemy military unit stands on its hex when the harvest runs; "Nothing until
+/// #1713 (Recommended)", a plowed sites.yaml field yields nothing on a ledger game; "Yes, recheck (Recommended)", a field
+/// yields only if its snapshot farmer still exists and still holds Work on it; "Per field, words later (Recommended)", one
+/// field food Why line per field; "Not in this change (Recommended)", no work XP.</summary>
+public class LedgerHarvestTests
+{
+ static Content Gdd03() => HistoricalPopulationTests.Real(true);
+
+ static GameState Dark(Content c) => Simulation.NewGame(c, 1, Mode.Historical, darkStart: true);
+
+ static string Ledger(GameState s) => string.Join("\n", s.PopulationLedger.Canonical());
+
+ // The fields with an enemy military unit (a side other than none and the player's) on their hex, read from the units.
+ static HashSet<string> EnemyHeld(Content c, GameState s) => new HashSet<string>(Gdd03FieldFixture.Fields(c)
+ .Where(f => s.Units.Values.Any(u => u.Side != "" && u.Side != Movement.PlayerSide && u.Q == f.Q && u.R == f.R))
+ .Select(f => f.Id), StringComparer.Ordinal);
+
+ // The farmers on the ledger's records: a Farmer at Work on an authored field (field/q,r), by field id; by default only
+ // on the fields no enemy unit stands on, the ones that yield.
+ static SortedDictionary<string, PopulationUnit> Farmers(Content c, GameState s, bool heldOnly = true)
+ {
+ var enemy = heldOnly ? EnemyHeld(c, s) : new HashSet<string>();
+ var fields = new HashSet<string>(Gdd03FieldFixture.Fields(c).Select(f => f.Id).Where(f => !enemy.Contains(f)), StringComparer.Ordinal);
+ var byField = new SortedDictionary<string, PopulationUnit>(StringComparer.Ordinal);
+ foreach (var u in s.PopulationLedger.Units)
+ if (u.Profession == CivilianProfession.Farmer && u.Assignment.Kind == PopulationAssignmentKind.Work
+ && u.Assignment.Target != null && fields.Contains(u.Assignment.Target))
+ byField.Add(u.Assignment.Target, u);
+ return byField;
+ }
+
+ // farmer.output at the record's tier (content/gdd03-balance.yaml) times field_food_per_turn (rules.yaml), read here.
+ static int Expected(Content c, MvpRules r, PopulationUnit farmer) =>
+ Gdd03FieldRates.FromCatalogue(c.Gdd03Balance!).FoodFor(farmer.Tier) * r.FieldFoodPerTurn!.Value;
+
+ static Gdd03Field Field(Content c, string id) => Gdd03FieldFixture.Fields(c).Single(f => f.Id == id);
+
+ static void EnemyOn(GameState s, Gdd03Field f)
+ {
+ var id = s.Units.Count == 0 ? 0 : s.Units.Keys.Max() + 1;
+ s.Units.Add(id, new Unit(id, "infantry", f.Q, f.R, side: "arab", strength: 1));
+ }
+
+ // R-FIELD-002, R-VET-002 (#2112): every held field with a snapshot farmer adds farmer.output at that tier times
+ // field_food_per_turn, one field food line per field in ordinal field-id order, adding up to the stock's change. The
+ // ledger is unchanged and reconciles.
+ [Fact]
+ public void TheDarkStartsFarmersYieldTheirTierOnHeldFields()
+ {
+ var c = Gdd03();
+ var s = Dark(c);
+ var r = c.RulesAt(s.Date).Mvp!;
+ var farmers = Farmers(c, s);
+ Assert.NotEmpty(farmers);
+ Assert.Contains(farmers.Values, f => f.Tier == CivilianTier.Novice);
+ Assert.Contains(farmers.Values, f => f.Tier == CivilianTier.Trained);
+ Assert.Contains(farmers.Values, f => f.Tier == CivilianTier.Veteran);
+ // Every authored field has its farmer; a field an enemy unit already stands on at the start keeps it, unpaid.
+ Assert.Equal(Gdd03FieldFixture.Fields(c).Count, Farmers(c, s, heldOnly: false).Count);
+ var enemyHeld = EnemyHeld(c, s);
+ var expected = farmers.ToDictionary(x => x.Key, x => Expected(c, r, x.Value), StringComparer.Ordinal);
+ var food = s.Food; var ledger = Ledger(s);
+ var month = Gdd03SyntheticMonthContext.CreateLive(c, s);
+ var why = new List<Cause>();
+
+ Pools.Harvest(c, s, r, month, why);
+
+ Assert.Equal(food + expected.Values.Sum(), s.Food);
+ Assert.Equal(expected.Keys.OrderBy(x => x, StringComparer.Ordinal), why.Select(x => x.Args.Single()));
+ Assert.All(why, x => Assert.Equal(("economy", "food", CauseKeys.FieldFood), (x.System, x.Target, x.Key)));
+ Assert.Equal(expected.Keys.Select(k => (double)expected[k]), why.Select(x => x.Delta));
+ Assert.DoesNotContain(why, x => enemyHeld.Contains(x.Args.Single()));
+ Assert.Equal((double)(s.Food - food), why.Sum(x => x.Delta));
+ s.PopulationLedger.Reconcile();
+ Assert.Equal(ledger, Ledger(s));
+ }
+
+ // The same on HistoricalPopulation.LedgerFixture, with its date set.
+ [Fact]
+ public void TheLedgerFixtureHarvests()
+ {
+ var c = Gdd03();
+ var s = HistoricalPopulation.LedgerFixture(c);
+ s.Date = c.Rules.Start;
+ var r = c.RulesAt(s.Date).Mvp!;
+ var farmers = Farmers(c, s);
+ Assert.NotEmpty(farmers);
+ var food = s.Food;
+ var why = new List<Cause>();
+ Pools.Harvest(c, s, r, Gdd03SyntheticMonthContext.CreateLive(c, s), why);
+ Assert.Equal(food + farmers.Values.Sum(f => Expected(c, r, f)), s.Food);
+ Assert.Equal(farmers.Count, why.Count);
+ }
+
+ // "an unworked field produces nothing" (owner, 3 November 2026, #1694): a farmer taken off the field before the
+ // snapshot leaves it unworked; it adds 0 and writes no line, and the other fields still yield.
+ [Fact]
+ public void AnUnworkedFieldYieldsNothing()
+ {
+ var c = Gdd03();
+ var s = Dark(c);
+ var r = c.RulesAt(s.Date).Mvp!;
+ var farmers = Farmers(c, s);
+ var (field, farmer) = farmers.First();
+ s.PopulationLedger.ChangeAssignment(farmer.Id, PopulationAssignment.Unassigned);
+ var food = s.Food;
+ var why = new List<Cause>();
+ Pools.Harvest(c, s, r, Gdd03SyntheticMonthContext.CreateLive(c, s), why);
+ Assert.Equal(food + farmers.Where(x => x.Key != field).Sum(x => Expected(c, r, x.Value)), s.Food);
+ Assert.DoesNotContain(why, x => x.Args.Single() == field);
+ Assert.Equal(farmers.Count - 1, why.Count);
+ }
+
+ // "Held unless enemy on it (Recommended)", D6 ("its people stay"): an enemy military unit on a field's hex when the
+ // harvest runs stops that field's Food, and its farmer's record is unchanged. With the unit gone, the next snapshot
+ // yields again with no new assignment.
+ [Fact]
+ public void AnEnemyHeldFieldYieldsNothingAndKeepsItsFarmer()
+ {
+ var c = Gdd03();
+ var s = Dark(c);
+ var r = c.RulesAt(s.Date).Mvp!;
+ var farmers = Farmers(c, s);
+ var (field, farmer) = farmers.Last();
+ var month = Gdd03SyntheticMonthContext.CreateLive(c, s);
+ EnemyOn(s, Field(c, field)); // after the snapshot: the test is at harvest time
+ var food = s.Food;
+ var why = new List<Cause>();
+
+ Pools.Harvest(c, s, r, month, why);
+
+ Assert.Equal(food + farmers.Where(x => x.Key != field).Sum(x => Expected(c, r, x.Value)), s.Food);
+ Assert.DoesNotContain(why, x => x.Args.Single() == field);
+ Assert.Equal(farmer, s.PopulationLedger.Get(farmer.Id));
+
+ // A halutz (no side) or the player's own unit holds nothing.
+ var enemy = s.Units.Keys.Max();
+ s.Units.Remove(enemy);
+ s.Units.Add(enemy, new Unit(enemy, "halutz", Field(c, field).Q, Field(c, field).R));
+ var again = new List<Cause>(); var before = s.Food;
+ Pools.Harvest(c, s, r, Gdd03SyntheticMonthContext.CreateLive(c, s), again);
+ Assert.Equal(before + farmers.Values.Sum(x => Expected(c, r, x)), s.Food);
+ Assert.Contains(again, x => x.Args.Single() == field && x.Delta == Expected(c, r, farmer));
+ }
+
+ // The finding on #2972: at the dark start the Iraqi army (unit 11 today) already stands on field/11,12, a trained
+ // farmer's field. Under "Held unless enemy on it (Recommended)" that field yields nothing on turn 1 and its farmer
+ // keeps the record, so the turn's harvest is the other staffed fields only: 58 Food today, not the plan's 61.
+ [Fact]
+ public void TheDarkStartsEnemyHeldFieldYieldsNothingOnTurnOne()
+ {
+ var c = Gdd03();
+ var s = Dark(c);
+ var r = c.RulesAt(s.Date).Mvp!;
+ const string fieldId = "field/11,12";
+ var field = Field(c, fieldId);
+ // The unit is read from the state, not pinned by id.
+ var enemy = s.Units.Values.Where(u => u.Side != "" && u.Side != Movement.PlayerSide && u.Q == field.Q && u.R == field.R).ToList();
+ Assert.NotEmpty(enemy);
+ Assert.Contains(fieldId, EnemyHeld(c, s));
+ var all = Farmers(c, s, heldOnly: false);
+ Assert.True(all.TryGetValue(fieldId, out var farmer));
+ Assert.Equal(PopulationAssignmentKind.Work, farmer!.Assignment.Kind);
+ Assert.Equal(fieldId, farmer.Assignment.Target);
+ var others = Farmers(c, s);
+ Assert.DoesNotContain(fieldId, others.Keys);
+ Assert.Equal(all.Count - 1, others.Count);
+ var expected = others.Values.Sum(f => Expected(c, r, f)); // 58 today
+ var food = s.Food;
+ var why = new List<Cause>();
+
+ Pools.Harvest(c, s, r, Gdd03SyntheticMonthContext.CreateLive(c, s), why);
+
+ Assert.DoesNotContain(why, x => x.Key == CauseKeys.FieldFood && x.Args.Single() == fieldId);
+ Assert.Equal(others.Count, why.Count);
+ Assert.Equal(food + expected, s.Food);
+ Assert.Equal((double)expected, why.Sum(x => x.Delta));
+ Assert.Equal(farmer, s.PopulationLedger.Get(farmer.Id));
+ }
+
+ // "Yes, recheck (Recommended)": the snapshot's farmer must still exist and still hold Work on that field when the
+ // harvest runs. A farmer taken off after the snapshot, or lost, yields nothing for that field.
+ [Theory]
+ [InlineData("released")] [InlineData("lost")]
+ public void AFarmerWhoLeftAfterTheSnapshotYieldsNothing(string how)
+ {
+ var c = Gdd03();
+ var s = Dark(c);
+ var r = c.RulesAt(s.Date).Mvp!;
+ var farmers = Farmers(c, s);
+ var (field, farmer) = farmers.First();
+ var month = Gdd03SyntheticMonthContext.CreateLive(c, s);
+ Assert.Contains(farmer.Id, month.WorkEligibleIds);
+ if (how == "released") s.PopulationLedger.ChangeAssignment(farmer.Id, PopulationAssignment.Unassigned);
+ else s.PopulationLedger.RegisterCombatLoss(farmer.Id, "test/loss");
+ var food = s.Food;
+ var why = new List<Cause>();
+
+ Pools.Harvest(c, s, r, month, why);
+
+ Assert.Equal(food + farmers.Where(x => x.Key != field).Sum(x => Expected(c, r, x.Value)), s.Food);
+ Assert.DoesNotContain(why, x => x.Args.Single() == field);
+ }
+
+ // "Nothing until #1713 (Recommended)": a plowed sites.yaml field site adds nothing on a ledger game and writes no
+ // plowed-land line; the aggregate game of the same content still harvests it (R-FIELD-002, unchanged).
+ [Fact]
+ public void APlowedSiteFieldYieldsNothingOnALedgerGame()
+ {
+ var c = Gdd03();
+ var site = c.Sites.Where(x => x.Kinds.Contains(Projects.FieldKind)).OrderBy(x => x.Id, StringComparer.Ordinal).First();
+ var s = Dark(c);
+ var r = c.RulesAt(s.Date).Mvp!;
+ Assert.True(r.FieldFoodPerTurn > 0);
+ s.Sites[site.Id] = SiteWork.Built(site.Id, s.Date);
+ var food = s.Food;
+ var why = new List<Cause>();
+ Pools.Harvest(c, s, r, Gdd03SyntheticMonthContext.CreateLive(c, s), why);
+ Assert.Equal(food + Farmers(c, s).Values.Sum(x => Expected(c, r, x)), s.Food);
+ Assert.DoesNotContain(why, x => x.Key == CauseKeys.FoodHarvest);
+
+ var pub = Simulation.NewGame(c, 1, Mode.Historical);
+ pub.Sites[site.Id] = SiteWork.Built(site.Id, pub.Date);
+ var pubFood = pub.Food; var pubWhy = new List<Cause>();
+ Pools.Harvest(c, pub, r, pubWhy);
+ Assert.Equal(pubFood + r.FieldFoodPerTurn!.Value, pub.Food);
+ Assert.Equal(CauseKeys.FoodHarvest, Assert.Single(pubWhy).Key);
+ }
+
+ // "Not in this change (Recommended)": the harvest gives no work XP; no record changes at all.
+ [Fact]
+ public void TheHarvestGivesNoWorkXp()
+ {
+ var c = Gdd03();
+ var s = Dark(c);
+ var r = c.RulesAt(s.Date).Mvp!;
+ var xp = s.PopulationLedger.Units.Select(u => (u.Id, u.WorkXp, u.Tier)).ToList();
+ Pools.Harvest(c, s, r, Gdd03SyntheticMonthContext.CreateLive(c, s), new List<Cause>());
+ Assert.Equal(xp, s.PopulationLedger.Units.Select(u => (u.Id, u.WorkXp, u.Tier)));
+ }
+
+ // R-POP-002: an Open or synthetic ledger is still refused, with or without a month, and the state is unchanged. The
+ // no-month path stays refused on the dark start too (PopulationLedgerBoundaryTests keeps its pools.harvest row).
+ [Theory]
+ [InlineData("open", false)] [InlineData("open", true)] [InlineData("synthetic", false)] [InlineData("synthetic", true)]
+ [InlineData("dark", false)]
+ public void AnOpenOrSyntheticLedgerOrNoMonthIsStillRefused(string kind, bool withMonth)
+ {
+ var real = Gdd03();
+ var c = kind == "dark" ? real : PopulationLedgerTests.Content();
+ var s = kind == "dark" ? Dark(c)
+ : PopulationLedger.CreateFixture(c, PopulationLedgerTests.Bindings(),
+ new[] { new PopulationInventoryRow("fixture", 0, PopulationLedgerTests.Person()) }, mode: kind == "open" ? Mode.Open : null);
+ var month = withMonth ? Gdd03SyntheticMonthContext.CreateLive(real, Dark(real)) : null;
+ s.Food = 7;
+ var hash = s.Hash(); var before = s.Describe();
+ var why = new List<Cause>();
+ var r = real.RulesAt(real.Rules.Start).Mvp!;
+ if (month == null) Assert.Throws<NotSupportedException>(() => Pools.Harvest(c, s, r, why));
+ Assert.Throws<NotSupportedException>(() => Pools.Harvest(c, s, r, month, why));
+ Assert.Equal(hash, s.Hash()); Assert.Equal(before, s.Describe()); Assert.Empty(why);
+ }
+
+ // Determinism: the harvest on two clones of one state gives equal hashes and equal cause sequences.
+ [Fact]
+ public void TwoClonesHarvestEqually()
+ {
+ var c = Gdd03();
+ var a = Dark(c);
+ var b = a.Clone();
+ var r = c.RulesAt(a.Date).Mvp!;
+ var aWhy = new List<Cause>(); var bWhy = new List<Cause>();
+ Pools.Harvest(c, a, r, Gdd03SyntheticMonthContext.CreateLive(c, a), aWhy);
+ Pools.Harvest(c, b, r, Gdd03SyntheticMonthContext.CreateLive(c, b), bWhy);
+ Assert.Equal(a.Hash(), b.Hash());
+ Assert.NotEmpty(aWhy);
+ Assert.Equal(aWhy.Select(x => (x.Key, x.Delta, x.Message, string.Join(",", x.Args))),
+ bWhy.Select(x => (x.Key, x.Delta, x.Message, string.Join(",", x.Args))));
+ }
+}
diff --git a/sim/Statecraft.Sim.Tests/RemainingCauseKeysTests.cs b/sim/Statecraft.Sim.Tests/RemainingCauseKeysTests.cs
index 5e073fc06..5bc569f60 100644
--- a/sim/Statecraft.Sim.Tests/RemainingCauseKeysTests.cs
+++ b/sim/Statecraft.Sim.Tests/RemainingCauseKeysTests.cs
@@ -116,7 +116,7 @@ public class RemainingCauseKeysTests
sites++;
}
}
- Assert.Equal(130, sites); // 130 with R-UNIT-005's ledger Send home Arms line (owner, 8 November 2026, "Yes, one Why line (Recommended)", #1725 PR 7); 129 with R-ENEMY-007's truce-break line (a late operation inside an accepted truce, #2543); 128 with R-ENEMY-007's lapse cost (Q8, the event-amount Security line of a lapsed operation, #2543); 127 with R-ENEMY-007's keyed postponed/lapsed operation producer (#2543); 126 with #2558: EconomySystem.MoneyLine, the event Debt line worded for the Money row; 125 with #1711's CityHeld (R-CITY-010); 124 with #2534's enemy attack-order line (Combat.Give marks the order's own cause); 123 with #2471's gdd-0.3 field Food line (R-FIELD-002); 122 with #2527's FoodImported and the conversion's fx_reserves line; 120 with #2457's event Debt line (R-EFX-009); 119 with #1700 slice B's ProjectBuilderFreed; 118 with #1700's builders (R-CITY-011: two ProjectBuilder lines, ProjectWaiting, the build order's job-default line); 114 with #1703's gdd-0.3 housing surcharge and housing cohesion lines; 112 with the arms workshops' five (R-ARMS-005 with its job-default line, R-ARMS-006; #1701); 107 with R-MONEY-004's DollarsConverted (#813); 106 since #2212: EconomySystem.OtherMoney's line (105 since #2199: PayOrBorrow's Paid line)
+ Assert.Equal(131, sites); // 131 with #1694's ledger harvest field Food line (R-FIELD-002, Pools.Harvest given a month, #1725 PR 7); 130 with R-UNIT-005's ledger Send home Arms line (owner, 8 November 2026, "Yes, one Why line (Recommended)", #1725 PR 7); 129 with R-ENEMY-007's truce-break line (a late operation inside an accepted truce, #2543); 128 with R-ENEMY-007's lapse cost (Q8, the event-amount Security line of a lapsed operation, #2543); 127 with R-ENEMY-007's keyed postponed/lapsed operation producer (#2543); 126 with #2558: EconomySystem.MoneyLine, the event Debt line worded for the Money row; 125 with #1711's CityHeld (R-CITY-010); 124 with #2534's enemy attack-order line (Combat.Give marks the order's own cause); 123 with #2471's gdd-0.3 field Food line (R-FIELD-002); 122 with #2527's FoodImported and the conversion's fx_reserves line; 120 with #2457's event Debt line (R-EFX-009); 119 with #1700 slice B's ProjectBuilderFreed; 118 with #1700's builders (R-CITY-011: two ProjectBuilder lines, ProjectWaiting, the build order's job-default line); 114 with #1703's gdd-0.3 housing surcharge and housing cohesion lines; 112 with the arms workshops' five (R-ARMS-005 with its job-default line, R-ARMS-006; #1701); 107 with R-MONEY-004's DollarsConverted (#813); 106 since #2212: EconomySystem.OtherMoney's line (105 since #2199: PayOrBorrow's Paid line)
}
[Fact]
diff --git a/sim/Statecraft.Sim/Cities.cs b/sim/Statecraft.Sim/Cities.cs
index e592b9401..bc9ddcfa4 100644
--- a/sim/Statecraft.Sim/Cities.cs
+++ b/sim/Statecraft.Sim/Cities.cs
@@ -145,14 +145,22 @@ namespace Statecraft.Sim
{
var held = new HashSet<string>(StringComparer.Ordinal);
if (c.Ruleset != SaveGame.Gdd03Ruleset) return held;
- var enemy = new HashSet<(int Q, int R)>();
- foreach (var u in s.Units.Values)
- if (u.Side != "" && u.Side != Movement.PlayerSide) enemy.Add((u.Q, u.R));
+ var enemy = EnemyHexes(s);
foreach (var h in c.SettlementHexes)
if (s.Cities.ContainsKey(h.Id) && enemy.Contains((h.Q, h.R))) held.Add(h.Id);
return held;
}
+ /// <summary>The hexes an enemy military unit stands on (a halutz has no side, R-UNIT-001), <see cref="Held"/>'s
+ /// test; the ledger harvest reads it for fields (#1694).</summary>
+ internal static HashSet<(int Q, int R)> EnemyHexes(GameState s)
+ {
+ var enemy = new HashSet<(int Q, int R)>();
+ foreach (var u in s.Units.Values)
+ if (u.Side != "" && u.Side != Movement.PlayerSide) enemy.Add((u.Q, u.R));
+ return enemy;
+ }
+
/// <summary>R-MONEY-002: annual Money upkeep for the civilian places that exist at the start of step 7. Only completed
/// projects and camp sites count. The six rates are explicit content design values; all are 0 in the MVP. It counts
/// places, not people, so it runs on an initialized Historical ledger (the dark start, #1725 PR 7) and reads no
diff --git a/sim/Statecraft.Sim/Pools.cs b/sim/Statecraft.Sim/Pools.cs
index 764234eda..91a23c7f7 100644
--- a/sim/Statecraft.Sim/Pools.cs
+++ b/sim/Statecraft.Sim/Pools.cs
@@ -123,9 +123,25 @@ namespace Statecraft.Sim
/// <summary>R-FIELD-002, step 6 after the cities' production (D-A6): in ordinal site id order, every plowed field (a built
/// field site, R-FIELD-001) adds field_food_per_turn to the stock, with no workers (Q-FIELD-2). It comes before the
- /// nation eats in step 7, so in a turn with imports the import only tops the stock up by less.</summary>
- public static void Harvest(Content c, GameState s, MvpRules r, List<Cause> why)
+ /// nation eats in step 7, so in a turn with imports the import only tops the stock up by less. A state with an
+ /// initialized population ledger is refused here (R-POP-002); its harvest is the month overload's.</summary>
+ public static void Harvest(Content c, GameState s, MvpRules r, List<Cause> why) => Harvest(c, s, r, null, why);
+
+ /// <summary>R-FIELD-002 on a game with an initialized Historical ledger (#1694, #1725 PR 7). Owner, 8 November 2026,
+ /// on #1725: "One snapshot per turn (Recommended)", the farmers are those of the turn's one month snapshot
+ /// (<see cref="Gdd03SyntheticMonthContext.CreateLive"/>); "Yes, recheck (Recommended)", a field yields only if its
+ /// snapshot farmer's record still exists and still holds Work on that field when the harvest runs, and the field is
+ /// held; "Held unless enemy on it (Recommended)", a field is held unless an enemy military unit stands on its hex
+ /// now, the test of <see cref="Cities.Held"/>. A yielding field adds `farmer.output` at the snapshot tier (R-VET-002)
+ /// times field_food_per_turn, as <see cref="Gdd03FieldFixture.Yield"/>, in ordinal field-id order, with one
+ /// <see cref="CauseKeys.FieldFood"/> line each ("Per field, words later (Recommended)"); an unworked field adds 0.
+ /// "Nothing until #1713 (Recommended)": a plowed sites.yaml field adds nothing here. "Not in this change
+ /// (Recommended)": no work XP, and no record changes. Every check, the checked sum included, comes before the stock
+ /// is written. A synthetic or Open ledger, or a month on a game without a ledger, is refused (R-POP-002); without a
+ /// month this is the aggregate harvest above, refused on any initialized ledger.</summary>
+ internal static void Harvest(Content c, GameState s, MvpRules r, Gdd03SyntheticMonthContext? month, List<Cause> why)
{
+ if (month != null) { HarvestLedger(c, s, r, month, why); return; }
PopulationLedger.RefuseAggregate(s);
var yield = r.FieldFoodPerTurn!.Value; // the loader requires it in the GDD loop
if (yield == 0) return;
@@ -137,6 +153,38 @@ namespace Statecraft.Sim
}
}
+ static void HarvestLedger(Content c, GameState s, MvpRules r, Gdd03SyntheticMonthContext month, List<Cause> why)
+ {
+ if (why == null) throw new ArgumentNullException(nameof(why));
+ var ledger = s.PopulationLedger;
+ if (!c.UsesPopulationLedger || !ledger.IsInitialized || !ledger.IsHistorical)
+ throw new NotSupportedException("A ledger harvest needs an initialized Historical gdd-0.3 population ledger (R-POP-002).");
+ ledger.Reconcile();
+ var rates = Gdd03FieldRates.FromCatalogue(c.Gdd03Balance
+ ?? throw new ContentException(Gdd03BalanceCatalogue.FileName, "values.farmer.output", "required under gdd-0.3"));
+ var enemy = Cities.EnemyHexes(s);
+ var live = ledger.Units.ToDictionary(u => u.Id);
+ var working = new HashSet<int>(month.WorkEligibleIds);
+ var yields = new List<(string Field, int Food)>();
+ foreach (var field in Gdd03FieldFixture.Fields(c)) // ordinal field-id order
+ {
+ var farmers = month.OpeningPeople.Where(p => working.Contains(p.Id) && p.Assignment.Target == field.Id).ToArray();
+ if (farmers.Length > 1) throw new ArgumentException("A field's snapshot holds more than one farmer.");
+ var farmer = farmers.SingleOrDefault();
+ if (farmer == null || farmer.Profession != CivilianProfession.Farmer) continue; // unworked: nothing
+ if (!live.TryGetValue(farmer.Id, out var now) || now.Assignment.Kind != PopulationAssignmentKind.Work
+ || now.Assignment.Target != field.Id) continue; // left after the snapshot
+ if (enemy.Contains((field.Q, field.R))) continue; // not held
+ var food = rates.FoodPerTurn(farmer.Tier, r);
+ if (food > 0) yields.Add((field.Id, food));
+ }
+ var stock = yields.Aggregate(s.Food, (sum, y) => checked(sum + y.Food));
+ foreach (var (field, food) in yields)
+ why.Add(new Cause("economy", "food", food, FormattableString.Invariant($"{field}: its farmer yielded {food} units of Food"),
+ key: CauseKeys.FieldFood, args: new[] { field }));
+ s.Food = stock;
+ }
+
/// <summary>R-FOOD-001 under gdd-0.3 (#2470): the month's need of a population ledger, one ration (one population
/// unit's food) for each living own population id in <paramref name="snapshot"/>, whatever its status or
/// assignment. The order of the snapshot does not matter; a repeated id or a missing record is refused.</summary>