feat(#46 PR 2): per-region stat lever (regionChanges) + region-stat hover
CI / build + unit + e2e (pull_request) Successful in 2m31s
CI / build + unit + e2e (pull_request) Successful in 2m31s
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)
This commit is contained in:
+169
-14
@@ -12,6 +12,7 @@ import type {
|
||||
NationStats,
|
||||
Preset,
|
||||
RelationStatus,
|
||||
RegionStats,
|
||||
RoundItem,
|
||||
StatKey,
|
||||
} from '../shared/types';
|
||||
@@ -30,6 +31,7 @@ import {
|
||||
type MarkerInfo,
|
||||
type MarkerSpec,
|
||||
type NationOp,
|
||||
type RegionStatChange,
|
||||
type TurnEventSpec,
|
||||
type TurnResult,
|
||||
} from '../shared/protocol';
|
||||
@@ -187,6 +189,7 @@ export function buildSystemPrompt(preset: Preset, withNeighboursTool = false): s
|
||||
' {"nation":"<nationId>","type":"<military|diplomatic|economic|political|social|disaster|scientific|cultural>","title":"short headline","text":"1-3 sentences of narrative","outcome":"<success|failure|partial|neutral>"}',
|
||||
' ],',
|
||||
' "stateChanges": [{"nation":"<nationId>","stat":"<military|economy|stability|population>","op":"<set|add>","value":<0-100>}],',
|
||||
' "regionChanges": [{"region":"<region key or name>","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>"],',
|
||||
@@ -210,6 +213,7 @@ export function buildSystemPrompt(preset: Preset, withNeighboursTool = false): s
|
||||
'- 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.',
|
||||
'- Per-region stat changes ("regionChanges") target ONE region\'s stats directly, by its region key (preferred) or name, and make that region differ from the rest of its nation (a garrisoned border province, a bombed-out city, an industrial heartland). A nation-wide "stateChanges" entry applies to ALL of a nation\'s regions; a "regionChanges" entry overrides it for that one region. The user message\'s "playerRegionStats" lists the player\'s own regions\' current stats; use region keys from the "regions" table.',
|
||||
...territoryRules,
|
||||
'- If a field is not relevant this turn, set it to an empty array.',
|
||||
].join('\n');
|
||||
@@ -263,6 +267,19 @@ export function buildUserPrompt(
|
||||
)}. Simulate the combined consequences across all nations and advance the world by one period. Return a single TurnResult.`
|
||||
: 'The player takes no action this period; let the world advance on its own momentum. Return a single TurnResult.';
|
||||
|
||||
// (v0.29, #46 PR 2) The player's own regions' current per-region stats, so the
|
||||
// model can reason about — and target via `regionChanges` — the player's
|
||||
// individual regions. Bounded to the player's territory (not the whole
|
||||
// world's 1,800 regions) to keep the prompt small. Always emitted: {} when
|
||||
// the player has no region with a stats entry yet.
|
||||
const playerRegionStats: Record<string, RegionStats> = {};
|
||||
if (state.regionStats) {
|
||||
for (const key of player?.territory ?? []) {
|
||||
const rs = state.regionStats[key];
|
||||
if (rs) playerRegionStats[key] = rs;
|
||||
}
|
||||
}
|
||||
|
||||
const payload: Record<string, unknown> = {
|
||||
state: {
|
||||
turn: state.turn,
|
||||
@@ -284,6 +301,7 @@ export function buildUserPrompt(
|
||||
playerActions,
|
||||
pending: items,
|
||||
roundInstruction,
|
||||
playerRegionStats,
|
||||
};
|
||||
if (regionReference) payload.regions = regionReference;
|
||||
if (frontier !== undefined) payload.frontier = frontier;
|
||||
@@ -328,8 +346,13 @@ function extractBalancedObject(text: string): string | null {
|
||||
/**
|
||||
* Parse raw LLM output into a validated TurnResult, or null if unusable. Strips
|
||||
* code fences, extracts the first balanced object, JSON.parse, then validates.
|
||||
* (v0.29, #46 PR 2) The optional `regionKeyResolver` is threaded to
|
||||
* `validateTurnResult` to resolve `regionChanges` refs to region keys.
|
||||
*/
|
||||
export function parseTurnResult(raw: string): TurnResult | null {
|
||||
export function parseTurnResult(
|
||||
raw: string,
|
||||
regionKeyResolver?: (ref: string) => string | null,
|
||||
): TurnResult | null {
|
||||
const cleaned = stripFence(raw);
|
||||
const jsonText = extractBalancedObject(cleaned);
|
||||
if (!jsonText) return null;
|
||||
@@ -339,7 +362,7 @@ export function parseTurnResult(raw: string): TurnResult | null {
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
return validateTurnResult(obj);
|
||||
return validateTurnResult(obj, regionKeyResolver);
|
||||
}
|
||||
|
||||
function str(s: unknown, max = 0): string | null {
|
||||
@@ -400,14 +423,23 @@ export function validateNationOps(raw: unknown): NationOp[] {
|
||||
* Validate and normalize an arbitrary parsed object into a safe TurnResult.
|
||||
* Ignores unknown/invalid entries; clamps numeric stats to 0-100. Returns null
|
||||
* only when the input is not even a plain object.
|
||||
*
|
||||
* (v0.29, #46 PR 2) The optional `regionKeyResolver` resolves each
|
||||
* `regionChanges` ref (key or name) to a concrete region key, dropping
|
||||
* unknown/ambiguous refs; without it the refs are kept as-is (shape-only), so
|
||||
* callers that build a TurnResult by hand (tests) need not supply it.
|
||||
*/
|
||||
export function validateTurnResult(input: unknown): TurnResult | null {
|
||||
export function validateTurnResult(
|
||||
input: unknown,
|
||||
regionKeyResolver?: (ref: string) => string | null,
|
||||
): TurnResult | null {
|
||||
if (typeof input !== 'object' || input === null || Array.isArray(input)) return null;
|
||||
const o = input as Record<string, unknown>;
|
||||
const result: TurnResult = {
|
||||
date: typeof o.date === 'string' ? o.date : '',
|
||||
events: [],
|
||||
stateChanges: [],
|
||||
regionChanges: [],
|
||||
relations: [],
|
||||
territoryChanges: [],
|
||||
unowned: [],
|
||||
@@ -507,6 +539,12 @@ export function validateTurnResult(input: unknown): TurnResult | null {
|
||||
// moves (a new marker's owner is the region's post-turn owner).
|
||||
result.markers = validateMarkerOps(o.markers);
|
||||
|
||||
// (v0.29, #46 PR 2) Per-region stat changes: each targets a single region's
|
||||
// stats (by key or name). Resolved to a key here when a resolver is
|
||||
// supplied; applied by applyTurnResult after the nation-wide stateChanges
|
||||
// and before the derived-stat recompute.
|
||||
result.regionChanges = validateRegionChanges(o.regionChanges, regionKeyResolver);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -547,6 +585,61 @@ export function validateMarkerOps(raw: unknown): { add: MarkerSpec[]; remove: st
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* (v0.29, #46 PR 2) Validate the raw `regionChanges` array of a turn into a
|
||||
* safe {@link RegionStatChange} list — the fine-grained, per-region stat lever
|
||||
* that complements the nation-wide `stateChanges`. Defensive like the rest of
|
||||
* the parser — never throws. Each entry needs a non-empty `region` (the
|
||||
* region's stable key, preferred, or its human-readable name — capped at 120
|
||||
* chars), a known stat, a finite numeric `value`, and an op of `set` or `add`.
|
||||
*
|
||||
* When `regionKeyResolver` is provided, each `region` ref is resolved to a
|
||||
* concrete region key (key first, then a unique case-insensitive name match —
|
||||
* see {@link resolveRegionKey}) and the resolved key is stored; a ref that
|
||||
* resolves to `null` (unknown or ambiguous) is dropped, exactly like an
|
||||
* unresolvable nation ref. When the resolver is absent (pure unit tests), the
|
||||
* ref is kept as-is (shape-only validation) — a name that is not a key simply
|
||||
* no-ops later in `applyTurnResult` (its `regionStats` lookup misses). `set`
|
||||
* values are clamped to 0–100 here; `add` deltas are clamped against the
|
||||
* current value at apply time (they may legitimately exceed 100 in the raw
|
||||
* input, since they are added to an existing 0–100 value).
|
||||
*/
|
||||
export function validateRegionChanges(
|
||||
raw: unknown,
|
||||
regionKeyResolver?: (ref: string) => string | null,
|
||||
): RegionStatChange[] {
|
||||
if (!Array.isArray(raw)) return [];
|
||||
const out: RegionStatChange[] = [];
|
||||
for (const e of raw) {
|
||||
if (!e || typeof e !== 'object') continue;
|
||||
const c = e as Record<string, unknown>;
|
||||
const region = str(c.region, 120);
|
||||
const stat = str(c.stat);
|
||||
if (!region || !stat || !VALID_STATS.has(stat)) continue;
|
||||
if (typeof c.value !== 'number' || !Number.isFinite(c.value)) continue;
|
||||
if (c.op !== 'set' && c.op !== 'add') continue;
|
||||
// Resolve the ref to a key when a resolver is available; drop it when the
|
||||
// resolver says the ref is unknown or ambiguous (never throw). Without a
|
||||
// resolver the ref is kept as-is (a name that is not a key no-ops later in
|
||||
// applyTurnResult, whose regionStats lookup simply misses it).
|
||||
let finalRegion: string;
|
||||
if (regionKeyResolver) {
|
||||
const resolved = regionKeyResolver(region);
|
||||
if (resolved === null) continue; // unknown or ambiguous → drop
|
||||
finalRegion = resolved;
|
||||
} else {
|
||||
finalRegion = region;
|
||||
}
|
||||
out.push({
|
||||
region: finalRegion,
|
||||
stat: stat as StatKey,
|
||||
op: c.op,
|
||||
value: c.op === 'set' ? clampStat(c.value) : c.value,
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
@@ -559,6 +652,8 @@ export function isMeaningful(result: TurnResult): boolean {
|
||||
return (
|
||||
result.events.length > 0 ||
|
||||
result.stateChanges.length > 0 ||
|
||||
// (v0.29, #46 PR 2) a per-region stat change is a real world change.
|
||||
result.regionChanges.length > 0 ||
|
||||
result.unowned.length > 0 ||
|
||||
result.nationOps.length > 0 ||
|
||||
// (v0.27, #44) a marker placed or removed this turn is a real world change.
|
||||
@@ -761,6 +856,18 @@ export function applyTurnResult(
|
||||
}
|
||||
n.stats[c.stat] = c.op === 'set' ? clampStat(c.value) : clampStat(n.stats[c.stat] + c.value);
|
||||
}
|
||||
// (v0.29, #46 PR 2) Fine-grained, per-region stat changes: each targets ONE
|
||||
// region's own stats entry (by its resolved region key). Applied AFTER the
|
||||
// nation-wide stateChanges (so a region-level change overrides the
|
||||
// nation-level one for that single region) and BEFORE the weighted-median
|
||||
// recompute below, which propagates every region's final value up into its
|
||||
// owning nation's derived `stats`. A region with no stats entry (unowned /
|
||||
// no man's land) is a no-op — there is nothing to change.
|
||||
for (const c of result.regionChanges) {
|
||||
const rs = next.regionStats[c.region];
|
||||
if (!rs) continue; // no entry (unowned) → no-op
|
||||
rs[c.stat] = c.op === 'set' ? clampStat(c.value) : clampStat(rs[c.stat] + c.value);
|
||||
}
|
||||
for (const n of Object.values(next.nations)) {
|
||||
if (n.territory.length === 0) continue; // 0-region guard: no regions to aggregate
|
||||
if (!n.territory.some((k) => next.regionStats[k])) continue; // no entry: keep n.stats
|
||||
@@ -908,6 +1015,37 @@ export function resolveNationRef(state: GameState, ref: string): string | null {
|
||||
return matches.length === 1 ? matches[0].id : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* (v0.29, #46 PR 2) Resolve a **region** reference (a `regionChanges` entry's
|
||||
* `region` — the LLM may write either the region's stable **key** or its
|
||||
* human-readable **name**) to a concrete region key: an exact key match wins,
|
||||
* then a unique case-insensitive name match (via `nameOf`). Returns `null`
|
||||
* when the reference is empty, unknown, or ambiguous (two or more regions
|
||||
* share that name) — every caller treats `null` as "drop this change" and
|
||||
* nothing here ever throws. Mirrors {@link resolveNationRef}. `validKeys` is
|
||||
* the set of all region keys and `nameOf` maps a key to its human name (both
|
||||
* supplied by server/regions.ts).
|
||||
*/
|
||||
export function resolveRegionKey(
|
||||
ref: string,
|
||||
validKeys: ReadonlySet<string>,
|
||||
nameOf: (key: string) => string | undefined,
|
||||
): string | null {
|
||||
const r = (ref ?? '').trim();
|
||||
if (!r) return null;
|
||||
if (validKeys.has(r)) return r; // exact key first
|
||||
const lower = r.toLowerCase();
|
||||
let match: string | null = null;
|
||||
for (const k of validKeys) {
|
||||
const name = nameOf(k);
|
||||
if (name && name.trim().toLowerCase() === lower) {
|
||||
if (match !== null) return null; // ambiguous: two or more regions share the name
|
||||
match = k;
|
||||
}
|
||||
}
|
||||
return match;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a fresh, unused nation id for a newly created nation (split
|
||||
* parts, v0.24 #16 P4b): the first free of `n1`, `n2`, ... The caller adds
|
||||
@@ -1177,8 +1315,18 @@ export async function runTurn(opts: {
|
||||
* still region-consistent, just unweighted.
|
||||
*/
|
||||
geoOf?: (key: string) => { area: number; population: number } | undefined;
|
||||
/**
|
||||
* (v0.29, #46 PR 2) Region ref resolver: resolves a `regionChanges` entry's
|
||||
* `region` (a region key, preferred, or a human-readable name) to a concrete
|
||||
* region key, or `null` when the ref is unknown or ambiguous (two or more
|
||||
* regions share the name) — the engine drops such entries. Present, the
|
||||
* model may name a region by its name and it is resolved before apply;
|
||||
* absent, refs are kept as-is (a name that is not a key simply no-ops in
|
||||
* applyTurnResult's regionStats lookup).
|
||||
*/
|
||||
regionKeyResolver?: (ref: string) => string | null;
|
||||
}): Promise<{ state: GameState; result: TurnResult }> {
|
||||
const { llm, preset, state, items, regionReference, validRegionKeys, getNeighbours, centroidOf, geoOf } = opts;
|
||||
const { llm, preset, state, items, regionReference, validRegionKeys, getNeighbours, centroidOf, geoOf, regionKeyResolver } = opts;
|
||||
const chatWithTools = llm.chatWithTools;
|
||||
const useTools = getNeighbours !== undefined && chatWithTools !== undefined;
|
||||
const system = buildSystemPrompt(preset, useTools);
|
||||
@@ -1216,18 +1364,24 @@ export async function runTurn(opts: {
|
||||
return llm.chat(history as ChatMessage[], { temperature: 0.4, maxTokens: DEFAULT_MAX_TOKENS });
|
||||
};
|
||||
|
||||
let result = parseTurnResult(await call([
|
||||
{ role: 'system', content: system },
|
||||
{ role: 'user', content: user },
|
||||
]));
|
||||
|
||||
if (result === null || !isMeaningful(result)) {
|
||||
result = parseTurnResult(await call([
|
||||
let result = parseTurnResult(
|
||||
await call([
|
||||
{ role: 'system', content: system },
|
||||
{ role: 'user', content: user },
|
||||
{ role: 'assistant', content: '' },
|
||||
{ role: 'user', content: nudge },
|
||||
]));
|
||||
]),
|
||||
regionKeyResolver,
|
||||
);
|
||||
|
||||
if (result === null || !isMeaningful(result)) {
|
||||
result = parseTurnResult(
|
||||
await call([
|
||||
{ role: 'system', content: system },
|
||||
{ role: 'user', content: user },
|
||||
{ role: 'assistant', content: '' },
|
||||
{ role: 'user', content: nudge },
|
||||
]),
|
||||
regionKeyResolver,
|
||||
);
|
||||
}
|
||||
|
||||
if (result === null || !isMeaningful(result)) {
|
||||
@@ -1235,6 +1389,7 @@ export async function runTurn(opts: {
|
||||
date: addDays(state.date, 2),
|
||||
events: [genericUnclearEvent(state)],
|
||||
stateChanges: [],
|
||||
regionChanges: [],
|
||||
relations: [],
|
||||
territoryChanges: [],
|
||||
unowned: [],
|
||||
|
||||
Reference in New Issue
Block a user