@chrischall/warapp-mcp 0.14.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -83,6 +83,20 @@ export function decisionLogMode(env = process.env) {
83
83
  }
84
84
  /** The keys of `PlanInput` that are not kept in {@link LoggedInput}. */
85
85
  const INPUT_DROPPED = new Set(['graph', 'board', 'vacated', 'bonusPush', 'previousBoard']);
86
+ /** #568: the stages of an estimate as the decision log keeps them. */
87
+ export function estimateStages(e) {
88
+ return {
89
+ visible: e.base + e.bonusIncome,
90
+ observed: e.observed,
91
+ tracked: e.tracked,
92
+ prior: e.stated ? e.stated.full : e.prior,
93
+ stated: e.stated ? e.stated.scaled : null,
94
+ blend: e.priorBlend ? e.priorBlend.figure : null,
95
+ thin: e.thinEvidence ? e.thinEvidence.figure : null,
96
+ known: e.known ? e.known.income : null,
97
+ card: e.card ? e.card.armies : 0,
98
+ };
99
+ }
86
100
  /** Chat messages kept per turn at most. */
87
101
  export const MAX_LOGGED_CHAT = 50;
88
102
  /** Game events kept at most per log (the newest). */
@@ -225,10 +239,19 @@ export function decodeInput(logged, board, graph) {
225
239
  };
226
240
  }
227
241
  /** The estimates as logged: ids, figures and flags only. */
228
- export function loggedEstimates(estimates) {
242
+ export function loggedEstimates(estimates, tracks) {
243
+ const methods = new Map((tracks ?? []).flatMap((t) => (t.incomeMethod ? [[t.playerId, t.incomeMethod]] : [])));
229
244
  return [...estimates]
230
245
  .sort((a, b) => a.playerId - b.playerId)
231
- .map((e) => ({ player: e.playerId, estimate: e.estimate, source: e.source, coverage: e.coverage?.share ?? null, thin: !!e.thinEvidence }));
246
+ .map((e) => ({
247
+ player: e.playerId,
248
+ estimate: e.estimate,
249
+ source: e.source,
250
+ coverage: e.coverage?.share ?? null,
251
+ thin: !!e.thinEvidence,
252
+ ...(methods.has(e.playerId) ? { method: methods.get(e.playerId) } : {}),
253
+ stages: estimateStages(e),
254
+ }));
232
255
  }
233
256
  /** My income as `input` gives it, card armies out; `undefined` when it holds none. */
234
257
  function earnedIncome(input) {
@@ -237,7 +260,7 @@ function earnedIncome(input) {
237
260
  return undefined;
238
261
  return income - (typeof cardArmies === 'number' ? cardArmies : 0);
239
262
  }
240
- function decisionOf(plan, outlook, outlookLean, estimates, income) {
263
+ function decisionOf(plan, outlook, outlookLean, estimates, income, tracks) {
241
264
  return encodeValue({
242
265
  goal: plan.goal,
243
266
  profile: plan.profile,
@@ -252,7 +275,7 @@ function decisionOf(plan, outlook, outlookLean, estimates, income) {
252
275
  warnings: plan.warnings,
253
276
  outlook: outlook ?? null,
254
277
  ...(outlookLean ? { outlookLean } : {}),
255
- ...(estimates ? { estimates: loggedEstimates(estimates) } : {}),
278
+ ...(estimates ? { estimates: loggedEstimates(estimates, tracks) } : {}),
256
279
  ...(income !== undefined ? { income } : {}),
257
280
  });
258
281
  }
@@ -402,7 +425,7 @@ export async function recordDecision(dir, gameId, playerId, rec, opts = {}) {
402
425
  kind: 'planned',
403
426
  input,
404
427
  planner: { version: VERSION, ...(build ? { build } : {}) },
405
- decision: decisionOf(rec.plan, rec.outlookState, rec.outlookLean, rec.estimates, earnedIncome(rec.input)),
428
+ decision: decisionOf(rec.plan, rec.outlookState, rec.outlookLean, rec.estimates, earnedIncome(rec.input), rec.input.tracks),
406
429
  times: encodeValue({ plannedAt: iso(rec.now), ...rec.times }),
407
430
  ...(rec.firstMover !== undefined ? { firstMover: rec.firstMover ? { ...rec.firstMover } : null } : {}),
408
431
  ...(rec.cards ? { cards: encodeValue(rec.cards) } : {}),
@@ -653,6 +676,22 @@ export async function recordCheck(dir, gameId, playerId, turn, summary, opts = {
653
676
  return false;
654
677
  }
655
678
  }
679
+ /**
680
+ * #570: keep the resolved turn's visible orders on that turn's entry (an entry is started when none exists).
681
+ * Read again, the newest read wins. `true` when written. Never throws.
682
+ */
683
+ export async function recordSeenTurn(dir, gameId, playerId, seen, opts = {}) {
684
+ try {
685
+ const kept = { orders: seen.orders, ...(seen.omitted ? { omitted: seen.omitted } : {}) };
686
+ return await updateDecisionLog(dir, gameId, playerId, (log) => {
687
+ const was = log.turns[String(seen.turn)] ?? {};
688
+ return { ...log, turns: { ...log.turns, [String(seen.turn)]: { ...was, seen: kept } } };
689
+ }, opts);
690
+ }
691
+ catch {
692
+ return false;
693
+ }
694
+ }
656
695
  // ---------------------------------------------------------------------------------------------
657
696
  // #437 task 2: per-game events and context
658
697
  /** States in which a seat's change is no event (still in, or not yet in). */
@@ -53,6 +53,13 @@ export const finishedPath = (dir, salt, me, gameId) => join(finishedDir(dir), `$
53
53
  /** The processed marks: not a record (its name is no key), so the prune and the record list skip it. */
54
54
  export const processedPath = (dir) => join(finishedDir(dir), 'processed.json');
55
55
  const KEY = /^[0-9a-f]{32}$/;
56
+ /**
57
+ * The version of what the end-of-game pass collects and processes from a history. Bump it whenever the capture
58
+ * or its processing (profiles, map record, lessons, decision-log truth, stats) gains or changes a metric:
59
+ * warapp_backfill_history's `reread: 'outdated'` then reads again the history of every game whose record was
60
+ * kept under an older one (a record kept before this field reads as 0). 1: the first versioned capture.
61
+ */
62
+ export const COLLECTOR_VERSION = 1;
56
63
  /**
57
64
  * #541/#542: the version of the stats computation. 2: seat lines stop and resume as the client's (a return to
58
65
  * Playing resumes; an AI takeover runs on under the seat with `aiFrom`). 3 (#542 follow-up): a seat ordering after
@@ -90,6 +97,39 @@ export async function readFinishedState(path) {
90
97
  return 'unreadable';
91
98
  }
92
99
  }
100
+ /** The record at `path` summarised: `missing`, `unreadable` (as {@link readFinishedState}), or its summary. Never throws. */
101
+ export async function readFinishedSummary(path) {
102
+ let text;
103
+ try {
104
+ text = await readFile(path, 'utf8');
105
+ }
106
+ catch (e) {
107
+ return e.code === 'ENOENT' ? 'missing' : 'unreadable';
108
+ }
109
+ try {
110
+ const v = JSON.parse(text);
111
+ if (!isRec(v) || v.version !== VERSION || typeof v.status !== 'string' || !STATUSES.has(v.status))
112
+ return 'unreadable';
113
+ const r = v;
114
+ const f = isRec(r.failure) ? r.failure : undefined;
115
+ const stats = isRec(r.stats) ? r.stats : undefined;
116
+ return {
117
+ status: r.status,
118
+ collector: typeof r.collector === 'number' && Number.isInteger(r.collector) && r.collector >= 0 ? r.collector : 0,
119
+ ...(f && typeof f.reason === 'string'
120
+ ? { failure: { reason: f.reason, ...('kind' in f && typeof f.kind === 'string' ? { kind: f.kind } : {}) } }
121
+ : {}),
122
+ ...(Array.isArray(r.turns) ? { turns: r.turns.length } : {}),
123
+ ...(Array.isArray(r.boards) ? { boards: r.boards.length } : {}),
124
+ ...(stats && typeof stats.version === 'number' ? { statsVersion: stats.version } : {}),
125
+ ...(Array.isArray(r.kinds) ? { kinds: r.kinds.filter((k) => typeof k === 'string') } : {}),
126
+ ...(isRec(r.outcome) && typeof r.outcome.result === 'string' ? { result: r.outcome.result } : {}),
127
+ };
128
+ }
129
+ catch {
130
+ return 'unreadable';
131
+ }
132
+ }
93
133
  /**
94
134
  * Write a record atomically (0600), then keep the newest {@link MAX_FINISHED_RECORDS}: never a path in
95
135
  * `protect` (the sweep's window, src/tools/end-of-game.ts), nor the one just written. Throws on a failed write.
@@ -199,6 +239,7 @@ export function finishedRecordOf(p) {
199
239
  const stored = kept ? storeBoards(kept.boards, p.game?.players.map((x) => x.id) ?? [p.me], key) : undefined;
200
240
  return {
201
241
  version: VERSION,
242
+ collector: COLLECTOR_VERSION,
202
243
  status: p.status,
203
244
  ...(p.failure ? { failure: p.failure } : {}),
204
245
  ...(p.layout ? { layout: p.layout } : {}),
@@ -0,0 +1,102 @@
1
+ // The #318 calibration and opening-benchmark harness over the data directory: the body of
2
+ // `scripts/calibrate.mjs`, moved here (#569) so the script and warapp_calibration's `harness: true` share it.
3
+ // It reads the end-of-game records, settings records, stored maps and cached boards (src/calibration-source.ts)
4
+ // and returns aggregates only — no game id, player id or name. No request, nothing written. The pure parts are
5
+ // src/analysis/calibrate.ts; docs/PLAN-PROFILES.md "Calibration" says what it approximates.
6
+ import { profileFormatOf } from '../analysis/opponent-profile.js';
7
+ import { trackGame } from '../analysis/opponents.js';
8
+ import { applyBonusOverrides } from '../analysis/overrides.js';
9
+ import { aggregateBenchmarks, aggregateEstimates, benchmarkByEra, estimateSamples, openingBenchmark, openingEra, openingFlags, ratioSummary, } from '../analysis/calibrate.js';
10
+ import { addCalibration } from '../analysis/game-lessons.js';
11
+ import { calibrationSources } from '../calibration-source.js';
12
+ import { holdsSeat } from '../player-states.js';
13
+ import { graphOf } from './common.js';
14
+ import { plannerSettings } from './turn.js';
15
+ /** What the opening benchmark approximates: printed by the script and reported by the tool. */
16
+ export const HARNESS_APPROXIMATIONS = [
17
+ 'Opening benchmark approximations: the planner sees the whole board (no fog); opponents never attack me —',
18
+ 'they hold the land and armies the history shows, except land I hold in the replay; card plays are left out;',
19
+ 'with luck or weighted rounding a battle is resolved at its expectation (counted as inexact).',
20
+ 'Eras (#503): pre-tool = never planned by this server, or no local cache names the game; pre-rule-4f = turn 1',
21
+ 'before 2026-11-13 08:24Z by its turn-1 time where known, else game id below 45690000 (ids are assigned at creation,',
22
+ 'so the id boundary approximates the time); current = the rest. A game with a turn with no orders of mine (read off',
23
+ 'the history boards: no capture, no failed attack, no orders cached; army growth alone is not orders) or a boot of my seat in turns',
24
+ '1-4 is reported apart, never averaged in.',
25
+ ];
26
+ /** Run the harness over `dir`. `turns`: the opening benchmark's length (default the module's). Never requests. */
27
+ export async function calibrationHarness(dir, opts = {}) {
28
+ const src = await calibrationSources(dir);
29
+ const counts = { histories: src.statuses, skipped: src.skipped, scored: 0, recordOnly: 0, benchmarked: 0, samples: 0 };
30
+ const byFormat = {};
31
+ const benchByFormat = {};
32
+ const eraEntries = [];
33
+ for (const input of src.inputs) {
34
+ const { history: h, settings, map, cached } = input;
35
+ if (input.source === 'record-only')
36
+ counts.recordOnly++;
37
+ const me = h.me;
38
+ const graph = graphOf(applyBonusOverrides(map, settings));
39
+ const seated = h.players.filter((p) => holdsSeat(p.state));
40
+ const format = profileFormatOf(seated);
41
+ const mine = seated.find((p) => p.id === me);
42
+ const myTeam = typeof mine?.team === 'number' && mine.team >= 0 ? mine.team : undefined;
43
+ const opponents = seated.filter((p) => p.id !== me && (myTeam === undefined || p.team !== myTeam)).map((p) => p.id);
44
+ const asPlaying = seated.map(({ state: _s, ...p }) => p);
45
+ const ps = plannerSettings(settings);
46
+ const samples = estimateSamples({
47
+ graph,
48
+ me,
49
+ cached,
50
+ history: h.boards,
51
+ plannerSettings: ps,
52
+ incomeSettings: settings,
53
+ settings,
54
+ game: trackGame(asPlaying, settings, map),
55
+ players: asPlaying,
56
+ opponents,
57
+ });
58
+ counts.samples += samples.length;
59
+ if (samples.length)
60
+ counts.scored++;
61
+ const agg = aggregateEstimates(samples);
62
+ const f = (byFormat[format] ??= {});
63
+ for (const [k, c] of Object.entries(agg))
64
+ f[k] = addCalibration(f[k] ?? {}, c);
65
+ const bench = openingBenchmark({
66
+ graph,
67
+ me,
68
+ history: h.boards,
69
+ plannerSettings: ps,
70
+ incomeSettings: settings,
71
+ players: asPlaying,
72
+ winners: seated.filter((p) => p.state === 'Won').map((p) => p.id),
73
+ ...(opts.turns ? { turns: opts.turns } : {}),
74
+ });
75
+ if (bench.turns.length) {
76
+ counts.benchmarked++;
77
+ (benchByFormat[format] ??= []).push(bench);
78
+ // #503: the era (turn-1 time where known — no record keeps one yet — else the game id) and the
79
+ // opening window's flags (turns with no orders of mine, a boot of my seat).
80
+ const o = input.opening;
81
+ const { era, basis } = openingEra({ planned: o.planned, ...(o.gameId !== undefined ? { gameId: o.gameId } : {}) });
82
+ const flags = openingFlags({
83
+ me,
84
+ history: h.boards,
85
+ sentTurns: o.sentTurns,
86
+ failedAttackTurns: o.failedAttackTurns,
87
+ booted: { turn: o.bootedTurn },
88
+ });
89
+ eraEntries.push({ era, basis, format, territories: graph.territoryById.size, flags, bench });
90
+ }
91
+ }
92
+ const calibration = {};
93
+ for (const [format, ests] of Object.entries(byFormat))
94
+ for (const [k, c] of Object.entries(ests))
95
+ for (const [band, stats] of Object.entries(c))
96
+ ((calibration[format] ??= {})[k] ??= {})[band] = ratioSummary(stats);
97
+ const benchmark = {};
98
+ for (const [format, list] of Object.entries(benchByFormat))
99
+ benchmark[format] = aggregateBenchmarks(list);
100
+ benchmark.all = aggregateBenchmarks(Object.values(benchByFormat).flat());
101
+ return { counts, calibration, benchmark, byEra: benchmarkByEra(eraEntries) };
102
+ }
@@ -0,0 +1,110 @@
1
+ // warapp_calibration (#569, for #568): the income estimates this server planned with, scored against the
2
+ // truth its finished games kept — read-only, from this server's state alone (no war.app request), so an agent
3
+ // can run the calibration on a hosted server whose data directory no local script can reach. The pure part is
4
+ // src/analysis/income-calibration.ts; `harness: true` adds the #318 harness (src/tools/calibration-harness.ts).
5
+ // Name-free: games are numbered by their place in the report, never by id; no player is named or numbered.
6
+ import { toolAnnotations } from '@chrischall/mcp-utils';
7
+ import { z } from 'zod';
8
+ import { incomeCalibration, incomeSamples } from '../analysis/income-calibration.js';
9
+ import { profileFormatOf } from '../analysis/opponent-profile.js';
10
+ import { listDecisionLogs, readDecisionLog } from '../decision-log.js';
11
+ import { holdsSeat } from '../player-states.js';
12
+ import { readGameRecord } from '../replay.js';
13
+ import { calibrationHarness, HARNESS_APPROXIMATIONS } from './calibration-harness.js';
14
+ import { respond } from './common.js';
15
+ import { mintMeta } from './hints.js';
16
+ import { refuse } from './write-kit.js';
17
+ /** Scored rows returned at most with `samples: true`. */
18
+ export const MAX_SAMPLES = 2000;
19
+ export const CALIBRATION_NOTE = 'Each sample is one income estimate a planned turn worked from, against that opponent\'s true income (base plus ' +
20
+ 'full bonuses, cards and the army cap aside) on the board the turn was played on, read from the finished game\'s ' +
21
+ 'history. ratio = estimate ÷ truth; meanError = estimate − truth in armies. Reported only: nothing plans on it. ' +
22
+ 'Only games whose decision log was given the end-of-game truth count (games played on builds with the decision log, ' +
23
+ 'finished, their history read); `method` (the tracker\'s, incl. rise-capped) is logged only since #569. The ' +
24
+ 'consequences block is a proxy: a lost territory has many causes.';
25
+ /** Every finished decision log in `dir` as the scoring reads it, in game-id order; lotteries counted apart. Never throws. */
26
+ export async function calibrationGames(dir) {
27
+ const listed = (await listDecisionLogs(dir)).filter((l) => l.status !== 'active');
28
+ const games = [];
29
+ let lotteries = 0;
30
+ let withoutTruth = 0;
31
+ for (const l of listed) {
32
+ const log = await readDecisionLog(dir, l.gameId, l.playerId);
33
+ if (!log)
34
+ continue;
35
+ if (log.join?.lottery !== undefined) {
36
+ lotteries++;
37
+ continue;
38
+ }
39
+ if (!Object.values(log.turns).some((e) => e.accuracy?.estimates.length)) {
40
+ withoutTruth++;
41
+ continue;
42
+ }
43
+ games.push({ ...(await formatOf(dir, log)), turns: log.turns });
44
+ }
45
+ return { games, logs: listed.length, lotteries, withoutTruth };
46
+ }
47
+ async function formatOf(dir, log) {
48
+ const game = await readGameRecord(dir, log.gameId);
49
+ if (game?.players.length) {
50
+ const seated = game.players.filter((p) => holdsSeat(p.state));
51
+ return { format: profileFormatOf(seated), seats: seated.length };
52
+ }
53
+ if (log.join)
54
+ return { format: log.join.flags.format, seats: log.join.flags.seats };
55
+ const seats = log.seats ? Object.keys(log.seats).length : null;
56
+ return { format: seats === 2 ? '1v1' : 'unknown', seats };
57
+ }
58
+ export function registerCalibrationTool(server, dataDir) {
59
+ server.registerTool('warapp_calibration', {
60
+ title: 'Score the income estimates against finished games',
61
+ _meta: mintMeta('lookup', ['how accurate are the income estimates', 'calibrate opponent income', 'estimate accuracy']),
62
+ description: 'Score the opponent income estimates this server planned with against the truth its finished games kept ' +
63
+ '(the decision log\'s end-of-game truth): each estimate ÷ the true income, and its signed error in armies, ' +
64
+ 'overall and by format, seats, phase (turns 1–4, 5–10, 11+), frontier coverage band, estimate source, thin ' +
65
+ 'evidence, the tracker\'s income method (rise-capped or not; logged since #569), leader vs trailer, and phase ' +
66
+ 'by coverage; the catch-up lag after a true income jump of 1.5× or more (turns until the estimate reaches two ' +
67
+ 'thirds of the truth); a consequences proxy (turns that lost a territory the plan did not concede, with an ' +
68
+ 'estimate under half the truth vs without); the largest misses; each pipeline stage\'s figure ÷ the truth ' +
69
+ '(visible, observed, tracked, prior, stated, blend, thin, known; logged since #568); and what correcting the ' +
70
+ 'tracked figure by its coverage band would have read at dampings 0 to 1 (leave one game out). `samples: true` adds the scored rows ' +
71
+ `(at most ${MAX_SAMPLES}), name-free, as a fixture set; \`harness: true\` also runs the #318 harness over the ` +
72
+ 'cached boards (tracker, fog prior and plan estimate by coverage band, and the opening benchmark), which can ' +
73
+ 'take a while on many games. Games are numbered by their place in the report, never by id, and no player is ' +
74
+ 'named. Makes no war.app request and writes nothing. Read-only.',
75
+ annotations: toolAnnotations({ title: 'Income estimate calibration', readOnly: true, destructive: false, idempotent: true, openWorld: false }),
76
+ inputSchema: z.object({
77
+ samples: z.boolean().optional().describe(`Also return the scored rows, name-free (default false; at most ${MAX_SAMPLES}).`),
78
+ harness: z.boolean().optional().describe('Also run the #318 harness over the cached boards and the opening benchmark (default false).'),
79
+ format: z.enum(['1v1', 'ffa', 'team']).optional().describe('Only games of this format.'),
80
+ }),
81
+ }, async ({ samples, harness, format }) => {
82
+ const dir = dataDir();
83
+ if (!dir)
84
+ refuse('This server has no data directory, so there is nothing to score.', 'Nothing to do here.');
85
+ const src = await calibrationGames(dir);
86
+ const games = format ? src.games.filter((g) => g.format === format) : src.games;
87
+ const report = incomeCalibration(games);
88
+ const rows = samples ? incomeSamples(games) : [];
89
+ const extra = harness ? await calibrationHarness(dir) : undefined;
90
+ return respond(undefined, ['compact'], () => ({
91
+ readAs: CALIBRATION_NOTE,
92
+ sources: {
93
+ finishedLogs: src.logs,
94
+ scoredGames: report.games,
95
+ lotteriesLeftOut: src.lotteries,
96
+ withoutTruth: src.withoutTruth,
97
+ ...(format ? { format, otherFormats: src.games.length - games.length } : {}),
98
+ },
99
+ ...(report.samples
100
+ ? { report }
101
+ : {
102
+ report: null,
103
+ empty: 'No finished game with the end-of-game truth in its decision log yet: the truth is written when a finished ' +
104
+ "game's history is read (warapp_backfill_history, warapp_my_games' sweep, warapp_get_game on it).",
105
+ }),
106
+ ...(samples ? { samples: rows.slice(0, MAX_SAMPLES), ...(rows.length > MAX_SAMPLES ? { samplesLeftOut: rows.length - MAX_SAMPLES } : {}) } : {}),
107
+ ...(extra ? { harness: { ...extra, approximations: HARNESS_APPROXIMATIONS } } : {}),
108
+ }));
109
+ });
110
+ }
@@ -21,7 +21,7 @@ import { assumedWarning, awardView, loadAward, openingThreat } from './award.js'
21
21
  import { readLedger } from '../relations-store.js';
22
22
  import { resolveIntel } from '../analysis/intel.js';
23
23
  import { allyAttackLine, attacksOnAllies, modAllianceWarnings } from './mod-alliances.js';
24
- import { avoidPlayersArg, avoidTerritoriesArg, gameIdArg, graphOf, knownIncomeArg, namer, readAnnotations, respond, untrustedDescription, untrustedText, viewArg } from './common.js';
24
+ import { avoidPlayersArg, avoidTerritoriesArg, gameIdArg, graphOf, knownIncomeArg, namer, playerNamer, readAnnotations, respond, untrustedDescription, untrustedText, viewArg } from './common.js';
25
25
  import { lookupMeta } from './hints.js';
26
26
  import { HEADROOM_COMPACT, headroomView, readTripwires, safeHeadroom, teamsOf, tripwireWarnings, untrustedDeploy } from './survival.js';
27
27
  import { loadLiveGame, standInLine, standInOf } from './live-context.js';
@@ -31,6 +31,8 @@ import { resolvePlayer, resolveTerritory } from './resolve.js';
31
31
  import { BELOW_PLAN_BASIS, boardHistory, bordersBelowPlan, currentTurn, truceRelations, friendsOf, guardOffWarnings, modsWarning, plannerSettings, requirePlayingSeat, requireTurnPhase, turnOrdersArg, } from './turn.js';
32
32
  import { resolveTeamsFor } from './team-source.js';
33
33
  import { stressOpponents } from './stress-opponents.js';
34
+ import { observedLowWarning } from '../analysis/opponents.js';
35
+ import { statedShiftWarning } from '../analysis/plan/estimates.js';
34
36
  import { sanctionPercentage } from '../analysis/cards-in-effect.js';
35
37
  import { CARD_SANCTIONS, sanctionsPlayed } from './sanctions-played.js';
36
38
  import { COMMANDER_SIZING, commanderCheckOn, defaultFoggedCount, foggedAttackersArg, foggedCommanderOn, foggedCommanderText, myLargestStack } from './commander-check.js';
@@ -488,6 +490,8 @@ export function registerCheckPlanTool(server, ctx) {
488
490
  await captureCheck(ctx, game.id, me.id, turn, checkPlanLog(report, { whatIf: enemy_deploy !== undefined || known_income !== undefined }));
489
491
  const name = namer(map);
490
492
  const playerName = new Map(game.players.map((p) => [p.id, p.name]));
493
+ /** #573: a player in a warning sentence, by name (delimited) and id, as warapp_track_opponents names it. */
494
+ const playerNamed = playerNamer(game.players);
491
495
  const who = (id) => ({ id, name: playerName.get(id) ?? String(id) });
492
496
  const bonusOf = (id) => {
493
497
  const b = map.bonuses.find((x) => x.id === id);
@@ -730,6 +734,14 @@ export function registerCheckPlanTool(server, ctx) {
730
734
  ...(modRead ? modAllianceWarnings(modRead) : []),
731
735
  // #275 (b): an untrusted estimate is the first thing said (not under an explicit enemy_deploy).
732
736
  ...(enemy_deploy === undefined ? tripwireWarnings(trip.tripwires, (w) => untrustedOf.get(w.player) ?? untrustedDeploy(w, income), (p) => estimates.find((x) => x.playerId === p)?.estimate) : []),
737
+ // #567: a known income that moved another opponent's estimate through #444's scale, by how much.
738
+ ...[statedShiftWarning(so.statedShifts, playerNamed)].filter((w) => w !== null),
739
+ // #567: an opponent tried at an income its tracker holds below what a turn surely read (not one given known_income).
740
+ ...(enemy_deploy === undefined
741
+ ? (tracks ?? [])
742
+ .filter((t) => t.observedLow && t.income !== null && !knownOf.has(t.playerId) && inView.has(t.playerId))
743
+ .map((t) => observedLowWarning(playerNamed(t.playerId), t.income, t.observedLow, t.incomeMethod))
744
+ : []),
733
745
  ...(award ? assumedWarning(award) : []),
734
746
  // #270: the static seats whose territories the test read as neutrals.
735
747
  ...[...seatTerritories(award?.board ?? seen, seats)]
@@ -834,6 +846,16 @@ export function registerCheckPlanTool(server, ctx) {
834
846
  ...(o.sanctioned?.applied && o.sanctioned.after !== undefined
835
847
  ? { sanctionApplied: { player: o.id, percentage: sanctionPercentage(o.sanctioned.percentages), before: o.sanctioned.before, after: o.sanctioned.after } }
836
848
  : {}),
849
+ // #567: the uncapped low end its tracker read above the income it holds (reported only).
850
+ ...(() => {
851
+ const t = tracks?.find((x) => x.playerId === o.id);
852
+ return t?.observedLow && enemy_deploy === undefined && !knownOf.has(o.id) ? { observedLow: t.observedLow } : {};
853
+ })(),
854
+ // #567: its estimate without the known incomes that scaled its fog prior (#444).
855
+ ...(() => {
856
+ const sh = so.statedShifts.find((x) => x.player === o.id);
857
+ return sh ? { statedScaled: { was: sh.was, by: sh.by.map((b) => b.id) } } : {};
858
+ })(),
837
859
  })),
838
860
  // Whether the replies carry the card the clock adds (default "clock").
839
861
  assumeEnemyCards: assumeCards,
@@ -15,6 +15,12 @@ export const knownIncomeArg = z
15
15
  .array(z.object({
16
16
  player: z.coerce.number().int().describe('The player\'s GameFeed id (as warapp_get_game lists it).'),
17
17
  income: z.coerce.number().int().min(0).max(10_000).describe('The income it earns per turn, card armies aside.'),
18
+ source: z
19
+ .enum(['chat', 'board'])
20
+ .optional()
21
+ .describe('Where the figure came from (#567): "board" (the default) — your own what-if or board evidence — replaces only this ' +
22
+ "player's estimate; \"chat\" — the player stated it — also scales the fog prior of the opponents who stated none, once " +
23
+ 'two or more players in view have stated one (#444). Incomes warapp_record_intel kept count as "chat".'),
18
24
  }))
19
25
  .max(50)
20
26
  .optional()
@@ -121,6 +127,14 @@ export const UNTRUSTED_PREVIEW_NOTE = `Names and chat text in this preview (in $
121
127
  * words, so delimited) and the account id the approval is bound to.
122
128
  */
123
129
  export const shownAccount = (name, id) => `${name === undefined ? 'you' : untrustedText(name)} (${id})`;
130
+ /**
131
+ * A player as a warning sentence names it (#573): its name, delimited (their own words), and its GameFeed id;
132
+ * the bare id when the game does not list the player or names it not.
133
+ */
134
+ export const playerNamer = (players) => (id) => {
135
+ const name = players.find((p) => p.id === id)?.name;
136
+ return name ? `${untrustedText(name)} (${id})` : String(id);
137
+ };
124
138
  export const untrustedDescription = (description) => `${description} ${UNTRUSTED_DESCRIPTION_SUFFIX}`;
125
139
  /** The `view` parameter over `views`, with a note naming what compact keeps. */
126
140
  export const viewArg = (views, note) => viewParam(views, { note });
@@ -23,7 +23,8 @@ import { parseFeedTime } from '../normalize.js';
23
23
  import { bonusTerritories } from '../analysis/bonuses.js';
24
24
  import { policyChecks } from '../open-games.js';
25
25
  import { nameFreeSettings } from '../replay.js';
26
- import { recordPicksAdvice, recordPicksAward, recordPicksSent, decisionLogMode, decisionLogOwner, decisionLogPath, decisionOutcome, recordGameEvent, recordJoin, recordOpponentRead, recordSeats, fillOutcome, recordChat, recordCheck, recordDecision, recordObservations, recordSubmission, } from '../decision-log.js';
26
+ import { readSeenTurn } from '../turn-orders.js';
27
+ import { recordPicksAdvice, recordPicksAward, recordPicksSent, decisionLogMode, decisionLogOwner, decisionLogPath, decisionOutcome, recordGameEvent, recordJoin, recordOpponentRead, recordSeats, fillOutcome, recordChat, recordCheck, recordDecision, recordObservations, recordSeenTurn, recordSubmission, } from '../decision-log.js';
27
28
  const modeOf = (ctx) => (ctx.decisionLog ? { mode: ctx.decisionLog } : {});
28
29
  /** Every bonus of the map with its member territories (superbonuses flattened). */
29
30
  const bonusesOf = (graph) => new Map([...graph.bonusById.keys()].map((id) => [id, bonusTerritories(graph, id)]));
@@ -76,6 +77,18 @@ export async function captureChat(ctx, gameId, me, turn, chat, opts = {}) {
76
77
  return;
77
78
  await recordChat(ctx.dataDir, gameId, me, turn, chat, { ...modeOf(ctx), ...opts });
78
79
  }
80
+ /**
81
+ * #570: keep the resolved turn's visible orders (every player's, from the LatestGameInfo's GameTurn) on that
82
+ * turn's entry — only when the GameTurn is the turn just before `turn`, the one being played. Never throws.
83
+ */
84
+ export async function captureSeenTurn(ctx, game, me, info, turn) {
85
+ if (!ctx.dataDir || turn === null)
86
+ return false;
87
+ const seen = readSeenTurn(info, game.players);
88
+ if (!seen || seen.turn !== turn - 1)
89
+ return false;
90
+ return recordSeenTurn(ctx.dataDir, game.id, me, seen, modeOf(ctx));
91
+ }
79
92
  /** Log warapp_check_plan's summary of the turn (the latest run wins). Never throws. */
80
93
  export async function captureCheck(ctx, gameId, me, turn, summary) {
81
94
  if (!ctx.dataDir)
@@ -28,7 +28,7 @@ import { profileFormatOf } from '../analysis/opponent-profile.js';
28
28
  import { trackGame } from '../analysis/opponents.js';
29
29
  import { recordLessons, recordLessonsExcluded, recordMapExcluded, recordMapGame } from '../lessons-store.js';
30
30
  import { endingOf, foldGame, markHistoryFolded, profileFileState } from '../profile-store.js';
31
- import { END_STATS_VERSION, MAX_FINISHED_RECORDS, finishedPath, finishedRecordOf, markProcessed, readFinishedRecord, readFinishedState, readProcessed, storedStats, touchFinished, writeFinishedRecord, } from '../finished-store.js';
31
+ import { COLLECTOR_VERSION, END_STATS_VERSION, MAX_FINISHED_RECORDS, finishedPath, finishedRecordOf, markProcessed, readFinishedRecord, readFinishedState, readFinishedSummary, readProcessed, storedStats, touchFinished, writeFinishedRecord, } from '../finished-store.js';
32
32
  import { playerKey } from '../player-record-store.js';
33
33
  import { withPathLock } from '../path-lock.js';
34
34
  import { finalOutlookOf, readOutlookLog } from '../outlook-log.js';
@@ -145,18 +145,19 @@ export async function endOfGame(deps, gameId, me, seen, opts = {}) {
145
145
  await closeOnly();
146
146
  return { status: 'record-unreadable' };
147
147
  }
148
- if (state !== 'missing' && state.status === 'captured')
148
+ const reread = opts.reread === true;
149
+ if (state !== 'missing' && state.status === 'captured' && !reread)
149
150
  return await keptOrBackfilled(dataDir, path, salt, me, opts.history ?? seen, opts.history);
150
- if (state !== 'missing' && (!opts.retry || !opts.history))
151
+ if (state !== 'missing' && !reread && (!opts.retry || !opts.history))
151
152
  return { status: 'already-processed' };
152
153
  // The one history read: the caller's, else one request, sent once (no transport retry) and never retried.
153
154
  let game = opts.history;
154
155
  let failure;
155
156
  if (!game) {
156
- if (state === 'missing' && (await isMarked(dataDir, salt, me, gameId)))
157
+ if (state === 'missing' && !reread && (await isMarked(dataDir, salt, me, gameId)))
157
158
  return { status: 'already-processed' };
158
- // The request is spent from here on, whatever follows: never again in this process.
159
- const key = attemptKey(dataDir, me, gameId);
159
+ // The request is spent from here on, whatever follows: never again in this process (a re-read once).
160
+ const key = `${attemptKey(dataDir, me, gameId)}${reread ? '|reread' : ''}`;
160
161
  if (attempted.has(key))
161
162
  return { status: 'attempted' };
162
163
  remember(attempted, key);
@@ -192,6 +193,9 @@ export async function endOfGame(deps, gameId, me, seen, opts = {}) {
192
193
  read = game;
193
194
  const shown = game ?? seen;
194
195
  const { record, history } = await buildRecord(dataDir, salt, me, gameId, game, shown, failure);
196
+ // A re-read that failed never replaces a capture kept before it.
197
+ if (reread && state !== 'missing' && state.status === 'captured' && record.status !== 'captured')
198
+ return { status: record.status, keptPrevious: true, ...(record.failure ? { failure: record.failure } : {}) };
195
199
  kept = excludedKind(record.kinds ?? []);
196
200
  try {
197
201
  const protect = opts.protectIds ? new Set(opts.protectIds.map((id) => finishedPath(dataDir, salt, me, id))) : undefined;
@@ -537,24 +541,92 @@ export const sweepWindow = (keep = MAX_FINISHED_RECORDS) => Math.max(1, Math.flo
537
541
  * sweep processed is so never read again (P2). `window` widens (or narrows) it for warapp_backfill_history,
538
542
  * at most `keep` games.
539
543
  */
540
- export async function sweepFinished(deps, me, gameIds, { limit = END_OF_GAME_PER_CALL, keep = MAX_FINISHED_RECORDS, window: size, } = {}) {
544
+ export async function sweepFinished(deps, me, gameIds, { limit = END_OF_GAME_PER_CALL, keep = MAX_FINISHED_RECORDS, window: size, only, reread, report, } = {}) {
541
545
  // warapp_backfill_history may widen the window, never past the record bound (every game in it is protected).
542
546
  const window = gameIds.slice(0, Math.max(1, Math.min(size ?? sweepWindow(keep), keep)));
547
+ const scope = only ? gameIds.filter((id) => only.includes(id)) : window;
543
548
  // #412: with profiling off no pass runs, but these games are over: their decision logs leave `active`
544
549
  // (no request; a log already closed costs one head read).
545
550
  if (deps.dataDir && !profileEnabled(deps.env))
546
- await finishDecisionLogs(deps.dataDir, window, me, { mode: decisionLogModeOf(deps.env) });
551
+ await finishDecisionLogs(deps.dataDir, scope, me, { mode: decisionLogModeOf(deps.env) });
552
+ const before = new Map();
553
+ if (report || reread)
554
+ for (const id of scope)
555
+ before.set(id, await gameStanding(deps, me, id));
547
556
  const todo = [];
548
- for (const id of window)
557
+ for (const id of scope) {
549
558
  if (await needsEndOfGame(deps.dataDir, deps.env, id, me))
550
- todo.push(id);
559
+ todo.push({ id, reread: false });
560
+ else if (reread && rereadWanted(before.get(id), reread))
561
+ todo.push({ id, reread: true });
562
+ }
551
563
  await refreshProcessed(deps, me, window).catch(() => undefined);
552
564
  const processed = [];
553
- for (const id of todo.slice(0, limit)) {
554
- const r = await endOfGame(deps, id, me, undefined, { fold: true, keep, protectIds: window });
555
- processed.push({ gameId: id, status: r.status, ...(r.turns !== undefined ? { turns: r.turns } : {}) });
565
+ const protectIds = only ? [...new Set([...window, ...scope])] : window;
566
+ for (const t of todo.slice(0, limit)) {
567
+ const r = await endOfGame(deps, t.id, me, undefined, { fold: true, keep, protectIds, ...(t.reread ? { reread: true } : {}) });
568
+ processed.push({
569
+ gameId: t.id,
570
+ status: r.status,
571
+ ...(t.reread ? { reread: true } : {}),
572
+ ...(r.turns !== undefined ? { turns: r.turns } : {}),
573
+ ...(r.failure ? { failure: failureCode(r.failure) } : {}),
574
+ ...(r.keptPrevious ? { keptPrevious: true } : {}),
575
+ });
576
+ }
577
+ const out = { processed, pending: Math.max(0, todo.length - limit) };
578
+ if (report) {
579
+ const thisCall = new Map(processed.map((p) => [p.gameId, p]));
580
+ const waiting = new Set(todo.slice(limit).map((t) => t.id));
581
+ const games = [];
582
+ for (const id of scope) {
583
+ const now = thisCall.has(id) ? await gameStanding(deps, me, id) : before.get(id);
584
+ const p = thisCall.get(id);
585
+ games.push({
586
+ gameId: id,
587
+ ...now,
588
+ ...(p ? { thisCall: p.reread ? 'reread' : 'read' } : waiting.has(id) ? { thisCall: 'waiting' } : {}),
589
+ });
590
+ }
591
+ out.games = games;
592
+ }
593
+ return out;
594
+ }
595
+ /** One game's standing from this server's state alone (no request). Never throws. */
596
+ export async function gameStanding(deps, me, gameId) {
597
+ const { dataDir, env } = deps;
598
+ if (!dataDir || !profileEnabled(env))
599
+ return { state: 'unknown' };
600
+ try {
601
+ const salt = await playerRecordSalt(dataDir);
602
+ if (!salt)
603
+ return { state: 'not-processed' };
604
+ const summary = await readFinishedSummary(finishedPath(dataDir, salt, me, gameId));
605
+ if (summary === 'unreadable')
606
+ return { state: 'record-unreadable' };
607
+ if (summary !== 'missing')
608
+ return { state: 'recorded', outdated: summary.collector < COLLECTOR_VERSION, ...summary };
609
+ return (await isMarked(dataDir, salt, me, gameId)) ? { state: 'processed-record-pruned' } : { state: 'not-processed' };
556
610
  }
557
- return { processed, pending: Math.max(0, todo.length - limit) };
611
+ catch {
612
+ return { state: 'unknown' };
613
+ }
614
+ }
615
+ /** Whether `reread` names a game in this standing. */
616
+ function rereadWanted(s, scope) {
617
+ if (s.state === 'processed-record-pruned')
618
+ return scope === 'all';
619
+ if (s.state !== 'recorded')
620
+ return false;
621
+ if (scope === 'all')
622
+ return true;
623
+ if (scope === 'failed')
624
+ return s.status !== 'captured';
625
+ return s.outdated;
626
+ }
627
+ /** A failure as the sweep reports it: codes only. */
628
+ function failureCode(f) {
629
+ return { reason: f.reason, ...('kind' in f && f.kind ? { kind: f.kind } : {}) };
558
630
  }
559
631
  /** Mark the window's records most recently used, so a prune drops a record outside the window first. */
560
632
  async function refreshProcessed(deps, me, window) {