Compare commits

..
Author SHA1 Message Date
kamilkrzywda 5477336537 feat: #66 contested regions / frontlines — 12th ability (v0.44.0)
CI / build + unit + e2e (pull_request) Successful in 2m10s
A third region state (contested frontline): a region in no nation's territory and not in unowned, opened/resolved by the LLM, tied to an active war. Sole-ownership invariant preserved. Durable GameState.contested; contested-inert stub; map legend stays at 7.
2026-10-16 15:21:45 +00:00
kamilkrzywda d946fdf0d7 Merge pull request 'feat: #65 sea control (v0.43.0)' (#78) from feat/65-naval-sea into master
CI / build + unit + e2e (push) Successful in 2m32s
2026-10-16 14:53:48 +02:00
kamilkrzywda c77e81c45b feat: #65 sea control — 11th ability (v0.43.0)
CI / build + unit + e2e (pull_request) Successful in 2m33s
Adds the sea ability: a fixed set of 12 named sea zones with sole-control
semantics, contest-by-higher-military, and a deterministic per-turn
+1 military/+1 economy bonus for each claimed zone. Durable (owns
GameState.seaZones), additive migration, stub-inert (e2e unaffected).

Fixes #65

Design note: Gitea #65 sketched a free-form 'naval' layer; the implemented
approved design is this richer 'sea' layer with a fixed zone set.
2026-10-16 12:50:22 +00:00
kamilkrzywda 13f91845fd Merge pull request 'feat(abilities): migration & refugees lever (v0.42.0, #64)' (#77) from feat/64-migration into master
CI / build + unit + e2e (push) Successful in 2m33s
2026-10-16 12:20:03 +02:00
kamilkrzywda 7e4faa73d3 feat(abilities): add migration & refugees lever (v0.42.0, #64)
CI / build + unit + e2e (pull_request) Successful in 2m12s
Add the 10th modular LLM ability: a turn-transient TurnResult.migration
lever declaring population flows between nations (migration / refugees /
diaspora / exodus). The source loses a little population + economy, the
destination gains a little (a large influx also strains its stability),
and the from<->to relation is nudged one step toward the positive end of
the ally/neutral/rival/hostile ladder (capped by kind; a war is never
touched). Deterministic per-scale tables, no hidden randomness, clamped
0-100, mirrored to owned regions, re-derived aggregates; never moves
territory. Registered last in ABILITIES; user prompt unchanged
(user.txt golden byte-identical), system goldens re-baselined. Fixes #64.
2026-10-16 10:15:45 +00:00
29 changed files with 3834 additions and 82 deletions
+122 -2
View File
@@ -102,8 +102,9 @@ history/
│ │ ├── shared.ts # shared helpers (stat dips / re-derive / ref resolution, …) │ │ ├── shared.ts # shared helpers (stat dips / re-derive / ref resolution, …)
│ │ ├── apply-helpers.ts # shared apply-path helpers │ │ ├── apply-helpers.ts # shared apply-path helpers
│ │ ├── <name>.ts # one module per ability: wars / takeovers / leaders / nuclear / │ │ ├── <name>.ts # one module per ability: wars / takeovers / leaders / nuclear /
│ │ │ # ideology / industry / economy / hybrid / disasters (v0.41.0 #63) │ │ │ # ideology / industry / economy / hybrid / disasters (v0.41.0 #63) /
│ │ ├── *.test.ts # per-ability unit tests (registry.test.ts pins the 9-ability contract) │ │ │ # migration (v0.42.0 #64)
│ │ ├── *.test.ts # per-ability unit tests (registry.test.ts pins the 12-ability contract)
│ │ └── goldens/ # pinned prompt goldens (system-no-tool / system-tool / user) │ │ └── goldens/ # pinned prompt goldens (system-no-tool / system-tool / user)
│ └── *.test.ts # unit tests (vitest) │ └── *.test.ts # unit tests (vitest)
└── src/ └── src/
@@ -509,6 +510,125 @@ history/
re-baselined in v0.41.0). `isMeaningful` is `events.length > 0`. The stub never proposes a re-baselined in v0.41.0). `isMeaningful` is `events.length > 0`. The stub never proposes a
disaster (`{ events: [] }`), so e2e (CI, `LLM_STUB=1`) is unaffected and the path is unit-tested disaster (`{ events: [] }`), so e2e (CI, `LLM_STUB=1`) is unaffected and the path is unit-tested
only (`server/abilities/disasters.test.ts`). only (`server/abilities/disasters.test.ts`).
- **Migration & refugees — population flows between nations with a deterministic dip (v0.42.0, #64).**
`TurnResult.migration = MigrationOps = { ops: MigrationOp[] }` (required, default
`{ ops: [] }`); `MigrationOp = { kind, from, to?, scale, detail? }` with `kind ∈
MIGRATION_KINDS = migration | refugees | diaspora | exodus` and `scale ∈
MIGRATION_SCALES = small | moderate | large` (`to` is required for every kind except
`exodus`, which has no destination). Like the hybrid / disasters layers this is
**turn-transient**: it owns NO `GameState` field (no durable list, no `db.ts` change) — a
flow that persists is simply re-declared each turn it continues. The DETERMINISTIC
`MIGRATION_SOURCE_EFFECTS` / `MIGRATION_DESTINATION_EFFECTS` tables
(`server/abilities/migration.ts`) map each `scale` to signed stat deltas (no hidden
randomness): the source LOSES population + economy (small −1/−1, moderate −2/−2,
large −4/−3) and the destination GAINS population + economy (small +1/+1, moderate
+2/+2, large +3/+3); a `large` influx additionally strains the destination's stability by
`LARGE_INFLUX_STABILITY_DIP = -2`. Neither side ever moves territory (sole ownership is
untouched) and none touch borders. Both `from` and `to` resolve by the shared
`resolveNationRef` (id first, then a case-insensitive unique name): an unknown / ambiguous
source, a missing / unknown / ambiguous destination, or a **self-flow** (`from` and `to`
the same nation) drops the WHOLE op (the source is untouched); `exodus` skips the
destination entirely. The from↔to relation then moves one step toward the positive end of
the ally/neutral/rival/hostile ladder via the self-contained `shiftRelationTowardPositive`
(the mirror of the hybrid layer's `shiftRelationTowardHostile`): capped at `ally` for
`refugees` (hosting refugees builds the strongest goodwill), `neutral` for `migration` /
`diaspora`, and not at all for `exodus`; a missing relation starts at `neutral` and a
`war` relation is NEVER touched (the nudge neither fabricates nor escalates a war).
`applyMigrationOp` (run in the `ABILITIES` loop after territory / wars / economy, before
markers) applies the source dip, then the destination dip (+ stability strain for `large`),
clamps both to 0–100, mirrors each to every region the nation owns (`regionStats`), and
re-derives each nation's aggregate `stats` (the same 0-region / no-entry guards, so a
0-region nation keeps its directly-mutated value and the effect persists). `payload()` is
`{}` (turn-transient), so the user-prompt golden (`user.txt`) is unchanged; the system
prompt gains the field's schema line + constraint bullet (the system goldens were
re-baselined in v0.42.0). `isMeaningful` is `ops.length > 0`. The stub never proposes a
migration (`{ ops: [] }`), so e2e (CI, `LLM_STUB=1`) is unaffected and the path is
unit-tested only (`server/abilities/migration.test.ts`). **Design note:** the Gitea #64
body sketched a simpler `flows: {type: 'refugees'|'settlers'}` shape with a settler
re-claim of no-man's-land; the implemented, approved design is this richer four-kind
nation-to-nation **stat** layer that deliberately never moves territory (a no-man's-land
re-claim stays the `regionChanges` lever's job).
- **Sea control — sole control of a fixed set of 12 named sea zones with a deterministic per-turn bonus (v0.43.0, #65).**
`TurnResult.sea = SeaOps = { control: SeaControlOp[] }` (required, default `{ control: [] }`);
`SeaControlOp = { zone, by }` where `zone` is one of the 12 fixed sea-zone ids from
`SEA_ZONES` in `shared/protocol.ts` (`north-atlantic`, `south-atlantic`, `pacific`, `indian`,
`mediterranean`, `north-sea`, `baltic`, `arctic`, `black-sea`, `gulf-mexico`, `red-sea`,
`sargasso`) and `by` is a nation ref (id first, then a case-insensitive unique name, via the
shared `resolveNationRef`; unknown / ambiguous → dropped, never thrown). Like the wars and
industry layers this is **durable** (unlike the turn-transient hybrid / disasters / migration
layers): it owns the `GameState.seaZones` field (required, `[]` at creation; a legacy SQLite
row without the field loads as `[]` — via the generic `ABILITIES` `stateFields` loop in
`db.ts`, no `db.ts` code change needed). `applySeaControl` (run in the `ABILITIES` loop after
territory / wars / economy, before markers) upserts the turn's ops into `next.seaZones`:
per zone (in first-appearance order) a single surviving op sets or replaces the zone's
controller (replace in place — preserving position — or append); two or more surviving ops
on the same zone for different resolved nations make the zone **contested** — the higher
current `stats.military` wins (a tie goes to the earlier-listed op) — deterministic, no
hidden randomness. The layer **never touches `territory` / `unowned`** — it is fully parallel
to but independent of land. Every committed turn (including a turn with an empty `control`),
`applySeaZoneBonuses` grants each existing claim's controller `SEA_ZONE_BONUS = 1` military
+ 1 economy (clamped to 0–100, mirrored to every region the nation owns, then the nation's
derived `stats` re-derived with the same 0-region / no-entry guards as the economy / migration
layers, so a 0-region nation keeps its directly-mutated value); a nation controlling several
zones stacks the bonus; a claim whose nation no longer exists (removed by a merge / split
this turn) is skipped — the claim is kept, never thrown. `isMeaningful` is
`control.length > 0`. The system prompt documents the field + constraints (at most 1–2 claims
per turn, each narrated in `events`); the user payload **always** carries the current
`seaZones` list (even when empty) — `payload()` → `{ seaZones: ctx.seaZones ?? [] }` — the
one ability whose `payload()` is not `{}` (the durable list, unlike the turn-transient
layers). The **stub never** proposes a sea op (`{ control: [] }`), so e2e (CI, `LLM_STUB=1`)
is unaffected and the path is unit-tested only (`server/abilities/sea.test.ts`).
**Design note:** the Gitea #65 body sketched a `naval` layer with a free-form `zones`
array; the implemented, approved design is this richer `sea` layer with a **fixed set of
12 named zones**, sole-control semantics, contest-by-higher-military, and a durable
`seaZones` list — a cleaner, more deterministic model that the LLM can reason about without
inventing zone names each turn.
- **Contested regions / frontlines — a `TurnResult.contested` lever opening/resolving war frontlines: a THIRD region state in no nation's `territory` and not in `unowned` (v0.44.0, #66).**
`TurnResult.contested = ContestedOps = { open: ContestOp[]; resolve: string[] }` (required,
default `{ open: [], resolve: [] }`); `ContestOp = { regionKey, parties }` where `regionKey` is
a region key or resolvable name and `parties` are TWO OR MORE nation refs (ids or names, via
the shared `resolveNationRef`). Like the `sea` / `industry` layers this is **durable**: it owns
the `GameState.contested: ContestedRegion[]` field (`ContestedRegion = { regionKey, parties }`
— `parties` store the RESOLVED nation ids; required, `[]` at creation; a legacy SQLite row
without the field loads as `[]` — via the generic `ABILITIES` `stateFields` loop in `db.ts`,
no `db.ts` code change needed). `applyContested` (run LAST in the `ABILITIES` loop, after
territory / wars / economy / sea — it sees the final post-claim ownership) runs **RESOLVE
first, then OPEN**: a `resolve` removes a currently-contested key and **releases it to no
man's land** (into `unowned`, out of any territory, `regionStats` deleted) — UNLESS a
concurrent winning claim by one of the contesting **parties** already re-owned it this turn
(the only claim the territory step permits on a contested key), in which case it stays owned
and keeps (or re-inits) its `regionStats`; an `open` makes a region a frontline only when it
is **contestable** — a **sole owner** at war (a shared **active** `War`) with at least one
party, or a **no-man's-land** region (0 owners AND in `unowned`) whose two parties are at war
with each other — a 2+-owner key or an owner not at war with any party is **dropped**
(an armistice/ended war does not count); on a successful open the key is **stripped from its
owner's `territory` (or from `unowned`)**, its `regionStats` entry deleted, and a
`{ regionKey, parties }` entry added to `next.contested` (**unique by `regionKey`** — a
re-open replaces a kept entry), with the stripped owner's derived stats re-derived (same
0-region / no-entry guards). The **sacrosanct sole-ownership invariant is never broken**: a
contested key is in **no** territory (never two) and is **never** in `unowned` while
contested (the two states are mutually exclusive). The **territory step in `engine.ts` is
guarded**: a normal `gain` on a currently-contested key is **dropped** unless this same turn
resolves the contest AND the gainer is one of the contesting parties (a party re-claim) — a
still-contested key is never a valid normal-claim target. The **map (client-only, like
no-man's-land)**: `WorldMap` renders a contested key in the distinct visible
`CONTESTED_FILL` / `CONTESTED_STROKE` (orange "hot" frontline) with a `"Contested: A vs B"`
hover sub-line (names from `GameState.contested`; a removed party degrades to a dash) — the
contested check runs **first** (before unowned / owned); the server `RegionMap` stays
owned-vs-absent (it never knows about contested). **The map legend stays at 7 items** (it is
derived from the `RegionMap` owners only — a contested key is absent from the `RegionMap`, so
no new legend entry; e2e legend assertions are unaffected). `isMeaningful` is
`open.length > 0 || resolve.length > 0`; the system prompt documents the field + constraints
(at most 1–2 contested-region changes per turn, each narrated in `events`); the user payload
carries the current frontlines (region key + party **names**) **only when non-empty** —
`payload()` → `{}` on a fresh / no-frontline world (unlike `sea`, which always emits). The
**stub never** opens or resolves a frontline (`{ open: [], resolve: [] }`), so e2e (CI,
`LLM_STUB=1`) is unaffected and the path is unit-tested only
(`server/abilities/contested.test.ts`, 52 tests, each asserting the sole-ownership invariants).
**Design note (deviation from the issue body):** the Gitea #66 body sketched a **two-owner**
`disputed` / `fronts` design that "relaxes sole-ownership"; the implemented, approved design
is this **third region state** (a contested key in NO territory, sole-ownership preserved)
with `open` / `resolve` ops and a minimum of two contesting parties.
- **Map click → dossier target (owner resolved from the RegionMap, by region key).** - **Map click → dossier target (owner resolved from the RegionMap, by region key).**
Clicking a sub-region does NOT open a popup — it switches the dossier to that sub-region's Clicking a sub-region does NOT open a popup — it switches the dossier to that sub-region's
owning nation (`focusNation(ownerId, {name})` in `App.tsx`, which also records which region was owning nation (`focusNation(ownerId, {name})` in `App.tsx`, which also records which region was
+38
View File
@@ -2,6 +2,44 @@
All notable changes to **History** are listed here, newest first. All notable changes to **History** are listed here, newest first.
## v0.44.0 — 2026-10-16 15:10
- **#66: Contested regions / frontlines — a `TurnResult.contested` lever letting the LLM declare a region a **contested** war frontline (a **third region state**: in **no** nation's `territory` and **not** in `unowned` / no-man's-land) and resolve existing frontlines.** It lands as the **12th ability** of the v0.40.0 modular system, in a new `server/abilities/contested.ts` module, **registered last** in the `ABILITIES` registry (after `sea`). Like the `sea` and `industry` layers it is **durable**: `GameState.contested` persists across turns and in SQLite. It is a **pure territory-state** layer — the contested key simply *leaves* ownership (sole ownership is never broken: a key is in at most one `territory`), it is never placed into two territories, and it never touches borders directly.
- **Types (`shared/protocol.ts`).** New `ContestOp` (`{ regionKey; parties }` — `regionKey` is a region key or resolvable name, `parties` are two or more nation refs (ids or names)), `ContestedOps` (`{ open: ContestOp[]; resolve: string[] }`), and `ContestedRegion` (`{ regionKey; parties }` — `parties` store the **resolved** nation ids); `TurnResult.contested` is **required**, placed between `sea` and `markers`, default `{ open: [], resolve: [] }`. New `CONTESTED_FILL = '#f97316'` / `CONTESTED_STROKE` (the distinct visible frontline fill/stroke for the map — a reddish/orange "hot" frontline on the dark basemap, clearly distinct from a nation color and from the no-man's-land grey) and `contestedTooltipLabel(parties)` (a short `"Contested: A vs B"` hover sub-line; a missing party name degrades to a dash, never crashes). `ContestedRegion` is imported into `shared/types.ts`; `GameState.contested: ContestedRegion[]` is **required** (`[]` at creation; a legacy SQLite row without the field loads as `[]` — additive, never wiped, via the generic `ABILITIES` `stateFields` loop in `db.ts` — no `db.ts` code change needed).
- **Ability module (`server/abilities/contested.ts`).** `field: 'contested'`; `default()` / `stub()` → a **fresh** `{ open: [], resolve: [] }` each call; `validate` wraps the exported `validateContestedOps` (defensive, never throws — accepts the `{ open, resolve }` object; an `open` op needs a non-empty `regionKey` (trimmed, ≤120) and **two or more** non-empty `party` refs (each trimmed, ≤200), a `resolve` entry a non-empty key (trimmed, ≤120); missing / malformed → dropped; a missing / malformed top-level object yields `{ open: [], resolve: [] }`); `apply` runs the exported `applyContested`; `schemaLine()` / `constraint()` supply the prompt text; **`payload()` → `{ contested: [{ regionKey, parties: [NAMES] }] }`** (the current frontlines with party **names** resolved from the stored ids) **only when non-empty** — `{}` on a fresh / no-frontline world (like the turn-transient layers, unlike `sea` which always emits); `isMeaningful` = `open.length > 0 || resolve.length > 0`; **`stateFields: ['contested']`** (the durable `GameState` field, for the `db.ts` legacy-row migration).
- **Open semantics (`applyContested`, OPEN phase).** Each `open` op's `regionKey` resolves to a concrete key (exact key first, then a unique case-insensitive name via the region manifest — with no manifest loaded the raw string is accepted; a key absent from the loaded manifest is dropped). Its `parties` resolve via the shared `resolveNationRef` (id first, then a unique name; unresolvable / ambiguous refs dropped, order preserved, duplicates removed) — an op left with **fewer than two distinct resolved parties** is dropped. A region is **contestable** only when either (a) it has a **sole owner** that is at war (a shared **active** `War`) with at least one of the parties, or (b) it has **zero owners AND is in `unowned`** (no man's land) and **two of the parties are at war with each other**. A region with **two or more owners** (corrupt), or whose owner is **not at war with any party**, is never contestable (dropped — an ended / armistice war does not count). On a successful open the key is **removed from its sole owner's `territory`** (or from `unowned` for a no-man's-land region), its `regionStats` entry is **deleted**, and a `{ regionKey, parties: [ids] }` entry is added to `next.contested` (**unique by `regionKey`** — a re-open replaces any kept entry for the same key). The stripped owner's derived `stats` are **re-derived** (the same 0-region / no-entry guards as the other layers, so a 0-region owner keeps its directly-mutated value).
- **Resolve semantics (`applyContested`, RESOLVE phase — runs FIRST).** Each key in `resolve` that is currently in `next.contested` is removed and its region **released to no man's land** (out of any territory, into `unowned`, `regionStats` deleted) — **UNLESS a concurrent winning claim by one of the contesting parties** already re-owned it this turn (the only claim the territory step permits on a contested key), in which case it **stays owned** and its `regionStats` is **kept** (or **re-initialised** as a copy of the owner's stats if absent). A key that is not currently contested is ignored (no-op). A resolved key owned by a **non-party** (defensive) is released as above.
- **Territory-step guard (`engine.ts applyTurnResult`).** A **currently-contested** key (in `state.contested`) sits in no nation's territory, so a normal `gain` would otherwise be treated as a free re-claim. The claims step is guarded: a normal claim on a contested key proceeds **only** when this same turn `resolve`s the contest **AND** the gainer is one of the contesting **parties** (a party re-claim); otherwise the frontline **stays contested** for the contested layer (which runs later in the turn) to decide its fate. A still-contested key is therefore never a valid normal-claim target.
- **Map (client `WorldMap.tsx`).** The contested state is decided by the client from `GameState.contested` (like no-man's-land), **never by the `RegionMap`** (which stays owned-vs-absent). A contested key is rendered with the distinct `CONTESTED_FILL` / `CONTESTED_STROKE` and a `"Contested: A vs B"` hover sub-line; the contested check runs **first** (before unowned / owned) in the fill-resolution, and the hover handler resolves the party names from `GameState.contested`. **The map legend stays at 7 items** (it is derived from the `RegionMap` owners only — a contested key is absent from the `RegionMap`, so it adds no legend entry — e2e legend assertions unaffected). `App.tsx` passes `contested={game.contested ?? []}` to `<WorldMap>`.
- **Registry & prompt.** `contested` is added **last** in `ABILITIES` (existing order untouched — the 12th entry); the system prompt gains the `contested` schema line and its constraint bullet ("a contested region is in NO nation's territory (never two) and is never no man's land while contested; at most 1–2 contested-region changes per turn, each narrated in `events`"); the user prompt gains `"contested"` (region key + party **names**) **only when the list is non-empty** (the one durable ability whose `payload()` can be `{}`). The two committed system-prompt **goldens** (`system-no-tool.txt`, `system-tool.txt`) are regenerated (each gains exactly the new `contested` schema line after `sea` + constraint bullet before the "Prefer 1-4 events" bullet); the **`user.txt` golden gains a `"contested"` entry** (the sample `b-r1` frontline with party names) as a new key after `seaZones`.
- **Tests.** New `server/abilities/contested.test.ts` (**52 tests**): the `CONTESTED_FILL` / `CONTESTED_STROKE` / `contestedTooltipLabel` surface; `validateContestedOps` (shape / leniency / drops / field caps / malformed top-level); `applyContested` OPEN (sole-owner-at-war with owner-as-party / party-not-owner, owner-not-at-war drop, no-man's-land open + NML-with-warring-parties + not-in-unowned drop, corrupt 2-owner drop, armistice-not-a-war drop, distinct-party / unresolvable / ambiguous drops, region-name + party-name resolve, manifest-gated key drop, owner stats re-derive + 0-region guard, two-opens-on-same-key, multi-key open); RESOLVE (release-to-NML, party-re-claim keeps + re-inits stats, non-party-owner release, multi-frontline, non-contested no-op, empty no-op); ordering (re-open replaces, resolve-then-open from NML, still-contested not re-openable, combined apply); and the ability const contract (field, `stateFields`, fresh `default()`/`stub()`, `isMeaningful`, `payload()` id→name / missing-nation fallback / `{}` when empty, `validate` wrapping, `apply` ctx wiring). Every apply test asserts the **sole-ownership invariants** (no key in >1 territory; a contested key in no territory and not unowned; an unowned key in no territory and not contested). `registry.test.ts` is updated for the **12-ability** contract (order, distinct fields, `fullDefaultTurn()`, `meaningfulFor`, durable `stateFields`, composes 13 / `extended[12]`, re-export pin, user-golden 15th arg). New `db.test.ts` legacy-row test (a pre-v0.44 save without `contested` loads with `[]`).
- **Design note (deviation from the issue body).** The Gitea #66 body sketched a **two-owner** design (`disputed` regions with `fronts`, explicitly "relaxing sole-ownership"). The approved, implemented design is a **third region state**: a contested key is in **no** nation's `territory` and not in `unowned` (sole ownership is preserved — a key is never in two territories), with `open` / `resolve` ops and a **minimum of two contesting parties** tied to an active war. This keeps the engine's sacrosanct sole-ownership invariant intact while still modelling a war frontline.
- **Guarantees.** No new runtime deps, `shared/` keeps zero runtime deps, no `@turf`/`@types/geojson` in any `.ts`. No engine randomness (the LLM declares; the engine applies fixed, deterministic rules). All existing unit tests green (additive); e2e (CI, `LLM_STUB=1`) unaffected (the stub is contested-inert — it never opens or resolves a frontline, and the map legend stays at 7).
- **Version** bumped `0.43.0 → 0.44.0`.
## v0.43.0 — 2026-10-16 12:09
- **#65: Sea control — a `TurnResult.sea` lever letting the LLM declare sole control over a fixed set of 12 named sea zones (North Atlantic, South Atlantic, Pacific, Indian, Mediterranean, North Sea, Baltic, Arctic, Black Sea, Gulf of Mexico, Red Sea, Sargasso), with a deterministic per-turn +1 military / +1 economy bonus for the controlling nation.** It is a **durable** feature (unlike the turn-transient `hybrid` / `disasters` / `migration` layers): `GameState.seaZones` persists across turns and in SQLite, and the user payload **always** carries the current `seaZones` list (even when empty) so the model knows who controls what. It lands as the **11th ability** of the v0.40.0 modular system, in a new `server/abilities/sea.ts` module, **registered last** in the `ABILITIES` registry (after `migration`). Sea control is fully **parallel to but independent of land**: it never touches `territory` / `unowned`, and moving land never touches a sea zone.
- **Types (`shared/protocol.ts`).** New `SEA_ZONES` (a frozen array of 12 `{ id, name }` pairs), `SEA_ZONE_IDS` (a `ReadonlySet` of all 12 ids), `isSeaZoneId(id)` (type guard), `seaZoneName(id)` (human-readable name; unknown → raw), `SeaControlOp` (`{ zone; by }`), and `SeaOps` (`{ control: SeaControlOp[] }`); `TurnResult.sea` is **required**, placed between `migration` and `markers`, default `{ control: [] }`. New `SeaZoneClaim` (`{ zone; by }`) in `shared/types.ts`; `GameState.seaZones: SeaZoneClaim[]` is **required** (`[]` at creation; a legacy SQLite row without the field loads as `[]` — additive, never wiped, via the generic `ABILITIES` `stateFields` loop in `db.ts` — no `db.ts` code change needed).
- **Ability module (`server/abilities/sea.ts`).** `field: 'sea'`; `default()` / `stub()` → a **fresh** `{ control: [] }` each call; `validate` wraps the exported `validateSeaOps` (defensive, never throws — accepts the `{ control: [...] }` object or a bare array; each op needs a valid `zone` (one of the 12 `SEA_ZONE_IDS`) and a non-empty `by` (trimmed, ≤200) — anything else is dropped); `apply` runs `applySeaControl` then `applySeaZoneBonuses`; `schemaLine()` / `constraint()` supply the prompt text; **`payload()` → `{ seaZones: ctx.seaZones ?? [] }` — the one ability that always emits a user-payload key** (the durable list, even when empty — unlike the turn-transient layers whose `payload()` is `{}`); `isMeaningful` = `control.length > 0`; **`stateFields: ['seaZones']`** (the durable `GameState` field, for the `db.ts` legacy-row migration).
- **Contest semantics (`applySeaControl`).** Each op's `by` is resolved via the shared `resolveNationRef` (id first, then a case-insensitive unique name; unknown / ambiguous → dropped, never thrown). Per zone (in first-appearance order): a single surviving op **sets or replaces** the zone's controller in `GameState.seaZones` (replace in place — preserving the entry's position — or append a new one); two or more surviving ops on the same zone for **different** resolved nations make the zone **contested**: the higher current `stats.military` wins (a tie goes to the op listed earlier in the `control` array) — deterministic, no hidden randomness. The layer **never touches `territory` / `unowned`**.
- **Per-turn bonus (`applySeaZoneBonuses`).** Every committed turn — **including a turn with an empty `control`** — each existing claim's controller earns `SEA_ZONE_BONUS = 1` military + 1 economy (clamped to 0–100, mirrored to every region the nation owns, then the nation's derived `stats` re-derived with the same 0-region / no-entry guards as the economy / migration layers, so a 0-region nation keeps its directly-mutated value). A nation controlling several zones **stacks** the bonus (one per zone). A claim whose nation no longer exists (removed by a merge / split this turn) is **skipped** — the claim is kept, never thrown.
- **Registry & prompt.** `sea` is added **last** in `ABILITIES` (existing order untouched); the system prompt gains the `sea` schema line and its constraint bullet ("at most 1–2 claims per turn, each narrated in `events`"); the **user prompt gains `"seaZones": []` as a new last key** (the intentional deviation from the turn-transient layers — the durable list is always emitted). The two committed system-prompt **goldens** are regenerated (each gains exactly the new `sea` schema line + constraint bullet); the **`user.txt` golden gains `"seaZones": []`** as the last key (verified by diff).
- **Tests.** New `server/abilities/sea.test.ts` (**~40 tests**): the zone-id predicate sets; `validateSeaOps` (shape / leniency / drops / field caps); `applySeaControl` (set / replace-in-place / append / contest by military / tie-break / same-nation dedup / name-resolve / unresolvable drop / ambiguous drop / territory-untouched); `applySeaZoneBonuses` (+1/+1 / clamping / stacking / 0-region direct-dip / stale-controller skip / empty no-op / territory-untouched); and the ability const contract (field, `stateFields`, fresh `default()`/`stub()`, `isMeaningful`, `payload()` incl. `?? []`, `validate` wrapping, `apply` ctx wiring). `registry.test.ts` is updated for the **11-ability** contract (order, distinct fields, `fullDefaultTurn()`, `meaningfulFor`, durable fields, composes 12 / `extended[11]`, re-export pin, user-golden 14th arg). New `db.test.ts` legacy-row test (a pre-v0.43 save without `seaZones` loads with `[]`).
- **Design note (deviation from the issue body).** The Gitea #65 body sketched a `naval` layer with a free-form `zones` array; the approved design implemented here is the richer `sea` layer with a **fixed set of 12 named zones**, sole-control semantics, contest-by-higher-military, and a durable `seaZones` list — a cleaner, more deterministic model that the LLM can reason about without inventing zone names each turn.
- **Guarantees.** No client (`src/`) changes, no new runtime deps, `shared/` keeps zero runtime deps, no `@turf`/`@types/geojson` in any `.ts`. All unit tests green (additive); e2e (CI, `LLM_STUB=1`) unaffected (the stub is sea-inert — it never proposes a sea op).
- **Version** bumped `0.42.0 → 0.43.0`.
## v0.42.0 — 2026-10-16 10:12
- **#64: Migration & refugees — a `TurnResult.migration` lever letting the LLM declare population flows between nations (ordinary migration / refugee flows / a spreading diaspora / an exodus), with a deterministic per-`scale` effect: the source loses a little population and economy, the destination gains a little (a `large` influx also strains its stability), and the from↔to relation is nudged one step toward the positive end of the ladder.** It is a **turn-transient** feature, exactly like the v0.34 `hybrid` and v0.41 `disasters` layers: **no new `GameState` field, no `db.ts` change, no durable list** — the ops are consumed inside `applyTurnResult` and leave nothing behind. It lands as the **10th ability** of the v0.40.0 modular system, in a new `server/abilities/migration.ts` module, **registered last** in the `ABILITIES` registry (after `disasters`).
- **Types (`shared/protocol.ts`).** New `MigrationKind` (`'migration' | 'refugees' | 'diaspora' | 'exodus'`), `MigrationScale` (`'small' | 'moderate' | 'large'`), `MigrationOp` (`{ kind; from; to?; scale; detail? }` — `to` is required for every kind except `exodus`, which has no destination), and `MigrationOps` (`{ ops: MigrationOp[] }`); `TurnResult.migration` is **required**, placed between `disasters` and `markers`, default `{ ops: [] }`.
- **Ability module (`server/abilities/migration.ts`).** `field: 'migration'`; `default()` / `stub()` → a **fresh** `{ ops: [] }` each call; `validate` wraps the exported `validateMigrationOps` (defensive, never throws — accepts the `{ ops: [...] }` object or a bare array; each op needs a valid `kind`, a valid `scale`, a non-empty `from` (trimmed, ≤200), and — for every kind except `exodus` — a non-empty `to` (trimmed, ≤200); an optional `detail` (trimmed, ≤300, empty dropped) — anything else is dropped); `apply` runs `applyMigrationOp` per op; `schemaLine()` / `constraint()` supply the prompt text; `payload()` → `{}` (no user-payload keys — both refs resolve from the existing nation ref table); `isMeaningful` = `ops.length > 0`; **no** `stateFields` (turn-transient, no durable `GameState` field).
- **Deterministic effects (tables, no hidden randomness).** `MIGRATION_SOURCE_EFFECTS` per scale — the source LOSES: small `{population:-1, economy:-1}`, moderate `{population:-2, economy:-2}`, large `{population:-4, economy:-3}`. `MIGRATION_DESTINATION_EFFECTS` per scale — the destination GAINS: small `{population:+1, economy:+1}`, moderate `{population:+2, economy:+2}`, large `{population:+3, economy:+3}`. `LARGE_INFLUX_STABILITY_DIP = -2` — a `large` influx additionally strains the destination's stability by 2. All clamped to 0–100.
- **Apply semantics (`applyMigrationOp`).** Resolution is drop-first: `from` must resolve to a nation (id first, then a unique name; unknown / ambiguous → drop); for every kind except `exodus` the `to` must resolve to a nation **distinct from** `from` (missing / unknown / ambiguous / self-flow → the **whole op** is dropped, the source untouched). Only then is the source dip applied (all four kinds, including `exodus`); `exodus` then returns (no destination, no nudge). Otherwise the destination gain is applied (plus the `large` stability strain), and the from↔to relation is nudged by the self-contained `shiftRelationTowardPositive` — the mirror of the hybrid layer's `shiftRelationTowardHostile`, but toward `ally` (`POSITIVE_ORDER = ['ally','neutral','rival','hostile']`, cap `ally` for `refugees`, `neutral` for `migration` / `diaspora`, none for `exodus`; a missing relation starts at `neutral`; a `war` relation is **never** touched — the nudge neither fabricates nor escalates a war). Each affected nation's dip is clamped to 0–100, **mirrored to every region it owns** (`regionStats`), and its derived `stats` **re-derived** afterwards (the same 0-region / no-entry guards as hybrid / economy / disasters — a 0-region nation keeps its directly-mutated value and the effect persists). It **never moves territory** (sole ownership is untouched). The **stub never** proposes a migration (`{ ops: [] }`), so e2e (CI, `LLM_STUB=1`) is unaffected and the path is covered by unit tests only.
- **Registry & prompt.** `migration` is added **last** in `ABILITIES` (existing order untouched); the system prompt gains the `migration` schema line and its constraint bullet ("at most 1–2 per turn, each narrated in `events` as a `social` or `diplomatic` event"); the user prompt is unchanged (`payload()` is `{}`). The two committed system-prompt **goldens** (`system-no-tool.txt`, `system-tool.txt`) are regenerated (each gains exactly the new `migration` schema line + constraint bullet); the **`user.txt` golden stays byte-identical** (no new user-payload keys — verified by checksum).
- **Tests.** New `server/abilities/migration.test.ts` (**38 tests**): the kind/scale predicate sets; the three effect tables (exact keys / signs / monotonicity); `validateMigrationOps` (shape / leniency / drops / field caps); `shiftRelationTowardPositive` (one-step nudge, caps, war-untouched, missing→neutral, unknown no-op); `applyMigrationOp` (small / moderate / large source & destination dips, the `large` stability strain, name-based resolve, the relation nudge by kind, war-untouched, exodus-only-source, self-flow drop, unknown / ambiguous source & destination drop, 0-region direct-dip persistence, territory-untouched, clamping at 0 and 100); and the ability const contract (field, no `stateFields`, fresh `default()`/`stub()`, `isMeaningful`, `payload() {}`, `validate` wrapping, `apply` ctx wiring). `registry.test.ts` is updated for the **10-ability** contract (order, distinct fields, `fullDefaultTurn()`, `meaningfulFor`, re-export pin); the goldens are regenerated (verified idempotent).
- **Design note (interpretation of the issue body).** The Gitea #64 body sketched a simpler `flows: { type: 'refugees' | 'settlers' }` shape that included a settler **re-claim of no-man's-land**; the refined, approved design implemented here is the richer `migration.ops` union of **four nation-to-nation population-flow kinds** (migration / refugees / diaspora / exodus) — a purely **stat** layer that **never moves territory** (sole ownership stays untouched; a no-man's-land re-claim is deliberately out of scope, as territory movement remains the `regionChanges` lever's job).
- **Guarantees.** No client (`src/`) changes, no new runtime deps, `shared/` keeps zero runtime deps, and no `@turf`/`@types/geojson` in any `.ts`. All unit tests green (additive); e2e (CI, `LLM_STUB=1`) unaffected (the stub is migration-inert).
- **Version** bumped `0.41.0 → 0.42.0`.
## v0.41.0 — 2026-10-16 09:07 ## v0.41.0 — 2026-10-16 09:07
- **#63: Disasters & pandemics — a `TurnResult.disasters` lever letting the LLM declare natural/man-made disasters (earthquake / flood / volcanic / wildfire / famine / plague / epidemic) on a nation or a region, with a deterministic stat dip (stability / economy / military).** It is a **turn-transient** feature, exactly like the v0.34 `hybrid` layer: **no new `GameState` field, no `db.ts` change, no durable list** — the ops are consumed inside `applyTurnResult` and leave nothing behind. It lands as the **9th ability** of the v0.40.0 modular system, in a new `server/abilities/disasters.ts` module, **registered last** in the `ABILITIES` registry (after `ideology`, before the loop appends `markers` / `nationOps`). - **#63: Disasters & pandemics — a `TurnResult.disasters` lever letting the LLM declare natural/man-made disasters (earthquake / flood / volcanic / wildfire / famine / plague / epidemic) on a nation or a region, with a deterministic stat dip (stability / economy / military).** It is a **turn-transient** feature, exactly like the v0.34 `hybrid` layer: **no new `GameState` field, no `db.ts` change, no durable list** — the ops are consumed inside `applyTurnResult` and leave nothing behind. It lands as the **9th ability** of the v0.40.0 modular system, in a new `server/abilities/disasters.ts` module, **registered last** in the `ABILITIES` registry (after `ideology`, before the loop appends `markers` / `nationOps`).
- **Types (`shared/protocol.ts`).** New `DisasterType` (`'earthquake' | 'flood' | 'volcanic' | 'wildfire' | 'famine' | 'plague' | 'epidemic'`), `DisasterSeverity` (`'minor' | 'moderate' | 'severe'`), `DisasterEvent` (`{ type; target; severity; detail? }` — `target` is a nation ref **or** a region key), and `DisastersOps` (`{ events: DisasterEvent[] }`); `TurnResult.disasters` is **required**, placed between `ideology` and `markers`, default `{ events: [] }`. - **Types (`shared/protocol.ts`).** New `DisasterType` (`'earthquake' | 'flood' | 'volcanic' | 'wildfire' | 'famine' | 'plague' | 'epidemic'`), `DisasterSeverity` (`'minor' | 'moderate' | 'severe'`), `DisasterEvent` (`{ type; target; severity; detail? }` — `target` is a nation ref **or** a region key), and `DisastersOps` (`{ events: DisasterEvent[] }`); `TurnResult.disasters` is **required**, placed between `ideology` and `markers`, default `{ events: [] }`.
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "history", "name": "history",
"version": "0.41.0", "version": "0.44.0",
"private": true, "private": true,
"type": "module", "type": "module",
"description": "AI-driven alternate-history simulator — the LLM is the world engine (Pax Historia style).", "description": "AI-driven alternate-history simulator — the LLM is the world engine (Pax Historia style).",
File diff suppressed because it is too large Load Diff
+301
View File
@@ -0,0 +1,301 @@
// The CONTESTED (contested regions / frontlines) ability (v0.44.0, #66) as a
// modular LLM-ability (v0.40.0, #67) — a THIRD region state, besides "owned by
// one nation" and "no man's land": a war frontline that is in **no** nation's
// `territory` and not in `unowned`, contested by two or more nations at war.
//
// Each turn the LLM may `open` a region as a contested frontline and/or
// `resolve` an existing one. `open` requires the region to have a SOLE owner
// that is at war with at least one of the parties, or to be no man's land (in
// `unowned`) with two or more of the parties at war with each other; a region
// with two or more owners, or whose owner is not at war with any party, cannot
// be contested (dropped). On a successful open the key is removed from its
// owner's `territory` (sole ownership is preserved — a contested key is in NO
// territory) and from `unowned`, its `regionStats` entry is deleted, and a
// `{ regionKey, parties }` entry (parties = resolved nation ids) is added to
// `GameState.contested` (unique by `regionKey` — re-opening replaces it).
// `resolve` removes the entry and releases the key to no man's land — UNLESS a
// concurrent winning claim by one of the parties (allowed by the
// territory-step guard in engine.ts) already re-owned it, in which case it
// stays owned and its stats are kept.
//
// A still-contested key is NOT a valid normal-claim target: a plain `gain` on
// it is dropped in the territory step (only a resolving party's claim
// re-owns it). The layer NEVER moves a key into two territories (sole
// ownership is sacrosanct), never touches borders directly (the key simply
// leaves ownership), and is deterministic (no hidden randomness — the LLM
// declares, the engine applies fixed rules).
//
// This is a DURABLE ability (unlike the turn-transient hybrid / disasters /
// migration layers): it owns the `GameState.contested` field, and the user
// payload carries the current contested list (only when non-empty).
import { deriveNationStats } from '../../shared/protocol';
import type { ContestedOps, ContestedRegion } from '../../shared/protocol';
// The map-fill constants + tooltip label live in the shared protocol module
// (like the sea-zone / no-man's-land constants); re-exported here so the
// index / engine re-export surface is one consistent place.
export {
CONTESTED_FILL,
CONTESTED_STROKE,
contestedTooltipLabel,
} from '../../shared/protocol';
import type { GameState } from '../../shared/types';
import { atWar } from './apply-helpers';
import { resolveNationRef, resolveRegionKey, str } from './shared';
import type { Ability, AbilityCtx } from './types';
/**
* (v0.44.0, #66) The SOLE owners of a region key in `next` (a key that is in no
* nation's `territory` yields `[]`; a corrupt 2+ owner key yields both). Pure.
*/
function currentOwners(next: GameState, key: string): string[] {
const owners: string[] = [];
for (const n of Object.values(next.nations)) {
if (n.territory.includes(key)) owners.push(n.id);
}
return owners;
}
/**
* (v0.44.0, #66) Resolve a region reference (a raw key or a human name) to a
* concrete region key: exact key first, then a unique case-insensitive name
* match. With no region-key manifest loaded (`validKeys` undefined) the raw
* string is accepted as the key (a name cannot be resolved without the
* manifest). Returns `null` when the reference is empty or unresolvable.
*/
function resolveKey(
ref: string,
validKeys?: ReadonlySet<string>,
nameOf?: (key: string) => string | undefined,
): string | null {
const r = (ref ?? '').trim();
if (!r) return null;
if (!validKeys) return r; // no manifest: accept the raw key as-is
return resolveRegionKey(r, validKeys, nameOf ?? (() => undefined));
}
/**
* (v0.44.0, #66) Resolve a list of party references to distinct nation ids
* (id first, then a case-insensitive unique name), preserving first-appearance
* order. An unresolvable ref is dropped. Pure.
*/
function resolveParties(next: GameState, refs: string[]): string[] {
const out: string[] = [];
for (const ref of refs) {
const id = resolveNationRef(next, ref);
if (id && !out.includes(id)) out.push(id);
}
return out;
}
/**
* (v0.44.0, #66) Re-derive a nation's aggregate `stats` from its regions'
* per-region stats, with the same 0-region / no-entry guards as the engine's
* main recompute (a nation with no region, or none with a stats entry, keeps
* its directly-mutated `stats`). Used after a contested open strips a region
* from its owner. Never throws.
*/
function rederiveOwnerStats(
next: GameState,
ownerId: string,
geoOf?: (key: string) => { area: number; population: number } | undefined,
): void {
const n = next.nations[ownerId];
if (!n) return;
if (n.territory.length > 0 && n.territory.some((k) => next.regionStats[k])) {
n.stats = deriveNationStats(n.territory, next.regionStats, geoOf);
}
}
/**
* (v0.44.0, #66) Validate the raw `contested` field of a turn into a safe
* {@link ContestedOps}. Defensive like the rest of the parser — never throws.
* `open`: each op needs a non-empty `regionKey` (capped at 120 chars) and
* TWO OR MORE non-empty `parties` refs (each capped at 200 chars); an op with
* a missing `regionKey` or fewer than two party refs is dropped. `resolve`:
* each entry is a non-empty region key (capped at 120 chars); empty / non-
* string entries are dropped. Both region keys and party refs are kept RAW
* here (like the hybrid / economy / industry refs) — whether a ref resolves to
* a real region / nation, and whether the war-linkage / ownership conditions
* hold, is checked at apply time (a ref that does not resolve, or a region that
* is not contestable, is dropped there). A missing / malformed top-level object
* yields `{ open: [], resolve: [] }`.
*/
export function validateContestedOps(raw: unknown): ContestedOps {
const out: ContestedOps = { open: [], resolve: [] };
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return out;
const o = raw as Record<string, unknown>;
if (Array.isArray(o.open)) {
for (const e of o.open) {
if (!e || typeof e !== 'object') continue;
const p = e as Record<string, unknown>;
const regionKey = str(p.regionKey, 120);
if (!regionKey) continue; // missing / empty region key: drop
if (!Array.isArray(p.parties)) continue; // missing / malformed parties: drop
const parties = p.parties
.map((x) => str(x, 200))
.filter((x): x is string => x !== null);
if (parties.length < 2) continue; // need at least two party refs
out.open.push({ regionKey, parties });
}
}
if (Array.isArray(o.resolve)) {
for (const e of o.resolve) {
const key = str(e, 120);
if (key) out.resolve.push(key);
}
}
return out;
}
/**
* (v0.44.0, #66) Apply the turn's contested-region ops to `next`, mutating in
* place and never throwing. Runs in the `ABILITIES` loop AFTER the territory
* step and the derived-stats recompute, and BEFORE markers / nationOps, so the
* owner / unowned / wars it inspects are all final for this turn.
*
* (1) RESOLVE (first): each key in `resolve` that is currently contested is
* removed from `next.contested` and released to no man's land (into
* `unowned`, out of any territory, `regionStats` deleted) — UNLESS a
* concurrent winning claim by one of the parties (the only claim the
* territory step permits on a contested key) already re-owned it, in
* which case it stays owned and keeps (or re-inits) its stats.
* (2) OPEN: each op that resolves to a contestable region (a sole owner at
* war with a party, or a no-man's-land region whose parties are at war
* with each other) is moved out of ownership (the owner's territory /
* `unowned`), its `regionStats` is deleted, and it is added to
* `next.contested` (unique by `regionKey` — an open replaces a kept
* entry for the same key). The stripped owner's derived stats are
* re-derived.
*
* A contested key is never placed into two territories and is never left in
* `unowned` (the two states are mutually exclusive), so the sole-ownership
* invariant holds after every op.
*/
export function applyContested(next: GameState, ops: ContestedOps, ctx: AbilityCtx): void {
const validKeys = ctx.validRegionKeys;
const nameOf = ctx.regionNameOf;
const geoOf = ctx.geoOf;
const open = Array.isArray(ops?.open) ? ops.open : [];
const resolve = Array.isArray(ops?.resolve) ? ops.resolve : [];
const prevContested = Array.isArray(next.contested) ? next.contested : [];
// (1) RESOLVE first: rebuild the kept list, dropping resolved keys. A
// resolved key is released to no man's land unless a party re-owned it.
const resolveSet = new Set(resolve);
const kept: ContestedRegion[] = [];
for (const c of prevContested) {
if (!resolveSet.has(c.regionKey)) {
kept.push(c); // not resolved this turn: keep
continue;
}
const owners = currentOwners(next, c.regionKey);
if (owners.length === 1 && c.parties.includes(owners[0])) {
// A party re-owned it via a concurrent winning claim (the territory step
// allowed it): keep it owned, ensure it has stats (the claim re-inits an
// absent entry; the post-claim recompute already reflected the gain).
if (!next.regionStats[c.regionKey]) {
next.regionStats[c.regionKey] = { ...next.nations[owners[0]].stats };
}
continue; // stays owned — not re-added to `contested`
}
// Release to no man's land: out of any territory (defensive — a contested
// key is normally in none), into `unowned`, and its per-region stats leave.
for (const n of Object.values(next.nations)) {
const i = n.territory.indexOf(c.regionKey);
if (i !== -1) n.territory.splice(i, 1);
}
if (!next.unowned.includes(c.regionKey)) next.unowned.push(c.regionKey);
delete next.regionStats[c.regionKey];
}
// (2) OPEN: each op that resolves to a contestable region is moved out of
// ownership and added to the contested list (unique by region key).
const opened = new Map<string, string[]>(); // region key -> resolved party ids
for (const op of open) {
const key = resolveKey(op.regionKey, validKeys, nameOf);
if (!key) continue;
const parties = resolveParties(next, op.parties);
if (parties.length < 2) continue; // fewer than two distinct resolved parties
const owners = currentOwners(next, key);
let ok = false;
if (owners.length === 1) {
// Sole owner present: the owner must be at war with at least one party
// (the owner may itself be a party — atWar is false for a==b, so this
// checks the owner against the OTHER parties).
ok = parties.some((p) => atWar(next.wars, owners[0], p));
} else if (owners.length === 0 && next.unowned.includes(key)) {
// No owner + no man's land: two of the parties must be at war with
// each other.
for (let i = 0; i < parties.length && !ok; i++) {
for (let j = i + 1; j < parties.length; j++) {
if (atWar(next.wars, parties[i], parties[j])) {
ok = true;
break;
}
}
}
}
// Two or more owners (corrupt), an owner not at war with any party, or a
// not-in-unowned keyless region: never contestable (dropped).
if (!ok) continue;
if (owners.length === 1) {
const n = next.nations[owners[0]];
const i = n.territory.indexOf(key);
if (i !== -1) n.territory.splice(i, 1);
rederiveOwnerStats(next, owners[0], geoOf);
} else {
const i = next.unowned.indexOf(key);
if (i !== -1) next.unowned.splice(i, 1);
}
delete next.regionStats[key];
opened.set(key, parties);
}
// Rebuild `next.contested`: the kept (unresolved) entries plus the newly
// opened ones, unique by region key (an open replaces a kept entry for the
// same key; a resolve removed its key from `kept` above).
const final: ContestedRegion[] = [];
const seen = new Set<string>();
for (const c of kept) {
if (opened.has(c.regionKey)) continue; // replaced by a re-open this turn
if (seen.has(c.regionKey)) continue; // dedupe (should not happen, but safe)
seen.add(c.regionKey);
final.push(c);
}
for (const [key, parties] of opened) {
if (seen.has(key)) continue;
seen.add(key);
final.push({ regionKey: key, parties });
}
next.contested = final;
}
export const contested: Ability<'contested'> = {
field: 'contested',
default: () => ({ open: [], resolve: [] }),
validate: (raw) => validateContestedOps(raw),
apply: (state, data, ctx) => applyContested(state, data, ctx),
schemaLine: () =>
' "contested": {"open":[{"regionKey":"<region key>","parties":["<nation 1>","<nation 2>"]}],"resolve":["<region key>"]},',
constraint: () =>
'- Contested regions ("contested") are WAR FRONTLINES: a region that no nation controls and that is not no man\'s land, contested by two or more nations at war. An "open" op ({"regionKey":"<key>","parties":["<a>","<b>"]}) makes a region a frontline — it leaves its owner\'s territory (or no-man\'s-land) and is contested: the region\'s sole owner must be at war with at least one of the parties, or (for a no-man\'s-land region) two of the parties must be at war with each other. A "resolve" op (["<key>"]) ends a frontline, releasing the region to no man\'s land — unless a party\'s concurrent claim re-owns it. A contested region is in NO nation\'s territory (never two) and is never no man\'s land while contested. The user message\'s "contested" field lists the current frontlines (region key + party names). Propose at most 1-2 contested-region changes per turn and narrate each one in "events" (a "military" event).',
isMeaningful: (data) => data.open.length > 0 || data.resolve.length > 0,
stateFields: ['contested'],
stub: () => ({ open: [], resolve: [] }),
// The user payload carries the current contested frontlines (region key +
// party NAMES, resolved from the stored ids) — but only when non-empty (a
// fresh / no-frontline world contributes nothing, like the turn-transient
// layers).
payload: (ctx) => {
if (!ctx.contested || ctx.contested.length === 0) return {};
return {
contested: ctx.contested.map((c) => ({
regionKey: c.regionKey,
parties: c.parties.map((id) => ctx.state.nations[id]?.name ?? id),
})),
};
},
};
+4
View File
@@ -70,6 +70,10 @@ function mkState(
trades: [], trades: [],
embargoes: [], embargoes: [],
industry: [], industry: [],
// (v0.43.0, #65) no sea-zone control on a fresh state.
seaZones: [],
// (v0.44.0, #66) no contested regions on a fresh state.
contested: [],
}; };
} }
@@ -40,6 +40,9 @@ Respond with ONLY a valid JSON object of exactly this shape. No prose, no commen
"leaders": {"changes":[{"target":"<nation id or name>","name":"<new leader name>","cause":"<assassination|death|appointed>"}]}, "leaders": {"changes":[{"target":"<nation id or name>","name":"<new leader name>","cause":"<assassination|death|appointed>"}]},
"ideology": {"changes":[{"target":"<nation id or name>","to":"<new form of government>"}]}, "ideology": {"changes":[{"target":"<nation id or name>","to":"<new form of government>"}]},
"disasters": {"events":[{"type":"<earthquake|flood|volcanic|wildfire|famine|plague|epidemic>","target":"<nation id or name, or region key>","severity":"<minor|moderate|severe>","detail":"<short detail>"}]}, "disasters": {"events":[{"type":"<earthquake|flood|volcanic|wildfire|famine|plague|epidemic>","target":"<nation id or name, or region key>","severity":"<minor|moderate|severe>","detail":"<short detail>"}]},
"migration": {"ops":[{"kind":"<migration|refugees|diaspora|exodus>","from":"<nation id or name>","to":"<nation id or name>","scale":"<small|moderate|large>","detail":"<short detail>"}]},
"sea": {"control":[{"zone":"<seaZoneId>","by":"<nation id or name>"}]},
"contested": {"open":[{"regionKey":"<region key>","parties":["<nation 1>","<nation 2>"]}],"resolve":["<region key>"]},
"markers": {"add":[{"type":"<city|factory|army|port|capital|fleet|rocket|gathering>","name":"<short name>","regionKey":"<region key>"}],"remove":["<marker id>"]} "markers": {"add":[{"type":"<city|factory|army|port|capital|fleet|rocket|gathering>","name":"<short name>","regionKey":"<region key>"}],"remove":["<marker id>"]}
} }
@@ -66,6 +69,9 @@ HARD CONSTRAINTS
- Leaders ("leaders") name each nation's current head of state and change it. Each change is {"target":"<nation id or name>","name":"<new leader name>","cause":"<assassination|death|appointed>"}: "assassination" kills the current leader (a dramatic, destabilizing blow — a −15 stability dip, a "military" event) and is only valid when the target already has a leader; "death" is a natural-causes succession (a quieter −3 dip, a "political" event), also only valid for a nation that has a leader; "appointed" sets (or creates) a leader and is always valid (a neutral 0 effect, a "political" event). Propose at most 1-2 changes per turn and narrate each one in "events". This is the HEAVY leader lever — use the lighter "hybrid" {"type":"assassinate"} op (a −5 stability dip, no leader replacement) for a mere hit on a leader or region without changing who is in charge. The user message's "nations" field lists each nation's current "leader" (omitted when a nation has none). - Leaders ("leaders") name each nation's current head of state and change it. Each change is {"target":"<nation id or name>","name":"<new leader name>","cause":"<assassination|death|appointed>"}: "assassination" kills the current leader (a dramatic, destabilizing blow — a −15 stability dip, a "military" event) and is only valid when the target already has a leader; "death" is a natural-causes succession (a quieter −3 dip, a "political" event), also only valid for a nation that has a leader; "appointed" sets (or creates) a leader and is always valid (a neutral 0 effect, a "political" event). Propose at most 1-2 changes per turn and narrate each one in "events". This is the HEAVY leader lever — use the lighter "hybrid" {"type":"assassinate"} op (a −5 stability dip, no leader replacement) for a mere hit on a leader or region without changing who is in charge. The user message's "nations" field lists each nation's current "leader" (omitted when a nation has none).
- Ideology ("ideology") is each nation's form of government — a free-form label such as "democracy", "fascism", or "military junta" — that can shift through a coup, a revolution, a reform, or a constitutional change. Each change is {"target":"<nation id or name>","to":"<new form of government>"}: the engine sets the nation's ideology, applies a small, deterministic stability dip (−5 — a regime shift always unsettles a nation), and narrates it with a "political" event. It is a third axis, distinct from a takeover (which RENAMES the nation) and from a leader change (who is in charge): the nation keeps its id, name, territory, relations, and leader — only its form of government and its stability move. Similar forms of government are a SOFT, prompt-level compatibility nudge only (nations with alike ideologies tend to ally and trade; very opposed ones tend to clash) — there is no engine gate behind it. Propose at most 1-2 changes per turn and narrate each one in "events". The user message's "nations" field lists each nation's current "ideology" (omitted when a nation has none). - Ideology ("ideology") is each nation's form of government — a free-form label such as "democracy", "fascism", or "military junta" — that can shift through a coup, a revolution, a reform, or a constitutional change. Each change is {"target":"<nation id or name>","to":"<new form of government>"}: the engine sets the nation's ideology, applies a small, deterministic stability dip (−5 — a regime shift always unsettles a nation), and narrates it with a "political" event. It is a third axis, distinct from a takeover (which RENAMES the nation) and from a leader change (who is in charge): the nation keeps its id, name, territory, relations, and leader — only its form of government and its stability move. Similar forms of government are a SOFT, prompt-level compatibility nudge only (nations with alike ideologies tend to ally and trade; very opposed ones tend to clash) — there is no engine gate behind it. Propose at most 1-2 changes per turn and narrate each one in "events". The user message's "nations" field lists each nation's current "ideology" (omitted when a nation has none).
- Disasters & pandemics ("disasters.events") are natural and man-made catastrophes — earthquakes, floods, volcanic eruptions, wildfires, famines, plagues, and epidemics — that hit a nation or a single region this turn. Each event names a "target" (a nation id / name, or a region key that hits that region's SOLE owner — a region with 0 or 2+ owners can't be hit) and a "severity" (minor / moderate / severe); the engine applies a small, DETERMINISTIC stat dip from the (type, severity) table (a severe plague is the hardest hit; none of them touch population, and none move borders — sole ownership is untouched). There is NO memory of past disasters (the layer is turn-transient): a plague or epidemic that persists is simply RE-DECLARED each turn it continues, with a fresh "severity". Propose at most 1-2 events per turn and narrate each one in "events" (a "disaster" event). - Disasters & pandemics ("disasters.events") are natural and man-made catastrophes — earthquakes, floods, volcanic eruptions, wildfires, famines, plagues, and epidemics — that hit a nation or a single region this turn. Each event names a "target" (a nation id / name, or a region key that hits that region's SOLE owner — a region with 0 or 2+ owners can't be hit) and a "severity" (minor / moderate / severe); the engine applies a small, DETERMINISTIC stat dip from the (type, severity) table (a severe plague is the hardest hit; none of them touch population, and none move borders — sole ownership is untouched). There is NO memory of past disasters (the layer is turn-transient): a plague or epidemic that persists is simply RE-DECLARED each turn it continues, with a fresh "severity". Propose at most 1-2 events per turn and narrate each one in "events" (a "disaster" event).
- Migration & refugees ("migration.ops") are people moving between nations this turn: a "kind" ("migration", "refugees", "diaspora", or "exodus"), a "from" (the source nation — id or name), a "to" (the destination nation — required for every kind except "exodus", which has no destination), and a "scale" (small / moderate / large). The engine applies a DETERMINISTIC effect (no hidden randomness): the source LOSES a small amount of population and economy, the destination GAINS a small amount of population and economy (a "large" influx additionally strains the destination's stability by 2), and the from↔to relation moves one step toward the positive end of the ally/neutral/rival/hostile ladder — capped at "ally" for "refugees" (hosting refugees builds the strongest goodwill), capped at "neutral" for "migration"/"diaspora" (milder ties), and not at all for "exodus"; the nudge never creates or escalates a "war" (a warring pair is left untouched). The layer is turn-transient (no memory): a continuing flow is simply RE-DECLARED each turn it persists. It never moves borders — sole ownership is untouched. Propose at most 1-2 per turn and narrate each one in "events" (a "social" or "diplomatic" event).
- Sea control ("sea") is the naval layer, fully parallel to but INDEPENDENT of land: each of the 12 fixed sea zones — "north-atlantic" (North Atlantic), "south-atlantic" (South Atlantic), "pacific" (Pacific Ocean), "indian" (Indian Ocean), "mediterranean" (Mediterranean Sea), "north-sea" (North Sea), "baltic" (Baltic Sea), "arctic" (Arctic Ocean), "black-sea" (Black Sea), "gulf-mexico" (Gulf of Mexico), "red-sea" (Red Sea), "sargasso" (Sargasso Sea) — is under the SOLE control of at most one nation. A control op ({"zone":"<id>","by":"<nation>"}) sets or replaces that zone's controller (the user message's "seaZones" field lists who controls what now); if two or more ops this turn claim the SAME zone for DIFFERENT nations, the zone is CONTESTED and the higher current "military" wins (a tie goes to the earlier-listed op). Every committed turn each zone's controller earns a small deterministic +1 military and +1 economy. Sea control NEVER moves land (no territory changes) — it is a parallel track. Propose at most 1-2 claims per turn and narrate each one in "events" (a "military" or "diplomatic" event).
- Contested regions ("contested") are WAR FRONTLINES: a region that no nation controls and that is not no man's land, contested by two or more nations at war. An "open" op ({"regionKey":"<key>","parties":["<a>","<b>"]}) makes a region a frontline — it leaves its owner's territory (or no-man's-land) and is contested: the region's sole owner must be at war with at least one of the parties, or (for a no-man's-land region) two of the parties must be at war with each other. A "resolve" op (["<key>"]) ends a frontline, releasing the region to no man's land — unless a party's concurrent claim re-owns it. A contested region is in NO nation's territory (never two) and is never no man's land while contested. The user message's "contested" field lists the current frontlines (region key + party names). Propose at most 1-2 contested-region changes per turn and narrate each one in "events" (a "military" event).
- Prefer 1-4 events per turn; keep each text 1-3 sentences. - Prefer 1-4 events per turn; keep each text 1-3 sentences.
- Keep your internal reasoning brief (a few sentences) and go straight to the JSON result; do not over-deliberate or re-derive facts already present in the state. - Keep your internal reasoning brief (a few sentences) and go straight to the JSON result; do not over-deliberate or re-derive facts already present in the state.
- Keep every stat value between 0 and 100. - Keep every stat value between 0 and 100.
+6
View File
@@ -40,6 +40,9 @@ You have a getNeighbours tool: given region keys it returns the region keys that
"leaders": {"changes":[{"target":"<nation id or name>","name":"<new leader name>","cause":"<assassination|death|appointed>"}]}, "leaders": {"changes":[{"target":"<nation id or name>","name":"<new leader name>","cause":"<assassination|death|appointed>"}]},
"ideology": {"changes":[{"target":"<nation id or name>","to":"<new form of government>"}]}, "ideology": {"changes":[{"target":"<nation id or name>","to":"<new form of government>"}]},
"disasters": {"events":[{"type":"<earthquake|flood|volcanic|wildfire|famine|plague|epidemic>","target":"<nation id or name, or region key>","severity":"<minor|moderate|severe>","detail":"<short detail>"}]}, "disasters": {"events":[{"type":"<earthquake|flood|volcanic|wildfire|famine|plague|epidemic>","target":"<nation id or name, or region key>","severity":"<minor|moderate|severe>","detail":"<short detail>"}]},
"migration": {"ops":[{"kind":"<migration|refugees|diaspora|exodus>","from":"<nation id or name>","to":"<nation id or name>","scale":"<small|moderate|large>","detail":"<short detail>"}]},
"sea": {"control":[{"zone":"<seaZoneId>","by":"<nation id or name>"}]},
"contested": {"open":[{"regionKey":"<region key>","parties":["<nation 1>","<nation 2>"]}],"resolve":["<region key>"]},
"markers": {"add":[{"type":"<city|factory|army|port|capital|fleet|rocket|gathering>","name":"<short name>","regionKey":"<region key>"}],"remove":["<marker id>"]} "markers": {"add":[{"type":"<city|factory|army|port|capital|fleet|rocket|gathering>","name":"<short name>","regionKey":"<region key>"}],"remove":["<marker id>"]}
} }
@@ -66,6 +69,9 @@ HARD CONSTRAINTS
- Leaders ("leaders") name each nation's current head of state and change it. Each change is {"target":"<nation id or name>","name":"<new leader name>","cause":"<assassination|death|appointed>"}: "assassination" kills the current leader (a dramatic, destabilizing blow — a −15 stability dip, a "military" event) and is only valid when the target already has a leader; "death" is a natural-causes succession (a quieter −3 dip, a "political" event), also only valid for a nation that has a leader; "appointed" sets (or creates) a leader and is always valid (a neutral 0 effect, a "political" event). Propose at most 1-2 changes per turn and narrate each one in "events". This is the HEAVY leader lever — use the lighter "hybrid" {"type":"assassinate"} op (a −5 stability dip, no leader replacement) for a mere hit on a leader or region without changing who is in charge. The user message's "nations" field lists each nation's current "leader" (omitted when a nation has none). - Leaders ("leaders") name each nation's current head of state and change it. Each change is {"target":"<nation id or name>","name":"<new leader name>","cause":"<assassination|death|appointed>"}: "assassination" kills the current leader (a dramatic, destabilizing blow — a −15 stability dip, a "military" event) and is only valid when the target already has a leader; "death" is a natural-causes succession (a quieter −3 dip, a "political" event), also only valid for a nation that has a leader; "appointed" sets (or creates) a leader and is always valid (a neutral 0 effect, a "political" event). Propose at most 1-2 changes per turn and narrate each one in "events". This is the HEAVY leader lever — use the lighter "hybrid" {"type":"assassinate"} op (a −5 stability dip, no leader replacement) for a mere hit on a leader or region without changing who is in charge. The user message's "nations" field lists each nation's current "leader" (omitted when a nation has none).
- Ideology ("ideology") is each nation's form of government — a free-form label such as "democracy", "fascism", or "military junta" — that can shift through a coup, a revolution, a reform, or a constitutional change. Each change is {"target":"<nation id or name>","to":"<new form of government>"}: the engine sets the nation's ideology, applies a small, deterministic stability dip (−5 — a regime shift always unsettles a nation), and narrates it with a "political" event. It is a third axis, distinct from a takeover (which RENAMES the nation) and from a leader change (who is in charge): the nation keeps its id, name, territory, relations, and leader — only its form of government and its stability move. Similar forms of government are a SOFT, prompt-level compatibility nudge only (nations with alike ideologies tend to ally and trade; very opposed ones tend to clash) — there is no engine gate behind it. Propose at most 1-2 changes per turn and narrate each one in "events". The user message's "nations" field lists each nation's current "ideology" (omitted when a nation has none). - Ideology ("ideology") is each nation's form of government — a free-form label such as "democracy", "fascism", or "military junta" — that can shift through a coup, a revolution, a reform, or a constitutional change. Each change is {"target":"<nation id or name>","to":"<new form of government>"}: the engine sets the nation's ideology, applies a small, deterministic stability dip (−5 — a regime shift always unsettles a nation), and narrates it with a "political" event. It is a third axis, distinct from a takeover (which RENAMES the nation) and from a leader change (who is in charge): the nation keeps its id, name, territory, relations, and leader — only its form of government and its stability move. Similar forms of government are a SOFT, prompt-level compatibility nudge only (nations with alike ideologies tend to ally and trade; very opposed ones tend to clash) — there is no engine gate behind it. Propose at most 1-2 changes per turn and narrate each one in "events". The user message's "nations" field lists each nation's current "ideology" (omitted when a nation has none).
- Disasters & pandemics ("disasters.events") are natural and man-made catastrophes — earthquakes, floods, volcanic eruptions, wildfires, famines, plagues, and epidemics — that hit a nation or a single region this turn. Each event names a "target" (a nation id / name, or a region key that hits that region's SOLE owner — a region with 0 or 2+ owners can't be hit) and a "severity" (minor / moderate / severe); the engine applies a small, DETERMINISTIC stat dip from the (type, severity) table (a severe plague is the hardest hit; none of them touch population, and none move borders — sole ownership is untouched). There is NO memory of past disasters (the layer is turn-transient): a plague or epidemic that persists is simply RE-DECLARED each turn it continues, with a fresh "severity". Propose at most 1-2 events per turn and narrate each one in "events" (a "disaster" event). - Disasters & pandemics ("disasters.events") are natural and man-made catastrophes — earthquakes, floods, volcanic eruptions, wildfires, famines, plagues, and epidemics — that hit a nation or a single region this turn. Each event names a "target" (a nation id / name, or a region key that hits that region's SOLE owner — a region with 0 or 2+ owners can't be hit) and a "severity" (minor / moderate / severe); the engine applies a small, DETERMINISTIC stat dip from the (type, severity) table (a severe plague is the hardest hit; none of them touch population, and none move borders — sole ownership is untouched). There is NO memory of past disasters (the layer is turn-transient): a plague or epidemic that persists is simply RE-DECLARED each turn it continues, with a fresh "severity". Propose at most 1-2 events per turn and narrate each one in "events" (a "disaster" event).
- Migration & refugees ("migration.ops") are people moving between nations this turn: a "kind" ("migration", "refugees", "diaspora", or "exodus"), a "from" (the source nation — id or name), a "to" (the destination nation — required for every kind except "exodus", which has no destination), and a "scale" (small / moderate / large). The engine applies a DETERMINISTIC effect (no hidden randomness): the source LOSES a small amount of population and economy, the destination GAINS a small amount of population and economy (a "large" influx additionally strains the destination's stability by 2), and the from↔to relation moves one step toward the positive end of the ally/neutral/rival/hostile ladder — capped at "ally" for "refugees" (hosting refugees builds the strongest goodwill), capped at "neutral" for "migration"/"diaspora" (milder ties), and not at all for "exodus"; the nudge never creates or escalates a "war" (a warring pair is left untouched). The layer is turn-transient (no memory): a continuing flow is simply RE-DECLARED each turn it persists. It never moves borders — sole ownership is untouched. Propose at most 1-2 per turn and narrate each one in "events" (a "social" or "diplomatic" event).
- Sea control ("sea") is the naval layer, fully parallel to but INDEPENDENT of land: each of the 12 fixed sea zones — "north-atlantic" (North Atlantic), "south-atlantic" (South Atlantic), "pacific" (Pacific Ocean), "indian" (Indian Ocean), "mediterranean" (Mediterranean Sea), "north-sea" (North Sea), "baltic" (Baltic Sea), "arctic" (Arctic Ocean), "black-sea" (Black Sea), "gulf-mexico" (Gulf of Mexico), "red-sea" (Red Sea), "sargasso" (Sargasso Sea) — is under the SOLE control of at most one nation. A control op ({"zone":"<id>","by":"<nation>"}) sets or replaces that zone's controller (the user message's "seaZones" field lists who controls what now); if two or more ops this turn claim the SAME zone for DIFFERENT nations, the zone is CONTESTED and the higher current "military" wins (a tie goes to the earlier-listed op). Every committed turn each zone's controller earns a small deterministic +1 military and +1 economy. Sea control NEVER moves land (no territory changes) — it is a parallel track. Propose at most 1-2 claims per turn and narrate each one in "events" (a "military" or "diplomatic" event).
- Contested regions ("contested") are WAR FRONTLINES: a region that no nation controls and that is not no man's land, contested by two or more nations at war. An "open" op ({"regionKey":"<key>","parties":["<a>","<b>"]}) makes a region a frontline — it leaves its owner's territory (or no-man's-land) and is contested: the region's sole owner must be at war with at least one of the parties, or (for a no-man's-land region) two of the parties must be at war with each other. A "resolve" op (["<key>"]) ends a frontline, releasing the region to no man's land — unless a party's concurrent claim re-owns it. A contested region is in NO nation's territory (never two) and is never no man's land while contested. The user message's "contested" field lists the current frontlines (region key + party names). Propose at most 1-2 contested-region changes per turn and narrate each one in "events" (a "military" event).
- Prefer 1-4 events per turn; keep each text 1-3 sentences. - Prefer 1-4 events per turn; keep each text 1-3 sentences.
- Keep your internal reasoning brief (a few sentences) and go straight to the JSON result; do not over-deliberate or re-derive facts already present in the state. - Keep your internal reasoning brief (a few sentences) and go straight to the JSON result; do not over-deliberate or re-derive facts already present in the state.
- Keep every stat value between 0 and 100. - Keep every stat value between 0 and 100.
+10
View File
@@ -205,5 +205,15 @@
"regionKey": "a-r1", "regionKey": "a-r1",
"type": "industry" "type": "industry"
} }
],
"seaZones": [],
"contested": [
{
"regionKey": "b-r1",
"parties": [
"Alpha",
"Bravo"
]
}
] ]
} }
+50 -4
View File
@@ -1,8 +1,8 @@
// The ordered LLM-ability registry. // The ordered LLM-ability registry.
// //
// `ABILITIES` is the single source of truth for the 9 per-feature LLM abilities. // `ABILITIES` is the single source of truth for the 12 per-feature LLM abilities.
// The engine iterates it in this order: // The engine iterates it in this order:
// takeovers → wars → hybrid → economy → industry → nuclear → leaders → ideology → disasters // takeovers → wars → hybrid → economy → industry → nuclear → leaders → ideology → disasters → migration → sea → contested
// for (a) the system-prompt schema lines + constraint bullets, (b) the per-ability // for (a) the system-prompt schema lines + constraint bullets, (b) the per-ability
// validate calls inside validateTurnResult, (c) the payload fields in buildUserPrompt, // validate calls inside validateTurnResult, (c) the payload fields in buildUserPrompt,
// (d) the ordered apply block inside applyTurnResult, (e) the isMeaningful check, // (d) the ordered apply block inside applyTurnResult, (e) the isMeaningful check,
@@ -23,13 +23,18 @@ import { nuclear } from './nuclear';
import { leaders } from './leaders'; import { leaders } from './leaders';
import { ideology } from './ideology'; import { ideology } from './ideology';
import { disasters } from './disasters'; import { disasters } from './disasters';
import { migration } from './migration';
import { sea } from './sea';
import { contested } from './contested';
import type { Ability, AbilityField } from './types'; import type { Ability, AbilityField } from './types';
/** /**
* The 9 per-feature LLM abilities in their canonical apply order. * The 12 per-feature LLM abilities in their canonical apply order.
* The order matters: it determines the order of the schema lines in the * The order matters: it determines the order of the schema lines in the
* system prompt, the order of the validate calls, the order of the apply * system prompt, the order of the validate calls, the order of the apply
* steps, and the order of the payload fields in the user prompt. * steps, and the order of the payload fields in the user prompt. New
* abilities are APPENDED last — never reorder existing entries (their order
* is pinned by the goldens and the stub's byte-identical output).
*/ */
export const ABILITIES: readonly Ability<AbilityField>[] = [ export const ABILITIES: readonly Ability<AbilityField>[] = [
takeovers, takeovers,
@@ -41,6 +46,9 @@ export const ABILITIES: readonly Ability<AbilityField>[] = [
leaders, leaders,
ideology, ideology,
disasters, disasters,
migration,
sea,
contested,
]; ];
// ── type re-exports ──────────────────────────────────────────────────────────── // ── type re-exports ────────────────────────────────────────────────────────────
@@ -139,3 +147,41 @@ export {
DISASTER_SEVERITIES, DISASTER_SEVERITIES,
DISASTER_EFFECTS, DISASTER_EFFECTS,
} from './disasters'; } from './disasters';
// ── migration ────────────────────────────────────────────────────────────────
export {
validateMigrationOps,
applyMigrationOp,
shiftRelationTowardPositive,
isMigrationKind,
isMigrationScale,
MIGRATION_KINDS,
MIGRATION_SCALES,
MIGRATION_SOURCE_EFFECTS,
MIGRATION_DESTINATION_EFFECTS,
LARGE_INFLUX_STABILITY_DIP,
} from './migration';
// ── sea ──────────────────────────────────────────────────────────────────────
export {
validateSeaOps,
applySeaControl,
applySeaZoneBonuses,
SEA_ZONE_BONUS,
SEA_ZONES,
SEA_ZONE_IDS,
isSeaZoneId,
seaZoneName,
} from './sea';
// ── contested (frontlines) ───────────────────────────────────────────────────
export {
validateContestedOps,
applyContested,
CONTESTED_FILL,
CONTESTED_STROKE,
contestedTooltipLabel,
} from './contested';
+574
View File
@@ -0,0 +1,574 @@
// Unit tests for the MIGRATION & REFUGEES ability (v0.42.0, #64) — the
// modular, turn-transient LLM-ability that moves population between nations:
// the source loses a small amount of population and economy, the destination
// gains a small amount (a `large` influx also strains the destination's
// stability), each side's aggregate stats are re-derived, and the from↔to
// relation is nudged one step toward the positive end of the ladder (capped by
// kind; a war is never touched). This is the ability's own test file (the
// registry's cross-cutting guarantees — order, distinct fields, the
// system/user goldens — are covered by ./registry.test.ts). The stub never
// proposes a migration, so the apply path is exercised here, not by the e2e
// suite.
import { describe, expect, it } from 'vitest';
import {
LARGE_INFLUX_STABILITY_DIP,
MIGRATION_DESTINATION_EFFECTS,
MIGRATION_KINDS,
MIGRATION_SCALES,
MIGRATION_SOURCE_EFFECTS,
applyMigrationOp,
isMigrationKind,
isMigrationScale,
migration,
shiftRelationTowardPositive,
validateMigrationOps,
} from './migration';
import type { MigrationScale } from '../../shared/protocol';
import type { GameState, Nation, NationStats, RelationStatus, RegionStats } from '../../shared/types';
// ---------------------------------------------------------------------------
// Fixture helpers
// ---------------------------------------------------------------------------
/** Build a NationStats from the four canonical indices (military, economy, stability, population). */
function NS(military: number, economy: number, stability: number, population: number): NationStats {
return { military, economy, stability, population };
}
/** Build a RegionStats from the four canonical indices. */
function RS(military: number, economy: number, stability: number, population: number): RegionStats {
return { military, economy, stability, population };
}
/** A minimal nation: the given id/name/stats/region-key territory, given relations. */
function mkNation(
id: string,
name: string,
stats: NationStats,
territory: string[],
relations: Record<string, RelationStatus> = {},
): Nation {
return { id, name, type: 'major', stats, territory, relations };
}
/**
* A minimal GameState carrying the given nations (keyed by id) and per-region
* stats. Every other required field is at its fresh-game baseline, so a test
* can focus purely on the migration effect.
*/
function mkState(
nations: Record<string, Nation>,
regionStats: Record<string, RegionStats>,
): GameState {
return {
id: 'g1',
presetId: 'test',
presetTitle: 'Test',
playerNationId: Object.keys(nations)[0] ?? 'uk',
turn: 1,
date: '1939-09-01',
nations,
events: [],
pending: [],
version: 1,
unowned: [],
pendingNationOps: [],
markers: [],
regionStats,
wars: [],
trades: [],
embargoes: [],
industry: [],
// (v0.43.0, #65) no sea-zone control on a fresh state.
seaZones: [],
// (v0.44.0, #66) no contested regions on a fresh state.
contested: [],
};
}
// ---------------------------------------------------------------------------
// Kind / scale constants + predicates
// ---------------------------------------------------------------------------
describe('MIGRATION_KINDS / MIGRATION_SCALES', () => {
it('exposes exactly the four kinds and three scales', () => {
expect([...MIGRATION_KINDS]).toEqual(['migration', 'refugees', 'diaspora', 'exodus']);
expect([...MIGRATION_SCALES]).toEqual(['small', 'moderate', 'large']);
});
});
describe('isMigrationKind / isMigrationScale', () => {
it('accepts each known kind and rejects unknown / non-strings', () => {
for (const k of MIGRATION_KINDS) expect(isMigrationKind(k)).toBe(true);
expect(isMigrationKind('immigration')).toBe(false);
expect(isMigrationKind(42)).toBe(false);
expect(isMigrationKind(undefined)).toBe(false);
});
it('accepts each known scale and rejects unknown / non-strings', () => {
for (const s of MIGRATION_SCALES) expect(isMigrationScale(s)).toBe(true);
expect(isMigrationScale('massive')).toBe(false);
expect(isMigrationScale(42)).toBe(false);
});
});
// ---------------------------------------------------------------------------
// Effect tables
// ---------------------------------------------------------------------------
describe('MIGRATION_SOURCE_EFFECTS / MIGRATION_DESTINATION_EFFECTS', () => {
it('every source scale dips exactly population and economy (both negative)', () => {
for (const s of MIGRATION_SCALES) {
const dips = MIGRATION_SOURCE_EFFECTS[s];
expect(Object.keys(dips).sort()).toEqual(['economy', 'population']);
expect(dips.population).toBeLessThan(0);
expect(dips.economy).toBeLessThan(0);
}
});
it('every destination scale gains exactly population and economy (both positive)', () => {
for (const s of MIGRATION_SCALES) {
const gains = MIGRATION_DESTINATION_EFFECTS[s];
expect(Object.keys(gains).sort()).toEqual(['economy', 'population']);
expect(gains.population).toBeGreaterThan(0);
expect(gains.economy).toBeGreaterThan(0);
}
});
it('source loses and destination gains monotonically with scale', () => {
const [small, moderate, large] = MIGRATION_SCALES;
const srcPop = (s: MigrationScale) => MIGRATION_SOURCE_EFFECTS[s].population!;
const dstPop = (s: MigrationScale) => MIGRATION_DESTINATION_EFFECTS[s].population!;
// A larger scale means the source LOSES more: the (negative) dip grows more
// negative as the scale grows, i.e. small > moderate > large.
expect(srcPop(small)).toBeGreaterThan(srcPop(moderate));
expect(srcPop(moderate)).toBeGreaterThan(srcPop(large));
// A larger scale means the destination GAINS more: the (positive) gain
// grows larger as the scale grows, i.e. small < moderate < large.
expect(dstPop(small)).toBeLessThan(dstPop(moderate));
expect(dstPop(moderate)).toBeLessThan(dstPop(large));
});
it('the large-influx stability strain is a small negative dip', () => {
expect(LARGE_INFLUX_STABILITY_DIP).toBeLessThan(0);
});
});
// ---------------------------------------------------------------------------
// validateMigrationOps
// ---------------------------------------------------------------------------
describe('validateMigrationOps', () => {
it('accepts the { ops: [...] } object shape and a bare array', () => {
const op = { kind: 'migration', from: 'a', to: 'b', scale: 'small' };
expect(validateMigrationOps({ ops: [op] })).toEqual([op]);
expect(validateMigrationOps([op])).toEqual([op]);
});
it('drops an op with an unknown / missing kind', () => {
expect(validateMigrationOps([{ kind: 'tsunami', from: 'a', to: 'b', scale: 'small' }])).toEqual(
[],
);
expect(
validateMigrationOps([
{ from: 'a', to: 'b', scale: 'small' },
{ kind: 'migration', from: 'a', to: 'b', scale: 'small' },
]),
).toEqual([{ kind: 'migration', from: 'a', to: 'b', scale: 'small' }]);
});
it('drops an op with an unknown / missing scale', () => {
expect(validateMigrationOps([{ kind: 'migration', from: 'a', to: 'b', scale: 'massive' }])).toEqual(
[],
);
expect(validateMigrationOps([{ kind: 'migration', from: 'a', to: 'b' }])).toEqual([]);
});
it('drops an op with an empty / missing from (the source)', () => {
expect(validateMigrationOps([{ kind: 'migration', from: '', to: 'b', scale: 'small' }])).toEqual(
[],
);
expect(validateMigrationOps([{ kind: 'migration', to: 'b', scale: 'small' }])).toEqual([]);
});
it('requires a non-empty `to` for every kind except exodus', () => {
// non-exodus kind missing `to`: dropped
expect(validateMigrationOps([{ kind: 'migration', from: 'a', scale: 'small' }])).toEqual([]);
expect(validateMigrationOps([{ kind: 'refugees', from: 'a', scale: 'small' }])).toEqual([]);
// exodus without a `to`: kept (an exodus has no destination)
expect(validateMigrationOps([{ kind: 'exodus', from: 'a', scale: 'small' }])).toEqual([
{ kind: 'exodus', from: 'a', scale: 'small' },
]);
});
it('caps `from` / `to` at 200 chars and `detail` at 300, dropping empty detail', () => {
const longFrom = 'f'.repeat(500);
const longDetail = 'd'.repeat(500);
const out = validateMigrationOps([
{ kind: 'migration', from: longFrom, to: 'b', scale: 'small', detail: longDetail },
]);
expect(out).toHaveLength(1);
expect(out[0].from).toHaveLength(200);
expect(out[0].detail).toHaveLength(300);
});
it('a missing / malformed top-level value yields an empty list', () => {
expect(validateMigrationOps(undefined)).toEqual([]);
expect(validateMigrationOps(null)).toEqual([]);
expect(validateMigrationOps('nope')).toEqual([]);
expect(validateMigrationOps({ ops: 'nope' })).toEqual([]);
expect(validateMigrationOps([{ kind: 'migration' }])).toEqual([]);
});
});
// ---------------------------------------------------------------------------
// shiftRelationTowardPositive
// ---------------------------------------------------------------------------
describe('shiftRelationTowardPositive', () => {
function pair(rel: Record<string, RelationStatus>): GameState {
return mkState(
{
a1: mkNation('a1', 'Alpha', NS(50, 50, 50, 50), ['a-r1'], rel),
b2: mkNation('b2', 'Bravo', NS(50, 50, 50, 50), ['b-r1'], rel),
},
{ 'a-r1': RS(50, 50, 50, 50), 'b-r1': RS(50, 50, 50, 50) },
);
}
it('nudges a neutral pair one step toward positive, symmetrically', () => {
const s = pair({ b2: 'neutral', a1: 'neutral' });
shiftRelationTowardPositive(s, 'a1', 'b2', 'ally');
expect(s.nations.a1.relations.b2).toBe('ally');
expect(s.nations.b2.relations.a1).toBe('ally');
});
it('never moves past the cap (migration/diaspora cap at neutral)', () => {
// hostile → rival (one step toward positive, still below the neutral cap)
let s = pair({ b2: 'hostile', a1: 'hostile' });
shiftRelationTowardPositive(s, 'a1', 'b2', 'neutral');
expect(s.nations.a1.relations.b2).toBe('rival');
// rival → neutral (reaches the cap)
s = pair({ b2: 'rival', a1: 'rival' });
shiftRelationTowardPositive(s, 'a1', 'b2', 'neutral');
expect(s.nations.a1.relations.b2).toBe('neutral');
// neutral → stays neutral (at the cap)
s = pair({ b2: 'neutral', a1: 'neutral' });
shiftRelationTowardPositive(s, 'a1', 'b2', 'neutral');
expect(s.nations.a1.relations.b2).toBe('neutral');
// ally → stays ally (more positive than the cap)
s = pair({ b2: 'ally', a1: 'ally' });
shiftRelationTowardPositive(s, 'a1', 'b2', 'neutral');
expect(s.nations.a1.relations.b2).toBe('ally');
});
it('refugees can nudge all the way to ally (cap ally)', () => {
let s = pair({ b2: 'hostile', a1: 'hostile' });
shiftRelationTowardPositive(s, 'a1', 'b2', 'ally');
expect(s.nations.a1.relations.b2).toBe('rival');
s = pair({ b2: 'rival', a1: 'rival' });
shiftRelationTowardPositive(s, 'a1', 'b2', 'ally');
expect(s.nations.a1.relations.b2).toBe('neutral');
s = pair({ b2: 'neutral', a1: 'neutral' });
shiftRelationTowardPositive(s, 'a1', 'b2', 'ally');
expect(s.nations.a1.relations.b2).toBe('ally');
// already ally: no change
s = pair({ b2: 'ally', a1: 'ally' });
shiftRelationTowardPositive(s, 'a1', 'b2', 'ally');
expect(s.nations.a1.relations.b2).toBe('ally');
});
it('a missing relation starts at neutral and nudges toward the cap', () => {
const s = pair({});
shiftRelationTowardPositive(s, 'a1', 'b2', 'ally');
expect(s.nations.a1.relations.b2).toBe('ally');
expect(s.nations.b2.relations.a1).toBe('ally');
});
it('never touches a war relation', () => {
const s = pair({ b2: 'war', a1: 'war' });
shiftRelationTowardPositive(s, 'a1', 'b2', 'ally');
expect(s.nations.a1.relations.b2).toBe('war');
expect(s.nations.b2.relations.a1).toBe('war');
});
it('is a no-op for an unknown nation id or an unknown cap', () => {
const s = pair({ b2: 'hostile', a1: 'hostile' });
shiftRelationTowardPositive(s, 'a1', 'zzz', 'ally'); // zzz absent
expect(s.nations.a1.relations.b2).toBe('hostile');
shiftRelationTowardPositive(s, 'a1', 'b2', 'nope' as RelationStatus); // bad cap
expect(s.nations.a1.relations.b2).toBe('hostile');
});
});
// ---------------------------------------------------------------------------
// applyMigrationOp
// ---------------------------------------------------------------------------
describe('applyMigrationOp', () => {
it('a small migration: source loses pop+eco, destination gains pop+eco, relation unchanged (neutral→neutral)', () => {
const state = mkState(
{
a1: mkNation('a1', 'Alpha', NS(80, 70, 60, 50), ['a-r1']),
b2: mkNation('b2', 'Bravo', NS(40, 30, 50, 60), ['b-r1']),
},
{ 'a-r1': RS(80, 70, 60, 50), 'b-r1': RS(40, 30, 50, 60) },
);
applyMigrationOp(state, { kind: 'migration', from: 'a1', to: 'b2', scale: 'small' });
// source: economy 70→69, population 50→49 (re-derived from its single region)
expect(state.nations.a1.stats).toEqual(NS(80, 69, 60, 49));
// destination: economy 30→31, population 60→61
expect(state.nations.b2.stats).toEqual(NS(40, 31, 50, 61));
// both regions mirrored
expect(state.regionStats['a-r1']).toEqual(RS(80, 69, 60, 49));
expect(state.regionStats['b-r1']).toEqual(RS(40, 31, 50, 61));
// a neutral pair is already at the neutral cap: no relation change
expect(state.nations.a1.relations.b2 ?? 'neutral').toBe('neutral');
expect(state.nations.b2.relations.a1 ?? 'neutral').toBe('neutral');
});
it('resolves `from` / `to` by name (not just id)', () => {
const state = mkState(
{
a1: mkNation('a1', 'Alpha', NS(80, 70, 60, 50), ['a-r1']),
b2: mkNation('b2', 'Bravo', NS(40, 30, 50, 60), ['b-r1']),
},
{ 'a-r1': RS(80, 70, 60, 50), 'b-r1': RS(40, 30, 50, 60) },
);
applyMigrationOp(state, { kind: 'migration', from: 'Alpha', to: 'Bravo', scale: 'moderate' });
// moderate: source pop -2 / eco -2; destination pop +2 / eco +2
expect(state.nations.a1.stats).toEqual(NS(80, 68, 60, 48));
expect(state.nations.b2.stats).toEqual(NS(40, 32, 50, 62));
});
it('a large influx strains the destination stability by 2', () => {
const state = mkState(
{
a1: mkNation('a1', 'Alpha', NS(80, 70, 60, 50), ['a-r1']),
b2: mkNation('b2', 'Bravo', NS(40, 30, 50, 60), ['b-r1']),
},
{ 'a-r1': RS(80, 70, 60, 50), 'b-r1': RS(40, 30, 50, 60) },
);
applyMigrationOp(state, { kind: 'refugees', from: 'a1', to: 'b2', scale: 'large' });
// destination: eco 30→33, pop 60→63, stability 50→48 (large influx strain)
expect(state.nations.b2.stats).toEqual(NS(40, 33, 48, 63));
expect(state.regionStats['b-r1']).toEqual(RS(40, 33, 48, 63));
// source: eco 70→67, pop 50→46
expect(state.nations.a1.stats).toEqual(NS(80, 67, 60, 46));
});
it('a refugees flow nudges the relation toward ally (cap ally); migration/diaspora stop at neutral', () => {
const mk = (rel: RelationStatus) =>
mkState(
{
a1: mkNation('a1', 'Alpha', NS(80, 70, 60, 50), ['a-r1'], { b2: rel }),
b2: mkNation('b2', 'Bravo', NS(40, 30, 50, 60), ['b-r1'], { a1: rel }),
},
{ 'a-r1': RS(80, 70, 60, 50), 'b-r1': RS(40, 30, 50, 60) },
);
// refugees: hostile → rival
let s = mk('hostile');
applyMigrationOp(s, { kind: 'refugees', from: 'a1', to: 'b2', scale: 'small' });
expect(s.nations.a1.relations.b2).toBe('rival');
// migration: hostile → rival (capped at neutral, one step only)
s = mk('hostile');
applyMigrationOp(s, { kind: 'migration', from: 'a1', to: 'b2', scale: 'small' });
expect(s.nations.a1.relations.b2).toBe('rival');
// migration: rival → neutral (reaches cap)
s = mk('rival');
applyMigrationOp(s, { kind: 'diaspora', from: 'a1', to: 'b2', scale: 'small' });
expect(s.nations.a1.relations.b2).toBe('neutral');
// refugees: neutral → ally
s = mk('neutral');
applyMigrationOp(s, { kind: 'refugees', from: 'a1', to: 'b2', scale: 'small' });
expect(s.nations.a1.relations.b2).toBe('ally');
});
it('never nudges a warring pair (a war is left untouched)', () => {
const state = mkState(
{
a1: mkNation('a1', 'Alpha', NS(80, 70, 60, 50), ['a-r1'], { b2: 'war' }),
b2: mkNation('b2', 'Bravo', NS(40, 30, 50, 60), ['b-r1'], { a1: 'war' }),
},
{ 'a-r1': RS(80, 70, 60, 50), 'b-r1': RS(40, 30, 50, 60) },
);
applyMigrationOp(state, { kind: 'refugees', from: 'a1', to: 'b2', scale: 'large' });
expect(state.nations.a1.relations.b2).toBe('war');
expect(state.nations.b2.relations.a1).toBe('war');
// the stat effects still apply (a war does not block population movement)
expect(state.nations.a1.stats).toEqual(NS(80, 67, 60, 46));
expect(state.nations.b2.stats).toEqual(NS(40, 33, 48, 63));
});
it('an exodus only affects the source: no destination, no relation nudge', () => {
const state = mkState(
{
a1: mkNation('a1', 'Alpha', NS(80, 70, 60, 50), ['a-r1'], { b2: 'rival' }),
b2: mkNation('b2', 'Bravo', NS(40, 30, 50, 60), ['b-r1'], { a1: 'rival' }),
},
{ 'a-r1': RS(80, 70, 60, 50), 'b-r1': RS(40, 30, 50, 60) },
);
applyMigrationOp(state, { kind: 'exodus', from: 'a1', scale: 'small' });
// source dips
expect(state.nations.a1.stats).toEqual(NS(80, 69, 60, 49));
// destination untouched
expect(state.nations.b2.stats).toEqual(NS(40, 30, 50, 60));
expect(state.regionStats['b-r1']).toEqual(RS(40, 30, 50, 60));
// no relation nudge
expect(state.nations.a1.relations.b2).toBe('rival');
});
it('a self-flow (from === to) is dropped entirely', () => {
const state = mkState(
{ a1: mkNation('a1', 'Alpha', NS(80, 70, 60, 50), ['a-r1']) },
{ 'a-r1': RS(80, 70, 60, 50) },
);
applyMigrationOp(state, { kind: 'migration', from: 'a1', to: 'a1', scale: 'large' });
// no change at all
expect(state.nations.a1.stats).toEqual(NS(80, 70, 60, 50));
expect(state.regionStats['a-r1']).toEqual(RS(80, 70, 60, 50));
});
it('an unknown or ambiguous source / destination drops the op', () => {
const base = () =>
mkState(
{
a1: mkNation('a1', 'Alpha', NS(80, 70, 60, 50), ['a-r1']),
b2: mkNation('b2', 'Bravo', NS(40, 30, 50, 60), ['b-r1']),
},
{ 'a-r1': RS(80, 70, 60, 50), 'b-r1': RS(40, 30, 50, 60) },
);
// unknown source
let s = base();
applyMigrationOp(s, { kind: 'migration', from: 'zzz', to: 'b2', scale: 'small' });
expect(s.nations.b2.stats).toEqual(NS(40, 30, 50, 60));
// unknown destination
s = base();
applyMigrationOp(s, { kind: 'migration', from: 'a1', to: 'zzz', scale: 'small' });
expect(s.nations.a1.stats).toEqual(NS(80, 70, 60, 50));
// ambiguous source (two nations share the name)
const amb = mkState(
{
a1: mkNation('a1', 'Twin', NS(80, 70, 60, 50), ['a-r1']),
a2: mkNation('a2', 'Twin', NS(20, 20, 20, 20), ['a-r2']),
b2: mkNation('b2', 'Bravo', NS(40, 30, 50, 60), ['b-r1']),
},
{ 'a-r1': RS(80, 70, 60, 50), 'a-r2': RS(20, 20, 20, 20), 'b-r1': RS(40, 30, 50, 60) },
);
applyMigrationOp(amb, { kind: 'migration', from: 'Twin', to: 'Bravo', scale: 'small' });
expect(amb.nations.b2.stats).toEqual(NS(40, 30, 50, 60));
});
it('a 0-region nation keeps its directly-mutated stats (no re-derive)', () => {
const state = mkState(
{
// a1 owns no regions — its stats are maintained directly, not derived
a1: mkNation('a1', 'Alpha', NS(80, 70, 60, 50), []),
b2: mkNation('b2', 'Bravo', NS(40, 30, 50, 60), ['b-r1']),
},
{ 'b-r1': RS(40, 30, 50, 60) },
);
applyMigrationOp(state, { kind: 'migration', from: 'a1', to: 'b2', scale: 'moderate' });
// source (0 regions) keeps the direct dip: eco 70→68, pop 50→48
expect(state.nations.a1.stats).toEqual(NS(80, 68, 60, 48));
// destination re-derived from its region
expect(state.nations.b2.stats).toEqual(NS(40, 32, 50, 62));
});
it('never moves territory (sole ownership untouched)', () => {
const state = mkState(
{
a1: mkNation('a1', 'Alpha', NS(80, 70, 60, 50), ['a-r1']),
b2: mkNation('b2', 'Bravo', NS(40, 30, 50, 60), ['b-r1']),
},
{ 'a-r1': RS(80, 70, 60, 50), 'b-r1': RS(40, 30, 50, 60) },
);
applyMigrationOp(state, { kind: 'refugees', from: 'a1', to: 'b2', scale: 'large' });
expect(state.nations.a1.territory).toEqual(['a-r1']);
expect(state.nations.b2.territory).toEqual(['b-r1']);
});
it('clamps affected stats to 0 and 100 (a source at the floor, a destination at the ceiling)', () => {
const state = mkState(
{
// a1 at the population / economy floor
a1: mkNation('a1', 'Alpha', NS(5, 3, 50, 1), ['a-r1']),
// b2 near the ceiling: a large gain (+3) pushes it past 100
b2: mkNation('b2', 'Bravo', NS(90, 98, 50, 98), ['b-r1']),
},
{ 'a-r1': RS(5, 3, 50, 1), 'b-r1': RS(90, 98, 50, 98) },
);
applyMigrationOp(state, { kind: 'migration', from: 'a1', to: 'b2', scale: 'large' });
// source clamps at 0 (pop 1-4→0, eco 3-3→0)
expect(state.nations.a1.stats.population).toBe(0);
expect(state.nations.a1.stats.economy).toBe(0);
// destination gains but clamps at 100 (pop 98+3→100, eco 98+3→100)
expect(state.nations.b2.stats.population).toBe(100);
expect(state.nations.b2.stats.economy).toBe(100);
});
});
// ---------------------------------------------------------------------------
// The Ability object contract
// ---------------------------------------------------------------------------
describe('migration ability', () => {
it('owns the "migration" field; default() is a fresh empty { ops: [] }', () => {
expect(migration.field).toBe('migration');
expect(migration.default()).toEqual({ ops: [] });
expect(migration.default()).not.toBe(migration.default());
});
it('default() is not meaningful; a populated value is', () => {
expect(migration.isMeaningful(migration.default())).toBe(false);
expect(
migration.isMeaningful({ ops: [{ kind: 'exodus', from: 'a1', scale: 'small' }] }),
).toBe(true);
});
it('validate() wraps the bare-list validator into the { ops } shape', () => {
expect(
migration.validate([{ kind: 'migration', from: 'a1', to: 'b2', scale: 'small' }]),
).toEqual({ ops: [{ kind: 'migration', from: 'a1', to: 'b2', scale: 'small' }] });
expect(migration.validate(undefined)).toEqual({ ops: [] });
});
it('the stub value equals default() (the stub never proposes a migration)', () => {
expect(migration.stub()).toEqual({ ops: [] });
});
it('payload() is always empty (turn-transient — no durable state to show)', () => {
expect(migration.payload({} as never)).toEqual({});
});
it('stateFields is undefined (the layer owns no durable GameState field)', () => {
expect(migration.stateFields).toBeUndefined();
});
it('apply() runs each validated op against the world (no throw on a bad ref)', () => {
const state = mkState(
{
a1: mkNation('a1', 'Alpha', NS(80, 70, 60, 50), ['a-r1']),
b2: mkNation('b2', 'Bravo', NS(40, 30, 50, 60), ['b-r1']),
},
{ 'a-r1': RS(80, 70, 60, 50), 'b-r1': RS(40, 30, 50, 60) },
);
const ctx = { previous: state, actingTurn: state.turn };
migration.apply(
state,
{
ops: [
{ kind: 'migration', from: 'a1', to: 'b2', scale: 'small' },
// an unknown source — must be dropped, not throw
{ kind: 'refugees', from: 'ghost', to: 'b2', scale: 'small' },
],
},
ctx,
);
expect(state.nations.a1.stats).toEqual(NS(80, 69, 60, 49));
expect(state.nations.b2.stats).toEqual(NS(40, 31, 50, 61));
});
});
+325
View File
@@ -0,0 +1,325 @@
// The MIGRATION & REFUGEES ability (v0.42.0, #64) as a modular LLM-ability
// (v0.40.0, #67). People moving between nations each turn: ordinary migration,
// refugee flows (fleeing a war or disaster), a spreading diaspora, and an
// exodus (people leaving with no destination). Unlike most other abilities this
// one is **turn-transient**: it owns NO `GameState` field (no durable list, no
// `db.ts` change) — exactly like the hybrid and disasters layers. Each op
// carries a `kind`, a source `from` (the nation people leave), a destination
// `to` (required for every kind except `exodus`), and a `scale` (small /
// moderate / large). The engine applies a DETERMINISTIC effect chosen from the
// per-`scale` tables below (no hidden randomness — the LLM chooses the kind and
// scale, the tables decide the magnitude): the source LOSES a small amount of
// population and economy, the destination GAINS a small amount of population and
// economy (a `large` influx additionally strains the destination's stability),
// both clamped to 0–100, mirrored to each side's regions (`regionStats`), and
// each side's derived `stats` re-derived afterwards (the same 0-region /
// no-entry guards as hybrid / economy / disasters, so a 0-region nation keeps
// its directly-mutated value and the effect persists to the next turn). The
// from↔to relation then moves one step toward the positive end of the
// ally/neutral/rival/hostile ladder (`shiftRelationTowardPositive`) — capped at
// `ally` for `refugees` (hosting refugees builds the strongest goodwill),
// `neutral` for `migration` / `diaspora` (milder ties), and not at all for
// `exodus`; a `war` relation is never touched (the nudge neither fabricates nor
// escalates a war). Both `from` and `to` are resolved by the shared
// `resolveNationRef` (id first, then a case-insensitive unique name); an
// unknown / ambiguous ref, a missing `to` (for a non-`exodus` kind), or a
// self-flow (`from` and `to` the same nation) drops the whole op. It never
// moves territory (sole ownership is untouched).
import { clampStat, deriveNationStats } from '../../shared/protocol';
import type { MigrationOp, MigrationScale, MigrationKind } from '../../shared/protocol';
import type { GameState, Nation, RelationStatus, StatKey } from '../../shared/types';
import { resolveNationRef, str } from './shared';
import type { Ability } from './types';
/** The four kinds of population flow a turn can declare (v0.42.0, #64). */
export const MIGRATION_KINDS: readonly MigrationKind[] = [
'migration',
'refugees',
'diaspora',
'exodus',
];
/** The three flow sizes a migration op can carry (v0.42.0, #64). */
export const MIGRATION_SCALES: readonly MigrationScale[] = ['small', 'moderate', 'large'];
const VALID_KINDS = new Set<string>(MIGRATION_KINDS);
const VALID_SCALES = new Set<string>(MIGRATION_SCALES);
/** True when `k` is one of the four known migration kinds (v0.42.0, #64). */
export function isMigrationKind(k: unknown): k is MigrationKind {
return typeof k === 'string' && VALID_KINDS.has(k);
}
/** True when `s` is one of the three known migration scales (v0.42.0, #64). */
export function isMigrationScale(s: unknown): s is MigrationScale {
return typeof s === 'string' && VALID_SCALES.has(s);
}
/**
* (v0.42.0, #64) The DETERMINISTIC per-`scale` stat dip applied to the SOURCE
* nation of a migration flow (the nation people leave). Each scale maps to a
* small set of signed (negative) stat deltas: the source loses population and
* economy. No hidden randomness — the LLM picks the scale, the table decides
* the magnitude. Military and stability are untouched by the source dip.
*/
export const MIGRATION_SOURCE_EFFECTS: Record<MigrationScale, Partial<Record<StatKey, number>>> = {
small: { population: -1, economy: -1 },
moderate: { population: -2, economy: -2 },
large: { population: -4, economy: -3 },
};
/**
* (v0.42.0, #64) The DETERMINISTIC per-`scale` stat gain applied to the
* DESTINATION nation of a migration flow (the nation people arrive in). Each
* scale maps to a small set of signed (positive) stat deltas: the destination
* gains population and economy. No hidden randomness. Military and stability
* are untouched by the base gain (the `large`-scale stability strain is applied
* separately, see {@link LARGE_INFLUX_STABILITY_DIP}).
*/
export const MIGRATION_DESTINATION_EFFECTS: Record<MigrationScale, Partial<Record<StatKey, number>>> =
{
small: { population: 1, economy: 1 },
moderate: { population: 2, economy: 2 },
large: { population: 3, economy: 3 },
};
/**
* (v0.42.0, #64) The extra STABILITY dip applied to the destination of a
* `large`-scale influx only — a big population surge strains a society even as
* it grows. Added on top of the base destination gain.
*/
export const LARGE_INFLUX_STABILITY_DIP = -2;
/**
* The positive-relations ladder, strongest (most positive) to weakest
* (least positive) — the same four non-war statuses, in the order a relation
* moves when it is nudged TOWARD the positive end. A missing relation is
* treated as `neutral`; `war` is never touched (a war is its own entity — a
* population flow neither fabricates nor escalates one). The `cap` in
* {@link shiftRelationTowardPositive} is a member of this array.
*/
const POSITIVE_ORDER: RelationStatus[] = ['ally', 'neutral', 'rival', 'hostile'];
/**
* (v0.42.0, #64) Nudge the bilateral relation between nations `a` and `b`
* ONE step toward the POSITIVE end (toward `ally`) of the
* {@link POSITIVE_ORDER} ladder, applied symmetrically to both directions, but
* never past the given `cap`. A missing relation starts at `neutral`; a `war`
* relation is never touched (a population flow neither fabricates nor
* escalates a war — a warring pair is left exactly as it is). Mutates `state`
* in place (the caller passes a clone — applyTurnResult does). Never throws.
*
* `cap` is the most-positive status the nudge may reach:
* - `refugees` → `ally` (hosting refugees builds the strongest goodwill)
* - `migration` / `diaspora` → `neutral` (milder ties)
* - `exodus` → no nudge at all
*/
export function shiftRelationTowardPositive(
state: GameState,
a: string,
b: string,
cap: RelationStatus,
): void {
const na = state.nations[a];
const nb = state.nations[b];
if (!na || !nb) return;
const capIdx = POSITIVE_ORDER.indexOf(cap);
if (capIdx === -1) return; // unknown cap: no-op (defensive)
const step = (cur: RelationStatus | undefined): RelationStatus | null => {
if (cur === 'war') return null; // never touch a war relation
const s = cur ?? 'neutral'; // a missing relation is neutral
const i = POSITIVE_ORDER.indexOf(s);
if (i === -1) return 'neutral'; // defensive: unknown status
if (i <= capIdx) return s; // already at or more positive than the cap: no change
return POSITIVE_ORDER[i - 1]; // one step toward the positive end
};
const stepA = step(na.relations[b]);
if (stepA !== null) na.relations[b] = stepA;
const stepB = step(nb.relations[a]);
if (stepB !== null) nb.relations[a] = stepB;
}
/**
* (v0.42.0, #64) Validate the raw `migration` field of a turn into a safe
* list of {@link MigrationOp}s. Defensive like the rest of the parser — never
* throws. The raw value may be the object `{ ops: [...] }` (the TurnResult
* shape) or a bare array (be lenient about either). Each op needs a known
* `kind` (one of {@link MIGRATION_KINDS}), a known `scale` (one of
* {@link MIGRATION_SCALES}), a non-empty `from` (the source nation, capped at
* 200 chars), and — for every kind except `exodus` — a non-empty `to`
* (the destination nation, capped at 200 chars); a non-empty `detail` is capped
* at 300 chars. An op with an unknown / missing `kind`, an unknown / missing
* `scale`, an empty `from`, or (for a non-`exodus` kind) an empty `to` is
* dropped. Resolution of `from` / `to` to concrete nation ids happens at apply
* time (`applyMigrationOp`), not here. A missing / malformed top-level value
* yields `{ ops: [] }`.
*/
export function validateMigrationOps(raw: unknown): MigrationOp[] {
let list: unknown[] | null = null;
if (Array.isArray(raw)) {
list = raw;
} else if (raw && typeof raw === 'object') {
const inner = (raw as Record<string, unknown>).ops;
if (Array.isArray(inner)) list = inner;
}
if (!list) return [];
const out: MigrationOp[] = [];
for (const e of list) {
if (!e || typeof e !== 'object') continue;
const o = e as Record<string, unknown>;
if (!isMigrationKind(o.kind)) continue; // unknown / missing kind: drop
if (!isMigrationScale(o.scale)) continue; // unknown / missing scale: drop
const from = str(o.from, 200);
if (!from) continue; // empty / missing source: drop
const detail = str(o.detail, 300);
if (o.kind === 'exodus') {
// an exodus has no destination — `to` is optional (and ignored)
out.push({
kind: o.kind,
from,
scale: o.scale,
...(detail ? { detail } : {}),
});
} else {
const to = str(o.to, 200);
if (!to) continue; // non-exodus kind needs a destination: drop
out.push({
kind: o.kind,
from,
to,
scale: o.scale,
...(detail ? { detail } : {}),
});
}
}
return out;
}
/**
* Apply a set of signed stat `dips` to a nation's `stats` AND to every region
* it owns that has a `regionStats` entry (clamped to 0–100), then re-derive
* the nation's aggregate `stats` as the area×population-weighted median of its
* regions — the same 0-region / no-entry guards as the hybrid / economy /
* disasters layers, so a 0-region nation keeps its directly-mutated value and
* the effect persists to the next turn. Mutates in place; never throws.
*/
function applyNationDips(
nation: Nation,
dips: Partial<Record<StatKey, number>>,
regionStats: GameState['regionStats'],
geoOf?: (key: string) => { area: number; population: number } | undefined,
): void {
(Object.keys(dips) as StatKey[]).forEach((k) => {
const d = dips[k];
if (typeof d === 'number') nation.stats[k] = clampStat(nation.stats[k] + d);
});
for (const key of nation.territory) {
const rs = regionStats[key];
if (!rs) continue; // a key with no entry is skipped
(Object.keys(dips) as StatKey[]).forEach((k) => {
const d = dips[k];
if (typeof d === 'number') rs[k] = clampStat(rs[k] + d);
});
}
// Re-derive the nation's aggregate stats so the effect persists (the main
// recompute ran earlier this turn; without this the change would be washed
// out next turn). A nation with no regionStats entry keeps its
// directly-mutated `stats`.
if (nation.territory.length > 0 && nation.territory.some((k) => regionStats[k])) {
nation.stats = deriveNationStats(nation.territory, regionStats, geoOf);
}
}
/**
* (v0.42.0, #64) Apply ONE migration / refugee op to the (cloned) `next` state,
* mutating it in place and never throwing. Resolution order:
* 1. `from` must resolve to a nation (id first, then a unique name); an
* unknown / ambiguous source drops the op.
* 2. For every kind except `exodus`, `to` must resolve to a nation distinct
* from `from` (a missing / unknown / ambiguous destination, or a
* self-flow, drops the op); `exodus` has no destination and skips this.
* Then the deterministic per-`scale` effects from
* {@link MIGRATION_SOURCE_EFFECTS} / {@link MIGRATION_DESTINATION_EFFECTS}
* are applied:
* - the SOURCE nation loses population and economy (all four kinds,
* including `exodus`) — for a non-`exodus` op this is applied only AFTER
* the destination is validated, so a self-flow or a bad destination drops
* the op entirely and never touches the source;
* - for a non-`exodus` kind the DESTINATION gains population and economy,
* and a `large` influx additionally strains its stability by
* {@link LARGE_INFLUX_STABILITY_DIP};
* - each affected nation's derived `stats` are re-derived afterwards (the
* same 0-region / no-entry guards, so the effect persists);
* - for a non-`exodus` kind the from↔to relation moves one step toward the
* positive end of the ladder (cap `ally` for `refugees`, `neutral` for
* `migration` / `diaspora`; a `war` relation is left untouched).
* The op never moves territory (sole ownership is untouched) and never creates
* or escalates a war.
*/
export function applyMigrationOp(
next: GameState,
op: MigrationOp,
geoOf?: (key: string) => { area: number; population: number } | undefined,
): void {
const from = resolveNationRef(next, op.from);
if (from === null) return; // unknown / ambiguous source: drop
const source = next.nations[from];
if (!source) return; // defensive: resolved id has no nation record
if (op.kind === 'exodus') {
// An exodus has no destination: the source loses population and economy
// and that is all (no gain, no relation nudge).
applyNationDips(source, MIGRATION_SOURCE_EFFECTS[op.scale], next.regionStats, geoOf);
return;
}
// Non-exodus: resolve the destination FIRST and drop the WHOLE op (including
// the source dip) when it is missing / unknown / ambiguous or a self-flow —
// so a self-flow or a bad destination never touches the source.
const to = op.to;
if (!to) return; // defensive: a non-exodus op should always have a `to`
const destId = resolveNationRef(next, to);
if (destId === null || destId === from) return; // unknown / self destination: drop
const dest = next.nations[destId];
if (!dest) return; // defensive
// The source loses population and economy (every non-exodus kind reaches
// here; the exodus path already applied its source dip and returned).
applyNationDips(source, MIGRATION_SOURCE_EFFECTS[op.scale], next.regionStats, geoOf);
// The destination gains population and economy; a large influx also strains
// its stability.
const destDips: Partial<Record<StatKey, number>> = { ...MIGRATION_DESTINATION_EFFECTS[op.scale] };
if (op.scale === 'large') {
destDips.stability = (destDips.stability ?? 0) + LARGE_INFLUX_STABILITY_DIP;
}
applyNationDips(dest, destDips, next.regionStats, geoOf);
// The from↔to relation moves one step toward the positive end, capped by
// kind (a `war` relation is left untouched by shiftRelationTowardPositive).
const cap: RelationStatus = op.kind === 'refugees' ? 'ally' : 'neutral';
shiftRelationTowardPositive(next, from, destId, cap);
}
export const migration: Ability<'migration'> = {
field: 'migration',
default: () => ({ ops: [] }),
// The low-level validator returns a bare list; the field's shape is the
// `{ ops }` object (mirrors the historical TurnResult shape).
validate: (raw) => ({ ops: validateMigrationOps(raw) }),
apply: (state, data, ctx) => {
for (const op of data.ops) {
applyMigrationOp(state, op, ctx.geoOf);
}
},
schemaLine: () =>
' "migration": {"ops":[{"kind":"<migration|refugees|diaspora|exodus>","from":"<nation id or name>","to":"<nation id or name>","scale":"<small|moderate|large>","detail":"<short detail>"}]},',
constraint: () =>
'- Migration & refugees ("migration.ops") are people moving between nations this turn: a "kind" ("migration", "refugees", "diaspora", or "exodus"), a "from" (the source nation — id or name), a "to" (the destination nation — required for every kind except "exodus", which has no destination), and a "scale" (small / moderate / large). The engine applies a DETERMINISTIC effect (no hidden randomness): the source LOSES a small amount of population and economy, the destination GAINS a small amount of population and economy (a "large" influx additionally strains the destination\'s stability by 2), and the from↔to relation moves one step toward the positive end of the ally/neutral/rival/hostile ladder — capped at "ally" for "refugees" (hosting refugees builds the strongest goodwill), capped at "neutral" for "migration"/"diaspora" (milder ties), and not at all for "exodus"; the nudge never creates or escalates a "war" (a warring pair is left untouched). The layer is turn-transient (no memory): a continuing flow is simply RE-DECLARED each turn it persists. It never moves borders — sole ownership is untouched. Propose at most 1-2 per turn and narrate each one in "events" (a "social" or "diplomatic" event).',
isMeaningful: (data) => data.ops.length > 0,
stub: () => ({ ops: [] }),
// The layer is turn-transient — it contributes nothing to the user payload
// (no durable state to show the model), so the payload is always empty.
payload: () => ({}),
};
+85 -11
View File
@@ -12,7 +12,7 @@
// by the disasters feature (its payload is always empty). // by the disasters feature (its payload is always empty).
// //
// 2. REGISTRY CONTRACT — the ABILITIES registry is the canonical ordered // 2. REGISTRY CONTRACT — the ABILITIES registry is the canonical ordered
// list of the 9 abilities; each ability's default() equals the canonical // list of the 12 abilities; each ability's default() equals the canonical
// TurnResult default for its field, is a FRESH value (never a shared // TurnResult default for its field, is a FRESH value (never a shared
// reference), its default is not "meaningful" while a populated value is, // reference), its default is not "meaningful" while a populated value is,
// and the registry composes (a hypothetical extra ability can be appended // and the registry composes (a hypothetical extra ability can be appended
@@ -31,6 +31,7 @@ import {
activeWarPairs, activeWarPairs,
applyDisasterEvent, applyDisasterEvent,
applyIndustryEffects, applyIndustryEffects,
applyMigrationOp,
atWar, atWar,
buildSystemPrompt, buildSystemPrompt,
buildUserPrompt, buildUserPrompt,
@@ -44,10 +45,18 @@ import {
isDisasterType, isDisasterType,
isHybridOpType, isHybridOpType,
isIndustryType, isIndustryType,
isMigrationKind,
isMigrationScale,
LARGE_INFLUX_STABILITY_DIP,
MIGRATION_DESTINATION_EFFECTS,
MIGRATION_KINDS,
MIGRATION_SCALES,
MIGRATION_SOURCE_EFFECTS,
NEW_NATION_STATS, NEW_NATION_STATS,
resolveNationRef, resolveNationRef,
resolveRegionKey, resolveRegionKey,
shiftRelationTowardHostile, shiftRelationTowardHostile,
shiftRelationTowardPositive,
syncWarRelations, syncWarRelations,
validateDisasterEvents, validateDisasterEvents,
validateEconomyOps, validateEconomyOps,
@@ -55,9 +64,24 @@ import {
validateIdeologyOps, validateIdeologyOps,
validateIndustryOps, validateIndustryOps,
validateLeaderOps, validateLeaderOps,
validateMigrationOps,
validateNuclearOps, validateNuclearOps,
validateTakeovers, validateTakeovers,
validateWarOps, validateWarOps,
validateSeaOps,
applySeaControl,
applySeaZoneBonuses,
SEA_ZONE_BONUS,
SEA_ZONES,
SEA_ZONE_IDS,
isSeaZoneId,
seaZoneName,
// contested (v0.44.0, #66)
validateContestedOps,
applyContested,
CONTESTED_FILL,
CONTESTED_STROKE,
contestedTooltipLabel,
} from '../engine'; } from '../engine';
import { createPresetStore } from '../presets'; import { createPresetStore } from '../presets';
import { ABILITIES } from './index'; import { ABILITIES } from './index';
@@ -71,9 +95,10 @@ import type {
RegionResources, RegionResources,
RelationStatus, RelationStatus,
RoundItem, RoundItem,
SeaZoneClaim,
TradeAgreement, TradeAgreement,
} from '../../shared/types'; } from '../../shared/types';
import type { MarkerInfo, TurnResult, WarInfo } from '../../shared/protocol'; import type { ContestedRegion, MarkerInfo, TurnResult, WarInfo } from '../../shared/protocol';
const here = path.dirname(fileURLToPath(import.meta.url)); const here = path.dirname(fileURLToPath(import.meta.url));
const goldensDir = path.join(here, 'goldens'); const goldensDir = path.join(here, 'goldens');
@@ -144,6 +169,10 @@ const state: GameState = {
trades: [], trades: [],
embargoes: [], embargoes: [],
industry: [], industry: [],
// (v0.43.0, #65) no sea-zone control on a fresh state.
seaZones: [],
// (v0.44.0, #66) no contested regions on a fresh state.
contested: [],
}; };
// --- buildUserPrompt arguments: every optional branch exercised. --- // --- buildUserPrompt arguments: every optional branch exercised. ---
@@ -180,6 +209,11 @@ const nationResources: Record<string, RegionResources> = {
}; };
const industryProjects: IndustryProject[] = [{ regionKey: 'a-r1', type: 'industry' }]; const industryProjects: IndustryProject[] = [{ regionKey: 'a-r1', type: 'industry' }];
const nuclear: Record<string, boolean> = { a1: true, b2: false, c3: false }; const nuclear: Record<string, boolean> = { a1: true, b2: false, c3: false };
const seaZones: SeaZoneClaim[] = [];
// (v0.44.0, #66) a non-empty contested sample so the golden's user payload
// includes the `contested` key (region key + party NAMES, resolved from the
// state's nations). `b-r1` is owned by b2; the parties are a1 + b2.
const contested: ContestedRegion[] = [{ regionKey: 'b-r1', parties: ['a1', 'b2'] }];
/** /**
* Assert the current prompt output is byte-identical to the committed golden — * Assert the current prompt output is byte-identical to the committed golden —
@@ -217,6 +251,9 @@ function fullDefaultTurn(): TurnResult {
leaders: { changes: [] }, leaders: { changes: [] },
ideology: { changes: [] }, ideology: { changes: [] },
disasters: { events: [] }, disasters: { events: [] },
migration: { ops: [] },
sea: { control: [] },
contested: { open: [], resolve: [] },
markers: { add: [], remove: [] }, markers: { add: [], remove: [] },
}; };
} }
@@ -242,11 +279,17 @@ function meaningfulFor(field: AbilityField): TurnResult[AbilityField] {
return { changes: [{ target: 'a1', to: 'democracy' }] }; return { changes: [{ target: 'a1', to: 'democracy' }] };
case 'disasters': case 'disasters':
return { events: [{ type: 'earthquake', target: 'a1', severity: 'minor' }] }; return { events: [{ type: 'earthquake', target: 'a1', severity: 'minor' }] };
case 'migration':
return { ops: [{ kind: 'migration', from: 'a1', to: 'b2', scale: 'small' }] };
case 'sea':
return { control: [{ zone: 'pacific', by: 'a1' }] };
case 'contested':
return { open: [{ regionKey: 'b-r1', parties: ['a1', 'b2'] }], resolve: [] };
} }
} }
describe('ABILITIES registry (v0.40.0, #67)', () => { describe('ABILITIES registry (v0.40.0, #67)', () => {
it('is the canonical 9-ability order (takeovers → disasters)', () => { it('is the canonical 12-ability order (takeovers → contested)', () => {
expect(ABILITIES.map((a) => a.field)).toEqual([ expect(ABILITIES.map((a) => a.field)).toEqual([
'takeovers', 'takeovers',
'wars', 'wars',
@@ -257,13 +300,16 @@ describe('ABILITIES registry (v0.40.0, #67)', () => {
'leaders', 'leaders',
'ideology', 'ideology',
'disasters', 'disasters',
'migration',
'sea',
'contested',
]); ]);
}); });
it('lists 9 distinct fields, each a key of TurnResult', () => { it('lists 12 distinct fields, each a key of TurnResult', () => {
const fields = ABILITIES.map((a) => a.field); const fields = ABILITIES.map((a) => a.field);
expect(fields).toHaveLength(9); expect(fields).toHaveLength(12);
expect(new Set(fields).size).toBe(9); expect(new Set(fields).size).toBe(12);
const all = fullDefaultTurn(); const all = fullDefaultTurn();
for (const f of fields) expect(f in all).toBe(true); for (const f of fields) expect(f in all).toBe(true);
}); });
@@ -293,6 +339,8 @@ describe('ABILITIES registry (v0.40.0, #67)', () => {
nationResources, nationResources,
industryProjects, industryProjects,
nuclear, nuclear,
seaZones,
contested,
), ),
); );
}); });
@@ -322,13 +370,13 @@ describe('ABILITIES registry (v0.40.0, #67)', () => {
it('declares exactly the durable GameState fields the db migration must default', () => { it('declares exactly the durable GameState fields the db migration must default', () => {
const owned: string[] = []; const owned: string[] = [];
for (const a of ABILITIES) if (a.stateFields) owned.push(...a.stateFields); for (const a of ABILITIES) if (a.stateFields) owned.push(...a.stateFields);
expect([...owned].sort()).toEqual(['embargoes', 'industry', 'trades', 'wars']); expect([...owned].sort()).toEqual(['contested', 'embargoes', 'industry', 'seaZones', 'trades', 'wars']);
}); });
it('composes: a hypothetical extra ability can be appended and every uniform loop still runs', () => { it('composes: a hypothetical extra ability can be appended and every uniform loop still runs', () => {
// The registry is a plain ordered array the engine iterates uniformly. A // The registry is a plain ordered array the engine iterates uniformly. A
// structural (field-name-agnostic) loop over the abilities — schema line, // structural (field-name-agnostic) loop over the abilities — schema line,
// constraint bullet — must keep working when a 10th ability is appended. // constraint bullet — must keep working when a 12th ability is appended.
// This documents the extension point without widening the closed // This documents the extension point without widening the closed
// AbilityField union. // AbilityField union.
interface Loopable { interface Loopable {
@@ -347,9 +395,9 @@ describe('ABILITIES registry (v0.40.0, #67)', () => {
'custom', 'custom',
]); ]);
// every uniform loop runs over all N abilities, the appended one included: // every uniform loop runs over all N abilities, the appended one included:
expect(extended.map((a) => a.schemaLine())).toHaveLength(10); expect(extended.map((a) => a.schemaLine())).toHaveLength(13);
expect(extended.map((a) => a.constraint())).toHaveLength(10); expect(extended.map((a) => a.constraint())).toHaveLength(13);
expect(extended[9].schemaLine()).toBe(' "custom": [],'); expect(extended[12].schemaLine()).toBe(' "custom": [],');
}); });
it('the engine still re-exports every name its callers import from it', () => { it('the engine still re-exports every name its callers import from it', () => {
@@ -388,6 +436,32 @@ describe('ABILITIES registry (v0.40.0, #67)', () => {
DISASTER_TYPES, DISASTER_TYPES,
DISASTER_SEVERITIES, DISASTER_SEVERITIES,
DISASTER_EFFECTS, DISASTER_EFFECTS,
// migration (v0.42.0, #64)
validateMigrationOps,
applyMigrationOp,
shiftRelationTowardPositive,
isMigrationKind,
isMigrationScale,
MIGRATION_KINDS,
MIGRATION_SCALES,
MIGRATION_SOURCE_EFFECTS,
MIGRATION_DESTINATION_EFFECTS,
LARGE_INFLUX_STABILITY_DIP,
// sea (v0.43.0, #65)
validateSeaOps,
applySeaControl,
applySeaZoneBonuses,
SEA_ZONE_BONUS,
SEA_ZONES,
SEA_ZONE_IDS,
isSeaZoneId,
seaZoneName,
// contested (v0.44.0, #66)
validateContestedOps,
applyContested,
CONTESTED_FILL,
CONTESTED_STROKE,
contestedTooltipLabel,
}; };
for (const [name, value] of Object.entries(reexported)) { for (const [name, value] of Object.entries(reexported)) {
expect(value, `engine should re-export ${name}`).toBeDefined(); expect(value, `engine should re-export ${name}`).toBeDefined();
+496
View File
@@ -0,0 +1,496 @@
// Unit tests for the SEA (naval / sea control) ability (v0.43.0, #65) — the
// modular, DURABLE LLM-ability that gives nations sole control over a fixed
// set of 12 named sea zones: the zone is upserted in `GameState.seaZones`
// (replace in place, contest by higher current military), and every committed
// turn the controller earns a deterministic +1 military / +1 economy bonus
// (clamped, mirrored to its regions, re-derived). The layer never touches
// `territory` / `unowned` — it is fully parallel to but independent of land.
// This is the ability's own test file (the registry's cross-cutting
// guarantees — order, distinct fields, the system/user goldens — are covered
// by ./registry.test.ts). The stub never proposes a sea op, so the apply path
// is exercised here, not by the e2e suite.
import { describe, expect, it } from 'vitest';
import {
SEA_ZONES,
SEA_ZONE_IDS,
applySeaControl,
applySeaZoneBonuses,
isSeaZoneId,
sea,
seaZoneName,
validateSeaOps,
} from './sea';
import type {
GameState,
Nation,
NationStats,
RegionStats,
SeaZoneClaim,
} from '../../shared/types';
// ---------------------------------------------------------------------------
// Fixture helpers
// ---------------------------------------------------------------------------
/** Build a NationStats from the four canonical indices (military, economy, stability, population). */
function NS(military: number, economy: number, stability: number, population: number): NationStats {
return { military, economy, stability, population };
}
/** Build a RegionStats from the four canonical indices. */
function RS(military: number, economy: number, stability: number, population: number): RegionStats {
return { military, economy, stability, population };
}
/** A minimal nation: the given id/name/stats/region-key territory. */
function mkNation(
id: string,
name: string,
stats: NationStats,
territory: string[],
): Nation {
return { id, name, type: 'major', stats, territory, relations: {} };
}
/**
* A minimal GameState carrying the given nations (keyed by id), per-region
* stats, and an optional existing sea-zone list. Every other required field
* is at its fresh-game baseline.
*/
function mkState(
nations: Record<string, Nation>,
regionStats: Record<string, RegionStats>,
seaZones: SeaZoneClaim[] = [],
): GameState {
return {
id: 'g1',
presetId: 'test',
presetTitle: 'Test',
playerNationId: Object.keys(nations)[0] ?? 'a1',
turn: 1,
date: '1939-09-01',
nations,
events: [],
pending: [],
version: 1,
unowned: [],
pendingNationOps: [],
markers: [],
regionStats,
wars: [],
trades: [],
embargoes: [],
industry: [],
seaZones,
// (v0.44.0, #66) no contested regions on a fresh state.
contested: [],
};
}
// ---------------------------------------------------------------------------
// SEA_ZONES / isSeaZoneId / seaZoneName
// ---------------------------------------------------------------------------
describe('SEA_ZONES / SEA_ZONE_IDS / isSeaZoneId / seaZoneName', () => {
it('exposes exactly the 12 fixed sea zones', () => {
expect(SEA_ZONES).toHaveLength(12);
const ids = SEA_ZONES.map((z) => z.id);
expect(ids).toEqual([
'north-atlantic',
'south-atlantic',
'pacific',
'indian',
'mediterranean',
'north-sea',
'baltic',
'arctic',
'black-sea',
'gulf-mexico',
'red-sea',
'sargasso',
]);
});
it('SEA_ZONE_IDS is a ReadonlySet of all 12 ids', () => {
expect(SEA_ZONE_IDS).toBeInstanceOf(Set);
expect(SEA_ZONE_IDS.size).toBe(12);
for (const z of SEA_ZONES) expect(SEA_ZONE_IDS.has(z.id)).toBe(true);
});
it('isSeaZoneId accepts each known id and rejects unknown / non-strings', () => {
for (const z of SEA_ZONES) expect(isSeaZoneId(z.id)).toBe(true);
expect(isSeaZoneId('atlantic-ocean')).toBe(false);
expect(isSeaZoneId('')).toBe(false);
});
it('seaZoneName returns the human-readable name; an unknown id is returned raw', () => {
expect(seaZoneName('pacific')).toBe('Pacific Ocean');
expect(seaZoneName('mediterranean')).toBe('Mediterranean Sea');
expect(seaZoneName('nope')).toBe('nope');
});
});
// ---------------------------------------------------------------------------
// validateSeaOps
// ---------------------------------------------------------------------------
describe('validateSeaOps', () => {
it('accepts the { control: [...] } object shape and a bare array', () => {
const op = { zone: 'pacific', by: 'a1' };
expect(validateSeaOps({ control: [op] })).toEqual({ control: [op] });
expect(validateSeaOps([op])).toEqual({ control: [op] });
});
it('drops an op with an unknown / missing zone', () => {
expect(validateSeaOps([{ zone: 'nope', by: 'a1' }])).toEqual({ control: [] });
expect(validateSeaOps([{ by: 'a1' }])).toEqual({ control: [] });
expect(validateSeaOps([{ zone: '', by: 'a1' }])).toEqual({ control: [] });
});
it('drops an op with an empty / missing `by` (the controller)', () => {
expect(validateSeaOps([{ zone: 'pacific', by: '' }])).toEqual({ control: [] });
expect(validateSeaOps([{ zone: 'pacific' }])).toEqual({ control: [] });
});
it('drops a non-object entry', () => {
expect(validateSeaOps([42, 'nope', null, { zone: 'pacific', by: 'a1' }])).toEqual({
control: [{ zone: 'pacific', by: 'a1' }],
});
});
it('a missing / malformed top-level value yields { control: [] }', () => {
expect(validateSeaOps(undefined)).toEqual({ control: [] });
expect(validateSeaOps(null)).toEqual({ control: [] });
expect(validateSeaOps('nope')).toEqual({ control: [] });
expect(validateSeaOps({ control: 'nope' })).toEqual({ control: [] });
});
it('caps `zone` at 100 and `by` at 200 chars', () => {
const longBy = 'f'.repeat(500);
const out = validateSeaOps([{ zone: 'pacific', by: longBy }]);
expect(out.control).toHaveLength(1);
expect(out.control[0].by).toHaveLength(200);
});
});
// ---------------------------------------------------------------------------
// applySeaControl
// ---------------------------------------------------------------------------
describe('applySeaControl', () => {
it('a single op sets a new zone claim', () => {
const state = mkState(
{ a1: mkNation('a1', 'Alpha', NS(80, 70, 60, 50), ['a-r1']) },
{ 'a-r1': RS(80, 70, 60, 50) },
);
applySeaControl(state, [{ zone: 'pacific', by: 'a1' }]);
expect(state.seaZones).toEqual([{ zone: 'pacific', by: 'a1' }]);
});
it('replaces an existing claim in place (position preserved)', () => {
const state = mkState(
{
a1: mkNation('a1', 'Alpha', NS(80, 70, 60, 50), ['a-r1']),
b2: mkNation('b2', 'Bravo', NS(90, 40, 20, 30), ['b-r1']),
},
{ 'a-r1': RS(80, 70, 60, 50), 'b-r1': RS(90, 40, 20, 30) },
[
{ zone: 'pacific', by: 'a1' },
{ zone: 'indian', by: 'b2' },
],
);
// b2 now claims pacific — the pacific claim moves to b2 but stays at index 0
applySeaControl(state, [{ zone: 'pacific', by: 'b2' }]);
expect(state.seaZones).toEqual([
{ zone: 'pacific', by: 'b2' },
{ zone: 'indian', by: 'b2' },
]);
});
it('appends a new zone after existing claims', () => {
const state = mkState(
{ a1: mkNation('a1', 'Alpha', NS(80, 70, 60, 50), ['a-r1']) },
{ 'a-r1': RS(80, 70, 60, 50) },
[{ zone: 'pacific', by: 'a1' }],
);
applySeaControl(state, [{ zone: 'arctic', by: 'a1' }]);
expect(state.seaZones).toEqual([
{ zone: 'pacific', by: 'a1' },
{ zone: 'arctic', by: 'a1' },
]);
});
it('a contest: the higher current military wins', () => {
const state = mkState(
{
a1: mkNation('a1', 'Alpha', NS(80, 70, 60, 50), ['a-r1']),
b2: mkNation('b2', 'Bravo', NS(90, 40, 20, 30), ['b-r1']),
},
{ 'a-r1': RS(80, 70, 60, 50), 'b-r1': RS(90, 40, 20, 30) },
);
// b2 has higher military (90 > 80) → b2 wins
applySeaControl(state, [
{ zone: 'pacific', by: 'a1' },
{ zone: 'pacific', by: 'b2' },
]);
expect(state.seaZones).toEqual([{ zone: 'pacific', by: 'b2' }]);
});
it('a contest tie: the earlier-listed op wins', () => {
const state = mkState(
{
a1: mkNation('a1', 'Alpha', NS(50, 50, 50, 50), ['a-r1']),
b2: mkNation('b2', 'Bravo', NS(50, 50, 50, 50), ['b-r1']),
},
{ 'a-r1': RS(50, 50, 50, 50), 'b-r1': RS(50, 50, 50, 50) },
);
// equal military (50 == 50) → a1 wins (listed first)
applySeaControl(state, [
{ zone: 'pacific', by: 'a1' },
{ zone: 'pacific', by: 'b2' },
]);
expect(state.seaZones).toEqual([{ zone: 'pacific', by: 'a1' }]);
});
it('two ops for the same nation on the same zone: a single claim (no contest)', () => {
const state = mkState(
{ a1: mkNation('a1', 'Alpha', NS(80, 70, 60, 50), ['a-r1']) },
{ 'a-r1': RS(80, 70, 60, 50) },
);
applySeaControl(state, [
{ zone: 'pacific', by: 'a1' },
{ zone: 'pacific', by: 'a1' },
]);
expect(state.seaZones).toEqual([{ zone: 'pacific', by: 'a1' }]);
});
it('resolves `by` by unique name (not just id)', () => {
const state = mkState(
{ a1: mkNation('a1', 'Alpha', NS(80, 70, 60, 50), ['a-r1']) },
{ 'a-r1': RS(80, 70, 60, 50) },
);
applySeaControl(state, [{ zone: 'pacific', by: 'Alpha' }]);
expect(state.seaZones).toEqual([{ zone: 'pacific', by: 'a1' }]);
});
it('an unresolvable `by` is dropped; if all ops on a zone drop, the zone is untouched', () => {
const state = mkState(
{ a1: mkNation('a1', 'Alpha', NS(80, 70, 60, 50), ['a-r1']) },
{ 'a-r1': RS(80, 70, 60, 50) },
[{ zone: 'pacific', by: 'a1' }],
);
// ghost does not exist → dropped; pacific stays as a1
applySeaControl(state, [{ zone: 'pacific', by: 'ghost' }]);
expect(state.seaZones).toEqual([{ zone: 'pacific', by: 'a1' }]);
// a NEW zone with only an unresolvable op → zone not added
applySeaControl(state, [{ zone: 'arctic', by: 'ghost' }]);
expect(state.seaZones).toEqual([{ zone: 'pacific', by: 'a1' }]);
});
it('an ambiguous name (two nations share it) drops the op', () => {
const state = mkState(
{
a1: mkNation('a1', 'Twin', NS(80, 70, 60, 50), ['a-r1']),
a2: mkNation('a2', 'Twin', NS(20, 20, 20, 20), ['a-r2']),
},
{ 'a-r1': RS(80, 70, 60, 50), 'a-r2': RS(20, 20, 20, 20) },
);
applySeaControl(state, [{ zone: 'pacific', by: 'Twin' }]);
// ambiguous → dropped
expect(state.seaZones).toEqual([]);
});
it('never touches `territory` or `unowned`', () => {
const state = mkState(
{
a1: mkNation('a1', 'Alpha', NS(80, 70, 60, 50), ['a-r1']),
b2: mkNation('b2', 'Bravo', NS(90, 40, 20, 30), ['b-r1']),
},
{ 'a-r1': RS(80, 70, 60, 50), 'b-r1': RS(90, 40, 20, 30) },
);
applySeaControl(state, [
{ zone: 'pacific', by: 'a1' },
{ zone: 'pacific', by: 'b2' },
]);
expect(state.nations.a1.territory).toEqual(['a-r1']);
expect(state.nations.b2.territory).toEqual(['b-r1']);
expect(state.unowned).toEqual([]);
});
});
// ---------------------------------------------------------------------------
// applySeaZoneBonuses
// ---------------------------------------------------------------------------
describe('applySeaZoneBonuses', () => {
it('a controller earns +1 military and +1 economy (clamped, mirrored, re-derived)', () => {
const state = mkState(
{ a1: mkNation('a1', 'Alpha', NS(50, 50, 50, 50), ['a-r1']) },
{ 'a-r1': RS(50, 50, 50, 50) },
[{ zone: 'pacific', by: 'a1' }],
);
applySeaZoneBonuses(state);
// +1 to both military and economy, mirrored to the region, re-derived
// (single region → re-derive gives back the region's value)
expect(state.nations.a1.stats).toEqual(NS(51, 51, 50, 50));
expect(state.regionStats['a-r1']).toEqual(RS(51, 51, 50, 50));
});
it('clamps to 0 and 100', () => {
// military at 99 → 100; economy at 1 → 2
const state = mkState(
{ a1: mkNation('a1', 'Alpha', NS(99, 1, 50, 50), ['a-r1']) },
{ 'a-r1': RS(99, 1, 50, 50) },
[{ zone: 'pacific', by: 'a1' }],
);
applySeaZoneBonuses(state);
expect(state.nations.a1.stats.military).toBe(100);
expect(state.nations.a1.stats.economy).toBe(2);
});
it('a nation controlling several zones stacks the bonus', () => {
const state = mkState(
{ a1: mkNation('a1', 'Alpha', NS(50, 50, 50, 50), ['a-r1']) },
{ 'a-r1': RS(50, 50, 50, 50) },
[
{ zone: 'pacific', by: 'a1' },
{ zone: 'indian', by: 'a1' },
],
);
applySeaZoneBonuses(state);
// +2 to both (one per zone)
expect(state.nations.a1.stats).toEqual(NS(52, 52, 50, 50));
});
it('a 0-region nation keeps its directly-mutated stats (no re-derive)', () => {
const state = mkState(
{ a1: mkNation('a1', 'Alpha', NS(50, 50, 50, 50), []) },
{},
[{ zone: 'pacific', by: 'a1' }],
);
applySeaZoneBonuses(state);
// direct mutation, no re-derive (no regions)
expect(state.nations.a1.stats).toEqual(NS(51, 51, 50, 50));
});
it('a stale controller (nation no longer in `nations`) is skipped; the claim is kept', () => {
// Build a state where the claim references a nation id that is not in `nations`
const state = mkState(
{ a1: mkNation('a1', 'Alpha', NS(50, 50, 50, 50), ['a-r1']) },
{ 'a-r1': RS(50, 50, 50, 50) },
[{ zone: 'pacific', by: 'ghost' }],
);
applySeaZoneBonuses(state);
// ghost is not in nations → skipped; a1 is unaffected
expect(state.nations.a1.stats).toEqual(NS(50, 50, 50, 50));
// the claim is kept (not removed)
expect(state.seaZones).toEqual([{ zone: 'pacific', by: 'ghost' }]);
});
it('an empty seaZones list is a no-op', () => {
const state = mkState(
{ a1: mkNation('a1', 'Alpha', NS(50, 50, 50, 50), ['a-r1']) },
{ 'a-r1': RS(50, 50, 50, 50) },
[],
);
applySeaZoneBonuses(state);
expect(state.nations.a1.stats).toEqual(NS(50, 50, 50, 50));
});
it('never touches `territory` or `unowned`', () => {
const state = mkState(
{ a1: mkNation('a1', 'Alpha', NS(50, 50, 50, 50), ['a-r1']) },
{ 'a-r1': RS(50, 50, 50, 50) },
[{ zone: 'pacific', by: 'a1' }],
);
applySeaZoneBonuses(state);
expect(state.nations.a1.territory).toEqual(['a-r1']);
expect(state.unowned).toEqual([]);
});
});
// ---------------------------------------------------------------------------
// The Ability object contract
// ---------------------------------------------------------------------------
describe('sea ability', () => {
it('owns the "sea" field; default() is a fresh empty { control: [] }', () => {
expect(sea.field).toBe('sea');
expect(sea.default()).toEqual({ control: [] });
expect(sea.default()).not.toBe(sea.default());
});
it('default() is not meaningful; a populated value is', () => {
expect(sea.isMeaningful(sea.default())).toBe(false);
expect(sea.isMeaningful({ control: [{ zone: 'pacific', by: 'a1' }] })).toBe(true);
});
it('validate() wraps the validator into the SeaOps shape', () => {
expect(sea.validate([{ zone: 'pacific', by: 'a1' }])).toEqual({
control: [{ zone: 'pacific', by: 'a1' }],
});
expect(sea.validate(undefined)).toEqual({ control: [] });
});
it('the stub value equals default() (the stub never proposes a sea op)', () => {
expect(sea.stub()).toEqual({ control: [] });
});
it('stateFields is [seaZones] (the durable GameState field)', () => {
expect(sea.stateFields).toEqual(['seaZones']);
});
it('payload() emits seaZones (even when empty / undefined)', () => {
expect(sea.payload({ seaZones: [] } as never)).toEqual({ seaZones: [] });
expect(sea.payload({} as never)).toEqual({ seaZones: [] });
expect(sea.payload({ seaZones: [{ zone: 'pacific', by: 'a1' }] } as never)).toEqual({
seaZones: [{ zone: 'pacific', by: 'a1' }],
});
});
it('apply() runs the ops then the per-turn bonus (no throw on a bad ref)', () => {
const state = mkState(
{
a1: mkNation('a1', 'Alpha', NS(50, 50, 50, 50), ['a-r1']),
b2: mkNation('b2', 'Bravo', NS(80, 40, 20, 30), ['b-r1']),
},
{ 'a-r1': RS(50, 50, 50, 50), 'b-r1': RS(80, 40, 20, 30) },
);
const ctx = { previous: state, actingTurn: state.turn };
sea.apply(
state,
{
control: [
{ zone: 'pacific', by: 'a1' },
{ zone: 'pacific', by: 'b2' },
// an unresolvable ref — must be dropped, not throw
{ zone: 'arctic', by: 'ghost' },
],
},
ctx,
);
// contest: b2 (military 80) beats a1 (military 50) → b2 controls pacific
expect(state.seaZones).toEqual([{ zone: 'pacific', by: 'b2' }]);
// b2 gets the +1/+1 bonus (it controls pacific)
expect(state.nations.b2.stats).toEqual(NS(81, 41, 20, 30));
// a1 is unaffected
expect(state.nations.a1.stats).toEqual(NS(50, 50, 50, 50));
});
it('apply() with an empty control still applies the per-turn bonus to existing claims', () => {
const state = mkState(
{ a1: mkNation('a1', 'Alpha', NS(50, 50, 50, 50), ['a-r1']) },
{ 'a-r1': RS(50, 50, 50, 50) },
[{ zone: 'pacific', by: 'a1' }],
);
const ctx = { previous: state, actingTurn: state.turn };
sea.apply(state, { control: [] }, ctx);
// no new claims, but the existing claim's controller earns the bonus
expect(state.seaZones).toEqual([{ zone: 'pacific', by: 'a1' }]);
expect(state.nations.a1.stats).toEqual(NS(51, 51, 50, 50));
});
});
+210
View File
@@ -0,0 +1,210 @@
// The SEA (naval / sea control) ability (v0.43.0, #65) as a modular
// LLM-ability (v0.40.0, #67) — the naval layer, fully parallel to but
// INDEPENDENT of land. The world has a fixed set of 12 named SEA ZONES
// (`SEA_ZONES` in shared/protocol.ts); each is under the SOLE CONTROL of at
// most one nation. Controlling a sea zone never moves land (`territory` /
// `unowned` are untouched) and moving land never touches a sea zone.
//
// Each turn the LLM declares `sea.control` ops — one op names the zone and
// the nation that (now) controls it. The engine resolves `by` (id first, then
// a case-insensitive unique name, via the shared `resolveNationRef`) and
// UPSERTS the zone's claim in `GameState.seaZones` (replace in place if the
// zone is already claimed, append if new). If two or more ops this turn claim
// the SAME zone for DIFFERENT resolved nations, the zone is CONTESTED: the
// higher current `stats.military` wins (a tie goes to the op listed earlier in
// the `control` array) — deterministic, no hidden randomness. An unresolvable
// `by` is dropped (never thrown).
//
// Every committed turn — INCLUDING a turn with an empty `control` — each
// existing claim's controller earns a small DETERMINISTIC bonus
// (`SEA_ZONE_BONUS = 1` military + 1 economy, clamped to 0–100, mirrored to
// the controller's regions and re-derived with the same 0-region / no-entry
// guards as the economy / migration layers); a claim whose nation no longer
// exists is skipped (the claim is kept, never thrown). The layer is DURABLE
// (unlike the turn-transient hybrid / disasters / migration layers):
// `GameState.seaZones` persists across turns and in SQLite, and the user
// payload always carries the current `seaZones` list (even when empty).
import {
clampStat,
deriveNationStats,
isSeaZoneId,
} from '../../shared/protocol';
export { SEA_ZONES, SEA_ZONE_IDS, isSeaZoneId, seaZoneName } from '../../shared/protocol';
import type { SeaControlOp, SeaOps } from '../../shared/protocol';
import type { GameState, Nation } from '../../shared/types';
import { resolveNationRef, str } from './shared';
import type { Ability } from './types';
/**
* (v0.43.0, #65) The DETERMINISTIC per-turn bonus each sea-zone controller
* earns (applied to BOTH `military` and `economy`, clamped to 0–100, mirrored
* to the controller's regions, and re-derived with the same 0-region /
* no-entry guards as the economy / migration layers). No hidden randomness.
*/
export const SEA_ZONE_BONUS = 1;
/**
* (v0.43.0, #65) Validate the raw `sea` field of a turn into a safe
* {@link SeaOps}. Defensive like the rest of the parser — never throws. The
* raw value may be the object `{ control: [...] }` (the TurnResult shape) or
* a bare array (be lenient about either). Each op needs a valid `zone` (one of
* {@link SEA_ZONES}) and a non-empty `by` (the controlling nation's id or
* unique name, capped at 200 chars). An op with an unknown / missing `zone` or
* an empty / missing `by` is dropped. Resolution of `by` to a concrete nation
* id happens at apply time (`applySeaControl`), not here. A missing /
* malformed top-level value yields `{ control: [] }`.
*/
export function validateSeaOps(raw: unknown): SeaOps {
const out: SeaOps = { control: [] };
let list: unknown[] | null = null;
if (Array.isArray(raw)) {
list = raw;
} else if (raw && typeof raw === 'object') {
const inner = (raw as Record<string, unknown>).control;
if (Array.isArray(inner)) list = inner;
}
if (!list) return out;
for (const e of list) {
if (!e || typeof e !== 'object') continue;
const o = e as Record<string, unknown>;
const zone = str(o.zone, 100);
if (!zone || !isSeaZoneId(zone)) continue; // unknown / missing zone: drop
const by = str(o.by, 200);
if (!by) continue; // empty / missing controller: drop
out.control.push({ zone, by });
}
return out;
}
/**
* (v0.43.0, #65) Upsert the turn's sea-control ops into `next.seaZones`,
* mutating in place and never throwing. Each op's `by` is resolved against the
* CURRENT state (id first, then a case-insensitive unique name) — an
* unresolvable ref is dropped. Per zone (in first-appearance order): a single
* surviving op SETS or REPLACES the zone's controller (replace the existing
* entry in place — preserving its position — or append a new one); two or
* more surviving ops on the same zone for DIFFERENT resolved nations make the
* zone CONTESTED — the higher current `stats.military` wins (a tie goes to the
* op listed earlier in the `control` array), and the winner becomes the
* controller. A zone whose ops all resolve to the same nation is simply (re-)
* set to that nation. Sea control never touches `territory` / `unowned`.
*/
export function applySeaControl(next: GameState, ops: SeaControlOp[]): void {
// Group the ops by zone, keeping the original (first-appearance) order of
// zones and each zone's ops (so the contest tie-break "earlier in the
// control array" is well-defined).
const byZone = new Map<string, { index: number; by: string }[]>();
ops.forEach((op, index) => {
const list = byZone.get(op.zone) ?? [];
list.push({ index, by: op.by });
byZone.set(op.zone, list);
});
for (const [zone, list] of byZone) {
// Resolve each op's `by`; an unresolvable ref is dropped (the zone is
// still decided by the ops that do resolve).
const resolved = list
.map(({ index, by }) => ({ index, id: resolveNationRef(next, by) }))
.filter((r): r is { index: number; id: string } => r.id !== null);
if (resolved.length === 0) continue; // nothing resolved: zone untouched
// Contest: the highest current `stats.military` wins; a strict `>` keeps
// the EARLIER-listed op on a tie (the list is in control-array order).
let winner = resolved[0];
for (const r of resolved) {
const mw = next.nations[winner.id]?.stats.military ?? 0;
const mr = next.nations[r.id]?.stats.military ?? 0;
if (mr > mw) winner = r;
}
const existing = next.seaZones.find((c) => c.zone === zone);
if (existing) {
existing.by = winner.id; // replace in place (position preserved)
} else {
next.seaZones.push({ zone, by: winner.id });
}
}
}
/**
* (v0.43.0, #65) The per-turn sea bonus, applied EVERY committed turn (not
* just to this turn's claims): each entry of `next.seaZones` grants its
* controller `SEA_ZONE_BONUS` military + `SEA_ZONE_BONUS` economy (clamped
* to 0–100, mirrored to every region the nation owns, then the nation's
* derived `stats` re-derived — the same 0-region / no-entry guards as the
* economy / migration layers, so a 0-region nation keeps its directly-mutated
* value). A nation controlling several zones stacks the bonus; a claim whose
* nation no longer exists (removed by a merge / split this turn) is skipped —
* the claim is kept, never thrown. Never throws.
*/
export function applySeaZoneBonuses(
next: GameState,
geoOf?: (key: string) => { area: number; population: number } | undefined,
): void {
if (next.seaZones.length === 0) return;
// nation id -> {military, economy} delta (claims for the same nation stack).
const delta = new Map<string, { military: number; economy: number }>();
for (const c of next.seaZones) {
const d = delta.get(c.by) ?? { military: 0, economy: 0 };
d.military += SEA_ZONE_BONUS;
d.economy += SEA_ZONE_BONUS;
delta.set(c.by, d);
}
const applyNation = (n: Nation, d: { military: number; economy: number }): void => {
(['military', 'economy'] as const).forEach((k) => {
n.stats[k] = clampStat(n.stats[k] + d[k]);
});
for (const key of n.territory) {
const rs = next.regionStats[key];
if (!rs) continue; // a key with no entry is skipped
(['military', 'economy'] as const).forEach((k) => {
rs[k] = clampStat(rs[k] + d[k]);
});
}
// Re-derive the nation's aggregate stats so the effect persists (the main
// recompute ran earlier this turn; without this the change would be washed
// out next turn). A nation with no regionStats entry keeps its
// directly-mutated `stats`.
if (n.territory.length > 0 && n.territory.some((k) => next.regionStats[k])) {
n.stats = deriveNationStats(n.territory, next.regionStats, geoOf);
}
};
for (const [id, d] of delta) {
const n = next.nations[id];
if (!n) continue; // a nation removed this turn: the bonus is dropped (claim kept)
applyNation(n, d);
}
}
export const sea: Ability<'sea'> = {
field: 'sea',
default: () => ({ control: [] }),
validate: (raw) => validateSeaOps(raw),
apply: (state, data, ctx) => {
// (1) APPLY OPS: this turn's control ops upsert `GameState.seaZones`
// (a single op sets/replaces the zone's controller; a same-zone
// contest goes to the higher current `stats.military`, a tie to the
// earlier-listed op).
// (2) PER-TURN BONUS: EVERY committed turn — including this one, and
// including turns with an empty `control` — each existing claim's
// controller earns the deterministic military/economy bonus, so a
// zone that stays held keeps paying out.
applySeaControl(state, data.control);
applySeaZoneBonuses(state, ctx.geoOf);
},
schemaLine: () =>
' "sea": {"control":[{"zone":"<seaZoneId>","by":"<nation id or name>"}]},',
constraint: () =>
'- Sea control ("sea") is the naval layer, fully parallel to but INDEPENDENT of land: each of the 12 fixed sea zones — "north-atlantic" (North Atlantic), "south-atlantic" (South Atlantic), "pacific" (Pacific Ocean), "indian" (Indian Ocean), "mediterranean" (Mediterranean Sea), "north-sea" (North Sea), "baltic" (Baltic Sea), "arctic" (Arctic Ocean), "black-sea" (Black Sea), "gulf-mexico" (Gulf of Mexico), "red-sea" (Red Sea), "sargasso" (Sargasso Sea) — is under the SOLE control of at most one nation. A control op ({"zone":"<id>","by":"<nation>"}) sets or replaces that zone\'s controller (the user message\'s "seaZones" field lists who controls what now); if two or more ops this turn claim the SAME zone for DIFFERENT nations, the zone is CONTESTED and the higher current "military" wins (a tie goes to the earlier-listed op). Every committed turn each zone\'s controller earns a small deterministic +1 military and +1 economy. Sea control NEVER moves land (no territory changes) — it is a parallel track. Propose at most 1-2 claims per turn and narrate each one in "events" (a "military" or "diplomatic" event).',
isMeaningful: (data) => data.control.length > 0,
stateFields: ['seaZones'],
stub: () => ({ control: [] }),
// Sea control is DURABLE (unlike the turn-transient hybrid / disasters /
// migration layers): the user payload ALWAYS carries the current `seaZones`
// list (even when empty) so the model knows who controls which zone.
payload: (ctx) => ({ seaZones: ctx.seaZones ?? [] }),
};
+10 -4
View File
@@ -12,16 +12,17 @@ import type {
IndustryProject, IndustryProject,
RegionResources, RegionResources,
RelationStatus, RelationStatus,
SeaZoneClaim,
TradeAgreement, TradeAgreement,
} from '../../shared/types'; } from '../../shared/types';
import type { MarkerInfo, TurnResult, WarInfo } from '../../shared/protocol'; import type { ContestedRegion, MarkerInfo, TurnResult, WarInfo } from '../../shared/protocol';
/** /**
* The 9 per-feature LLM abilities a turn can exercise, by the `TurnResult` * The 12 per-feature LLM abilities a turn can exercise, by the `TurnResult`
* field each one owns. This is the closed universe the ordered `ABILITIES` * field each one owns. This is the closed universe the ordered `ABILITIES`
* registry (./index.ts) is built from: a turn's world changes are exactly the * registry (./index.ts) is built from: a turn's world changes are exactly the
* core engine effects (events / stats / territory / no-man's-land / nation-ops * core engine effects (events / stats / territory / no-man's-land / nation-ops
* / markers) plus, in order, these nine abilities. * / markers) plus, in order, these twelve abilities.
*/ */
export type AbilityField = export type AbilityField =
| 'takeovers' | 'takeovers'
@@ -32,7 +33,10 @@ export type AbilityField =
| 'nuclear' | 'nuclear'
| 'leaders' | 'leaders'
| 'ideology' | 'ideology'
| 'disasters'; | 'disasters'
| 'migration'
| 'sea'
| 'contested';
/** /**
* Everything a single ability's `apply` may need from the surrounding turn. * Everything a single ability's `apply` may need from the surrounding turn.
@@ -88,6 +92,8 @@ export interface UserPromptCtx {
readonly embargoes?: Embargo[]; readonly embargoes?: Embargo[];
readonly nationResources?: Record<string, RegionResources>; readonly nationResources?: Record<string, RegionResources>;
readonly industryProjects?: IndustryProject[]; readonly industryProjects?: IndustryProject[];
readonly seaZones?: SeaZoneClaim[];
readonly contested?: ContestedRegion[];
} }
/** /**
+26
View File
@@ -38,6 +38,10 @@ function makeState(id: string): GameState {
embargoes: [], embargoes: [],
// (v0.36.0, #59) no industry projects. // (v0.36.0, #59) no industry projects.
industry: [], industry: [],
// (v0.43.0, #65) no sea-zone control on a fresh state.
seaZones: [],
// (v0.44.0, #66) no contested regions on a fresh state.
contested: [],
}; };
} }
@@ -244,6 +248,28 @@ describe('openDb', () => {
db.close(); db.close();
}); });
it('(v0.43.0 #65) a legacy row saved before the seaZones field existed loads with it defaulted to []', () => {
const db = openDb(':memory:');
const legacy = makeState('legacy');
delete (legacy as { seaZones?: unknown[] }).seaZones; // a pre-v0.43 save (field absent)
db.save(legacy);
const loaded = db.load('legacy');
expect(loaded).not.toBeNull();
expect(loaded!.seaZones).toEqual([]);
db.close();
});
it('(v0.44.0 #66) a legacy row saved before the contested field existed loads with it defaulted to []', () => {
const db = openDb(':memory:');
const legacy = makeState('legacy');
delete (legacy as { contested?: unknown[] }).contested; // a pre-v0.44 save (field absent)
db.save(legacy);
const loaded = db.load('legacy');
expect(loaded).not.toBeNull();
expect(loaded!.contested).toEqual([]);
db.close();
});
it('delete removes a game by id and reports absence otherwise', () => { it('delete removes a game by id and reports absence otherwise', () => {
const db = openDb(':memory:'); const db = openDb(':memory:');
db.save(makeState('a')); db.save(makeState('a'));
+49 -38
View File
@@ -133,6 +133,10 @@ function baseState(): GameState {
embargoes: [], embargoes: [],
// (v0.36.0, #59) no industry projects on a fresh state. // (v0.36.0, #59) no industry projects on a fresh state.
industry: [], industry: [],
// (v0.43.0, #65) no sea-zone control on a fresh state.
seaZones: [],
// (v0.44.0, #66) no contested regions on a fresh state.
contested: [],
}; };
} }
@@ -570,7 +574,7 @@ describe('validateNationOps (v0.23 #16 P4a)', () => {
relations: [], relations: [],
territoryChanges: [], territoryChanges: [],
unowned: [], unowned: [],
nationOps: [{ kind: 'rename', nationRef: 'France', to: 'French Republic' }], takeovers: [], wars: { declare: [], end: [] }, hybrid: { ops: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, ideology: { changes: [] }, disasters: { events: [] },markers: { add: [], remove: [] }, nationOps: [{ kind: 'rename', nationRef: 'France', to: 'French Republic' }], takeovers: [], wars: { declare: [], end: [] }, hybrid: { ops: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, ideology: { changes: [] }, disasters: { events: [] }, migration: { ops: [] }, sea: { control: [] }, contested: { open: [], resolve: [] }, markers: { add: [], remove: [] },
}); });
expect(withOps).not.toBeNull(); expect(withOps).not.toBeNull();
expect(withOps!.nationOps).toEqual([{ kind: 'rename', nationRef: 'France', to: 'French Republic' }]); expect(withOps!.nationOps).toEqual([{ kind: 'rename', nationRef: 'France', to: 'French Republic' }]);
@@ -592,7 +596,7 @@ describe('applyTurnResult (nation-op proposals, v0.23 #16 P4a)', () => {
relations: [], relations: [],
territoryChanges: [], territoryChanges: [],
unowned: [], unowned: [],
nationOps: [{ kind: 'rename', nationRef: 'de', to: 'Reich' }], takeovers: [], wars: { declare: [], end: [] }, hybrid: { ops: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, ideology: { changes: [] }, disasters: { events: [] },markers: { add: [], remove: [] }, nationOps: [{ kind: 'rename', nationRef: 'de', to: 'Reich' }], takeovers: [], wars: { declare: [], end: [] }, hybrid: { ops: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, ideology: { changes: [] }, disasters: { events: [] }, migration: { ops: [] }, sea: { control: [] }, contested: { open: [], resolve: [] }, markers: { add: [], remove: [] },
}); });
expect(next.nations.de.name).toBe('DE'); // still the old name expect(next.nations.de.name).toBe('DE'); // still the old name
expect(next.pendingNationOps).toEqual([{ kind: 'rename', nationRef: 'de', to: 'Reich' }]); expect(next.pendingNationOps).toEqual([{ kind: 'rename', nationRef: 'de', to: 'Reich' }]);
@@ -613,7 +617,7 @@ describe('applyTurnResult (nation-op proposals, v0.23 #16 P4a)', () => {
relations: [], relations: [],
territoryChanges: [], territoryChanges: [],
unowned: [], unowned: [],
nationOps: [{ kind: 'rename', nationRef: 'us', to: 'USA' }], takeovers: [], wars: { declare: [], end: [] }, hybrid: { ops: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, ideology: { changes: [] }, disasters: { events: [] },markers: { add: [], remove: [] }, // new proposal this turn nationOps: [{ kind: 'rename', nationRef: 'us', to: 'USA' }], takeovers: [], wars: { declare: [], end: [] }, hybrid: { ops: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, ideology: { changes: [] }, disasters: { events: [] }, migration: { ops: [] }, sea: { control: [] }, contested: { open: [], resolve: [] }, markers: { add: [], remove: [] }, // new proposal this turn
}); });
expect(next.pendingNationOps).toEqual([ expect(next.pendingNationOps).toEqual([
{ kind: 'rename', nationRef: 'de', to: 'Reich' }, // the old one survived { kind: 'rename', nationRef: 'de', to: 'Reich' }, // the old one survived
@@ -632,7 +636,7 @@ describe('applyTurnResult (nation-op proposals, v0.23 #16 P4a)', () => {
relations: [], relations: [],
territoryChanges: [], territoryChanges: [],
unowned: [], unowned: [],
nationOps: [{ kind: 'rename', nationRef: 'de', to: 'Reich' }], takeovers: [], wars: { declare: [], end: [] }, hybrid: { ops: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, ideology: { changes: [] }, disasters: { events: [] },markers: { add: [], remove: [] }, nationOps: [{ kind: 'rename', nationRef: 'de', to: 'Reich' }], takeovers: [], wars: { declare: [], end: [] }, hybrid: { ops: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, ideology: { changes: [] }, disasters: { events: [] }, migration: { ops: [] }, sea: { control: [] }, contested: { open: [], resolve: [] }, markers: { add: [], remove: [] },
}); });
expect(next.pendingNationOps).toEqual([{ kind: 'rename', nationRef: 'de', to: 'Reich' }]); expect(next.pendingNationOps).toEqual([{ kind: 'rename', nationRef: 'de', to: 'Reich' }]);
}); });
@@ -1089,7 +1093,7 @@ describe('applyTurnResult', () => {
relations: [], relations: [],
territoryChanges: [], territoryChanges: [],
unowned: [], unowned: [],
nationOps: [], takeovers: [], wars: { declare: [], end: [] }, hybrid: { ops: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, ideology: { changes: [] }, disasters: { events: [] },markers: { add: [], remove: [] }, nationOps: [], takeovers: [], wars: { declare: [], end: [] }, hybrid: { ops: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, ideology: { changes: [] }, disasters: { events: [] }, migration: { ops: [] }, sea: { control: [] }, contested: { open: [], resolve: [] }, markers: { add: [], remove: [] },
}; };
applyTurnResult(state, result); applyTurnResult(state, result);
expect(JSON.stringify(state)).toBe(snapshot); expect(JSON.stringify(state)).toBe(snapshot);
@@ -1106,7 +1110,7 @@ describe('applyTurnResult', () => {
relations: [], relations: [],
territoryChanges: [], territoryChanges: [],
unowned: [], unowned: [],
nationOps: [], takeovers: [], wars: { declare: [], end: [] }, hybrid: { ops: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, ideology: { changes: [] }, disasters: { events: [] },markers: { add: [], remove: [] }, nationOps: [], takeovers: [], wars: { declare: [], end: [] }, hybrid: { ops: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, ideology: { changes: [] }, disasters: { events: [] }, migration: { ops: [] }, sea: { control: [] }, contested: { open: [], resolve: [] }, markers: { add: [], remove: [] },
}; };
const next = applyTurnResult(state, result); const next = applyTurnResult(state, result);
expect(next.pending).toEqual([]); expect(next.pending).toEqual([]);
@@ -1129,7 +1133,7 @@ describe('applyTurnResult', () => {
// is not a real key at all. Both are proposed as a gain by DE. // is not a real key at all. Both are proposed as a gain by DE.
territoryChanges: [{ nation: 'de', gain: ['wales-bbbb', 'not-a-region-xyz'], lose: [] }], territoryChanges: [{ nation: 'de', gain: ['wales-bbbb', 'not-a-region-xyz'], lose: [] }],
unowned: [], unowned: [],
nationOps: [], takeovers: [], wars: { declare: [], end: [] }, hybrid: { ops: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, ideology: { changes: [] }, disasters: { events: [] },markers: { add: [], remove: [] }, nationOps: [], takeovers: [], wars: { declare: [], end: [] }, hybrid: { ops: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, ideology: { changes: [] }, disasters: { events: [] }, migration: { ops: [] }, sea: { control: [] }, contested: { open: [], resolve: [] }, markers: { add: [], remove: [] },
}; };
const next = applyTurnResult(state, result, new Set(['wales-bbbb'])); const next = applyTurnResult(state, result, new Set(['wales-bbbb']));
// the valid key was gained (taken from its sole previous owner); the bogus one was ignored // the valid key was gained (taken from its sole previous owner); the bogus one was ignored
@@ -1155,7 +1159,7 @@ describe('applyTurnResult', () => {
// released (not in state.unowned), so it does not enter GameState.unowned. // released (not in state.unowned), so it does not enter GameState.unowned.
territoryChanges: [{ nation: 'de', gain: ['POL', 'wales-bbbb'], lose: [] }], territoryChanges: [{ nation: 'de', gain: ['POL', 'wales-bbbb'], lose: [] }],
unowned: [], unowned: [],
nationOps: [], takeovers: [], wars: { declare: [], end: [] }, hybrid: { ops: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, ideology: { changes: [] }, disasters: { events: [] },markers: { add: [], remove: [] }, nationOps: [], takeovers: [], wars: { declare: [], end: [] }, hybrid: { ops: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, ideology: { changes: [] }, disasters: { events: [] }, migration: { ops: [] }, sea: { control: [] }, contested: { open: [], resolve: [] }, markers: { add: [], remove: [] },
}; };
const next = applyTurnResult(state, result); // no validKeys -> nothing filtered const next = applyTurnResult(state, result); // no validKeys -> nothing filtered
expect(next.nations.de.territory).toContain('wales-bbbb'); expect(next.nations.de.territory).toContain('wales-bbbb');
@@ -1173,7 +1177,7 @@ describe('applyTurnResult (sole-ownership invariants, v0.21 #16 P2)', () => {
regionChanges: [], regionChanges: [],
relations: [], relations: [],
unowned: [], unowned: [],
nationOps: [], takeovers: [], wars: { declare: [], end: [] }, hybrid: { ops: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, ideology: { changes: [] }, disasters: { events: [] },markers: { add: [], remove: [] }, nationOps: [], takeovers: [], wars: { declare: [], end: [] }, hybrid: { ops: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, ideology: { changes: [] }, disasters: { events: [] }, migration: { ops: [] }, sea: { control: [] }, contested: { open: [], resolve: [] }, markers: { add: [], remove: [] },
}; };
it('a double claim (two different gainers, one key) is rejected: the key stays with its original owner', () => { it('a double claim (two different gainers, one key) is rejected: the key stays with its original owner', () => {
@@ -1263,7 +1267,7 @@ describe('applyTurnResult (no man\'s land, v0.22 #16 P3)', () => {
relations: [], relations: [],
territoryChanges: [], territoryChanges: [],
unowned: [], unowned: [],
nationOps: [], takeovers: [], wars: { declare: [], end: [] }, hybrid: { ops: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, ideology: { changes: [] }, disasters: { events: [] },markers: { add: [], remove: [] }, nationOps: [], takeovers: [], wars: { declare: [], end: [] }, hybrid: { ops: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, ideology: { changes: [] }, disasters: { events: [] }, migration: { ops: [] }, sea: { control: [] }, contested: { open: [], resolve: [] }, markers: { add: [], remove: [] },
}; };
it('a release removes the key from its sole owner and marks it in GameState.unowned', () => { it('a release removes the key from its sole owner and marks it in GameState.unowned', () => {
@@ -1378,7 +1382,7 @@ describe('applyTurnResult (no man\'s land, v0.22 #16 P3)', () => {
it('a lone release is meaningful (it survives the retry/nudge path)', () => { it('a lone release is meaningful (it survives the retry/nudge path)', () => {
expect( expect(
isMeaningful({ date: 'x', events: [], stateChanges: [], regionChanges: [], relations: [], territoryChanges: [], unowned: ['GBR'], nationOps: [], takeovers: [], wars: { declare: [], end: [] }, hybrid: { ops: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, ideology: { changes: [] }, disasters: { events: [] },markers: { add: [], remove: [] } }), isMeaningful({ date: 'x', events: [], stateChanges: [], regionChanges: [], relations: [], territoryChanges: [], unowned: ['GBR'], nationOps: [], takeovers: [], wars: { declare: [], end: [] }, hybrid: { ops: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, ideology: { changes: [] }, disasters: { events: [] }, migration: { ops: [] }, sea: { control: [] }, contested: { open: [], resolve: [] }, markers: { add: [], remove: [] } }),
).toBe(true); ).toBe(true);
}); });
@@ -1685,9 +1689,9 @@ describe('buildSystemPrompt (tool mode, v0.21 #16 P2)', () => {
describe('isMeaningful', () => { describe('isMeaningful', () => {
it('is true with an event, false when everything is empty', () => { it('is true with an event, false when everything is empty', () => {
expect(isMeaningful({ date: 'x', events: [{ nation: 'uk', type: 'military', title: 't', text: 'b', outcome: 'neutral' }], stateChanges: [], regionChanges: [], relations: [], territoryChanges: [], unowned: [], nationOps: [], takeovers: [], wars: { declare: [], end: [] }, hybrid: { ops: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, ideology: { changes: [] }, disasters: { events: [] },markers: { add: [], remove: [] } })).toBe(true); expect(isMeaningful({ date: 'x', events: [{ nation: 'uk', type: 'military', title: 't', text: 'b', outcome: 'neutral' }], stateChanges: [], regionChanges: [], relations: [], territoryChanges: [], unowned: [], nationOps: [], takeovers: [], wars: { declare: [], end: [] }, hybrid: { ops: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, ideology: { changes: [] }, disasters: { events: [] }, migration: { ops: [] }, sea: { control: [] }, contested: { open: [], resolve: [] }, markers: { add: [], remove: [] } })).toBe(true);
expect(isMeaningful({ date: 'x', events: [], stateChanges: [{ nation: 'uk', stat: 'military', op: 'set', value: 5 }], regionChanges: [], relations: [], territoryChanges: [], unowned: [], nationOps: [], takeovers: [], wars: { declare: [], end: [] }, hybrid: { ops: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, ideology: { changes: [] }, disasters: { events: [] },markers: { add: [], remove: [] } })).toBe(true); expect(isMeaningful({ date: 'x', events: [], stateChanges: [{ nation: 'uk', stat: 'military', op: 'set', value: 5 }], regionChanges: [], relations: [], territoryChanges: [], unowned: [], nationOps: [], takeovers: [], wars: { declare: [], end: [] }, hybrid: { ops: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, ideology: { changes: [] }, disasters: { events: [] }, migration: { ops: [] }, sea: { control: [] }, contested: { open: [], resolve: [] }, markers: { add: [], remove: [] } })).toBe(true);
expect(isMeaningful({ date: 'x', events: [], stateChanges: [], regionChanges: [], relations: [], territoryChanges: [], unowned: [], nationOps: [], takeovers: [], wars: { declare: [], end: [] }, hybrid: { ops: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, ideology: { changes: [] }, disasters: { events: [] },markers: { add: [], remove: [] } })).toBe(false); expect(isMeaningful({ date: 'x', events: [], stateChanges: [], regionChanges: [], relations: [], territoryChanges: [], unowned: [], nationOps: [], takeovers: [], wars: { declare: [], end: [] }, hybrid: { ops: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, ideology: { changes: [] }, disasters: { events: [] }, migration: { ops: [] }, sea: { control: [] }, contested: { open: [], resolve: [] }, markers: { add: [], remove: [] } })).toBe(false);
}); });
it('(v0.23 #16 P4a) a turn that only proposes a nation-op is meaningful (it survives the retry/nudge path)', () => { it('(v0.23 #16 P4a) a turn that only proposes a nation-op is meaningful (it survives the retry/nudge path)', () => {
@@ -1700,7 +1704,7 @@ describe('isMeaningful', () => {
relations: [], relations: [],
territoryChanges: [], territoryChanges: [],
unowned: [], unowned: [],
nationOps: [{ kind: 'rename', nationRef: 'de', to: 'Reich' }], takeovers: [], wars: { declare: [], end: [] }, hybrid: { ops: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, ideology: { changes: [] }, disasters: { events: [] },markers: { add: [], remove: [] }, nationOps: [{ kind: 'rename', nationRef: 'de', to: 'Reich' }], takeovers: [], wars: { declare: [], end: [] }, hybrid: { ops: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, ideology: { changes: [] }, disasters: { events: [] }, migration: { ops: [] }, sea: { control: [] }, contested: { open: [], resolve: [] }, markers: { add: [], remove: [] },
}), }),
).toBe(true); ).toBe(true);
}); });
@@ -1721,7 +1725,7 @@ describe('isMeaningful', () => {
hybrid: { ops: [] }, hybrid: { ops: [] },
economy: { trade: [], embargo: [] }, industry: { projects: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] },
nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] },
ideology: { changes: [] }, disasters: { events: [] },markers: { add: [{ type: 'city', name: 'Lyon', regionKey: 'rhone-rhne' }], remove: [] }, ideology: { changes: [] }, disasters: { events: [] }, migration: { ops: [] }, sea: { control: [] }, contested: { open: [], resolve: [] }, markers: { add: [{ type: 'city', name: 'Lyon', regionKey: 'rhone-rhne' }], remove: [] },
}), }),
).toBe(true); ).toBe(true);
}); });
@@ -1742,7 +1746,7 @@ describe('isMeaningful', () => {
hybrid: { ops: [] }, hybrid: { ops: [] },
economy: { trade: [], embargo: [] }, industry: { projects: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] },
nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] },
ideology: { changes: [] }, disasters: { events: [] },markers: { add: [], remove: [] }, ideology: { changes: [] }, disasters: { events: [] }, migration: { ops: [] }, sea: { control: [] }, contested: { open: [], resolve: [] }, markers: { add: [], remove: [] },
}), }),
).toBe(true); ).toBe(true);
}); });
@@ -1765,7 +1769,7 @@ describe('takeovers (regime change, v0.32.0 #54)', () => {
hybrid: { ops: [] }, hybrid: { ops: [] },
economy: { trade: [], embargo: [] }, industry: { projects: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] },
nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] },
ideology: { changes: [] }, disasters: { events: [] },markers: { add: [], remove: [] }, ideology: { changes: [] }, disasters: { events: [] }, migration: { ops: [] }, sea: { control: [] }, contested: { open: [], resolve: [] }, markers: { add: [], remove: [] },
}; };
const next = applyTurnResult(state, result); const next = applyTurnResult(state, result);
expect(next.nations.de.name).toBe('The Reich'); expect(next.nations.de.name).toBe('The Reich');
@@ -1798,7 +1802,7 @@ describe('takeovers (regime change, v0.32.0 #54)', () => {
hybrid: { ops: [] }, hybrid: { ops: [] },
economy: { trade: [], embargo: [] }, industry: { projects: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] },
nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] },
ideology: { changes: [] }, disasters: { events: [] },markers: { add: [], remove: [] }, ideology: { changes: [] }, disasters: { events: [] }, migration: { ops: [] }, sea: { control: [] }, contested: { open: [], resolve: [] }, markers: { add: [], remove: [] },
}; };
const next = applyTurnResult(state, result); const next = applyTurnResult(state, result);
expect(next.playerNationId).toBe('uk'); // player still leads it expect(next.playerNationId).toBe('uk'); // player still leads it
@@ -1822,7 +1826,7 @@ describe('takeovers (regime change, v0.32.0 #54)', () => {
hybrid: { ops: [] }, hybrid: { ops: [] },
economy: { trade: [], embargo: [] }, industry: { projects: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] },
nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] },
ideology: { changes: [] }, disasters: { events: [] },markers: { add: [], remove: [] }, ideology: { changes: [] }, disasters: { events: [] }, migration: { ops: [] }, sea: { control: [] }, contested: { open: [], resolve: [] }, markers: { add: [], remove: [] },
}; };
const next = applyTurnResult(state, result); const next = applyTurnResult(state, result);
// no nation was renamed // no nation was renamed
@@ -1849,7 +1853,7 @@ describe('takeovers (regime change, v0.32.0 #54)', () => {
hybrid: { ops: [] }, hybrid: { ops: [] },
economy: { trade: [], embargo: [] }, industry: { projects: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] },
nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] },
ideology: { changes: [] }, disasters: { events: [] },markers: { add: [], remove: [] }, ideology: { changes: [] }, disasters: { events: [] }, migration: { ops: [] }, sea: { control: [] }, contested: { open: [], resolve: [] }, markers: { add: [], remove: [] },
}; };
const next = applyTurnResult(state, result); const next = applyTurnResult(state, result);
// neither was renamed (ambiguous) // neither was renamed (ambiguous)
@@ -1875,7 +1879,7 @@ describe('takeovers (regime change, v0.32.0 #54)', () => {
hybrid: { ops: [] }, hybrid: { ops: [] },
economy: { trade: [], embargo: [] }, industry: { projects: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] },
nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] },
ideology: { changes: [] }, disasters: { events: [] },markers: { add: [], remove: [] }, ideology: { changes: [] }, disasters: { events: [] }, migration: { ops: [] }, sea: { control: [] }, contested: { open: [], resolve: [] }, markers: { add: [], remove: [] },
}); });
expect(validated!.takeovers).toEqual([]); expect(validated!.takeovers).toEqual([]);
const next = applyTurnResult(state, validated!); const next = applyTurnResult(state, validated!);
@@ -1901,7 +1905,7 @@ describe('takeovers (regime change, v0.32.0 #54)', () => {
hybrid: { ops: [] }, hybrid: { ops: [] },
economy: { trade: [], embargo: [] }, industry: { projects: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] },
nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] },
ideology: { changes: [] }, disasters: { events: [] },markers: { add: [], remove: [] }, ideology: { changes: [] }, disasters: { events: [] }, migration: { ops: [] }, sea: { control: [] }, contested: { open: [], resolve: [] }, markers: { add: [], remove: [] },
}; };
const next = applyTurnResult(state, result); const next = applyTurnResult(state, result);
expect(next.nations.uk.name).toBe('The Commonwealth'); expect(next.nations.uk.name).toBe('The Commonwealth');
@@ -1925,7 +1929,7 @@ describe('takeovers (regime change, v0.32.0 #54)', () => {
hybrid: { ops: [] }, hybrid: { ops: [] },
economy: { trade: [], embargo: [] }, industry: { projects: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] },
nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] },
ideology: { changes: [] }, disasters: { events: [] },markers: { add: [], remove: [] }, ideology: { changes: [] }, disasters: { events: [] }, migration: { ops: [] }, sea: { control: [] }, contested: { open: [], resolve: [] }, markers: { add: [], remove: [] },
}; };
const next = applyTurnResult(state, result); const next = applyTurnResult(state, result);
expect(next.version).toBe(2); // exactly one bump for the whole turn expect(next.version).toBe(2); // exactly one bump for the whole turn
@@ -1947,7 +1951,7 @@ describe('takeovers (regime change, v0.32.0 #54)', () => {
hybrid: { ops: [] }, hybrid: { ops: [] },
economy: { trade: [], embargo: [] }, industry: { projects: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] },
nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] },
ideology: { changes: [] }, disasters: { events: [] },markers: { add: [], remove: [] }, ideology: { changes: [] }, disasters: { events: [] }, migration: { ops: [] }, sea: { control: [] }, contested: { open: [], resolve: [] }, markers: { add: [], remove: [] },
}; };
const next = applyTurnResult(state, result); const next = applyTurnResult(state, result);
expect(next.nations.de.name).toBe('The Reich'); expect(next.nations.de.name).toBe('The Reich');
@@ -1981,7 +1985,7 @@ describe('markers (point placement, v0.27 #44)', () => {
hybrid: { ops: [] }, hybrid: { ops: [] },
economy: { trade: [], embargo: [] }, industry: { projects: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] },
nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] },
ideology: { changes: [] }, disasters: { events: [] },markers: { add: [mk('city', 'Strasbourg', 'moselle-rygy')], remove: [] }, ideology: { changes: [] }, disasters: { events: [] }, migration: { ops: [] }, sea: { control: [] }, contested: { open: [], resolve: [] }, markers: { add: [mk('city', 'Strasbourg', 'moselle-rygy')], remove: [] },
}; };
const next = applyTurnResult(state, result, undefined, centroidOf); const next = applyTurnResult(state, result, undefined, centroidOf);
expect(next.markers).toHaveLength(1); expect(next.markers).toHaveLength(1);
@@ -2005,13 +2009,13 @@ describe('markers (point placement, v0.27 #44)', () => {
const add = [mk('city', 'Strasbourg', 'moselle-rygy')]; const add = [mk('city', 'Strasbourg', 'moselle-rygy')];
const first = applyTurnResult(state, { const first = applyTurnResult(state, {
date: '1939-09-03', events: [], stateChanges: [], regionChanges: [], relations: [], territoryChanges: [], date: '1939-09-03', events: [], stateChanges: [], regionChanges: [], relations: [], territoryChanges: [],
unowned: [], nationOps: [], takeovers: [], wars: { declare: [], end: [] }, hybrid: { ops: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, ideology: { changes: [] }, disasters: { events: [] },markers: { add, remove: [] }, unowned: [], nationOps: [], takeovers: [], wars: { declare: [], end: [] }, hybrid: { ops: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, ideology: { changes: [] }, disasters: { events: [] }, migration: { ops: [] }, sea: { control: [] }, contested: { open: [], resolve: [] }, markers: { add, remove: [] },
}, undefined, centroidOf); }, undefined, centroidOf);
expect(first.markers).toHaveLength(1); expect(first.markers).toHaveLength(1);
// a second turn proposes the exact same marker again // a second turn proposes the exact same marker again
const second = applyTurnResult(first, { const second = applyTurnResult(first, {
date: '1939-09-05', events: [], stateChanges: [], regionChanges: [], relations: [], territoryChanges: [], date: '1939-09-05', events: [], stateChanges: [], regionChanges: [], relations: [], territoryChanges: [],
unowned: [], nationOps: [], takeovers: [], wars: { declare: [], end: [] }, hybrid: { ops: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, ideology: { changes: [] }, disasters: { events: [] },markers: { add, remove: [] }, unowned: [], nationOps: [], takeovers: [], wars: { declare: [], end: [] }, hybrid: { ops: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, ideology: { changes: [] }, disasters: { events: [] }, migration: { ops: [] }, sea: { control: [] }, contested: { open: [], resolve: [] }, markers: { add, remove: [] },
}, undefined, centroidOf); }, undefined, centroidOf);
expect(second.markers).toHaveLength(1); expect(second.markers).toHaveLength(1);
expect(second.markers[0].id).toBe(first.markers[0].id); // stable id, no second copy expect(second.markers[0].id).toBe(first.markers[0].id); // stable id, no second copy
@@ -2038,7 +2042,7 @@ describe('markers (point placement, v0.27 #44)', () => {
hybrid: { ops: [] }, hybrid: { ops: [] },
economy: { trade: [], embargo: [] }, industry: { projects: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] },
nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] },
ideology: { changes: [] }, disasters: { events: [] },markers: { ideology: { changes: [] }, disasters: { events: [] }, migration: { ops: [] }, sea: { control: [] }, contested: { open: [], resolve: [] }, markers: {
add: [ add: [
{ type: 'city', name: 'Good', regionKey: 'moselle-rygy' }, // valid + centroid → kept { type: 'city', name: 'Good', regionKey: 'moselle-rygy' }, // valid + centroid → kept
{ type: 'city', name: 'NoCent', regionKey: 'other-key' }, // in validKeys, no centroid → dropped { type: 'city', name: 'NoCent', regionKey: 'other-key' }, // in validKeys, no centroid → dropped
@@ -2085,7 +2089,7 @@ describe('markers (point placement, v0.27 #44)', () => {
hybrid: { ops: [] }, hybrid: { ops: [] },
economy: { trade: [], embargo: [] }, industry: { projects: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] },
nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] },
ideology: { changes: [] }, disasters: { events: [] },markers: { ideology: { changes: [] }, disasters: { events: [] }, migration: { ops: [] }, sea: { control: [] }, contested: { open: [], resolve: [] }, markers: {
add: [ add: [
{ type: 'city', name: 'NewA', regionKey: 'new-a' }, { type: 'city', name: 'NewA', regionKey: 'new-a' },
{ type: 'city', name: 'NewB', regionKey: 'new-b' }, { type: 'city', name: 'NewB', regionKey: 'new-b' },
@@ -2110,7 +2114,7 @@ describe('markers (point placement, v0.27 #44)', () => {
]; ];
const next = applyTurnResult(state, { const next = applyTurnResult(state, {
date: '1939-09-03', events: [], stateChanges: [], regionChanges: [], relations: [], territoryChanges: [], date: '1939-09-03', events: [], stateChanges: [], regionChanges: [], relations: [], territoryChanges: [],
unowned: [], nationOps: [], takeovers: [], wars: { declare: [], end: [] }, hybrid: { ops: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, ideology: { changes: [] }, disasters: { events: [] },markers: { add: [], remove: [idA, 'zzzz-not-there'] }, unowned: [], nationOps: [], takeovers: [], wars: { declare: [], end: [] }, hybrid: { ops: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, ideology: { changes: [] }, disasters: { events: [] }, migration: { ops: [] }, sea: { control: [] }, contested: { open: [], resolve: [] }, markers: { add: [], remove: [idA, 'zzzz-not-there'] },
}, undefined, centroidOf); }, undefined, centroidOf);
expect(next.markers).toHaveLength(1); expect(next.markers).toHaveLength(1);
expect(next.markers[0].id).toBe(idB); // only A removed; the bogus id was a no-op expect(next.markers[0].id).toBe(idB); // only A removed; the bogus id was a no-op
@@ -2126,14 +2130,14 @@ describe('markers (point placement, v0.27 #44)', () => {
// 1) uk releases the region → the marker becomes ownerless // 1) uk releases the region → the marker becomes ownerless
const released = applyTurnResult(state, { const released = applyTurnResult(state, {
date: '1939-09-03', events: [], stateChanges: [], regionChanges: [], relations: [], territoryChanges: [], date: '1939-09-03', events: [], stateChanges: [], regionChanges: [], relations: [], territoryChanges: [],
unowned: ['moselle-rygy'], nationOps: [], takeovers: [], wars: { declare: [], end: [] }, hybrid: { ops: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, ideology: { changes: [] }, disasters: { events: [] },markers: { add: [], remove: [] }, unowned: ['moselle-rygy'], nationOps: [], takeovers: [], wars: { declare: [], end: [] }, hybrid: { ops: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, ideology: { changes: [] }, disasters: { events: [] }, migration: { ops: [] }, sea: { control: [] }, contested: { open: [], resolve: [] }, markers: { add: [], remove: [] },
}, undefined, centroidOf); }, undefined, centroidOf);
expect(released.markers[0].ownerNationId).toBeNull(); expect(released.markers[0].ownerNationId).toBeNull();
// 2) de re-claims the region → the marker's owner follows to de // 2) de re-claims the region → the marker's owner follows to de
const reclaimed = applyTurnResult(released, { const reclaimed = applyTurnResult(released, {
date: '1939-09-05', events: [], stateChanges: [], regionChanges: [], relations: [], date: '1939-09-05', events: [], stateChanges: [], regionChanges: [], relations: [],
territoryChanges: [{ nation: 'de', gain: ['moselle-rygy'], lose: [] }], territoryChanges: [{ nation: 'de', gain: ['moselle-rygy'], lose: [] }],
unowned: [], nationOps: [], takeovers: [], wars: { declare: [], end: [] }, hybrid: { ops: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, ideology: { changes: [] }, disasters: { events: [] },markers: { add: [], remove: [] }, unowned: [], nationOps: [], takeovers: [], wars: { declare: [], end: [] }, hybrid: { ops: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, ideology: { changes: [] }, disasters: { events: [] }, migration: { ops: [] }, sea: { control: [] }, contested: { open: [], resolve: [] }, markers: { add: [], remove: [] },
}, undefined, centroidOf); }, undefined, centroidOf);
expect(reclaimed.markers[0].ownerNationId).toBe('de'); expect(reclaimed.markers[0].ownerNationId).toBe('de');
}); });
@@ -2203,7 +2207,7 @@ describe('markers (point placement, v0.27 #44)', () => {
hybrid: { ops: [] }, hybrid: { ops: [] },
economy: { trade: [], embargo: [] }, industry: { projects: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] },
nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] },
ideology: { changes: [] }, disasters: { events: [] },markers: { add: [{ type: 'city', name: 'Strasbourg', regionKey: 'moselle-rygy' }], remove: [] }, ideology: { changes: [] }, disasters: { events: [] }, migration: { ops: [] }, sea: { control: [] }, contested: { open: [], resolve: [] }, markers: { add: [{ type: 'city', name: 'Strasbourg', regionKey: 'moselle-rygy' }], remove: [] },
}); });
const { state } = await runTurn({ const { state } = await runTurn({
llm: fakeLlm([result]), llm: fakeLlm([result]),
@@ -2278,6 +2282,10 @@ function mkTurnState(
embargoes: [], embargoes: [],
// (v0.36.0, #59) no industry projects on a fresh state. // (v0.36.0, #59) no industry projects on a fresh state.
industry: [], industry: [],
// (v0.43.0, #65) no sea-zone control on a fresh state.
seaZones: [],
// (v0.44.0, #66) no contested regions on a fresh state.
contested: [],
}; };
} }
@@ -2300,6 +2308,9 @@ function mkTurnResult(partial: Partial<TurnResult>): TurnResult {
leaders: partial.leaders ?? { changes: [] }, leaders: partial.leaders ?? { changes: [] },
ideology: partial.ideology ?? { changes: [] }, ideology: partial.ideology ?? { changes: [] },
disasters: partial.disasters ?? { events: [] }, disasters: partial.disasters ?? { events: [] },
migration: partial.migration ?? { ops: [] },
sea: partial.sea ?? { control: [] },
contested: partial.contested ?? { open: [], resolve: [] },
markers: partial.markers ?? { add: [], remove: [] }, markers: partial.markers ?? { add: [], remove: [] },
}; };
} }
@@ -3025,7 +3036,7 @@ describe('validateTakeovers (v0.32.0 #54)', () => {
hybrid: { ops: [] }, hybrid: { ops: [] },
economy: { trade: [], embargo: [] }, industry: { projects: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] },
nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] },
ideology: { changes: [] }, disasters: { events: [] },markers: { add: [], remove: [] }, ideology: { changes: [] }, disasters: { events: [] }, migration: { ops: [] }, sea: { control: [] }, contested: { open: [], resolve: [] }, markers: { add: [], remove: [] },
}); });
expect(withTakeovers).not.toBeNull(); expect(withTakeovers).not.toBeNull();
// the valid one survives, the empty-name one is dropped // the valid one survives, the empty-name one is dropped
@@ -3413,7 +3424,7 @@ describe('isMeaningful — wars (v0.33.0 #56)', () => {
hybrid: { ops: [] }, hybrid: { ops: [] },
economy: { trade: [], embargo: [] }, industry: { projects: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] },
nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] },
ideology: { changes: [] }, disasters: { events: [] },markers: { add: [], remove: [] }, ideology: { changes: [] }, disasters: { events: [] }, migration: { ops: [] }, sea: { control: [] }, contested: { open: [], resolve: [] }, markers: { add: [], remove: [] },
}), }),
).toBe(true); ).toBe(true);
}); });
@@ -3434,7 +3445,7 @@ describe('isMeaningful — wars (v0.33.0 #56)', () => {
hybrid: { ops: [] }, hybrid: { ops: [] },
economy: { trade: [], embargo: [] }, industry: { projects: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] },
nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] },
ideology: { changes: [] }, disasters: { events: [] },markers: { add: [], remove: [] }, ideology: { changes: [] }, disasters: { events: [] }, migration: { ops: [] }, sea: { control: [] }, contested: { open: [], resolve: [] }, markers: { add: [], remove: [] },
}), }),
).toBe(true); ).toBe(true);
}); });
@@ -3455,7 +3466,7 @@ describe('isMeaningful — wars (v0.33.0 #56)', () => {
hybrid: { ops: [] }, hybrid: { ops: [] },
economy: { trade: [], embargo: [] }, industry: { projects: [] }, economy: { trade: [], embargo: [] }, industry: { projects: [] },
nuclear: { arm: [], strikes: [] }, leaders: { changes: [] }, nuclear: { arm: [], strikes: [] }, leaders: { changes: [] },
ideology: { changes: [] }, disasters: { events: [] },markers: { add: [], remove: [] }, ideology: { changes: [] }, disasters: { events: [] }, migration: { ops: [] }, sea: { control: [] }, contested: { open: [], resolve: [] }, markers: { add: [], remove: [] },
}), }),
).toBe(false); ).toBe(false);
}); });
+84 -1
View File
@@ -16,6 +16,7 @@ import type {
RegionResources, RegionResources,
RegionStats, RegionStats,
RoundItem, RoundItem,
SeaZoneClaim,
StatKey, StatKey,
TradeAgreement, TradeAgreement,
} from '../shared/types'; } from '../shared/types';
@@ -34,6 +35,7 @@ import {
markerId, markerId,
MAX_MARKERS, MAX_MARKERS,
nationForPrompt, nationForPrompt,
type ContestedRegion,
type MarkerInfo, type MarkerInfo,
type MarkerSpec, type MarkerSpec,
type NationOp, type NationOp,
@@ -94,6 +96,29 @@ export {
DISASTER_TYPES, DISASTER_TYPES,
DISASTER_SEVERITIES, DISASTER_SEVERITIES,
DISASTER_EFFECTS, DISASTER_EFFECTS,
validateMigrationOps,
applyMigrationOp,
shiftRelationTowardPositive,
isMigrationKind,
isMigrationScale,
MIGRATION_KINDS,
MIGRATION_SCALES,
MIGRATION_SOURCE_EFFECTS,
MIGRATION_DESTINATION_EFFECTS,
LARGE_INFLUX_STABILITY_DIP,
validateSeaOps,
applySeaControl,
applySeaZoneBonuses,
SEA_ZONE_BONUS,
SEA_ZONES,
SEA_ZONE_IDS,
isSeaZoneId,
seaZoneName,
validateContestedOps,
applyContested,
CONTESTED_FILL,
CONTESTED_STROKE,
contestedTooltipLabel,
} from './abilities'; } from './abilities';
// --- The LLM's getNeighbours tool (v0.21, #16 P2: contiguous region transfers) --- // --- The LLM's getNeighbours tool (v0.21, #16 P2: contiguous region transfers) ---
@@ -366,6 +391,22 @@ export function buildUserPrompt(
* key on any nation) when undefined. * key on any nation) when undefined.
*/ */
nuclear?: Record<string, boolean>, nuclear?: Record<string, boolean>,
/**
* (v0.43.0, #65) The game's current sea-zone control (each a `{ zone, by }`
* pair of the fixed sea zones and their controlling nation id). Emitted
* verbatim (even when empty) so the model knows which of the 12 fixed sea
* zones each nation currently controls and can re-claim or contest them via
* `TurnResult.sea`. Omitted entirely when undefined.
*/
seaZones?: SeaZoneClaim[],
/**
* (v0.44.0, #66) The game's current contested regions (each a `{ regionKey,
* parties }` pair — a war frontline in no nation's territory and not in
* `unowned`). Emitted verbatim (even when empty) so the model knows which
* regions are frontlines (and can `resolve` them or see their parties);
* omitted entirely when undefined.
*/
contested?: ContestedRegion[],
): string { ): string {
const player = state.nations[state.playerNationId]; const player = state.nations[state.playerNationId];
const playerName = player?.name ?? state.playerNationId; const playerName = player?.name ?? state.playerNationId;
@@ -475,6 +516,8 @@ export function buildUserPrompt(
embargoes, embargoes,
nationResources, nationResources,
industryProjects, industryProjects,
seaZones,
contested,
}; };
Object.assign(payload, ABILITIES[0].payload(upCtx)); // takeovers → takeoverRisks Object.assign(payload, ABILITIES[0].payload(upCtx)); // takeovers → takeoverRisks
if (noMansLand !== undefined) payload.unowned = noMansLand; if (noMansLand !== undefined) payload.unowned = noMansLand;
@@ -483,6 +526,8 @@ export function buildUserPrompt(
Object.assign(payload, ABILITIES[2].payload(upCtx)); // hybrid → relations Object.assign(payload, ABILITIES[2].payload(upCtx)); // hybrid → relations
Object.assign(payload, ABILITIES[3].payload(upCtx)); // economy → trades, embargoes Object.assign(payload, ABILITIES[3].payload(upCtx)); // economy → trades, embargoes
Object.assign(payload, ABILITIES[4].payload(upCtx)); // industry → resources, industry Object.assign(payload, ABILITIES[4].payload(upCtx)); // industry → resources, industry
Object.assign(payload, ABILITIES[10].payload(upCtx)); // sea → seaZones (always emitted)
Object.assign(payload, ABILITIES[11].payload(upCtx)); // contested → contested (only when non-empty)
return JSON.stringify(payload, null, 2); return JSON.stringify(payload, null, 2);
} }
@@ -622,6 +667,9 @@ export function validateTurnResult(
leaders: { changes: [] }, leaders: { changes: [] },
ideology: { changes: [] }, ideology: { changes: [] },
disasters: { events: [] }, disasters: { events: [] },
migration: { ops: [] },
sea: { control: [] },
contested: { open: [], resolve: [] },
markers: { add: [], remove: [] }, markers: { add: [], remove: [] },
}; };
@@ -712,7 +760,7 @@ export function validateTurnResult(
// list for the player to confirm/reject. // list for the player to confirm/reject.
result.nationOps = validateNationOps(o.nationOps); result.nationOps = validateNationOps(o.nationOps);
// The 9 per-feature LLM abilities (v0.40.0, #67): each one's validate call // The 11 per-feature LLM abilities (v0.40.0, #67): each one's validate call
// is owned by its Ability module in the ABILITIES registry. The field's raw // is owned by its Ability module in the ABILITIES registry. The field's raw
// value is passed through a.validate() which returns the validated field shape. // value is passed through a.validate() which returns the validated field shape.
for (const a of ABILITIES) { for (const a of ABILITIES) {
@@ -906,6 +954,12 @@ export function applyTurnResult(
// (v0.36, #59) active industry projects; a legacy/corrupt clone without the // (v0.36, #59) active industry projects; a legacy/corrupt clone without the
// field starts empty (the turn then only ever adds to it). // field starts empty (the turn then only ever adds to it).
next.industry = next.industry ?? []; next.industry = next.industry ?? [];
// (v0.43.0, #65) sea-zone control; a legacy/corrupt clone without the field
// starts empty (the turn then upserts this turn's claims into it).
next.seaZones = next.seaZones ?? [];
// (v0.44.0, #66) contested regions (war frontlines); a legacy/corrupt clone
// without the field starts empty (the turn then opens/resolves contests).
next.contested = next.contested ?? [];
const actingTurn = state.turn; // this action resolves the current turn const actingTurn = state.turn; // this action resolves the current turn
next.turn = state.turn + 1; // then we advance to the next turn to play next.turn = state.turn + 1; // then we advance to the next turn to play
next.date = isDateLike(result.date) ? result.date : addDays(state.date, 2); next.date = isDateLike(result.date) ? result.date : addDays(state.date, 2);
@@ -1001,12 +1055,34 @@ export function applyTurnResult(
} }
set.add(gainer); set.add(gainer);
} }
// (v0.44.0, #66) Contested-region guard for the claims step below: a region
// that is currently a war frontline (in `state.contested`) sits in no
// nation's territory, so a normal `gain` would otherwise treat it as a free
// re-claim. A contested key may only be claimed by a normal claim when this
// same turn resolves the contest AND the gainer is one of the contesting
// parties (a party re-claim); otherwise the frontline stays contested for
// the contested layer (later in the turn) to decide its fate.
const contestedBefore = new Set((state.contested ?? []).map((c) => c.regionKey));
const resolveThisTurn = new Set(result.contested.resolve);
const contestedParties = new Map(
(state.contested ?? []).map((c) => [c.regionKey, c.parties]),
);
for (const [key, claiming] of claimants) { for (const [key, claiming] of claimants) {
if (claiming.size !== 1) continue; // double claim: the key stays as it was if (claiming.size !== 1) continue; // double claim: the key stays as it was
const gainer = [...claiming][0]; const gainer = [...claiming][0];
const owner = ownerOf.get(key); // undefined: no owner; '': 2+ owners (corrupt) const owner = ownerOf.get(key); // undefined: no owner; '': 2+ owners (corrupt)
if (owner === '') continue; // pre-existing double ownership: never touched if (owner === '') continue; // pre-existing double ownership: never touched
if (owner !== undefined && owner === gainer) continue; // self-gain: no-op if (owner !== undefined && owner === gainer) continue; // self-gain: no-op
// (v0.44.0, #66) a currently-contested frontline is not a normal claim
// target: a claim on it only proceeds when this turn resolves the contest
// and the gainer is one of the contesting parties (a party re-claim);
// otherwise the frontline stays contested for the contested layer below.
if (
contestedBefore.has(key) &&
(!resolveThisTurn.has(key) || !contestedParties.get(key)?.includes(gainer))
) {
continue;
}
// (v0.30, #50) MILITARY HARD GATE: a CONTESTED conquest (the key has a // (v0.30, #50) MILITARY HARD GATE: a CONTESTED conquest (the key has a
// different sole owner) only proceeds when the attacker's derived military // different sole owner) only proceeds when the attacker's derived military
// is not MORE than CONQUEST_MILITARY_MARGIN below the defender's. A // is not MORE than CONQUEST_MILITARY_MARGIN below the defender's. A
@@ -1583,6 +1659,13 @@ export async function runTurn(opts: {
state.industry ?? [], state.industry ?? [],
// (v0.37.0, #60) per-nation nuclear capability (flag or rocket marker). // (v0.37.0, #60) per-nation nuclear capability (flag or rocket marker).
nuclearCapability, nuclearCapability,
// (v0.43.0, #65) the current sea-zone control (always emitted — even when
// empty — so the model knows who controls which of the fixed sea zones).
state.seaZones ?? [],
// (v0.44.0, #66) the current contested regions (war frontlines) — emitted
// verbatim (even when empty) so the model knows which regions are
// frontlines and can resolve them.
state.contested ?? [],
); );
const nudge = const nudge =
'Your previous output was invalid. Respond with ONLY the JSON object described above for this batch — no prose, no fences.'; 'Your previous output was invalid. Respond with ONLY the JSON object described above for this batch — no prose, no fences.';
+4
View File
@@ -190,6 +190,10 @@ app.post('/api/games', (req: Request, res) => {
// declares them over time via TurnResult.industry (one per region, a // declares them over time via TurnResult.industry (one per region, a
// per-region SET). // per-region SET).
industry: [], industry: [],
// (v0.43.0, #65) no sea-zone control on a fresh state.
seaZones: [],
// (v0.44.0, #66) no contested regions on a fresh state.
contested: [],
}; };
// v0.19 (#16 P1): expand each nation's ISO_A3 country list to the region keys // v0.19 (#16 P1): expand each nation's ISO_A3 country list to the region keys
// of all its sub-regions, so ownership (and the choropleth) is at region // of all its sub-regions, so ownership (and the choropleth) is at region
+4
View File
@@ -59,6 +59,10 @@ const state: GameState = {
embargoes: [], embargoes: [],
// (v0.36.0, #59) the map is ownership-only; industry is unused here. // (v0.36.0, #59) the map is ownership-only; industry is unused here.
industry: [], industry: [],
// (v0.43.0, #65) no sea-zone control on a fresh state.
seaZones: [],
// (v0.44.0, #66) no contested regions on a fresh state.
contested: [],
}; };
// The RegionMap built from the fixture: the authoritative region key → owner source. // The RegionMap built from the fixture: the authoritative region key → owner source.
+4
View File
@@ -48,6 +48,10 @@ function mkState(
trades: [], trades: [],
embargoes: [], embargoes: [],
industry: [], industry: [],
// (v0.43.0, #65) no sea-zone control on a fresh state.
seaZones: [],
// (v0.44.0, #66) no contested regions on a fresh state.
contested: [],
}; };
if (regionStats !== undefined) base.regionStats = regionStats as GameState['regionStats']; if (regionStats !== undefined) base.regionStats = regionStats as GameState['regionStats'];
else delete (base as { regionStats?: unknown }).regionStats; // simulate a legacy row else delete (base as { regionStats?: unknown }).regionStats; // simulate a legacy row
+4
View File
@@ -118,6 +118,10 @@ describe('regions (region-key loader, v0.19 #16 P1)', () => {
embargoes: [], embargoes: [],
// (v0.36.0, #59) unused here (allTerritoryKeys is ownership-only). // (v0.36.0, #59) unused here (allTerritoryKeys is ownership-only).
industry: [], industry: [],
// (v0.43.0, #65) no sea-zone control on a fresh state.
seaZones: [],
// (v0.44.0, #66) no contested regions on a fresh state.
contested: [],
}; };
// 16 GBR sub-regions + 42 FRA sub-regions, no overlap between the two. // 16 GBR sub-regions + 42 FRA sub-regions, no overlap between the two.
expect(allTerritoryKeys(state).size).toBe(58); expect(allTerritoryKeys(state).size).toBe(58);
+35 -2
View File
@@ -100,6 +100,21 @@ export interface StubPayload {
* deterministicTurn), so the industry path is covered by unit tests only. * deterministicTurn), so the industry path is covered by unit tests only.
*/ */
industry?: Array<{ regionKey: string; type: string }>; industry?: Array<{ regionKey: string; type: string }>;
/**
* (v0.43.0, #65) The currently active sea-zone control
* (`{ zone, by }` — fixed sea-zone id + controlling nation id), emitted by
* the engine's user prompt (always, even when empty). The stub ignores this
* field — it never claims, contests or re-claims a sea zone (see
* deterministicTurn), so the sea path is covered by unit tests only.
*/
seaZones?: Array<{ zone: string; by: string }>;
/**
* (v0.44.0, #66) The currently contested regions (war frontlines,
* `{ regionKey, parties }`), emitted by the engine's user prompt. The stub
* ignores this field — it never opens or resolves a contest (see
* deterministicTurn), so the contested path is covered by unit tests only.
*/
contested?: Array<{ regionKey: string; parties: string[] }>;
} }
function truncate(s: string, n: number): string { function truncate(s: string, n: number): string {
@@ -173,6 +188,23 @@ function truncate(s: string, n: number): string {
* (v0.39.0, #62) The stub likewise NEVER changes a nation's ideology (it * (v0.39.0, #62) The stub likewise NEVER changes a nation's ideology (it
* always returns `ideology: { changes: [] }`) — the ideology path is covered * always returns `ideology: { changes: [] }`) — the ideology path is covered
* by unit tests only, keeping the e2e assertions untouched. * by unit tests only, keeping the e2e assertions untouched.
*
* (v0.41.0, #63) The stub likewise NEVER declares a disaster or pandemic (it
* always returns `disasters: { events: [] }`) — the disasters path is covered
* by unit tests only, keeping the e2e assertions untouched.
*
* (v0.42.0, #64) The stub likewise NEVER declares a migration / refugee flow
* (it always returns `migration: { ops: [] }`) — the migration path is
* covered by unit tests only, keeping the e2e assertions untouched.
*
* (v0.43.0, #65) The stub likewise NEVER claims, contests or re-claims a sea
* zone (it always returns `sea: { control: [] }`) — the sea-control path is
* covered by unit tests only, keeping the e2e assertions untouched.
*
* (v0.44.0, #66) The stub likewise NEVER opens or resolves a contested region
* (a war frontline) — it always returns `contested: { open: [], resolve: [] }`
* — the contested path is covered by unit tests only, keeping the e2e
* assertions untouched.
*/ */
export function deterministicTurn(p: StubPayload): TurnResult { export function deterministicTurn(p: StubPayload): TurnResult {
const state = p.state; const state = p.state;
@@ -252,13 +284,14 @@ export function deterministicTurn(p: StubPayload): TurnResult {
nationOps: [], // the stub never proposes nation ops (see doc comment) nationOps: [], // the stub never proposes nation ops (see doc comment)
}; };
// The 9 ability fields, filled by the registry in its canonical order. The // The 12 ability fields, filled by the registry in its canonical order. The
// stub is ability-inert: every ability contributes its own no-op default // stub is ability-inert: every ability contributes its own no-op default
// (each ability's `stub()` — see the per-ability doc comments above), so the // (each ability's `stub()` — see the per-ability doc comments above), so the
// e2e assertions are unaffected. The insertion order here (ABILITIES) is the // e2e assertions are unaffected. The insertion order here (ABILITIES) is the
// historical key order pinned by the stub's deterministic output // historical key order pinned by the stub's deterministic output
// (takeovers → wars → hybrid → economy → industry → nuclear → leaders → // (takeovers → wars → hybrid → economy → industry → nuclear → leaders →
// ideology → disasters), which must stay byte-identical. // ideology → disasters → migration → sea → contested), which must stay
// byte-identical.
const abilities = {} as Record<AbilityField, unknown>; const abilities = {} as Record<AbilityField, unknown>;
for (const a of ABILITIES) abilities[a.field] = a.stub(); for (const a of ABILITIES) abilities[a.field] = a.stub();
+254
View File
@@ -650,6 +650,186 @@ export interface DisastersOps {
events: DisasterEvent[]; events: DisasterEvent[];
} }
// --- Migration & refugees (v0.42.0, #64) --------------------------------------
//
// People moving between nations each turn: ordinary migration, refugee flows
// (fleeing a war or disaster), a spreading diaspora, and an exodus (people
// leaving with no destination). Each op names a `kind`, a source `from` (the
// nation people leave), a destination `to` (required for every kind except
// `exodus`), and a `scale` (small / moderate / large). The engine applies a
// DETERMINISTIC effect chosen from the per-`scale` tables
// `MIGRATION_SOURCE_EFFECTS` / `MIGRATION_DESTINATION_EFFECTS` (defined in
// `server/abilities/migration.ts`) — no hidden randomness: the LLM chooses the
// kind and scale, the tables decide the magnitude. The source LOSES a small
// amount of population and economy, the destination GAINS a small amount of
// population and economy (a `large` influx additionally strains the
// destination's stability), both clamped to 0–100, mirrored to each side's
// regions (`regionStats`), and each side's derived `stats` re-derived
// afterwards (the same 0-region / no-entry guards as the hybrid / economy /
// disasters layers). The from↔to relation moves one step toward the positive
// end of the ally/neutral/rival/hostile ladder (`shiftRelationTowardPositive`)
// — capped at `ally` for `refugees`, `neutral` for `migration` / `diaspora`,
// and not at all for `exodus` — and a `war` relation is never touched. It is
// **turn-transient** like the hybrid / disasters layers: there is NO `GameState`
// field, no durable list, and no `db.ts` change — a continuing flow is simply
// re-declared each turn it persists. It never moves territory (sole ownership
// is untouched) and never creates or escalates a war.
/** The kind of population flow a migration op describes (v0.42.0, #64). */
export type MigrationKind = 'migration' | 'refugees' | 'diaspora' | 'exodus';
/** The size of a migration flow (v0.42.0, #64). */
export type MigrationScale = 'small' | 'moderate' | 'large';
/**
* A single migration / refugee flow (v0.42.0, #64): the `kind`, the source
* `from` (a nation id / name — the nation people leave), the destination `to`
* (a nation id / name — required for every kind except `exodus`, which has no
* destination), the `scale`, and an optional short `detail`. The deterministic
* stat effects are looked up from `MIGRATION_SOURCE_EFFECTS` /
* `MIGRATION_DESTINATION_EFFECTS` by `scale`.
*/
export interface MigrationOp {
/** The kind of flow (one of {@link MigrationKind}). */
kind: MigrationKind;
/** The source nation (by id or name) people leave. */
from: string;
/** The destination nation (by id or name). Required for every kind except `exodus`. */
to?: string;
/** How many people moved (one of {@link MigrationScale}). */
scale: MigrationScale;
/** Optional short annotation (≤300 chars). */
detail?: string;
}
/** The migration block of a `TurnResult`. Required; default `{ ops: [] }`. */
export interface MigrationOps {
ops: MigrationOp[];
}
// ---------------------------------------------------------------------------
// (v0.43.0, #65) Sea zones & sea control — the naval layer, fully parallel to
// but INDEPENDENT of land. The world has a fixed set of 12 named SEA ZONES
// ({@link SEA_ZONES}); each is under the SOLE CONTROL of at most one nation.
// Controlling a sea zone never moves land (`territory` / `unowned` are
// untouched) and moving land never touches a sea zone. `SeaZoneClaim` (the
// durable per-zone record, `{ zone, by }`) lives in `shared/types.ts` like
// `Trade` / `Embargo` / `War` / `IndustryProject`; `GameState.seaZones` is a
// list of them, unique per zone (`[]` at creation; a legacy SQLite row
// without the field loads as `[]` — additive, never wiped). Each turn the LLM
// declares `TurnResult.sea.control` ops — one op names the zone and the
// nation that (now) controls it. The engine resolves `by` (id first, then a
// case-insensitive unique name) and UPSERTS the zone's claim (replace in
// place if the zone is already claimed, append if new). If two or more ops
// this turn claim the SAME zone for DIFFERENT resolved nations, the zone is
// CONTESTED: the higher current `stats.military` wins (a tie goes to the op
// listed earlier in the `control` array) — deterministic, no hidden
// randomness; an unresolvable `by` is dropped (never thrown). Every committed
// turn — including a turn with an empty `control` — each existing claim's
// controller earns a small DETERMINISTIC bonus (`SEA_ZONE_BONUS = 1` military
// + 1 economy, clamped to 0–100, mirrored to the controller's regions and
// re-derived with the same 0-region / no-entry guards as the economy /
// migration layers); a claim whose nation no longer exists is skipped (the
// claim is kept, never thrown). The layer is DURABLE (unlike the turn-
// transient hybrid / disasters / migration layers): `GameState.seaZones`
// persists across turns and in SQLite. The user payload carries the current
// `seaZones` list so the model knows who controls which zone.
/** The 12 named sea zones the world model knows (v0.43.0, #65). */
export const SEA_ZONES = [
{ id: 'north-atlantic', name: 'North Atlantic' },
{ id: 'south-atlantic', name: 'South Atlantic' },
{ id: 'pacific', name: 'Pacific Ocean' },
{ id: 'indian', name: 'Indian Ocean' },
{ id: 'mediterranean', name: 'Mediterranean Sea' },
{ id: 'north-sea', name: 'North Sea' },
{ id: 'baltic', name: 'Baltic Sea' },
{ id: 'arctic', name: 'Arctic Ocean' },
{ id: 'black-sea', name: 'Black Sea' },
{ id: 'gulf-mexico', name: 'Gulf of Mexico' },
{ id: 'red-sea', name: 'Red Sea' },
{ id: 'sargasso', name: 'Sargasso Sea' },
] as const;
/** The set of valid sea-zone ids (v0.43.0, #65). */
export const SEA_ZONE_IDS: ReadonlySet<string> = new Set(SEA_ZONES.map((z) => z.id));
/** Whether `id` is one of the fixed sea-zone ids (v0.43.0, #65). */
export function isSeaZoneId(id: string): boolean {
return SEA_ZONE_IDS.has(id);
}
/** The display name of a sea-zone id; an unknown id is returned as-is (v0.43.0, #65). */
export function seaZoneName(id: string): string {
return SEA_ZONES.find((z) => z.id === id)?.name ?? id;
}
/**
* A single sea-control op (v0.43.0, #65): `zone` is one of the fixed
* {@link SEA_ZONES} ids and `by` is the nation that (now) controls it (by id
* or name). One op SETS or REPLACES the zone's controller; two or more ops on
* the same zone for different nations are CONTESTED — the higher current
* `stats.military` wins (a tie: the earlier-listed op).
*/
export interface SeaControlOp {
/** The sea zone (one of {@link SEA_ZONE_IDS}). */
zone: string;
/** The controlling nation (by id or name). */
by: string;
}
/** The sea-control block of a `TurnResult`. Required; default `{ control: [] }`. */
export interface SeaOps {
control: SeaControlOp[];
}
/**
* (v0.44.0, #66) A single `open` op: make a region **contested** — a war
* frontline that is in **no** nation's `territory` and not in `unowned` (a
* third region state, besides "owned by one nation" and "no man's land").
* `regionKey` is the region key (or a resolvable region name); `parties` are
* two or more nation refs (ids or names), resolved via the shared
* `resolveNationRef` — the stored `ContestedRegion.parties` are the resolved
* nation ids.
*/
export interface ContestOp {
/** The region key to make contested (the model names it by key or name). */
regionKey: string;
/**
* The nations contesting the region — two or more refs (ids or names). At
* least two distinct, resolvable nations are required, and the region's
* sole owner (if any) must be at war with one of them (or, for a
* no-man's-land region, two of the parties must be at war with each other).
*/
parties: string[];
}
/**
* The contested-region block of a `TurnResult`. Required; default
* `{ open: [], resolve: [] }`. `open` makes a region a contested frontline
* (it leaves its owner's `territory` and `unowned` — sole ownership is
* preserved); `resolve` ends a contest, releasing the region to no man's
* land — unless a concurrent winning claim by one of the parties re-owns it
* (re-initialising its `regionStats`).
*/
export interface ContestedOps {
/** Regions to make contested this turn. */
open: ContestOp[];
/** Region keys to resolve (release to no man's land) this turn. */
resolve: string[];
}
/**
* A contested region — a region key that is a war frontline: in **no**
* nation's `territory` and not in `unowned`, contested by `parties` (resolved
* nation ids, two or more). Stored in `GameState.contested` (unique by
* `regionKey`).
*/
export interface ContestedRegion {
regionKey: string;
parties: string[];
}
/** The exact JSON object the world-simulator LLM must return for a turn. */ /** The exact JSON object the world-simulator LLM must return for a turn. */
export interface TurnResult { export interface TurnResult {
date: string; date: string;
@@ -819,6 +999,59 @@ export interface TurnResult {
* `{ events: [] }`. * `{ events: [] }`.
*/ */
disasters: DisastersOps; disasters: DisastersOps;
/**
* (v0.42.0, #64) Migration & refugee flows this turn — people moving between
* nations: ordinary `migration`, `refugees` fleeing a war or disaster, a
* spreading `diaspora`, and an `exodus` (people leaving with no destination).
* Each op names a `from` (the source nation, by id or name) and, for every
* kind except `exodus`, a `to` (the destination nation, by id or name), plus
* a `scale` (small / moderate / large). Applied directly by `applyTurnResult`
* (like the disasters / hybrid layers): the source LOSES a small amount of
* population and economy, the destination GAINS a small amount of population
* and economy (a `large` influx additionally strains the destination's
* stability by 2), both clamped to 0–100, mirrored to each side's regions,
* and each side's derived `stats` re-derived afterwards; the from↔to
* relation moves one step toward the positive end of the
* ally/neutral/rival/hostile ladder (capped at `ally` for `refugees`,
* `neutral` for `migration` / `diaspora`, not at all for `exodus`; a `war`
* relation is never touched). The layer is turn-transient (no `GameState`
* field, no `db.ts` change) — a continuing flow is simply re-declared each
* turn it persists. It never moves borders (sole ownership is untouched) and
* never creates or escalates a war. At most 1–2 per turn, each narrated in
* `events` (a `social` or `diplomatic` event). Required; default
* `{ ops: [] }`.
*/
migration: MigrationOps;
/**
* (v0.43.0, #65) Sea-zone control ops this turn — the naval layer, fully
* parallel to but INDEPENDENT of land: each op names one of the 12 fixed
* sea zones (`SEA_ZONES`) and the nation that now controls it. The engine
* resolves `by` (id first, then a case-insensitive unique name) and
* upserts the zone's claim in `GameState.seaZones` (a single op sets or
* replaces the controller; two or more ops on the same zone for different
* nations are CONTESTED — the higher current `stats.military` wins, a tie
* goes to the op listed earlier in `control`; an unresolvable `by` is
* dropped, never thrown). Every committed turn, each existing claim's
* controller earns a small deterministic military/economy bonus
* (`SEA_ZONE_BONUS`). Sea control never moves land: `territory` and
* `unowned` are untouched. At most 1–2 per turn, each narrated in `events`
* (a `military` or `diplomatic` event). Required; default
* `{ control: [] }`.
*/
sea: SeaOps;
/**
* (v0.44.0, #66) Contested regions / frontlines: `open` makes a region a
* contested war frontline (it leaves its owner's `territory` and `unowned`
* — a third region state in no territory and not no man's land — and is
* contested by two or more nations at war); `resolve` ends a contest,
* releasing the region to no man's land unless a concurrent winning claim
* by one of the parties re-owns it. A region with a sole owner not at war
* with any party, or two or more owners, cannot be contested. Sole
* ownership is never broken; a still-contested key is not a valid normal
* claim target. At most 1–2 per turn, each narrated in `events`. Required;
* default `{ open: [], resolve: [] }`.
*/
contested: ContestedOps;
/** /**
* (v0.27, #44) Map-marker ops this turn. `add` places new named markers * (v0.27, #44) Map-marker ops this turn. `add` places new named markers
* (the engine positions each at its region's centroid + a small * (the engine positions each at its region's centroid + a small
@@ -1060,6 +1293,27 @@ export const UNOWNED_STROKE = 'rgba(255,255,255,0.14)';
/** The border of an owned region (brighter than unowned). */ /** The border of an owned region (brighter than unowned). */
export const OWNED_STROKE = 'rgba(255,255,255,0.30)'; export const OWNED_STROKE = 'rgba(255,255,255,0.30)';
/**
* The distinct, visible fill + stroke for a **contested** region (a war
* frontline — a key that is in no nation's `territory` and not in `unowned`).
* Reddish/orange to read as a "hot" frontline on the dark basemap — clearly
* distinct from a nation color and from the no-man's-land grey. The contested
* state is decided by the client (via `GameState.contested`), never by the
* `RegionMap` (which only knows owned vs absent).
*/
export const CONTESTED_FILL = '#f97316';
export const CONTESTED_STROKE = 'rgba(255,237,213,0.55)';
/**
* The hover-tooltip sub-line for a contested region: a short "Contested:
* A vs B" line naming the contesting parties. A missing party name (a nation
* removed by a merge/split) degrades to a dash, never crashes.
*/
export function contestedTooltipLabel(parties: string[]): string {
const names = parties.map((p) => p || '—');
return `Contested: ${names.join(' vs ')}`;
}
/** The hover-tooltip sub-line for a region with no owning nation. */ /** The hover-tooltip sub-line for a region with no owning nation. */
export function unownedTooltipLabel(isNoMansLand: boolean): string { export function unownedTooltipLabel(isNoMansLand: boolean): string {
return isNoMansLand ? "No man's land" : 'No owner'; return isNoMansLand ? "No man's land" : 'No owner';
+4
View File
@@ -461,6 +461,10 @@ export function worldDraftToGameState(
embargoes: [], embargoes: [],
// (v0.36, #59) No industry projects on a fresh (dynamic) game. // (v0.36, #59) No industry projects on a fresh (dynamic) game.
industry: [], industry: [],
// (v0.43.0, #65) no sea-zone control on a fresh state.
seaZones: [],
// (v0.44.0, #66) no contested regions on a fresh state.
contested: [],
}; };
return state; return state;
} }
+44 -1
View File
@@ -3,7 +3,7 @@
// (The single `import type` below erases at compile time, so no runtime // (The single `import type` below erases at compile time, so no runtime
// dependency on protocol.ts is introduced — see the GameState.pendingNationOps // dependency on protocol.ts is introduced — see the GameState.pendingNationOps
// doc comment.) // doc comment.)
import type { NationOp } from './protocol'; import type { NationOp, ContestedRegion } from './protocol';
/** A nation's 0–100 status indices. Every value is clamped to 0–100 by the engine. */ /** A nation's 0–100 status indices. Every value is clamped to 0–100 by the engine. */
export interface NationStats { export interface NationStats {
@@ -249,6 +249,23 @@ export interface IndustryProject {
type: IndustryType; type: IndustryType;
} }
/**
* (v0.43.0, #65) One sea-zone claim: which nation controls one of the fixed
* sea zones (see `SEA_ZONES` in `shared/protocol.ts`). The world keeps at
* most ONE claim per zone — a new op on an already-claimed zone REPLACES the
* controller in place (the zone's entry is updated, never duplicated), and if
* a turn declares the same zone for two different resolved nations the higher
* current `stats.military` wins (a tie: the op listed earlier in the turn's
* `control` array). Sea control is fully parallel to but INDEPENDENT of land:
* it never touches `territory` / `unowned`.
*/
export interface SeaZoneClaim {
/** The sea zone (one of `SEA_ZONE_IDS`). */
zone: string;
/** The id of the nation that controls it (resolved, not a name). */
by: string;
}
/** /**
* (v0.33.0, #56) A first-class **war** — a named, ongoing armed conflict * (v0.33.0, #56) A first-class **war** — a named, ongoing armed conflict
* between two or more nations. Unlike the boolean `war` relation (which a * between two or more nations. Unlike the boolean `war` relation (which a
@@ -443,6 +460,32 @@ export interface GameState {
* with this defaulted to `[]` (see server/db.ts) — additive, no data wipe. * with this defaulted to `[]` (see server/db.ts) — additive, no data wipe.
*/ */
industry: IndustryProject[]; industry: IndustryProject[];
/**
* (v0.43.0, #65) Sea-zone control (see {@link SeaZoneClaim}): one entry per
* controlled sea zone — which of the 12 fixed zones (`SEA_ZONES`) each
* nation controls. At most ONE entry per zone (unique by `zone`); a turn's
* `sea.control` ops upsert entries (a re-claim by a different nation
* replaces the controller in place; a same-zone contest goes to the higher
* current `stats.military`, a tie to the earlier-listed op). Every
* committed turn each claim's controller earns a small deterministic
* military/economy bonus (`SEA_ZONE_BONUS`). Sea control never moves land
* (`territory` / `unowned` are untouched). Always `[]` on a fresh game;
* rows saved before v0.43 load with this defaulted to `[]` (see
* server/db.ts) — additive, no data wipe.
*/
seaZones: SeaZoneClaim[];
/**
* (v0.44.0, #66) Contested regions / frontlines (see {@link ContestedRegion}):
* one entry per region key that is a war frontline — a key in **no** nation's
* `territory` and not in `unowned`, contested by two or more nations at war.
* A region becomes contested when a turn's `contested.open` succeeds (it
* leaves its owner's `territory` and `unowned` — sole ownership is preserved);
* it is resolved (released to no man's land, or re-claimed by a party) by a
* later `contested.resolve`. At most ONE entry per region key (unique by
* `regionKey`). Always `[]` on a fresh game; rows saved before v0.44 load
* with this defaulted to `[]` (see server/db.ts) — additive, no data wipe.
*/
contested: ContestedRegion[];
} }
/** /**
+1
View File
@@ -834,6 +834,7 @@ function GameScreen({
unowned={game.unowned ?? []} unowned={game.unowned ?? []}
markers={game.markers ?? []} markers={game.markers ?? []}
regionStats={game.regionStats ?? {}} regionStats={game.regionStats ?? {}}
contested={game.contested ?? []}
onFocusNation={focusNation} onFocusNation={focusNation}
/> />
+58 -4
View File
@@ -9,11 +9,15 @@ import 'maplibre-gl/dist/maplibre-gl.css';
import workerUrl from 'maplibre-gl/dist/maplibre-gl-worker.mjs?url'; import workerUrl from 'maplibre-gl/dist/maplibre-gl-worker.mjs?url';
maplibregl.setWorkerUrl(workerUrl); maplibregl.setWorkerUrl(workerUrl);
import { import {
CONTESTED_FILL,
CONTESTED_STROKE,
contestedTooltipLabel,
mapFeatureOwner, mapFeatureOwner,
MARKER_TYPE_INFO, MARKER_TYPE_INFO,
nationColor, nationColor,
regionFillStyle, regionFillStyle,
unownedTooltipLabel, unownedTooltipLabel,
type ContestedRegion,
type RegionMap, type RegionMap,
type RegionOwner, type RegionOwner,
} from '@shared/protocol'; } from '@shared/protocol';
@@ -146,6 +150,12 @@ function cameraForPreset(presetId: string): { center: [number, number]; zoom: nu
* no man's land mid-game (`GameState.unowned`) — gets the distinct visible grey * no man's land mid-game (`GameState.unowned`) — gets the distinct visible grey
* (`NO_MANS_LAND_FILL`); every other ownerless region keeps the faint * (`NO_MANS_LAND_FILL`); every other ownerless region keeps the faint
* preset-unassigned look. Both come from the shared `regionFillStyle` contract. * preset-unassigned look. Both come from the shared `regionFillStyle` contract.
*
* (v0.44.0, #66) A **contested** region (a war frontline — `contestedSet`, from
* `GameState.contested`) takes precedence over both unowned looks: it is in no
* nation's territory and not no man's land, so it renders the distinct
* reddish/orange `CONTESTED_FILL` / `CONTESTED_STROKE`. The state is decided by
* the client, never by the RegionMap (which has no entry for a contested key).
*/ */
function applyRegions( function applyRegions(
geo: FeatureCollection, geo: FeatureCollection,
@@ -153,6 +163,7 @@ function applyRegions(
playerNationId: string, playerNationId: string,
idKey: Record<string, string>, idKey: Record<string, string>,
unownedSet: ReadonlySet<string>, unownedSet: ReadonlySet<string>,
contestedSet: ReadonlySet<string>,
): FeatureCollection { ): FeatureCollection {
const out: FeatureCollection = JSON.parse(JSON.stringify(geo)); const out: FeatureCollection = JSON.parse(JSON.stringify(geo));
for (const f of out.features) { for (const f of out.features) {
@@ -165,6 +176,18 @@ function applyRegions(
// key the RegionMap by it — never the sub-region id or the repacked id. // key the RegionMap by it — never the sub-region id or the repacked id.
const key = idKey[subId] ?? ''; const key = idKey[subId] ?? '';
f.properties.regionKey = key; f.properties.regionKey = key;
// (v0.44.0, #66) A contested frontline takes precedence over every other
// state (owned, unowned, no man's land): the key is in no nation's
// territory and not no man's land, so it renders the distinct contested
// fill/stroke (decided by the client from `GameState.contested`, never by
// the RegionMap, which has no entry for it).
if (key !== '' && contestedSet.has(key)) {
f.properties.fill = CONTESTED_FILL;
f.properties.stroke = CONTESTED_STROKE;
f.properties.owner = '';
f.properties.ownerId = '';
f.properties.isPlayer = 0;
} else {
const r = key ? regions[key] : undefined; const r = key ? regions[key] : undefined;
if (r) { if (r) {
const style = regionFillStyle(r, false); const style = regionFillStyle(r, false);
@@ -184,6 +207,7 @@ function applyRegions(
f.properties.isPlayer = 0; f.properties.isPlayer = 0;
} }
} }
}
return out; return out;
} }
@@ -412,8 +436,14 @@ function hoverHtml(
noMansLand = false, noMansLand = false,
regionKey?: string, regionKey?: string,
regionStats?: Record<string, RegionStats>, regionStats?: Record<string, RegionStats>,
contestedParties?: string[],
): string { ): string {
if (!region || !nation) { if (!region || !nation) {
// (v0.44.0, #66) A contested frontline (a region in no nation's territory
// and not no man's land) names its contesting parties in the sub-line.
if (contestedParties && contestedParties.length > 0) {
return `<div class="hm-popup"><div class="hm-popup-title">${esc(subRegionName || 'Contested')}</div><div class="hm-popup-sub">${contestedTooltipLabel(contestedParties)}</div></div>`;
}
return `<div class="hm-popup"><div class="hm-popup-title">${esc(subRegionName || 'Unclaimed')}</div><div class="hm-popup-sub">${unownedTooltipLabel(noMansLand)}</div></div>`; return `<div class="hm-popup"><div class="hm-popup-title">${esc(subRegionName || 'Unclaimed')}</div><div class="hm-popup-sub">${unownedTooltipLabel(noMansLand)}</div></div>`;
} }
// (v0.29, #46 PR 2) The region's OWN per-region stats (not the nation's // (v0.29, #46 PR 2) The region's OWN per-region stats (not the nation's
@@ -479,6 +509,15 @@ interface Props {
* stats. * stats.
*/ */
regionStats?: Record<string, RegionStats>; regionStats?: Record<string, RegionStats>;
/**
* (v0.44.0, #66) The game's contested regions / war frontlines
* (`GameState.contested` — a region key + its contesting party ids). Such a
* region is in no nation's territory and not no man's land (a third region
* state): it renders the distinct reddish/orange `CONTESTED_FILL` and its
* hover tooltip names the parties. The map legend is unaffected (a
* contested key is absent from the RegionMap, so it adds no entry).
*/
contested?: ContestedRegion[];
} }
/** /**
@@ -536,6 +575,7 @@ export default function WorldMap({
onFocusNation, onFocusNation,
markers, markers,
regionStats, regionStats,
contested,
}: Props) { }: Props) {
const containerRef = useRef<HTMLDivElement>(null); const containerRef = useRef<HTMLDivElement>(null);
const mapRef = useRef<maplibregl.Map | null>(null); const mapRef = useRef<maplibregl.Map | null>(null);
@@ -553,6 +593,10 @@ export default function WorldMap({
const markersRef = useRef<MapMarker[]>(markers ?? []); const markersRef = useRef<MapMarker[]>(markers ?? []);
// (v0.29, #46 PR 2) latest per-region stats, for the hover tooltip. // (v0.29, #46 PR 2) latest per-region stats, for the hover tooltip.
const regionStatsRef = useRef<Record<string, RegionStats>>(regionStats ?? {}); const regionStatsRef = useRef<Record<string, RegionStats>>(regionStats ?? {});
// (v0.44.0, #66) latest contested regions, region key -> contesting party
// NAMES (the stored parties are resolved nation ids, resolved here so the
// hover tooltip can show "Contested: A vs B").
const contestedRef = useRef<Map<string, string[]>>(new Map());
regionsRef.current = regions; regionsRef.current = regions;
nationsRef.current = nations; nationsRef.current = nations;
playerRef.current = playerNationId; playerRef.current = playerNationId;
@@ -561,6 +605,11 @@ export default function WorldMap({
onFocusNationRef.current = onFocusNation; onFocusNationRef.current = onFocusNation;
markersRef.current = markers ?? []; markersRef.current = markers ?? [];
regionStatsRef.current = regionStats ?? {}; regionStatsRef.current = regionStats ?? {};
{
const m = new Map<string, string[]>();
for (const c of contested ?? []) m.set(c.regionKey, c.parties.map((id) => nations[id]?.name ?? id));
contestedRef.current = m;
}
// Diffing state for the transient territory-change flash (owned by this component // Diffing state for the transient territory-change flash (owned by this component
// so a resync with identical data never re-flashes). // so a resync with identical data never re-flashes).
@@ -721,9 +770,12 @@ export default function WorldMap({
const pKey = f.properties?.regionKey; const pKey = f.properties?.regionKey;
const keyStr = typeof pKey === 'string' && pKey !== '' ? pKey : undefined; const keyStr = typeof pKey === 'string' && pKey !== '' ? pKey : undefined;
const noMansLand = !region && keyStr !== undefined && unownedRef.current.has(keyStr); const noMansLand = !region && keyStr !== undefined && unownedRef.current.has(keyStr);
// (v0.44.0, #66) a contested frontline (in no territory, not no man's
// land) names its contesting parties in the tooltip sub-line.
const contestedParties = !region && keyStr !== undefined ? contestedRef.current.get(keyStr) : undefined;
hoverPopup hoverPopup
.setLngLat(e.lngLat) .setLngLat(e.lngLat)
.setHTML(hoverHtml(p?.name ?? subId, region, nation, noMansLand, keyStr, regionStatsRef.current)) .setHTML(hoverHtml(p?.name ?? subId, region, nation, noMansLand, keyStr, regionStatsRef.current, contestedParties))
.addTo(map); .addTo(map);
map.getCanvas().style.cursor = 'pointer'; map.getCanvas().style.cursor = 'pointer';
}; };
@@ -799,7 +851,7 @@ export default function WorldMap({
const idKey = idKeyRef.current; const idKey = idKeyRef.current;
const src = map.getSource(REGIONS_SOURCE) as GeoSource | undefined; const src = map.getSource(REGIONS_SOURCE) as GeoSource | undefined;
if (!geo || !idKey || !src) return; if (!geo || !idKey || !src) return;
src.setData(applyRegions(geo, regionsRef.current, playerRef.current, idKey, unownedRef.current)); src.setData(applyRegions(geo, regionsRef.current, playerRef.current, idKey, unownedRef.current, new Set(contestedRef.current.keys())));
}; };
// Stamp the current markers onto the marker source (v0.27, #44). // Stamp the current markers onto the marker source (v0.27, #44).
@@ -977,7 +1029,7 @@ export default function WorldMap({
if (map && geo && idKey) { if (map && geo && idKey) {
const src = map.getSource(REGIONS_SOURCE) as GeoSource | undefined; const src = map.getSource(REGIONS_SOURCE) as GeoSource | undefined;
if (src) void src.setData(applyRegions(geo, cur, playerNationId, idKey, unownedSet)); if (src) void src.setData(applyRegions(geo, cur, playerNationId, idKey, unownedSet, new Set(contestedRef.current.keys())));
} }
if (wasPrimed && prev && idKey) { if (wasPrimed && prev && idKey) {
@@ -989,7 +1041,9 @@ export default function WorldMap({
// up as ownerId changes above, so they flash like any other transfer. // up as ownerId changes above, so they flash like any other transfer.
if (changed.size > 0) flashApiRef.current?.([...changed]); if (changed.size > 0) flashApiRef.current?.([...changed]);
} }
}, [regions, playerNationId, unowned]); // (v0.44.0, #66) re-paint when the contested set changes too — a contested
// key is absent from the RegionMap, so the diff alone wouldn't repaint it.
}, [regions, playerNationId, unowned, contested]);
// (v0.27, #44) Repaint the marker symbol layer whenever the marker list // (v0.27, #44) Repaint the marker symbol layer whenever the marker list
// changes (a turn placed/removed markers) or the nations record changes // changes (a turn placed/removed markers) or the nations record changes