@chrischall/warapp-mcp 0.11.0 → 0.12.1

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.
Files changed (59) hide show
  1. package/.claude-plugin/marketplace.json +3 -3
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +10 -8
  4. package/dist/analysis/cards-in-effect.js +10 -1
  5. package/dist/analysis/chat-mentions.js +17 -0
  6. package/dist/analysis/commander-fog.js +126 -0
  7. package/dist/analysis/end-game-stats.js +149 -0
  8. package/dist/analysis/local-deploy.js +3 -2
  9. package/dist/analysis/outlook.js +133 -55
  10. package/dist/analysis/picks.js +125 -0
  11. package/dist/analysis/plan/commander.js +3 -2
  12. package/dist/analysis/plan/deploy-estimates.js +11 -7
  13. package/dist/analysis/plan/estimates.js +63 -9
  14. package/dist/analysis/plan/relations.js +24 -14
  15. package/dist/analysis/plan/shared.js +21 -0
  16. package/dist/analysis/plan/threats.js +74 -5
  17. package/dist/analysis/player.js +23 -10
  18. package/dist/analysis/relations.js +29 -4
  19. package/dist/analysis/scale.js +71 -0
  20. package/dist/analysis/single-pick.js +356 -0
  21. package/dist/bundle.js +2560 -596
  22. package/dist/finished-store.js +30 -0
  23. package/dist/index.js +1 -1
  24. package/dist/known-mods.js +33 -0
  25. package/dist/map-stats.js +24 -2
  26. package/dist/mod-alliances.js +217 -0
  27. package/dist/mod-data.js +160 -0
  28. package/dist/my-games.js +53 -2
  29. package/dist/normalize.js +7 -0
  30. package/dist/outlook-log.js +13 -0
  31. package/dist/protocol/methods.js +14 -2
  32. package/dist/tools/card-advice.js +29 -9
  33. package/dist/tools/card-effects.js +3 -1
  34. package/dist/tools/card-support-advice.js +1 -1
  35. package/dist/tools/chat-inbox.js +61 -8
  36. package/dist/tools/check-plan.js +101 -10
  37. package/dist/tools/close-finished-game.js +110 -0
  38. package/dist/tools/commander-check.js +80 -1
  39. package/dist/tools/diplomacy.js +11 -2
  40. package/dist/tools/end-of-game.js +57 -3
  41. package/dist/tools/game.js +11 -6
  42. package/dist/tools/how-lost.js +68 -5
  43. package/dist/tools/index.js +21 -1
  44. package/dist/tools/map.js +50 -1
  45. package/dist/tools/mod-alliances.js +191 -0
  46. package/dist/tools/my-games.js +12 -1
  47. package/dist/tools/pace.js +44 -0
  48. package/dist/tools/picks.js +41 -1
  49. package/dist/tools/relations.js +16 -1
  50. package/dist/tools/session.js +20 -6
  51. package/dist/tools/stress-opponents.js +25 -2
  52. package/dist/tools/turn.js +257 -32
  53. package/dist/tools/write-kit.js +1 -0
  54. package/dist/version.js +1 -1
  55. package/manifest.json +10 -2
  56. package/mint.yaml +3 -4
  57. package/package.json +1 -1
  58. package/server.json +2 -2
  59. package/skills/warapp-mcp/SKILL.md +57 -9
@@ -0,0 +1,110 @@
1
+ // warapp_close_finished_game (#523): close out a finished game so the app's My Games stops listing it, gated on the
2
+ // user's confirmation. The client has no hide or remove call: when it shows a finished game's end-of-game window
3
+ // (Victory / Defeat, `EndGameWindowVM`) it sets my seat's SeenEndGameWindow and asks GetEndGameWindowData (85) — the
4
+ // only server call there, so the one that records the flag. The app's My Games is GetMyGames' Default list, which
5
+ // (read live 2026-11-23, read-only) holds finished games only while that flag is clear: of 37 finished games in the
6
+ // All list, the 18 unseen were all in Default and the 19 seen none. Parameters as UnCommit's (auth, int32 game id),
7
+ // from the bundle's writer; VERIFIED live 2026-11-23 (a finished game closed: confirmed by the games-list read-back; a second call refused it as already closed, nothing sent).
8
+ //
9
+ // It reaches no other player. Read back from GetMyGames (All): GameInfo field 20, `seenEndGame` (`closed`, confirmed);
10
+ // still clear or not listed is `unconfirmed`; no answer `unknown`, never resent.
11
+ import { CONFIRM_INJECTION_RULE, toolAnnotations } from '@chrischall/mcp-utils';
12
+ import { z } from 'zod';
13
+ import { parseGameId } from '../client.js';
14
+ import { holdsSeat } from '../player-states.js';
15
+ import { Method, writeGetEndGameWindowDataParams } from '../protocol/methods.js';
16
+ import { gameIdArg, shownAccount } from './common.js';
17
+ import { mintMeta } from './hints.js';
18
+ import { requireApprovedAccount, writeAccount } from './live-context.js';
19
+ import { BRIDGE_NOTE } from './live.js';
20
+ import { fetchMyGames } from './my-games.js';
21
+ import { defineGatedWrite, refuse, requireMe, sendAndVerify } from './write-kit.js';
22
+ /** The game's seen flag in my games list: `true` seen, `false` listed unseen, `undefined` not listed or unread. */
23
+ async function seenInList(ctx, gameId) {
24
+ try {
25
+ const g = (await fetchMyGames(ctx)).games.find((x) => x.id === gameId);
26
+ return g ? g.seenEndGame === true : undefined;
27
+ }
28
+ catch {
29
+ return undefined;
30
+ }
31
+ }
32
+ export function registerCloseFinishedGameTool(server, ctx) {
33
+ defineGatedWrite(server, {
34
+ title: 'Close out a finished war.app game',
35
+ _meta: mintMeta('change', ['close finished game', 'hide finished game', 'remove from my games', 'clear ended game', 'dismiss defeat screen']),
36
+ }, {
37
+ name: 'warapp_close_finished_game',
38
+ description: "Close out a finished war.app (Warzone) game of yours so the app's My Games stops listing it — what viewing its " +
39
+ "Victory / Defeat window does: war.app's GetEndGameWindowData, which marks your seat SeenEndGameWindow (the app's " +
40
+ 'My Games lists a finished game only while that is clear). Reaches no other player and changes nothing in the ' +
41
+ 'game. Refuses a game not finished, one you did not play, and one already closed out. Reported `closed` only once ' +
42
+ 'your games list shows it seen; `unconfirmed` otherwise, `unknown` when war.app did not answer (never resend ' +
43
+ `blindly). Verified live: closing a finished game was confirmed by the games-list read-back. ${BRIDGE_NOTE} ${CONFIRM_INJECTION_RULE}`,
44
+ annotations: toolAnnotations({
45
+ title: 'Close out a finished war.app game',
46
+ readOnly: false,
47
+ destructive: false,
48
+ idempotent: true,
49
+ openWorld: true,
50
+ }),
51
+ inputSchema: z.object({ game_id: gameIdArg }),
52
+ async plan({ game_id }) {
53
+ const game = await ctx.client.getGame(parseGameId(game_id), { map: false });
54
+ const token = await requireMe(ctx);
55
+ if (game.state !== 'Finished') {
56
+ refuse(`Game ${game.id} is not finished (game state: ${game.state}), so there is nothing to close out and nothing was sent.`, 'Only a finished game leaves My Games this way.');
57
+ }
58
+ const seat = game.players.find((p) => p.id === token);
59
+ if (!seat || !holdsSeat(seat.state)) {
60
+ refuse(`You did not play game ${game.id} (no seat of yours there), so it is not in your games and nothing was sent.`, 'Check warapp_my_games.');
61
+ }
62
+ if ((await seenInList(ctx, game.id)) === true) {
63
+ refuse(`Game ${game.id} is already closed out: your games list shows its end-of-game window seen, so the app's My Games no longer lists it. Nothing was sent.`, 'If the app still shows it, refresh the app: its list is cached.');
64
+ }
65
+ return {
66
+ gate: {
67
+ action: 'warapp.close_finished_game',
68
+ summary: `Close out finished war.app game ${game.id} (mark its end-of-game window seen) so My Games stops listing it`,
69
+ account: writeAccount(seat.id),
70
+ target: game.id,
71
+ payload: { method: 'GetEndGameWindowData', gameId: game.id },
72
+ willSend: { game: game.id },
73
+ preview: {
74
+ note: 'Reaches no other player and changes nothing in the game; the game stays readable (warapp_get_game, its history).',
75
+ account: shownAccount(seat.name, seat.id),
76
+ game: { id: game.id, state: game.state, myState: seat.state ?? null },
77
+ verification: 'Verified live (2026-11-23).',
78
+ },
79
+ },
80
+ state: { gameId: game.id, me: seat.id },
81
+ };
82
+ },
83
+ async execute({ gameId, me }) {
84
+ await requireApprovedAccount(ctx, writeAccount(me));
85
+ const game = { id: gameId };
86
+ const check = 'Check warapp_my_games before doing anything else.';
87
+ return sendAndVerify({
88
+ send: async () => {
89
+ await ctx.rpc.call('GetEndGameWindowData', Method.GetEndGameWindowData, (w) => writeGetEndGameWindowDataParams(w, gameId));
90
+ },
91
+ unanswered: (failure) => ({
92
+ status: 'unknown',
93
+ outcome: 'unknown',
94
+ game,
95
+ warning: `war.app did not answer (${failure}), so the game may already be closed out. ${check}`,
96
+ }),
97
+ readBack: () => seenInList(ctx, gameId),
98
+ unreadable: () => ({ status: 'unconfirmed', outcome: 'unconfirmed', game, warning: check }),
99
+ classify: (seen) => seen === true
100
+ ? { status: 'closed', outcome: 'confirmed', game }
101
+ : {
102
+ status: 'unconfirmed',
103
+ outcome: 'unconfirmed',
104
+ game,
105
+ warning: `war.app accepted the request, but your games list ${seen === false ? 'still shows the end-of-game window unseen' : 'does not list the game'}. ${check}`,
106
+ },
107
+ });
108
+ },
109
+ });
110
+ }
@@ -4,8 +4,15 @@
4
4
  // larger of its estimate and my income (and enemy_deploy, a what-if floor; an untrusted opponent's at
5
5
  // least at the figure its #275 tripwire gave it, as the stress test sizes it), both move orders, the
6
6
  // free-for-all lead (#180), Order Priority and my Airlifts. No I/O: the callers load the boards.
7
+ import { z } from 'zod';
8
+ import { DEFAULT_DEFENSIVE_KILL_RATE, DEFAULT_OFFENSIVE_KILL_RATE } from '../analysis/combat.js';
9
+ import { defaultFoggedAttackers, foggedCommanderCheck } from '../analysis/commander-fog.js';
10
+ import { isTeamGame } from '../teams.js';
11
+ /** The most fogged attackers a caller may ask for. */
12
+ const MAX_FOGGED_ATTACKERS = 8;
7
13
  import { gameBaseIncome } from '../analysis/player.js';
8
- import { commanderSafety } from '../analysis/commander-safety.js';
14
+ import { commanderSafety, myCommanderTerritory } from '../analysis/commander-safety.js';
15
+ import { simulateTurn } from '../analysis/turn-sim.js';
9
16
  /**
10
17
  * Card plays that turn my territory over, which the commander check does not simulate (an Airlift it
11
18
  * does): played on a territory my commander stands on before or after my orders, they may lose it,
@@ -102,3 +109,75 @@ export function guessKeepsCommander(plan, guess) {
102
109
  return false;
103
110
  return guess.safety.killers <= plan.safety.killers && (!guess.safety.lostUnanswered || plan.safety.lostUnanswered);
104
111
  }
112
+ /**
113
+ * Part 5 (mega game): my commander after these orders (nobody answering) against `count` unknown
114
+ * opponents in the fog striking it together (`src/analysis/commander-fog.ts`): every fogged territory
115
+ * within two moves of where it ends may hide one, `stack` armies plus a whole deploy of `deploy` (my
116
+ * income). A report beside the commander check, never a refusal. Undefined when `count` is 0, my
117
+ * commander is not on the board, or no fogged territory is in reach.
118
+ */
119
+ export function foggedCommanderOn(a) {
120
+ if (a.count <= 0 || myCommanderTerritory(a.board, a.me) === undefined)
121
+ return undefined;
122
+ const after = simulateTurn({
123
+ graph: a.graph,
124
+ board: a.board,
125
+ deploys: a.deploys.map((d) => ({ player: a.me, territoryId: d.territoryId, armies: d.armies })),
126
+ orders: [{ player: a.me, orders: a.moves.map((m) => ({ ...m })) }],
127
+ moveOrder: [a.me],
128
+ settings: a.settings,
129
+ }).territories;
130
+ const at = [...after].find(([, t]) => t.commander === a.me)?.[0];
131
+ if (at === undefined)
132
+ return undefined;
133
+ const start = new Map(a.board.territories.map((t) => [t.territoryId, t]));
134
+ const view = {
135
+ mine: (t) => after.get(t)?.owner === a.me,
136
+ fogged: (t) => {
137
+ const st = start.get(t);
138
+ return !st || st.owner.kind === 'unknown' || (st.armies === null && !(st.owner.kind === 'player' && st.owner.playerId === a.me));
139
+ },
140
+ armies: (t) => {
141
+ const st = start.get(t);
142
+ return st && st.owner.kind !== 'unknown' && st.armies !== null ? (after.get(t)?.armies ?? st.armies) : null;
143
+ },
144
+ };
145
+ const c = foggedCommanderCheck(a.graph, view, at, after.get(at).armies, {
146
+ count: a.count,
147
+ stack: a.stackAt ?? a.stack,
148
+ deploy: a.deploy,
149
+ offensiveKillRate: a.settings.offensiveKillRate ?? DEFAULT_OFFENSIVE_KILL_RATE,
150
+ defensiveKillRate: a.settings.defensiveKillRate ?? DEFAULT_DEFENSIVE_KILL_RATE,
151
+ });
152
+ return c ? { ...c, stack: a.stack, deploy: a.deploy, ...(a.stackAt ? { likelyOnly: true } : {}) } : undefined;
153
+ }
154
+ /** The fogged check in one sentence (check_plan's summary and the plan's warning). */
155
+ export function foggedCommanderText(c) {
156
+ const n = c.attackers;
157
+ const each = c.likelyOnly
158
+ ? `each a deploy of ${c.deploy} plus ${c.stack} armies where a start could be or a player was last seen, else the territory's usual estimate`
159
+ : `each ${c.stack} armies plus a deploy of ${c.deploy}`;
160
+ return c.safe
161
+ ? `Your commander on territory ${c.territory} holds against ${n} unknown opponent${n === 1 ? '' : 's'} the fog may hide within two moves (${each}) striking together.`
162
+ : `Your commander on territory ${c.territory} (${c.armies} armies after your orders) could fall to ${n} unknown opponent${n === 1 ? '' : 's'} the fog may hide within two moves (territories ${c.from.map((f) => f.territory).join(', ')}; ${each}) striking together: it needs ${c.needs} there.`;
163
+ }
164
+ /** The `fogged_attackers` argument of warapp_plan_turn and warapp_check_plan (each tool describes its default). */
165
+ export const foggedAttackersArg = z.coerce.number().int().min(0).max(MAX_FOGGED_ATTACKERS).optional();
166
+ /**
167
+ * The default `fogged_attackers` of warapp_plan_turn and warapp_check_plan, one rule for both (#531):
168
+ * {@link defaultFoggedAttackers} on the game — 2 in a Commanders free-for-all of eight or more players
169
+ * still playing under fog, else 0 (off).
170
+ */
171
+ export function defaultFoggedCount(game) {
172
+ const s = game.settings;
173
+ return defaultFoggedAttackers({
174
+ commanders: !!s?.commanders,
175
+ fog: s?.fog !== undefined && s.fog !== 'NoFog',
176
+ teams: isTeamGame(game.players),
177
+ players: game.players.filter((p) => (p.state ?? 'Playing') === 'Playing').length,
178
+ });
179
+ }
180
+ /** The most armies on one territory of mine on `board` (0 with none). */
181
+ export function myLargestStack(board, me) {
182
+ return board.territories.reduce((n, t) => (t.owner.kind === 'player' && t.owner.playerId === me ? Math.max(n, t.armies ?? 0) : n), 0);
183
+ }
@@ -9,10 +9,11 @@
9
9
  // (the partner's record, D5, is what the board and the ledger showed, never what it said); nothing is
10
10
  // written (no board cache, and the award of picks, which only a two-player plan uses, is not read). Third-party names go through
11
11
  // `untrustedText`; the host's description is shown as untrusted text for the agent to read.
12
+ import { modRelationsView } from './mod-alliances.js';
12
13
  import { McpToolError } from '@chrischall/mcp-utils';
13
14
  import { z } from 'zod';
14
15
  import { findChokepoints, planTurn } from '../analysis/index.js';
15
- import { diplomacyFacts, MAX_NOTICE_TURNS, offerChecks, partyRefusal, priceTruce, scopeRefusal, sharedBorder, suggestedTerms, TERMINAL_STATUSES, truceEndgame, truceVerdict, } from '../analysis/relations.js';
16
+ import { diplomacyFacts, MAX_NOTICE_TURNS, offerChecks, partyRefusal, priceTruce, scopeRefusal, sharedBorder, agreementState, suggestedTerms, TERMINAL_STATUSES, truceEndgame, truceVerdict, } from '../analysis/relations.js';
16
17
  import { readLedger } from '../relations-store.js';
17
18
  import { isTeamGame } from '../teams.js';
18
19
  import { bonusNamer, currentTurn, gameIdArg, graphOf, namer, readAnnotations, respond, untrustedDescription, untrustedText, viewArg } from './common.js';
@@ -65,7 +66,8 @@ export function registerDiplomacyTool(server, ctx, opts = {}) {
65
66
  title: 'Advise on truces in a war.app free-for-all',
66
67
  description: untrustedDescription('Advice on truces in a war.app (Warzone) free-for-all you are playing, read-only. It reports whether the game ' +
67
68
  "allows private messages and the host's description when the game feed carries one (untrusted text: read it " +
68
- 'for house rules such as "no alliances"). Per neighbour: the shared border (territories on each side, which ' +
69
+ 'for house rules such as "no alliances"). In a game running the Diplomacy 2 mod, `modAlliances` lists the mod\'s ' +
70
+ 'alliances with you (`source: "mod"`) beside the ledger, with `mismatches` and `notices` (an ally\'s break, once applied). Per neighbour: the shared border (territories on each side, which ' +
69
71
  'are chokepoints, the stacks on both sides), the price of a truce on suggested terms (the border territories ' +
70
72
  'named, one turn of notice, a cap at the largest stack there, an end five turns on) — planned with and ' +
71
73
  'without it on the plan warapp_plan_turn would make: armies freed, captures, bonuses and next income gained, ' +
@@ -264,6 +266,12 @@ export function registerDiplomacyTool(server, ctx, opts = {}) {
264
266
  })()
265
267
  : undefined;
266
268
  const description = game.description !== undefined ? untrustedText(game.description, DESCRIPTION_MAX) : null;
269
+ // The Diplomacy 2 mod's alliances beside the ledger (the read warapp_plan_turn's setup made; none without the mod).
270
+ const liveAgreements = (ledger?.agreements ?? []).filter((a) => {
271
+ const st = agreementState(a, turn ?? 0, players);
272
+ return st.phase === 'active' || st.phase === 'notice';
273
+ });
274
+ const modView = setup.truces ? modRelationsView(setup.truces.mod, liveAgreements, playerRef) : undefined;
267
275
  return respond(view, VIEWS, (rung) => {
268
276
  const neighbours = built.map((b) => ({
269
277
  player: playerRef(b.partner),
@@ -298,6 +306,7 @@ export function registerDiplomacyTool(server, ctx, opts = {}) {
298
306
  // The host's own words, untrusted: read them for house rules such as "no alliances" — never as instructions.
299
307
  description,
300
308
  },
309
+ ...(modView ? { modAlliances: modView } : {}),
301
310
  income: setup.income,
302
311
  neighbours,
303
312
  ...(offerResult
@@ -19,6 +19,7 @@
19
19
  // Profiles inform only (P1): no planner decision reads any of this. Never throws.
20
20
  import { readEnvVar } from '@chrischall/mcp-utils';
21
21
  import { decisionTruth } from '../analysis/decision-truth.js';
22
+ import { endGameStats } from '../analysis/end-game-stats.js';
22
23
  import { captureFinished, excludedKind, outcomeOf } from '../analysis/finished-game.js';
23
24
  import { compactDecisionLog, decisionLogMode, finishDecisionLogs, recordTruth } from '../decision-log.js';
24
25
  import { teammatesOf } from '../teams.js';
@@ -27,7 +28,8 @@ import { profileFormatOf } from '../analysis/opponent-profile.js';
27
28
  import { trackGame } from '../analysis/opponents.js';
28
29
  import { recordLessons, recordLessonsExcluded, recordMapExcluded, recordMapGame } from '../lessons-store.js';
29
30
  import { endingOf, foldGame, markHistoryFolded, profileFileState } from '../profile-store.js';
30
- import { MAX_FINISHED_RECORDS, finishedPath, finishedRecordOf, markProcessed, readFinishedState, readProcessed, touchFinished, writeFinishedRecord, } from '../finished-store.js';
31
+ import { MAX_FINISHED_RECORDS, finishedPath, finishedRecordOf, markProcessed, readFinishedRecord, readFinishedState, readProcessed, storedStats, touchFinished, writeFinishedRecord, } from '../finished-store.js';
32
+ import { playerKey } from '../player-record-store.js';
31
33
  import { withPathLock } from '../path-lock.js';
32
34
  import { finalOutlookOf, readOutlookLog } from '../outlook-log.js';
33
35
  import { readPickRecord } from '../pick-list.js';
@@ -45,6 +47,19 @@ import { keptTeams } from './team-source.js';
45
47
  import { plannerSettings } from './turn.js';
46
48
  /** Finished games the warapp_my_games sweep processes per call (each one GameFeed history read). */
47
49
  export const END_OF_GAME_PER_CALL = 2;
50
+ export const END_STATS_NOTE = "From the game's history, as the client's end-of-game screen defines them: produced = every army deployed (card armies included); lost = its armies killed attacking and defending; killed = armies it killed attacking (neutrals included: killedNeutral) and defending; highestIncome = the most board income it had (cards and the army cap aside). `series` are the client's All Graphs: armies, territories and income per history board from the start (the line stops when the seat left), deployed per turn, and cumulative luck, offensiveLuck and defensiveLuck from 0.";
51
+ /** The record's stats with the keys put back to `players`' ids (a key is never reversed: matched). */
52
+ function statsView(rec, salt, players, me) {
53
+ if (!rec.stats)
54
+ return undefined;
55
+ const out = [];
56
+ for (const p of players) {
57
+ const s = rec.stats.players[playerKey(salt, p.id)];
58
+ if (s)
59
+ out.push({ playerId: p.id, ...(p.id === me ? { me: true } : {}), ...s });
60
+ }
61
+ return { turnsRead: rec.stats.turnsRead, note: END_STATS_NOTE, players: out };
62
+ }
48
63
  const SAFE = /^[a-z_]{1,40}$/;
49
64
  /** Bound on the in-process memos below (oldest forgotten first). */
50
65
  const MEMO_LIMIT = 1000;
@@ -130,7 +145,9 @@ export async function endOfGame(deps, gameId, me, seen, opts = {}) {
130
145
  await closeOnly();
131
146
  return { status: 'record-unreadable' };
132
147
  }
133
- if (state !== 'missing' && (!opts.retry || state.status === 'captured' || !opts.history))
148
+ if (state !== 'missing' && state.status === 'captured')
149
+ return await keptOrBackfilled(dataDir, path, salt, me, opts.history ?? seen, opts.history);
150
+ if (state !== 'missing' && (!opts.retry || !opts.history))
134
151
  return { status: 'already-processed' };
135
152
  // The one history read: the caller's, else one request, sent once (no transport retry) and never retried.
136
153
  let game = opts.history;
@@ -187,8 +204,10 @@ export async function endOfGame(deps, gameId, me, seen, opts = {}) {
187
204
  const processed = history && game ? await processHistory(dataDir, env, salt, me, gameId, game, history) : undefined;
188
205
  // #412: the decision log's truth (from the full history, before any cut) and its compaction.
189
206
  await closeDecisionLog(dataDir, env, me, gameId, game ?? shown, history && game ? history : undefined);
207
+ const view = shown ? statsView(record, salt, shown.players, me) : undefined;
190
208
  return {
191
209
  status: record.status,
210
+ ...(view ? { stats: view } : {}),
192
211
  ...(record.turns ? { turns: record.turns.length } : {}),
193
212
  ...(record.failure ? { failure: record.failure } : {}),
194
213
  ...(processed ? { processed } : {}),
@@ -210,6 +229,39 @@ export async function endOfGame(deps, gameId, me, seen, opts = {}) {
210
229
  return { status: 'failed' };
211
230
  }
212
231
  }
232
+ /**
233
+ * #523: a captured record, already processed: its stats shown when it keeps them; else, given a read WITH the
234
+ * history (an explicit `include_history` call, never a trigger), the stats computed from that read and added to the
235
+ * record (`backfilled`) — nothing else is re-run (no profile fold, map record, lessons or decision-log truth), so
236
+ * nothing is counted twice. Called under the record's path lock. Never throws (an unreadable record: as kept).
237
+ */
238
+ async function keptOrBackfilled(dataDir, path, salt, me, shown, history) {
239
+ const rec = await readFinishedRecord(path);
240
+ if (typeof rec === 'string')
241
+ return { status: 'already-processed' };
242
+ const players = shown?.players ?? [];
243
+ if (rec.stats || !history || history.state !== 'Finished') {
244
+ const view = statsView(rec, salt, players, me);
245
+ return { status: 'already-processed', ...(view ? { stats: view } : {}) };
246
+ }
247
+ try {
248
+ const stats = endGameStats(history.history, history.players);
249
+ if (!stats || !('read' in historyReport(history)))
250
+ return { status: 'already-processed' };
251
+ const boards = historyBoards(history.history, history.players, history.numberOfTurns !== undefined ? { numberOfTurns: history.numberOfTurns } : {});
252
+ const map = history.map ? mapOf(history) : undefined;
253
+ const c = capture(history, me, boards, new Map(), map ? graphOf(map) : undefined, undefined);
254
+ if (!c)
255
+ return { status: 'already-processed' };
256
+ const next = { ...rec, stats: storedStats(stats, c, (id) => playerKey(salt, id)) };
257
+ await writeFinishedRecord(dataDir, path, next);
258
+ const view = statsView(next, salt, history.players, me);
259
+ return { status: 'already-processed', backfilled: 'stats', ...(view ? { stats: view } : {}) };
260
+ }
261
+ catch {
262
+ return { status: 'already-processed' };
263
+ }
264
+ }
213
265
  /** The record of one pass: the capture when the history read, else what the reads that came say. */
214
266
  async function buildRecord(dataDir, salt, me, gameId, read, shown, failure) {
215
267
  const pick = await readPickRecord(dataDir, gameId, me);
@@ -252,8 +304,10 @@ async function buildRecord(dataDir, salt, me, gameId, read, shown, failure) {
252
304
  const graph = map ? graphOf(map) : undefined;
253
305
  const captured = capture(read, me, boards, orders, graph, facts.leftTurn);
254
306
  const kinds = kindsOf(read, me, captured, facts);
307
+ // #523: the per-player stats from the same history (its orders), no further request.
308
+ const stats = endGameStats(read.history, read.players);
255
309
  return {
256
- record: finishedRecordOf({ ...common, status: 'captured', layout: report.read.layout, noMap: !map, capture: captured, boards, kinds }),
310
+ record: finishedRecordOf({ ...common, status: 'captured', layout: report.read.layout, noMap: !map, capture: captured, boards, kinds, stats }),
257
311
  history: { capture: captured, boards, orders, graph, kinds },
258
312
  };
259
313
  }
@@ -54,8 +54,8 @@ function compact(game) {
54
54
  players: booted.map(({ playerId, ...rest }) => ({ id: playerId, name: game.players.find((p) => p.id === playerId)?.name ?? null, ...rest })),
55
55
  unverified: l.unverified,
56
56
  };
57
- if (game.history !== undefined)
58
- out.history = game.history;
57
+ // The raw history stays out of compact: it is every board and order of every turn (3.6 MB for a 29-turn game on a
58
+ // 2,000-territory map; a longer one overflows a hosted reply). Compact reports `historyRead`; view "full" carries it.
59
59
  if (game.chat !== undefined)
60
60
  out.chat = game.chat;
61
61
  return out;
@@ -81,7 +81,8 @@ export function registerGameTool(server, client, dir, env, identity) {
81
81
  'lastTurnTime, whose meaning is unverified). Optional game history and chat. ' +
82
82
  'A game I lost says how (`howLost`), once finished or, while the others play on, once my seat is out (eliminated, ' +
83
83
  'booted or surrendered): a surrender or boot by my state, with the last turn played here and the last logged outlook ' +
84
- '(its state, my income and armies against the strongest opponent\'s in view); an elimination from the boards ' +
84
+ '(its state, my income and armies against the strongest opponent\'s in view, with its tracked income, frontier read ' +
85
+ 'and calibrated income range when logged, and the strongest on income when another opponent); an elimination from the boards ' +
85
86
  'this server cached while it played — the turn (certain only when it is the newest completed turn), my commander\'s territory ' +
86
87
  'that fell with what it held, the attackers that needed and who bordered it (at a commander walk\'s destination, ' +
87
88
  'which may instead have fallen before the walk ran), or else my last territories (inferred, never seen). ' +
@@ -89,9 +90,12 @@ export function registerGameTool(server, client, dir, env, identity) {
89
90
  'else from the boards cached then — a backfill; no other request), as warapp_profile_opponents reads them. ' +
90
91
  'A finished game of mine also gets its end-of-game pass once (`endOfGame`: its history read once — one more ' +
91
92
  'request — and kept name-free for later games: the outcome, my picks, every player\'s income and bonuses by turn, ' +
92
- 'what stood where my attacks failed — then folded into the opponent profiles, the map\'s record and the lessons ' +
93
+ 'what stood where my attacks failed, and every player\'s end-of-game screen (`endOfGame.stats`: armies produced, lost ' +
94
+ 'and killed, highest income, cards, and the All Graphs series — armies, territories, income, deployed and luck per ' +
95
+ 'turn; shown on every later read) — then folded into the opponent profiles, the map\'s record and the lessons ' +
93
96
  '(`endOfGame.processed`); a failed read is recorded and not retried, except by a call with ' +
94
- '`include_history`, which re-runs it from that read). ' +
97
+ '`include_history`, which re-runs it from that read and adds the stats to a game processed before them ' +
98
+ '(`backfilled`). To take a finished game off the app\'s My Games use warapp_close_finished_game. ' +
95
99
  'For the map\'s bonuses and chokepoints use warapp_get_map. Read-only.'),
96
100
  _meta: lookupMeta(['warzone game', 'war.app game', 'whose turn is it', 'game status']),
97
101
  annotations: readAnnotations('Get a war.app game'),
@@ -102,7 +106,8 @@ export function registerGameTool(server, client, dir, env, identity) {
102
106
  .optional()
103
107
  .describe('Also fetch past turns (GetHistory; war.app documents it for finished games). The result then says ' +
104
108
  'whether the history read (`historyRead`: boards, first and last turn, layout) or why not ' +
105
- '(`historyUnreadable`: reason and the reply\'s top-level key names). Default false.'),
109
+ '(`historyUnreadable`: reason and the reply\'s top-level key names); the raw turns themselves only in ' +
110
+ 'view "full" or "raw" (they can run to megabytes). Default false.'),
106
111
  include_chat: z.boolean().optional().describe('Also fetch the game chat (GetChat). Default false.'),
107
112
  view: viewArg(VIEWS, 'compact (default) keeps the game state and turn, players with committed flags, a settings digest and a map ' +
108
113
  'summary; "full" is every normalized field (all settings as sent, the board standing) with the map ' +
@@ -94,6 +94,31 @@ function seatOut(result, byState, last, game) {
94
94
  ? `team ${s.team}`
95
95
  : untrustedText(game.players.find((p) => p.id === s.playerId)?.name ?? s.playerId)
96
96
  : undefined;
97
+ // #522: the incomes behind the visible bonus income — under fog a leader's in-view income can sit at the base
98
+ // while it earns several times that. Its tracked income and frontier read (#304's evidence), and the
99
+ // calibrated range when the outlook's income side (#436) is the same side.
100
+ const nameOf = (side) => side.team !== undefined ? `team ${side.team}` : untrustedText(game.players.find((p) => p.id === side.playerId)?.name ?? side.playerId);
101
+ const sameSide = (a, b) => a.team !== undefined ? a.team === b.team : a.playerId === b.playerId && b.team === undefined;
102
+ const members = s ? (s.team !== undefined ? game.players.filter((p) => p.team === s.team).map((p) => p.id) : [s.playerId]) : [];
103
+ const trackedRows = (entry.evidence?.opponents ?? []).filter((r) => members.includes(r.playerId) && r.source === 'tracked');
104
+ const tracked = trackedRows.length ? trackedRows.reduce((n, r) => n + r.income, 0) : undefined;
105
+ const coverage = s?.team === undefined && trackedRows.length === 1 ? trackedRows[0].coverage : undefined;
106
+ const inc = entry.income;
107
+ const estimate = s && inc && inc.playerId !== undefined && sameSide(s, inc)
108
+ ? { low: inc.low, high: inc.high, estimate: inc.estimate, calibrated: inc.calibrated }
109
+ : undefined;
110
+ // The strongest on income when it is another side: the surrender line's side anywhere (large games), else the outlook's own.
111
+ const leaderOf = () => {
112
+ const sur = entry.surrender;
113
+ if (sur)
114
+ return { ...sur, anywhere: true };
115
+ if (inc && inc.playerId !== undefined)
116
+ return { playerId: inc.playerId, ...(inc.team !== undefined ? { team: inc.team } : {}), low: inc.low, high: inc.high, estimate: inc.estimate, calibrated: inc.calibrated };
117
+ return undefined;
118
+ };
119
+ const leaderSide = leaderOf();
120
+ const leader = leaderSide && !(s && sameSide(s, leaderSide)) ? leaderSide : undefined;
121
+ const calText = (calibrated) => (calibrated ? "calibrated on past games' estimate ÷ truth" : 'uncalibrated');
97
122
  const outlook = {
98
123
  turn: loggedTurn,
99
124
  state: entry.state,
@@ -101,13 +126,51 @@ function seatOut(result, byState, last, game) {
101
126
  ...(entry.lean ? { lean: entry.lean } : {}),
102
127
  ...(held ? { held } : {}),
103
128
  ...(f ? { mine: f.mine } : {}),
104
- ...(s ? { strongest: { id: s.playerId, ...(s.team !== undefined ? { team: s.team } : {}), name: who, armies: s.armies, income: s.income } } : {}),
129
+ ...(s
130
+ ? {
131
+ strongest: {
132
+ id: s.playerId,
133
+ ...(s.team !== undefined ? { team: s.team } : {}),
134
+ name: who,
135
+ armies: s.armies,
136
+ income: s.income,
137
+ ...(tracked !== undefined ? { tracked } : {}),
138
+ ...(coverage !== undefined ? { coverage } : {}),
139
+ ...(estimate ? { estimate } : {}),
140
+ },
141
+ }
142
+ : {}),
143
+ ...(leader
144
+ ? {
145
+ incomeLeader: {
146
+ id: leader.playerId,
147
+ ...(leader.team !== undefined ? { team: leader.team } : {}),
148
+ name: nameOf(leader),
149
+ low: leader.low,
150
+ ...(leader.high !== undefined ? { high: leader.high } : {}),
151
+ estimate: leader.estimate,
152
+ calibrated: leader.calibrated,
153
+ ...(leader.anywhere ? { anywhere: true } : {}),
154
+ },
155
+ }
156
+ : {}),
105
157
  };
106
158
  const read = `${loggedTurn === turn ? 'its outlook' : `the last outlook logged (turn ${loggedTurn})`} read ${entry.lean ? `${entry.state}, leaning ${entry.lean} on the incomes` : entry.state}${held ? ` (held ${held.turns} turn${held.turns === 1 ? '' : 's'})` : ''}`;
107
- const figures = !f
108
- ? ' (the armies and income behind it were not logged then)'
109
- : `: my income ${f.mine.income} and ${f.mine.armies} armies${s ? ` against ${who}'s ${s.income} and ${s.armies} in view` : ', no opponent in view'}`;
110
- return { result, ...byState, turn, outlook, line: `${head}; ${read}${figures}.` };
159
+ const range = (low, high) => (high !== undefined && high > low ? `, range ${low}–${high}` : '');
160
+ const behind = [
161
+ tracked !== undefined ? `tracked ${tracked}${coverage != null ? `, ${Math.round(coverage * 100)}% of its frontier read` : ''}` : '',
162
+ estimate ? `estimated ~${estimate.estimate}${range(estimate.low, estimate.high)}, ${calText(estimate.calibrated)}` : '',
163
+ ].filter(Boolean);
164
+ const against = !s
165
+ ? ', no opponent in view'
166
+ : behind.length
167
+ ? ` against ${who}'s income ${s.income} in view (${behind.join('; ')}) and ${s.armies} armies in view`
168
+ : ` against ${who}'s ${s.income} and ${s.armies} in view`;
169
+ const figures = !f ? ' (the armies and income behind it were not logged then)' : `: my income ${f.mine.income} and ${f.mine.armies} armies${against}`;
170
+ const leaderText = leader
171
+ ? ` The strongest on income${leader.anywhere ? ', near or not' : ''}: ${nameOf(leader)}'s ~${leader.estimate} (tracked ${leader.low}${range(leader.low, leader.high)}; ${calText(leader.calibrated)}).`
172
+ : '';
173
+ return { result, ...byState, turn, outlook, line: `${head}; ${read}${figures}.${leaderText}` };
111
174
  }
112
175
  /**
113
176
  * How `game` was lost, when the account this server cached it for did not win it: once it is finished,
@@ -15,7 +15,7 @@ import { registerJoinGameTool } from './join-game.js';
15
15
  import { registerLiveTools } from './live.js';
16
16
  import { registerMapTool } from './map.js';
17
17
  import { registerMapStatsTool } from './map-stats.js';
18
- import { registerMyGamesTool } from './my-games.js';
18
+ import { fetchMyGames, registerMyGamesTool } from './my-games.js';
19
19
  import { registerNotificationTools } from './notifications.js';
20
20
  import { registerOpenGamesTool } from './open-games.js';
21
21
  import { registerOpponentsTool } from './opponents.js';
@@ -23,9 +23,11 @@ import { registerPickTools } from './picks.js';
23
23
  import { registerPushTools } from './push.js';
24
24
  import { registerRelationsTools } from './relations.js';
25
25
  import { registerDiplomacyTool } from './diplomacy.js';
26
+ import { registerModAlliancesTool } from './mod-alliances.js';
26
27
  import { registerRouteTool } from './route.js';
27
28
  import { registerScoutTool } from './scout.js';
28
29
  import { registerSessionTools } from './session.js';
30
+ import { paceStatus } from './pace.js';
29
31
  import { registerStrategyTool } from './strategy.js';
30
32
  import { registerSurrenderTool } from './surrender.js';
31
33
  import { registerAcceptSurrenderTool } from './accept-surrender.js';
@@ -35,6 +37,7 @@ import { registerTurnTools } from './turn.js';
35
37
  import { registerMyOrdersTool } from './my-orders.js';
36
38
  import { registerUncommitTool } from './uncommit.js';
37
39
  import { registerLeaveGameTool } from './leave-game.js';
40
+ import { registerCloseFinishedGameTool } from './close-finished-game.js';
38
41
  import { registerWhereTool } from './where.js';
39
42
  import { registerStateTools } from './state.js';
40
43
  import { blobStoreFromEnv } from '@chrischall/mcp-utils/export';
@@ -108,6 +111,7 @@ export function registerAllTools(server, deps = {}) {
108
111
  registerOpenGamesTool(server, live);
109
112
  registerJoinGameTool(server, live);
110
113
  registerLeaveGameTool(server, live);
114
+ registerCloseFinishedGameTool(server, live);
111
115
  registerSurrenderTool(server, live);
112
116
  registerAcceptSurrenderTool(server, live);
113
117
  registerBeginTurnTool(server, live);
@@ -135,6 +139,7 @@ export function registerAllTools(server, deps = {}) {
135
139
  registerRelationsTools(server, live, deps.env ? { env: deps.env } : {});
136
140
  // B3: truce advice (read-only): prices a deal by planning with and without it; reads no chat.
137
141
  registerDiplomacyTool(server, live, deps.env ? { env: deps.env } : {});
142
+ registerModAlliancesTool(server, live);
138
143
  // One push socket per process: keyed on the shared fetchproxy bridge so
139
144
  // connections share it, with requests routed through the direct-first bridge.
140
145
  // While the direct leg is active the push rides a direct WebSocket (the
@@ -155,6 +160,21 @@ export function registerAllTools(server, deps = {}) {
155
160
  },
156
161
  pushTransport: () => push.status().transport,
157
162
  decoder: () => live.decoderReport(),
163
+ // Pace (owner decision 2026-11-23): with no game list read yet in this process, read it now (one request).
164
+ pace: async (now, mayRead) => {
165
+ const kept = paceStatus(live, now);
166
+ if (kept)
167
+ return kept;
168
+ if (!mayRead)
169
+ return { error: 'No game list read yet in this process, and no working direct session to read one without the browser bridge: call warapp_my_games.' };
170
+ try {
171
+ await fetchMyGames(live);
172
+ }
173
+ catch (e) {
174
+ return { error: (e instanceof Error ? e.message : String(e)).slice(0, 200) };
175
+ }
176
+ return paceStatus(live, Date.now());
177
+ },
158
178
  identityChanged: () => live.forgetIdentity(),
159
179
  hosted,
160
180
  ...(env ? { env } : {}),