Nation-op proposals (P4a, #16): protocol types, pendingNationOps state, engine propose/resolve (stage 1)

- shared/protocol.ts: RenameOp/SplitOp/MergeOp + NationOp union; TurnResult.nationOps (required); ConfirmNationOp/RejectNationOp request+response types
- shared/types.ts: GameState.pendingNationOps (type-only import of NationOp — no runtime cycle)
- server/engine.ts: validateNationOps parser wired into validateTurnResult; isMeaningful counts proposals; applyTurnResult appends to the surviving pending list (never applies); runTurn fallback literal; system prompt gains the nationOps JSON field + rename proposal rule (both modes); new resolveNationRef/applyNationOp/confirmNationOp/rejectNationOp (id-first then unique case-insensitive name; rename changes Nation.name only; split/merge no-op until P4b; index validation returns null for 400)
- server/db.ts: legacy rows load with pendingNationOps defaulted to []
- server/index.ts: fresh games start with pendingNationOps: []
- server/stub.ts: deterministicTurn returns nationOps: [] (the stub never proposes — unit-only coverage, matching P3)
- tests: fixture updates (engine/db/map/regions) + new suites for resolveNationRef, validateNationOps, proposal lifecycle, confirm/reject (151 tests total)
This commit is contained in:
2026-10-14 12:47:58 +00:00
parent edaa8f55d1
commit e9fa267fd0
10 changed files with 615 additions and 12 deletions
+171 -7
View File
@@ -19,6 +19,7 @@ import {
isDateLike,
makeEvent,
nationForPrompt,
type NationOp,
type TurnEventSpec,
type TurnResult,
} from '../shared/protocol';
@@ -176,13 +177,15 @@ export function buildSystemPrompt(preset: Preset, withNeighboursTool = false): s
' "stateChanges": [{"nation":"<nationId>","stat":"<military|economy|stability|population>","op":"<set|add>","value":<0-100>}],',
' "relations": [{"a":"<nationId>","b":"<nationId>","set":"<ally|neutral|rival|hostile|war>"}],',
' "territoryChanges": [{"nation":"<nationId>","gain":["<region key>"],"lose":["<region key>"]}],',
' "unowned": ["<region key>"]',
' "unowned": ["<region key>"],',
' "nationOps": [{"kind":"rename","nationRef":"<nation id or name>","to":"<new name>"}]',
'}',
'',
'HARD CONSTRAINTS',
'- Use only nation ids and region keys that exist in the provided state.',
'- A region key identifies one sub-region; the "regions" table in the user message maps each key to "<region name> (<parent country ISO_A3>)". Use those keys in territoryChanges and unowned.',
'- List in "unowned" only region keys that a nation currently owns, and narrate each release in "events".',
'- To rename a nation, add {"kind":"rename","nationRef":"<nation id or name>","to":"<new name>"} to "nationOps". This is a PROPOSAL: it only takes effect if the player confirms it, so use it only when the narrative justifies it (a revolution, reunification, regime change) — at most 1-2 per turn — and narrate it in "events".',
'- 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 every stat value between 0 and 100.',
@@ -316,6 +319,53 @@ function str(s: unknown, max = 0): string | null {
return max ? t.slice(0, max) : t;
}
/**
* Validate a raw (LLM) `nationOps` array into safe {@link NationOp} values
* (v0.23, #16 P4a). Defensive like the rest of the parser: entries with an
* unknown `kind` or missing/empty required fields are dropped, never throw.
* Rename: non-empty `nationRef` + `to` (each capped at 200 chars — resolution
* of `nationRef` to a concrete nation happens later, at confirm time). Split:
* non-empty `nationRef` + at least one part with a name. Merge: non-empty
* `nationRefs` (capped at 20) + `survivingRef` + `into`.
*/
export function validateNationOps(raw: unknown): NationOp[] {
if (!Array.isArray(raw)) return [];
const out: NationOp[] = [];
for (const e of raw) {
if (!e || typeof e !== 'object') continue;
const o = e as Record<string, unknown>;
if (o.kind === 'rename') {
const nationRef = str(o.nationRef, 200);
const to = str(o.to, 200);
if (nationRef && to) out.push({ kind: 'rename', nationRef, to });
} else if (o.kind === 'split') {
const nationRef = str(o.nationRef, 200);
const parts = (Array.isArray(o.parts) ? o.parts : [])
.filter((p): p is Record<string, unknown> => !!p && typeof p === 'object')
.map((p) => {
const name = str(p.name, 200);
const territory = Array.isArray(p.territory)
? p.territory.filter((k): k is string => typeof k === 'string' && k.trim() !== '')
: [];
return { name, territory };
})
.filter((p): p is { name: string; territory: string[] } => p.name !== null);
if (nationRef && parts.length > 0) out.push({ kind: 'split', nationRef, parts });
} else if (o.kind === 'merge') {
const nationRefs = (Array.isArray(o.nationRefs) ? o.nationRefs : [])
.map((x) => (typeof x === 'string' ? x.trim().slice(0, 200) : ''))
.filter((x) => x !== '')
.slice(0, 20);
const survivingRef = str(o.survivingRef, 200);
const into = str(o.into, 200);
if (nationRefs.length > 0 && survivingRef && into) {
out.push({ kind: 'merge', nationRefs, survivingRef, into });
}
}
}
return out;
}
/**
* Validate and normalize an arbitrary parsed object into a safe TurnResult.
* Ignores unknown/invalid entries; clamps numeric stats to 0-100. Returns null
@@ -331,6 +381,7 @@ export function validateTurnResult(input: unknown): TurnResult | null {
relations: [],
territoryChanges: [],
unowned: [],
nationOps: [],
};
if (Array.isArray(o.events)) {
@@ -415,17 +466,29 @@ export function validateTurnResult(input: unknown): TurnResult | null {
}
}
// (v0.23, #16 P4a) Nation-management ops the LLM proposes this turn. These
// are NOT applied by the turn — applyTurnResult appends them to the pending
// list for the player to confirm/reject.
result.nationOps = validateNationOps(o.nationOps);
return result;
}
/**
* A turn is "meaningful" if it produced at least an event, a stat change, or
* a no-man's-land release (v0.22 #16 P3: a release is a real world change even
* when the model under-narrates it, so it must survive the retry/nudge path
* instead of being replaced by the generic "unclear" result).
* A turn is "meaningful" if it produced at least an event, a stat change, a
* no-man's-land release (v0.22 #16 P3: a release is a real world change even
* when the model under-narrates it), or a nation-op proposal (v0.23 #16 P4a:
* a proposal is a real pending-world change the player will resolve, so it
* must survive the retry/nudge path instead of being replaced by the generic
* "unclear" result).
*/
export function isMeaningful(result: TurnResult): boolean {
return result.events.length > 0 || result.stateChanges.length > 0 || result.unowned.length > 0;
return (
result.events.length > 0 ||
result.stateChanges.length > 0 ||
result.unowned.length > 0 ||
result.nationOps.length > 0
);
}
// --- Applying the delta -------------------------------------------------------
@@ -443,7 +506,10 @@ function genericUnclearEvent(state: GameState): TurnEventSpec {
/**
* Apply a TurnResult to a GameState immutably: advance the date/turn, append
* events, apply stat changes (clamped), symmetric relations, and territory
* moves (including no-man's-land releases, v0.22 #16 P3).
* moves (including no-man's-land releases, v0.22 #16 P3). It also appends any
* proposed nation-ops to the pending list (v0.23 #16 P4a) without applying
* them — see the doc comment on `pendingNationOps` for why that list
* deliberately survives across turns.
*/
export function applyTurnResult(state: GameState, result: TurnResult, validKeys?: ReadonlySet<string>): GameState {
const next: GameState = JSON.parse(JSON.stringify(state));
@@ -559,6 +625,13 @@ export function applyTurnResult(state: GameState, result: TurnResult, validKeys?
}
next.unowned = [...unowned];
// (v0.23, #16 P4a) Nation-op proposals are NOT applied by the turn — they
// are appended to the pending list, which (unlike `pending`) SURVIVES
// across turns until the player confirms or rejects each one. `next` is a
// deep clone of `state`, so `next.pendingNationOps` is a copy of whatever
// the state already held (or undefined for a legacy row) — start from that
// and append the new proposals, defaulting a missing field to `[]`.
next.pendingNationOps = [...(next.pendingNationOps ?? []), ...result.nationOps];
return next;
}
@@ -593,6 +666,96 @@ export function removeRoundItem(state: GameState, index: number | undefined): Ga
return next;
}
// --- Nation-management ops (v0.23, #16 P4a: the hybrid "LLM proposes,
// player confirms" model) ----------------------------------------------------
//
// A NationOp proposed by a turn lands in `GameState.pendingNationOps` (see
// applyTurnResult) and waits there across turns. These functions resolve the
// player's decision on one pending proposal, by index. Like removeRoundItem
// they are pure: clone the state, mutate the clone, bump `version` once,
// return the new state — and return `null` for a bad index so the route can
// answer 400 without mutating anything.
/** True when `index` is a valid, in-bounds integer position in the pending list. */
function validPendingOpIndex(state: GameState, index: number): boolean {
const len = state.pendingNationOps?.length ?? 0;
return Number.isInteger(index) && index >= 0 && index < len;
}
/**
* Resolve a nation reference (the `nationRef` of a NationOp — the LLM may
* write either the nation's stable `id` or its human-readable `name`) to a
* concrete nation id: an exact id match wins, then a unique case-insensitive
* name match. Returns `null` when the reference is empty, unknown, or
* ambiguous (two or more nations share that name) — every caller treats
* `null` as "no-op" and nothing here ever throws.
*/
export function resolveNationRef(state: GameState, ref: string): string | null {
const r = (ref ?? '').trim();
if (!r) return null;
if (state.nations[r]) return r; // exact id first
const matches = Object.values(state.nations).filter(
(n) => n.name.trim().toLowerCase() === r.toLowerCase(),
);
return matches.length === 1 ? matches[0].id : null;
}
/**
* Apply one NationOp to a state, MUTATING the passed object in place (the
* caller passes a clone — confirmNationOp does) and NOT bumping `version`
* (the route-level functions do that once per decision). Rename changes only
* `Nation.name` — the id, its territory, its relations (keyed by id), and the
* player pointer all stay valid, so nothing downstream breaks; a
* player-supplied `edits.name` overrides the proposed `to` (an empty edit
* falls back to the proposal's own name). An unresolvable or ambiguous
* `nationRef` is a silent no-op. Split and merge are declared for P4b and are
* a no-op until then — the op stays pending-free once the player resolves it,
* but the world does not change yet.
*/
export function applyNationOp(state: GameState, op: NationOp, edits?: { name?: string }): void {
if (op.kind !== 'rename') return; // split/merge: declared for P4b, not applied yet
const id = resolveNationRef(state, op.nationRef);
if (id === null) return; // invalid/ambiguous ref: no-op
const n = state.nations[id];
if (!n) return;
const name = (edits?.name ?? '').trim() || op.to.trim();
if (name) n.name = name;
}
/**
* Confirm a pending nation-op proposal by index: apply it (a rename takes
* effect, optionally with a player-edited name; split/merge are a no-op until
* P4b) and remove it from `pendingNationOps`, bumping `version`. Returns
* `null` for an invalid index, so the route answers 400 without mutating.
* Reused by the /nation-op/confirm route.
*/
export function confirmNationOp(
state: GameState,
index: number,
edits?: { name?: string },
): GameState | null {
if (!validPendingOpIndex(state, index)) return null;
const next: GameState = JSON.parse(JSON.stringify(state));
next.version = (state.version ?? 0) + 1;
const op = next.pendingNationOps[index];
applyNationOp(next, op, edits);
next.pendingNationOps.splice(index, 1);
return next;
}
/**
* Reject (drop) a pending nation-op proposal by index without applying it,
* bumping `version`. Returns `null` for an invalid index, so the route
* answers 400 without mutating. Reused by the /nation-op/reject route.
*/
export function rejectNationOp(state: GameState, index: number): GameState | null {
if (!validPendingOpIndex(state, index)) return null;
const next: GameState = JSON.parse(JSON.stringify(state));
next.version = (state.version ?? 0) + 1;
next.pendingNationOps.splice(index, 1);
return next;
}
/**
* Run one turn end-to-end against the (injectable) LLM: build prompts, parse/
* validate, retry once with a nudge if the result is empty/invalid, and — if
@@ -674,6 +837,7 @@ export async function runTurn(opts: {
relations: [],
territoryChanges: [],
unowned: [],
nationOps: [],
};
}