feat(#57): hybrid war — TurnResult.hybrid ops (spy/sabotage/assassinate/cyber/economic/information/proxy) with exposure backfire
CI / build + unit + e2e (pull_request) Successful in 2m7s

This commit is contained in:
2026-10-15 16:42:27 +00:00
parent f45c01b8d6
commit 8eeb6df284
7 changed files with 868 additions and 22 deletions
+307
View File
@@ -24,12 +24,15 @@ import {
clampStat,
deriveNationStats,
fnv1a32,
HYBRID_OP_TYPES,
isDateLike,
isMarkerType,
makeEvent,
markerId,
MAX_MARKERS,
nationForPrompt,
type HybridOp,
type HybridOpType,
type MarkerInfo,
type MarkerSpec,
type NationOp,
@@ -55,6 +58,12 @@ const VALID_EVENT_TYPES = new Set<string>(EVENT_TYPES);
const VALID_RELATIONS = new Set<string>(RELATION_STATUSES);
const VALID_OUTCOMES = new Set<string>(['success', 'failure', 'partial', 'neutral']);
const VALID_STATS = new Set<string>(['military', 'economy', 'stability', 'population']);
const VALID_HYBRID_TYPES = new Set<string>(HYBRID_OP_TYPES);
/** True when `t` is one of the seven known hybrid op types (v0.34.0, #57). */
export function isHybridOpType(t: unknown): t is HybridOpType {
return typeof t === 'string' && VALID_HYBRID_TYPES.has(t);
}
// --- The LLM's getNeighbours tool (v0.21, #16 P2: contiguous region transfers) ---
@@ -206,6 +215,7 @@ export function buildSystemPrompt(preset: Preset, withNeighboursTool = false): s
' ],',
' "takeovers": [{"nationRef":"<nation id or name>","newRegimeName":"<name of the new regime>"}],',
' "wars": {"declare":[{"sides":["<nationId>","<nationId>"],"aims":["<short aim>"]}],"end":[{"id":"<war id>","outcome":"<armistice|capitulation>","terms":"<short terms>"}]},',
' "hybrid": {"ops":[{"type":"<spy|sabotage|assassinate|cyber|economic|information|proxy>","from":"<nation id or name>","target":"<nation id or name, or region key>","detail":"<short detail>","outcome":"<success|exposed>"}]},',
' "markers": {"add":[{"type":"<city|factory|army|port|capital|fleet|rocket|gathering>","name":"<short name>","regionKey":"<region key>"}],"remove":["<marker id>"]}',
'}',
'',
@@ -225,6 +235,7 @@ export function buildSystemPrompt(preset: Preset, withNeighboursTool = false): s
'- Merge: add {"kind":"merge","nationRefs":["<id or name>","<id or name>"],"survivingRef":"<id or name of the surviving nation>","into":"<new name>"} when states reunify or one is absorbed. Use at least 2 input nations and "survivingRef" must name one of them — the survivor keeps its id and its stats.',
'- Takeover (automatic, NOT player-confirmed): add {"takeovers":[{"nationRef":"<nation id or name>","newRegimeName":"<name of the new regime>"}]} when a low-stability nation (e.g. stability < 30) hosting a "gathering" marker is overthrown in a coup or revolution. This renames the nation to the new regime (e.g. "France" → "Vichy Regime"). Also emit a narrative "event" (political or social, outcome "success") and a stability/economy shock via "stateChanges". A takeover is an automatic in-world regime change — use "nationOps" rename only for a diplomatic/political name change that the player must confirm.',
'- Wars ("wars") are named conflicts, each with a stable id. To DECLARE one, add {"declare":[{"sides":["<id>","<id>"],"aims":[...]}]} with at least 2 distinct belligerents: while it is active the engine AUTOMATICALLY sets both directions of every warring pair\'s relation to "war" and drags in the mutual-defense allies of each belligerent, so do NOT also emit a "war" relation for those pairs (you can never "make peace" between them without ending the war). To END an active war, add {"end":[{"id":"<war id from the user message\'s "wars" field>","outcome":"<armistice|capitulation>"}]} — only active wars can be ended, and when one ends its belligerent pairs fall back to "hostile". Propose at most 1-2 declarations per turn and narrate each declaration and each ending in "events".',
'- Covert / hybrid ops ("hybrid.ops") are non-kinetic operations — spies, sabotage, assassination attempts, cyberattacks, economic pressure, disinformation, and proxy support. Unlike territory they NEVER move borders: a successful op applies a small, deterministic effect (a small dip in the target\'s economy / stability / military for sabotage / assassinate / cyber / economic, or a relation nudge toward hostile for information / proxy), while an "exposed" op backfires (no effect, and the actor\'s relation with the target sours by one step toward hostile). "target" may be a nation id / name or a region key (a region key hits that region\'s sole owner). Keep each detail short, propose at most a few per turn, and narrate each op 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.',
@@ -276,6 +287,14 @@ export function buildUserPrompt(
* Omitted entirely when undefined.
*/
wars?: WarInfo[],
/**
* (v0.34.0, #57) The player's current relations to every other nation
* (`nationId -> RelationStatus`). Emitted verbatim (even when empty) so the
* model sees the relation ladder it can nudge with `information` / `proxy`
* hybrid ops and knows the current state before an `exposed` backfire.
* Omitted entirely when undefined.
*/
relations?: Record<string, RelationStatus>,
): string {
const player = state.nations[state.playerNationId];
const playerName = player?.name ?? state.playerNationId;
@@ -389,6 +408,7 @@ export function buildUserPrompt(
if (noMansLand !== undefined) payload.unowned = noMansLand;
if (markers !== undefined) payload.markers = markers;
if (wars !== undefined) payload.wars = wars;
if (relations !== undefined) payload.relations = relations;
return JSON.stringify(payload, null, 2);
}
@@ -528,6 +548,7 @@ export function validateTurnResult(
nationOps: [],
takeovers: [],
wars: { declare: [], end: [] },
hybrid: { ops: [] },
markers: { add: [], remove: [] },
};
@@ -626,6 +647,12 @@ export function validateTurnResult(
// Applied directly by applyTurnResult (after takeovers, before markers).
result.wars = validateWarOps(o.wars);
// (v0.34.0, #57) Covert hybrid ops (spies, sabotage, assassination, cyber,
// economic, disinformation, proxy). Applied directly by applyTurnResult
// (after wars, before markers) — a deterministic per-type effect or an
// exposed backfire.
result.hybrid = { ops: validateHybridOps(o.hybrid) };
// (v0.27, #44) Map-marker ops: new placements (validated here) and
// removals by stable id. Applied by applyTurnResult after the territory
// moves (a new marker's owner is the region's post-turn owner).
@@ -806,6 +833,54 @@ export function validateWarOps(raw: unknown): { declare: WarDeclareOp[]; end: Wa
return out;
}
/**
* (v0.34.0, #57) Validate the raw `hybrid` field of a turn into a safe
* `{ ops }` shape. 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 `type` (one of
* {@link HYBRID_OP_TYPES}), a non-empty `from` (the acting nation, capped at
* 200 chars) and a non-empty `target` (a nation id/name or a region key, capped
* at 200 chars); an `outcome` of exactly `success` or `exposed` is kept (the
* default, `success`, is stored as absent to keep the shape minimal — the
* engine treats a missing outcome as success); a non-empty `detail` is capped
* at 300 chars. Resolution of `from` / `target` to concrete nation ids or
* region owners happens at apply time (`applyHybridOp`), not here.
*/
export function validateHybridOps(raw: unknown): HybridOp[] {
if (!Array.isArray(raw)) {
// Lenient: accept the `{ ops: [...] }` object shape (or a non-array → []).
if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
const inner = (raw as Record<string, unknown>).ops;
if (!Array.isArray(inner)) return [];
return validateHybridOpsList(inner);
}
return [];
}
return validateHybridOpsList(raw);
}
function validateHybridOpsList(raw: unknown[]): HybridOp[] {
const out: HybridOp[] = [];
for (const e of raw) {
if (!e || typeof e !== 'object') continue;
const o = e as Record<string, unknown>;
if (!isHybridOpType(o.type)) continue;
const from = str(o.from, 200);
const target = str(o.target, 200);
if (!from || !target) continue;
const detail = str(o.detail, 300);
const exposed = o.outcome === 'exposed'; // 'success' / missing → success
out.push({
type: o.type,
from,
target,
...(detail ? { detail } : {}),
...(exposed ? { outcome: 'exposed' as const } : {}),
});
}
return out;
}
/**
* (v0.33.0, #56) The UNORDERED pairs of belligerents of a set of ACTIVE
* wars: a war with sides [a, b, c] contributes the pairs {a,b}, {a,c},
@@ -879,6 +954,217 @@ export function syncWarRelations(prev: GameState, next: GameState): void {
}
}
// --- Hybrid war (v0.34.0, #57): covert, non-kinetic operations -------------
//
// The engine's DETERMINISTIC effects for the seven hybrid op types. There is no
// hidden randomness: the LLM declares an intended `outcome` (success / exposed)
// and the engine acts only on that. Each effect is small and documented:
//
// spy informational only — no stat, no relation (pure intel)
// sabotage a small ECONOMY dip on the target
// assassinate a small STABILITY dip on the target (absent the named-leaders
// feature, #61, a leader's removal sours the polity)
// cyber a small MILITARY dip on the target
// economic a small ECONOMY dip on the target
// information a relation nudge toward hostile (cap hostile) — disinformation
// proxy a light relation nudge toward hostile (cap rival) — proxy war
//
// A successful stat op dips the target's `regionStats` (the single named region
// when the target was a region key, otherwise every region the target owns) and
// re-derives the target nation's aggregate stats so the effect persists. A
// successful information/proxy and any exposed op sour the actor's relation
// with the target by one step on the hostile ladder.
/** The deterministic per-type stat effect of a hybrid op (v0.34.0, #57). */
export const HYBRID_STAT_EFFECT: Record<HybridOpType, { stat: StatKey; delta: number } | null> = {
spy: null, // informational only
sabotage: { stat: 'economy', delta: -3 },
assassinate: { stat: 'stability', delta: -5 },
cyber: { stat: 'military', delta: -3 },
economic: { stat: 'economy', delta: -5 },
information: null, // relation nudge only
proxy: null, // relation nudge only
};
/**
* The hostile-relations ladder, weakest to strongest (the `cap` in
* {@link shiftRelationTowardHostile} is a member of this array). A missing
* relation is treated as `neutral`; `war` is never touched (a war is its own
* entity — a covert op neither fabricates nor ends one).
*/
const HOSTILE_ORDER: RelationStatus[] = ['ally', 'neutral', 'rival', 'hostile'];
/**
* (v0.34.0, #57) Nudge the bilateral relation between nations `a` and `b`
* ONE step toward hostile (on the {@link HOSTILE_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 covert op
* neither fabricates nor downgrades a war). Used for the `information` /
* `proxy` nudge and the `exposed` backfire. Mutates `state` in place (the
* caller passes a clone — applyTurnResult does). Never throws.
*/
export function shiftRelationTowardHostile(
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 = HOSTILE_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 = HOSTILE_ORDER.indexOf(s);
if (i === -1) return 'neutral'; // defensive: unknown status
if (i >= capIdx) return s; // at or past the cap: no change
return HOSTILE_ORDER[i + 1];
};
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.34.0, #57) The display name of a hybrid op's target for the auto
* backfire event: a nation target shows the nation's name; a region target
* shows the region's display name (or its raw key when no resolver is given).
*/
function hybridTargetDisplayName(
target: { nation: Nation; regionKey?: string },
regionNameOf?: (key: string) => string | undefined,
): string {
if (target.regionKey !== undefined) return regionNameOf?.(target.regionKey) ?? target.regionKey;
return target.nation.name;
}
/**
* (v0.34.0, #57) Resolve a hybrid op's `target` (a nation id/name OR a region
* key) to the concrete nation it affects. A nation ref resolves via
* {@link resolveNationRef}; a region key resolves to its SOLE owner (a region
* with zero or 2+ owners can't be a valid target). Returns the affected nation
* plus the specific region key (when the target was a region) so a stat op can
* dip just that region. `validKeys` (when supplied) gates the region-key path;
* a ref that is neither a known nation nor a valid region key returns `null`.
* Pure; never throws.
*/
function resolveHybridTarget(
state: GameState,
target: string,
validKeys?: ReadonlySet<string>,
): { nation: Nation; regionKey?: string } | null {
const id = resolveNationRef(state, target);
if (id !== null) {
const n = state.nations[id];
return n ? { nation: n } : null;
}
const key = (target ?? '').trim();
if (!key) return null;
if (validKeys && !validKeys.has(key)) return null; // unknown region key
const owners = Object.values(state.nations).filter((n) => n.territory.includes(key));
if (owners.length !== 1) return null; // 0 or 2+ owners: not a targetable region
return { nation: owners[0], regionKey: key };
}
/**
* (v0.34.0, #57) Apply ONE hybrid 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 actor drops the op.
* 2. `target` must resolve to a concrete nation (a nation ref, or a region
* key's sole owner); an unresolvable target drops the op.
* 3. A self-target (`from` and the target nation are the same) is dropped.
* Then, per type:
* - an `exposed` op BACKFIRES: no intended effect, the actor's relation with
* the target sours by one step (cap hostile), and an auto diplomatic/
* failure event is emitted (the engine's own narrative, mirroring the
* "repelled" auto-event).
* - a successful stat op (sabotage / assassinate / cyber / economic) dips the
* target's `regionStats` by its per-type delta — the single named region
* when the target was a region key, otherwise every region the target
* owns — then re-derives the target nation's aggregate stats (the same
* 0-region / no-entry guards as the main recompute), so the effect
* persists to the next turn.
* - a successful `information` / `proxy` sours the actor's relation with the
* target by one step (information caps at hostile, proxy at rival).
* - `spy` is informational only (no stat, no relation) — a no-op except for
* whatever the LLM narrates in `events`.
*/
function applyHybridOp(
next: GameState,
op: HybridOp,
geoOf?: (key: string) => { area: number; population: number } | undefined,
validKeys?: ReadonlySet<string>,
regionNameOf?: (key: string) => string | undefined,
actingTurn?: number,
): void {
const turn = actingTurn ?? next.turn;
const from = resolveNationRef(next, op.from);
if (from === null) return; // unknown / ambiguous actor: drop
const target = resolveHybridTarget(next, op.target, validKeys);
if (target === null) return; // unresolvable target: drop
if (from === target.nation.id) return; // self-target: drop
if (op.outcome === 'exposed') {
// Backfire: no intended effect; the relation sours by one step (cap
// hostile) and an auto diplomatic/failure event is emitted.
shiftRelationTowardHostile(next, from, target.nation.id, 'hostile');
const actor = next.nations[from];
next.events.push(
makeEvent(
{
nation: from,
type: 'diplomatic',
title: 'Covert operation exposed',
text: `${actor?.name ?? from}'s ${op.type} operation against ${hybridTargetDisplayName(
target,
regionNameOf,
)} was exposed; relations sour in response.`,
outcome: 'failure',
},
turn,
next.date,
),
);
return;
}
const eff = HYBRID_STAT_EFFECT[op.type];
if (eff) {
// A successful stat op: dip the target's region(s), then re-derive.
if (target.regionKey !== undefined) {
const rs = next.regionStats[target.regionKey];
if (rs) rs[eff.stat] = clampStat(rs[eff.stat] + eff.delta);
} else {
for (const key of target.nation.territory) {
const rs = next.regionStats[key];
if (!rs) continue;
rs[eff.stat] = clampStat(rs[eff.stat] + eff.delta);
}
}
// Re-derive the target nation's aggregate stats. The main recompute ran
// earlier this turn, so without this the dip would be washed out next
// turn. The same 0-region / no-entry guards as the main recompute apply.
if (target.nation.territory.length > 0) {
if (target.nation.territory.some((k) => next.regionStats[k])) {
target.nation.stats = deriveNationStats(
target.nation.territory,
next.regionStats,
geoOf,
);
}
}
return;
}
// information / proxy: a relation nudge (spy is a pure no-op here).
if (op.type === 'information') shiftRelationTowardHostile(next, from, target.nation.id, 'hostile');
else if (op.type === 'proxy') shiftRelationTowardHostile(next, from, target.nation.id, 'rival');
}
/**
* 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
@@ -901,6 +1187,9 @@ export function isMeaningful(result: TurnResult): boolean {
// (v0.33.0, #56) a war declared or ended is a real world change.
result.wars.declare.length > 0 ||
result.wars.end.length > 0 ||
// (v0.34.0, #57) a hybrid op (a successful one or an exposed backfire) is
// a real world change (a stat dip or a soured relation).
result.hybrid.ops.length > 0 ||
// (v0.27, #44) a marker placed or removed this turn is a real world change.
result.markers.add.length > 0 ||
result.markers.remove.length > 0
@@ -1246,6 +1535,17 @@ export function applyTurnResult(
syncWarRelations(state, next);
}
// --- Hybrid war (v0.34.0, #57): covert, non-kinetic operations ---
//
// Each op's deterministic per-type effect is applied to the post-wars state
// (a stat dip on the target's regions, or a relation nudge toward hostile).
// An `exposed` op backfires instead. They never move borders, so they run
// after the territory changes and before the markers (a marker's owner is
// recomputed from the final ownership, unaffected by a stat/relation dip).
for (const op of result.hybrid.ops) {
applyHybridOp(next, op, geoOf, validKeys, regionNameOf, actingTurn);
}
// --- Map markers (v0.27, #44) ---
//
// Markers are anchored to a region key and are processed against the FINAL
@@ -1744,6 +2044,11 @@ export async function runTurn(opts: {
sides: w.sides,
...(w.aims && w.aims.length > 0 ? { aims: w.aims } : {}),
}));
// (v0.34.0, #57) the player's current relations to every other nation, so the
// model sees the ladder its `information` / `proxy` hybrid ops nudge (and the
// starting point before an `exposed` backfire). Always emitted ({} when the
// player has no relations yet).
const relations = state.nations[state.playerNationId]?.relations ?? {};
const user = buildUserPrompt(
state,
items,
@@ -1752,6 +2057,7 @@ export async function runTurn(opts: {
state.unowned ?? [],
markers,
wars,
relations,
);
const nudge =
'Your previous output was invalid. Respond with ONLY the JSON object described above for this batch — no prose, no fences.';
@@ -1806,6 +2112,7 @@ export async function runTurn(opts: {
nationOps: [],
takeovers: [],
wars: { declare: [], end: [] },
hybrid: { ops: [] },
markers: { add: [], remove: [] },
};
}