Add the 9th modular LLM ability: a turn-transient `TurnResult.disasters`
lever letting the LLM declare natural/man-made disasters (earthquake /
flood / volcanic / wildfire / famine / plague / epidemic) on a nation or
a region, applying a DETERMINISTIC (type, severity) stat dip (no hidden
randomness). Like the hybrid layer it owns no GameState field, needs no
db.ts change, and leaves no durable list — an ongoing plague/epidemic is
simply re-declared each turn it persists.
- shared/protocol.ts: DisasterType / DisasterSeverity / DisasterEvent /
DisastersOps, and `TurnResult.disasters` (between `ideology` and
`markers`; required, default `{ events: [] }`).
- server/abilities/disasters.ts: the ability module (validate / apply /
schemaLine / constraint / isMeaningful / inert stub / empty payload; no
stateFields). `DISASTER_EFFECTS` is the deterministic (type, severity)
dip table (population never touched). Target resolution mirrors hybrid
(a region key hits its SOLE owner; 0/2+ owners dropped) but has NO
`from` field, so there is no self-target drop. Dips clamp to 0-100,
mirror to the target's regions (regionStats), and re-derive the target
nation's stats (same 0-region / no-entry guards).
- Registered last in ABILITIES (after ideology). System-prompt goldens
regenerated (one schema line + one constraint bullet each); the
user.txt golden stays byte-identical (payload() is {}).
- New server/abilities/disasters.test.ts (33 tests); registry.test.ts
updated to the 9-ability contract.
- Secondary cleanups from the v0.40 refactor: AGENTS.md (abilities/ in
the Layout tree + a "how to add a new ability" bullet + a disasters
bullet), delete the orphaned validateTakeovers JSDoc, fold both inline
`as unknown` casts into the top-level ./abilities import, and de-dup
`str` (now imported from ./abilities/shared).
Version bumped 0.40.0 -> 0.41.0.
- package.json: 0.39.0 → 0.40.0.
- CHANGELOG.md: new v0.40.0 entry documenting the modular LLM-ability
system (the behavior-preserving extraction of the 8 per-feature
abilities into the ordered ABILITIES registry), with the guarantees
(byte-identical prompts/mutations/stub, zero client changes, no new
deps, shared/ stays dep-free) and the new registry/golden tests.
Verified: typecheck + lint + 522 unit tests + build all green.
Fixes#74
Adds server/abilities/registry.test.ts, the safety net for the refactor:
- GOLDEN PROMPTS: the refactored engine's system prompt (both tool
variants) and user prompt are asserted BYTE-IDENTICAL to the committed
fixtures in server/abilities/goldens/ (captured in P1 from the
pre-refactor engine). The state builder the goldens were captured from
is re-embedded here, with a REGEN_GOLDENS=1 mode to rewrite the
fixtures after an intentional prompt change (verified a no-op — the
refactored output is exactly stable).
- REGISTRY CONTRACT: ABILITIES is the canonical 8-ability order with 8
distinct TurnResult fields; each ability's default() equals the
canonical TurnResult default and is a FRESH value (never a shared
reference); the default is never "meaningful" while a populated value
is; the registry declares exactly the durable GameState fields the db
migration must default (wars/trades/embargoes/industry); the registry
composes (a hypothetical extra ability appends cleanly to every
uniform loop); and the engine still re-exports every name its callers
import from it (backward compatibility).
The throwaway _golden-capture.ts is deleted (its logic is now the
REGEN mode of this test).
Fixes#74
Behavior-preserving rewire: every per-ability code path now iterates the
ordered ABILITIES registry instead of hand-enumerating the eight fields.
- engine.ts: buildSystemPrompt (schema lines + constraint bullets),
buildUserPrompt (payload keys at their historical positions),
validateTurnResult (per-field validate), applyTurnResult (ordered apply
block), isMeaningful, and the runTurn "unclear" fallback all drive off
ABILITIES. The eight moved ability bodies (~1,249 lines) are deleted;
the names the engine and its tests import are re-exported from
./abilities.
- abilities/types.ts: Ability.stub is a zero-arg method (the stub has no
GameState/AbilityCtx to pass; it needs none) — all eight implementations
were already arg-less.
- stub.ts: deterministicTurn fills the eight ability fields from the
registry (each contributes its inert default), between the core fields
and markers — JSON output stays byte-identical (verified against
origin/master).
- db.ts: the legacy-row migration for ability-owned GameState fields
(wars/trades/embargoes/industry) iterates the registry's stateFields,
only-if-undefined, instead of a hardcoded field list.
No client changes, no new deps, no shared/ runtime deps. typecheck + lint
+ 511 unit tests green; stub JSON byte-identical to origin/master.
Fixes#74
Each per-feature LLM ability is now a self-contained module in
server/abilities/ with its own Ability<K> const (schema line, constraint
bullet, validator, applier, isMeaningful, stub default, user-payload
field). The ordered ABILITIES registry (index.ts) assembles them in the
canonical order: takeovers → wars → hybrid → economy → industry → nuclear
→ leaders → ideology.
All function bodies are moved VERBATIM from engine.ts. The engine is
untouched in this commit — P4 will rewire it to use the registry.
Move the 5 shared reference/id primitives (resolveNationRef, resolveRegionKey,
freshNationId, freshWarId, NEW_NATION_STATS) from engine.ts into the new
server/abilities/shared.ts (breaking the engine<->ability import cycle), and
add server/abilities/types.ts with the Ability<K> interface + AbilityCtx /
UserPromptCtx types that the 8 per-feature ability modules will implement.
engine.ts imports the helpers and re-exports them so existing callers
(server/index.ts, the unit tests) are untouched. Behavior is identical; all
511 unit tests, lint and typecheck stay green.
Adds deterministic golden fixtures (server/abilities/goldens/) pinning the
EXACT output of buildSystemPrompt (no-tool + tool modes) and buildUserPrompt
for a fixed wwii-1939 preset plus a crafted state that exercises every
optional payload branch (regions, frontier, frontierMilitary, takeoverRisks,
unowned, markers, wars, relations, trades, embargoes, resources, industry).
These are the target: the v0.40.0 modular ability registry (P2-P5) must
reproduce these byte-for-byte. Part of #74.
Per-nation named leaders (Nation.leader) and a required TurnResult.leaders
lever ({ changes: [{ target, name, cause }] }). Each change sets the target
nation's leader and applies a deterministic stability dip by cause
(assassination -15, death -3, appointed 0) mirrored to its regions and
re-derived into its stats, plus a narration event (military for an
assassination, political for a death/appointment). An assassination/death
requires the target to already have a leader (a leaderless target is
dropped); an appointment always creates/sets one. Unknown/ambiguous targets
are dropped, never thrown.
- shared/types.ts: optional Nation.leader
- shared/protocol.ts: LeaderCause/LeaderChange/LeaderOps, LEADER_STABILITY_EFFECT,
TurnResult.leaders (required, between nuclear and markers), leader in nationForPrompt
- server/engine.ts: validateLeaderOps, applyLeaderChange, the applyTurnResult
leader block (after nuclear, before markers), isMeaningful, system-prompt
contract + constraint, validateTurnResult + runTurn fallback
- server/stub.ts: leaders always { changes: [] } (e2e unaffected)
- tests: 15 engine.test.ts leader tests + 2 db.test.ts round-trips
- version 0.37.0 -> 0.38.0, CHANGELOG entry
Promote the bare 'war' relation to a named War entity in GameState.wars:
- War: { id, sides[], declaredTurn, declaredDate?, aims?, status, front? }
- TurnResult.wars: { declare: WarDeclareOp[], end: WarEndOp[] }
- syncWarRelations: derive 'war' from active wars, fallback to 'hostile' on end
- Mutual-defense drag-in: belligerent allies added to sides (one level)
- Bare 'war' back-compat: never downgraded, never force-created
- Stub: empty wars (e2e unaffected); ~30 new unit tests
v0.33.0
Additive 'Create scenario' path (v0.31): the home screen's create-scenario
card opens a ScenarioForm (pick one of 3 light era templates + a free-text
description + an editable, era-prefilled start year) whose 'Generate world'
posts the draft request; the CheckpointReview screen shows the generated
world (per-nation stats/territory/relations + backstory) and the advisor's
checkpoint list as an approve/remove checklist, then the player picks a
nation to lead and finalizes into a saved, playable game. Both LLM steps ride
the scenario client (deterministic stub under LLM_STUB=1); a failure toasts
and stays on the current screen. The turn stub and static presets are
untouched. New e2e covers the full deterministic flow (near-future 2035,
remove checkpoint 3, lead Boreas, finalize, one empty jump) and the 3-template
manifest.
- GET /api/scenarios/templates: the 3 era templates (templateStore from
presets/templates/).
- POST /api/scenarios/draft: generateDraft (template + description + year) ->
{ world, checkpoints } (502 on transport failure / unusable world).
- POST /api/scenarios/commit: finalizeWorld (constrained to approved
checkpoints, optionally based on the re-sent draft) -> saved GameState,
returns { id } (a normal game at #/game/<id>).
- scenarioLlm: the deterministic scenario stub under LLM_STUB=1 (distinct
from the untouched turn stub), the live client otherwise.
- jump route: synthesize a minimal Preset for dynamic games (presetId
'dynamic', no static file) so their turns run; genuinely-missing static
presets still 404.
Fixes#52
- server/scenario.ts: buildGeneratePrompt / buildRegeneratePrompt, defensive
parseGenerate / parseRegenerate (fence-strip + balanced-object + validate),
generateDraft (draft world + advisor checkpoints) and finalizeWorld (final
world constrained to approved checkpoints -> playable GameState), all over
the injectable LlmClient with a nudge re-send. SCENARIO_* markers for the
stub.
- server/stubScenario.ts: deterministic scenario stub transport (fixed 3-nation
world + checkpoint list; finalize refines stability per approved checkpoint)
+ makeScenarioStubLlmClient. Distinct from and never touching turn stub.ts.
- server/regions.ts: validCountryCodes() accessor (ISO_A3 parents) for draft
territory validation.
- shared/scenario.ts: worldDraftToGameState now guards a dangling playerNationId
(falls back to the first nation) so a finalize that drops it stays playable.
- server/scenario.test.ts: 16 tests (prompt builders, defensive parsing,
generateDraft/finalizeWorld over a fake client + the stub).
Fixes#52
- Add a hard military conquest gate (canConquer, CONQUEST_MILITARY_MARGIN=15)
enforced in applyTurnResult: a contested invasion is repelled when the
attacker's military is more than 15 below the defender's; re-claims of
unowned regions are never gated. Emits a new 'repelled' event.
- Document the soft levers in the system prompt: stability<30 + gathering
marker -> non-military takeover; economy growth/decay drives other stats.
- Emit bounded frontierMilitary (per-neighbour balance) and takeoverRisks
hints in the user payload (only when present).
- repelled outcome color (#9f1239); full unit test coverage; stub untouched.
- Bump to v0.30.0.
Fixes#50
v0.29.0 — the LLM can now target individual regions' stats via
TurnResult.regionChanges (set/add per stat, clamped 0-100), applied
after nation-wide stateChanges and before the weighted-median
recompute. The map hover tooltip shows each region's own four stats.
The stub stays deterministic (regionChanges: []).
Fixes#46 (PR 2 of 2)
#41: re-partition the RU-ARK mainland's 28-part lat>=68 Arctic-coast band
into two new regions via a new turf-free, idempotent pipeline stage
scripts/split-arkhangel-band.mjs (npm run split:regions:band), mirroring the
#31 split:
- RU-PEO (Pechora, 13 parts, ~37,678 km2) -> key pechora-qwhs
- RU-YAM (Yamal, 15 parts, ~51,722 km2) -> key yamal-gosw
- RU-ARK keeps its id/name/key arkhangel-sk-lhbk (ownership-safe); the 5-part
lat<68 core (~305,229 km2) stays RU-ARK.
Pure re-partition: no geometry moved (byte-identical union). The two new
features are inserted immediately after RU-ARK-SZ. Manifests regenerated with
the real scripts (1,798 -> 1,800 keys + adjacency; adjacency pairs 4,471 ->
4,473). Fixed-point dataset unchanged except feature count (11,794 parts /
11,795 rings / 164,801 verts / 1 KZ-KZY hole). Four dataset/manifest tests
updated (RUS 82 -> 84 sub-regions). Version 0.25.0 -> 0.26.0.
Fixes#41