@chrischall/warapp-mcp 0.6.0 → 0.7.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.
Files changed (90) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +99 -6
  4. package/dist/analysis/accept-surrender.js +20 -2
  5. package/dist/analysis/calibrate.js +1 -0
  6. package/dist/analysis/card-support.js +175 -16
  7. package/dist/analysis/card-threats.js +68 -3
  8. package/dist/analysis/chat-advice.js +182 -0
  9. package/dist/analysis/chat-blocks.js +106 -0
  10. package/dist/analysis/chat-intent.js +559 -0
  11. package/dist/analysis/chat-read.js +159 -0
  12. package/dist/analysis/decision-replay.js +279 -0
  13. package/dist/analysis/decision-truth.js +146 -0
  14. package/dist/analysis/finished-game.js +62 -3
  15. package/dist/analysis/game-lessons.js +12 -6
  16. package/dist/analysis/opponent-profile.js +46 -3
  17. package/dist/analysis/opponents.js +245 -19
  18. package/dist/analysis/outlook.js +323 -17
  19. package/dist/analysis/plan/after-leftover.js +4 -1
  20. package/dist/analysis/plan/captures.js +4 -3
  21. package/dist/analysis/plan/estimates.js +70 -6
  22. package/dist/analysis/plan/guard-off.js +2 -1
  23. package/dist/analysis/plan/holds.js +79 -6
  24. package/dist/analysis/plan/leftover.js +145 -5
  25. package/dist/analysis/plan/relations.js +115 -2
  26. package/dist/analysis/plan/shared.js +201 -11
  27. package/dist/analysis/plan/stand-still.js +2 -2
  28. package/dist/analysis/plan/stockpile.js +104 -0
  29. package/dist/analysis/plan/strike.js +34 -7
  30. package/dist/analysis/plan/targets.js +168 -53
  31. package/dist/analysis/plan/threats.js +108 -5
  32. package/dist/analysis/plan/transfers.js +11 -0
  33. package/dist/analysis/plan/two-move.js +70 -0
  34. package/dist/analysis/plan/vacated.js +124 -2
  35. package/dist/analysis/planner.js +302 -42
  36. package/dist/analysis/since-last.js +18 -5
  37. package/dist/board.js +36 -2
  38. package/dist/build-id.js +106 -0
  39. package/dist/bundle.js +14943 -10146
  40. package/dist/chat-automation.js +22 -0
  41. package/dist/client.js +14 -0
  42. package/dist/decision-log.js +1093 -0
  43. package/dist/finished-store.js +5 -1
  44. package/dist/lessons-store.js +322 -21
  45. package/dist/open-games.js +36 -16
  46. package/dist/outlook-log.js +42 -1
  47. package/dist/protocol/methods.js +4 -2
  48. package/dist/review-export.js +198 -0
  49. package/dist/state-bundle.js +62 -3
  50. package/dist/state-cli.js +5 -3
  51. package/dist/strategy/notes.js +56 -0
  52. package/dist/tools/accept-surrender.js +23 -9
  53. package/dist/tools/award.js +5 -1
  54. package/dist/tools/card-advice.js +77 -23
  55. package/dist/tools/card-support-advice.js +36 -7
  56. package/dist/tools/chat-advice.js +330 -0
  57. package/dist/tools/chat-inbox.js +15 -4
  58. package/dist/tools/chat.js +41 -11
  59. package/dist/tools/check-plan.js +14 -2
  60. package/dist/tools/decision-capture.js +459 -0
  61. package/dist/tools/end-of-game.js +146 -18
  62. package/dist/tools/game-kind.js +92 -0
  63. package/dist/tools/how-lost.js +7 -2
  64. package/dist/tools/index.js +3 -0
  65. package/dist/tools/join-game.js +10 -4
  66. package/dist/tools/live-context.js +6 -0
  67. package/dist/tools/live.js +10 -1
  68. package/dist/tools/map-curves.js +73 -0
  69. package/dist/tools/notifications.js +4 -3
  70. package/dist/tools/opponents.js +2 -0
  71. package/dist/tools/past-games.js +74 -8
  72. package/dist/tools/picks.js +49 -10
  73. package/dist/tools/profile-hook.js +62 -3
  74. package/dist/tools/profile-opponents.js +2 -0
  75. package/dist/tools/push.js +2 -2
  76. package/dist/tools/relations.js +2 -0
  77. package/dist/tools/scout.js +16 -2
  78. package/dist/tools/state.js +6 -1
  79. package/dist/tools/strategy.js +3 -3
  80. package/dist/tools/stress-opponents.js +2 -0
  81. package/dist/tools/surrender-pending.js +10 -1
  82. package/dist/tools/surrender.js +18 -3
  83. package/dist/tools/turn.js +313 -18
  84. package/dist/tools/where.js +3 -1
  85. package/dist/version.js +1 -1
  86. package/manifest.json +23 -2
  87. package/mint.yaml +23 -0
  88. package/package.json +1 -1
  89. package/server.json +20 -2
  90. package/skills/warapp-mcp/SKILL.md +42 -8
@@ -8,7 +8,7 @@
8
8
  // players' names in it, read only to classify the notification and find the game its link names.
9
9
  // A game-ended notification runs the end-of-game pass on that game (#312, src/tools/end-of-game.ts:
10
10
  // idempotent, one history read per game, at most END_OF_GAME_PER_CALL per call), which folds its live
11
- // profile too; then any kept opponent profile still unfolded is folded (B2, `foldFinishedGame`) — one
11
+ // profile too; then any kept opponent profile still unfolded is folded (B2, `foldKeptProfile`: never a lottery or no-show game, #437) — one
12
12
  // GameFeed read (no map) only when one is kept unfolded, none otherwise.
13
13
  //
14
14
  // Dismissing marks read and never deletes; deleting is its own tool, one 318 per id, error 699 read as
@@ -16,8 +16,9 @@
16
16
  import { CONFIRM_INJECTION_RULE, toolAnnotations } from '@chrischall/mcp-utils';
17
17
  import { z } from 'zod';
18
18
  import { classifyNotification, readInAppNotifications } from '../notifications.js';
19
- import { foldFinishedGame, hasUnfoldedProfile, profileEnabled } from '../profile-store.js';
19
+ import { hasUnfoldedProfile, profileEnabled } from '../profile-store.js';
20
20
  import { END_OF_GAME_PER_CALL, endOfGame, finishedAccount, needsEndOfGame } from './end-of-game.js';
21
+ import { foldKeptProfile } from './profile-hook.js';
21
22
  import { Method, NOTIFICATION_ID, NOTIFICATION_NOT_FOUND, NOTIFICATIONS_PAGE_SIZE, writeAcknowledgeInAppNotificationsParams, writeDeleteInAppNotificationParams, writeGetInAppNotificationsParams, } from '../protocol/methods.js';
22
23
  import { notSent, WarappServerError } from '../protocol/rpc.js';
23
24
  import { readAnnotations, respond, untrustedDescription } from './common.js';
@@ -127,7 +128,7 @@ async function foldEndedGames(ctx, env, games) {
127
128
  lookups++;
128
129
  try {
129
130
  const game = await ctx.client.getGame(gameId, { map: false });
130
- const files = game.state === 'Finished' ? await foldFinishedGame(dir, game, env) : 0;
131
+ const files = await foldKeptProfile(dir, game, env);
131
132
  if (files > 0)
132
133
  out.push({ gameId, files });
133
134
  }
@@ -12,6 +12,7 @@ import { pastGamesFor } from './past-games.js';
12
12
  import { profileFormatOf } from '../analysis/opponent-profile.js';
13
13
  import { recordProfile } from './profile-hook.js';
14
14
  import { boardHistory, currentTurn, plannerSettings, requireTurnPhase } from './turn.js';
15
+ import { captureObservation } from './decision-capture.js';
15
16
  import { resolveTeamsFor } from './team-source.js';
16
17
  const VIEWS = ['compact', 'full'];
17
18
  export function registerOpponentsTool(server, ctx, deps = {}) {
@@ -65,6 +66,7 @@ export function registerOpponentsTool(server, ctx, deps = {}) {
65
66
  const tracks = trackOpponents(graph, boards, me.id, settings, trackGame(game.players, game.settings, map, game.endRules));
66
67
  if (ctx.dataDir && turn !== null) {
67
68
  await writeBoardCache(ctx.dataDir, game.id, me.id, turn, board);
69
+ await captureObservation(ctx, game.id, me.id, [{ turn, board, source: 'live' }]);
68
70
  await writeGameRecord(ctx.dataDir, game);
69
71
  await recordProfile(ctx.dataDir, deps.env, game, me, boards, teamsKnown);
70
72
  }
@@ -1,8 +1,28 @@
1
1
  import { PACE_TURNS, startRegion } from '../analysis/game-lessons.js';
2
- import { lessonsSummary, mapRecordStarts, mapRecordSummary, readLessons, readMapRecord } from '../lessons-store.js';
2
+ import { MIN_CALIBRATION_SAMPLES } from '../analysis/outlook.js';
3
+ import { formatPaceAt, lessonsSummary, outlookCalibration, mapPaceAt, mapRecordStarts, mapRecordSummary, readLessons, readMapRecord, readMapRecords, } from '../lessons-store.js';
3
4
  import { profileEnabled } from '../profile-store.js';
4
5
  /** The note every view carries: where it comes from, and that no plan reads it. */
5
- export const PAST_GAMES_NOTE = 'From your own finished games (their histories, read once at the end of each game): reported only — no plan, ranking or estimate reads it.';
6
+ export const PAST_GAMES_NOTE = "From your own finished games (their histories, read once at the end of each game): reported only — no plan or ranking reads it; only the past winners' income per turn tops a thinly read opponent's estimate (#419).";
7
+ /** #437: the note beside games counted apart. */
8
+ export const EXCLUDED_NOTE = 'Lottery and no-show games are counted apart: they are in no figure here.';
9
+ /** #437: the note beside a record read for the current game's format and settings. */
10
+ export const MATCHED_NOTE = "Only the games of this game's format (and Local Deployment / Commanders setting) are read: `entries` of the `of` kept matched; `settingsUnknown` of them were kept before the setting was.";
11
+ /** The `matched` and `excluded` parts a view carries (#437). */
12
+ function matchParts(s) {
13
+ return {
14
+ ...(s.matched ? { matched: { ...s.matched, note: MATCHED_NOTE } } : {}),
15
+ ...(s.excluded ? { excluded: { ...s.excluded, note: EXCLUDED_NOTE } } : {}),
16
+ };
17
+ }
18
+ /** #437: the map-record match of a game: its format, Local Deployment and Commanders. */
19
+ export function mapMatchOf(format, settings) {
20
+ return {
21
+ format,
22
+ ...(settings?.localDeployments !== undefined ? { localDeployments: settings.localDeployments } : {}),
23
+ ...(settings?.commanders !== undefined ? { commanders: settings.commanders } : {}),
24
+ };
25
+ }
6
26
  /** Start bonuses listed on the compact views. */
7
27
  export const MAP_RECORD_COMPACT = 8;
8
28
  /** The record of `mapId` when it holds a game; `unreadable` when it cannot be parsed; `undefined` otherwise (off, no data dir, no map, none kept). Never throws. */
@@ -20,11 +40,13 @@ export async function mapRecordFor(dataDir, env, mapId) {
20
40
  /**
21
41
  * The map record as warapp_plan_picks and warapp_map_stats show it: games, my results, my results per
22
42
  * bonus my start touched (`inPrimary` when the given picks touch it too), the bonuses winners started
23
- * in, and the pace (medians of the winners' and my income after turns 4 and 8). Pure.
43
+ * in, and the pace (medians of the winners' and my income after turns 4 and 8). With `match` (#437: the
44
+ * current game's format and settings) only the games that match, and `matched` says how many; `excluded`
45
+ * counts the lottery and no-show games kept apart. Pure.
24
46
  */
25
47
  export function mapRecordView(rec, o) {
26
- const { mine, winners } = mapRecordStarts(rec);
27
- const summary = mapRecordSummary(rec);
48
+ const { mine, winners } = mapRecordStarts(rec, o.match);
49
+ const summary = mapRecordSummary(rec, o.match);
28
50
  const primary = o.graph && o.picks ? new Set(startRegion(o.graph, o.picks).bonuses) : undefined;
29
51
  const cap = (xs) => (o.full ? xs : xs.slice(0, MAP_RECORD_COMPACT));
30
52
  return {
@@ -37,18 +59,20 @@ export function mapRecordView(rec, o) {
37
59
  { winners: t === 4 ? summary.pace.winners.income4 : summary.pace.winners.income8, mine: t === 4 ? summary.pace.mine.income4 : summary.pace.mine.income8 },
38
60
  ])),
39
61
  ...(!o.full && (mine.length > MAP_RECORD_COMPACT || winners.length > MAP_RECORD_COMPACT) ? { more: 'view "full" lists every start bonus' } : {}),
62
+ ...matchParts(summary),
40
63
  note: PAST_GAMES_NOTE,
41
64
  };
42
65
  }
43
66
  /**
44
67
  * The pace beside my income on the boards after turns 4 and 8 (warapp_plan_turn): with `turnsCompleted`
45
68
  * one of {@link PACE_TURNS} and a record with a figure for it, my income now beside the median winner's
46
- * and my own past median there; `undefined` otherwise. Pure.
69
+ * and my own past median there; `undefined` otherwise. With `match` (#437) only the games of the current
70
+ * game's format and settings. Pure.
47
71
  */
48
- export function paceView(rec, turnsCompleted, myIncome) {
72
+ export function paceView(rec, turnsCompleted, myIncome, match) {
49
73
  if (turnsCompleted === null || !PACE_TURNS.includes(turnsCompleted))
50
74
  return undefined;
51
- const s = mapRecordSummary(rec);
75
+ const s = mapRecordSummary(rec, match);
52
76
  const four = turnsCompleted === 4;
53
77
  const winners = four ? s.pace.winners.income4 : s.pace.winners.income8;
54
78
  const myPast = four ? s.pace.mine.income4 : s.pace.mine.income8;
@@ -61,6 +85,7 @@ export function paceView(rec, turnsCompleted, myIncome) {
61
85
  myPast,
62
86
  games: s.games,
63
87
  ...(winners !== null ? { behindWinners: myIncome < winners } : {}),
88
+ ...matchParts(s),
64
89
  note: PAST_GAMES_NOTE,
65
90
  };
66
91
  }
@@ -83,6 +108,7 @@ export async function pastGamesFor(dataDir, env, format) {
83
108
  return {
84
109
  thisFormat: format,
85
110
  ...s,
111
+ ...(s.excluded ? { excluded: { ...s.excluded, note: EXCLUDED_NOTE } } : {}),
86
112
  readAs: 'calibration: per coverage band (the share of its frontier the track read, #294), n turns × opponents scored, the mean and geometric mean of ' +
87
113
  'the tracked income ÷ the true income from the history, and the shares read under half (low) and over 1.5× (high).',
88
114
  note: PAST_GAMES_NOTE,
@@ -92,3 +118,43 @@ export async function pastGamesFor(dataDir, env, format) {
92
118
  return undefined;
93
119
  }
94
120
  }
121
+ /**
122
+ * #419 (owner decision of 2026-11-20): the pace past winners set after `afterTurn` completed turns (the turn
123
+ * planned − 1), the fog prior's upper bound under thin evidence: this map's median winner over its games `match`
124
+ * reads when there are `MIN_PACE_GAMES` (3) or more (`map`), else the median winner ÷ mine over every map's
125
+ * games of the format (`format`), else `undefined` — as with profiling off, no data dir, map or turn. Never throws.
126
+ */
127
+ export async function fogPaceFor(dataDir, env, mapId, match, afterTurn) {
128
+ if (!dataDir || mapId === undefined || afterTurn === null || afterTurn < 0 || !profileEnabled(env ?? process.env))
129
+ return undefined;
130
+ try {
131
+ const rec = await readMapRecord(dataDir, mapId);
132
+ const own = rec === 'unreadable' ? null : mapPaceAt(rec, afterTurn, match);
133
+ if (own)
134
+ return { basis: 'map', afterTurn, games: own.games, income: own.income };
135
+ const fmt = formatPaceAt(await readMapRecords(dataDir), afterTurn, match);
136
+ return fmt ? { basis: 'format', afterTurn, games: fmt.games, ratio: fmt.ratio } : undefined;
137
+ }
138
+ catch {
139
+ return undefined;
140
+ }
141
+ }
142
+ /**
143
+ * #436 (owner decision of 2026-11-20): the outlook's calibration — past games' tracked income ÷ true income per
144
+ * coverage band, this format's band with `MIN_CALIBRATION_SAMPLES` or more, else every format's
145
+ * (`outlookCalibration`); `undefined` when off, without a data dir, unreadable or with no band. Never throws.
146
+ */
147
+ export async function outlookCalibrationFor(dataDir, env, format) {
148
+ if (!dataDir || !profileEnabled(env ?? process.env))
149
+ return undefined;
150
+ try {
151
+ const file = await readLessons(dataDir);
152
+ if (file === 'unreadable')
153
+ return undefined;
154
+ const c = outlookCalibration(file, format, MIN_CALIBRATION_SAMPLES);
155
+ return Object.keys(c).length ? c : undefined;
156
+ }
157
+ catch {
158
+ return undefined;
159
+ }
160
+ }
@@ -4,7 +4,7 @@
4
4
  import { McpToolError } from '@chrischall/mcp-utils';
5
5
  import { z } from 'zod';
6
6
  import { clientPickLimits, planPicks } from '../analysis/picks.js';
7
- import { DEFAULT_TERRITORY_LIMIT } from '../analysis/opponents.js';
7
+ import { DEFAULT_TERRITORY_LIMIT, fullDistribution } from '../analysis/opponents.js';
8
8
  import { OWNER_PICKABLE } from '../live.js';
9
9
  import { bonusNamer, gameIdArg, graphOf, namer, readAnnotations, respond, untrustedDescription, untrustedText, viewArg } from './common.js';
10
10
  import { lookupMeta } from './hints.js';
@@ -15,14 +15,37 @@ import { teammateOrdersOf } from '../team-orders.js';
15
15
  import { readTeammatePicks } from './team.js';
16
16
  import { pickingNeutrals } from '../pick-list.js';
17
17
  import { mapOf } from './map.js';
18
- import { mapRecordFor, mapRecordView } from './past-games.js';
18
+ import { profileFormatOf } from '../analysis/opponent-profile.js';
19
+ import { mapMatchOf, mapRecordFor, mapRecordView } from './past-games.js';
19
20
  import { keepPickable } from './where.js';
20
21
  import { resolveTeams } from './team-source.js';
22
+ import { capturePicksAdvice, picksAdviceLog } from './decision-capture.js';
21
23
  const VIEWS = ['compact', 'full'];
22
24
  /** The only GameFeed state in which territories are picked. */
23
25
  export const PICK_PHASE_STATE = 'DistributingTerritories';
24
26
  /** TerritoryLimit assumed when the settings do not say (war.app's usual default; shared with the outlook). */
25
27
  export { DEFAULT_TERRITORY_LIMIT };
28
+ /**
29
+ * The territories each player is granted, as the pick advisor plans them (#428): the settings'
30
+ * TerritoryLimit when set; under full distribution (DistributionMode 0 with no limit) every territory is
31
+ * dealt, so the client's no-cap share — floor(pickable ÷ players), at least 1 — the picks only choosing
32
+ * which ones; otherwise (a limited start that does not say) {@link DEFAULT_TERRITORY_LIMIT}. `warning`
33
+ * says which assumption it made.
34
+ */
35
+ export function pickTerritoryLimit(settings, players, pickable) {
36
+ const set = settings?.territoryLimit;
37
+ if (set !== undefined && set > 0)
38
+ return { limit: set };
39
+ if (fullDistribution(settings)) {
40
+ const n = Math.max(1, players);
41
+ const limit = Math.max(1, Math.floor(pickable / n));
42
+ return {
43
+ limit,
44
+ warning: `Full distribution (DistributionMode 0, no territory limit): every territory is dealt, so each of the ${n} players gets about ${limit} of the ${pickable} pickable; the list only says which you would rather hold.`,
45
+ };
46
+ }
47
+ return { limit: DEFAULT_TERRITORY_LIMIT, warning: `Territory limit missing from settings; assumed ${DEFAULT_TERRITORY_LIMIT}.` };
48
+ }
26
49
  /** The pick scorer's view of the game settings. */
27
50
  export function pickSettings(s) {
28
51
  if (!s)
@@ -146,16 +169,16 @@ export function registerPickTools(server, ctx, deps = {}) {
146
169
  const { game, source: teamSource } = await resolveTeams(ctx, feed);
147
170
  const map = mapOf(game);
148
171
  const warnings = [];
149
- let territoryLimit = game.settings?.territoryLimit;
150
- if (territoryLimit === undefined || territoryLimit <= 0) {
151
- territoryLimit = DEFAULT_TERRITORY_LIMIT;
152
- warnings.push(`Territory limit missing from settings; assumed ${DEFAULT_TERRITORY_LIMIT}.`);
153
- }
172
+ const active = game.players.filter((p) => (p.state ?? 'Playing') === 'Playing').length;
173
+ const players = Math.max(2, active || game.players.length);
174
+ // #428: the limit set, else the full-distribution share, else the default (each with a warning).
175
+ const limitRead = pickTerritoryLimit(game.settings, game.players.length, pickable.length);
176
+ const territoryLimit = limitRead.limit;
177
+ if (limitRead.warning)
178
+ warnings.push(limitRead.warning);
154
179
  // The list is as long as war.app's client allows (players × territories per player, #129),
155
180
  // never shorter than the primary.
156
181
  const maxPicks = Math.max(territoryLimit, clientPickLimits({ territoryLimit, players: game.players.length, pickable: pickable.length })?.max ?? 0);
157
- const active = game.players.filter((p) => (p.state ?? 'Playing') === 'Playing').length;
158
- const players = Math.max(2, active || game.players.length);
159
182
  const settings = pickSettings(game.settings);
160
183
  // A team game (C2): only the players off my team are opponents. My seat is looked up only here.
161
184
  const team = isTeamGame(game.players) ? await teamOf(ctx, game, warnings) : undefined;
@@ -207,6 +230,15 @@ export function registerPickTools(server, ctx, deps = {}) {
207
230
  const alt = plan.alternative;
208
231
  // #312 E3: what my finished games on this map say (reported only: the ranking above never reads it).
209
232
  const record = await mapRecordFor(ctx.dataDir, deps.env, game.settings?.mapId);
233
+ // #437 task 3: the advice into the game's decision log (ids, scores and codes; a re-plan replaces it).
234
+ await capturePicksAdvice(ctx, game, picksAdviceLog(plan, {
235
+ players,
236
+ territoryLimit,
237
+ maxPicks,
238
+ spread: spread === true,
239
+ warnings,
240
+ ...(team ? { team: { teammates: team.map((p) => p.id), listsRead: mateLists.filter((l) => l !== null).length, mirrored: !!coord?.mirrored } } : {}),
241
+ }));
210
242
  return respond(view, VIEWS, (rung) => ({
211
243
  game: { id: game.id, name: game.name ?? null, state: game.state },
212
244
  players,
@@ -308,7 +340,14 @@ export function registerPickTools(server, ctx, deps = {}) {
308
340
  ? {
309
341
  mapRecord: record === 'unreadable'
310
342
  ? record
311
- : mapRecordView(record, { bonusName, full: rung === 'full', graph: graphOf(map), picks: plan.groups.primary.territoryIds }),
343
+ : mapRecordView(record, {
344
+ bonusName,
345
+ full: rung === 'full',
346
+ graph: graphOf(map),
347
+ picks: plan.groups.primary.territoryIds,
348
+ // #437: only the games of this game's format and settings.
349
+ match: mapMatchOf(profileFormatOf(game.players), game.settings),
350
+ }),
312
351
  }
313
352
  : {}),
314
353
  ...(rung === 'full' ? { settings } : {}),
@@ -3,10 +3,12 @@
3
3
  // turns its boards show are observed and kept (src/profile-store.ts). Best effort, never throws.
4
4
  // Its own module so src/tools/turn.ts can call it without importing the tool that imports turn.ts.
5
5
  import { stat, utimes } from 'node:fs/promises';
6
- import { foldFinishedGame, profileEnabled, profileFileState, profileGameFolded, profileGamePath, profileSeatsOf, readProfileTurns, recordBehaviour, } from '../profile-store.js';
6
+ import { quietNeighbour } from '../analysis/opponent-profile.js';
7
+ import { foldFinishedGame, observeBoards, profileEnabled, profileFileState, profileGameFolded, profileGamePath, profileSeatsOf, readProfileTurns, recordBehaviour, } from '../profile-store.js';
7
8
  import { teammatesOf } from '../teams.js';
8
9
  import { boardCachePath, readBoardHistory, readCachedOrders, readCachedPlayer } from '../trend.js';
9
10
  import { graphOf } from './common.js';
11
+ import { foldExclusion } from './game-kind.js';
10
12
  import { mapOf } from './map.js';
11
13
  import { keptTeams } from './team-source.js';
12
14
  /** The combat settings an observation reads, from the game's settings. */
@@ -62,13 +64,65 @@ export async function recordProfile(dataDir, env, game, me, boards, teamsKnown)
62
64
  // Best effort: profiling never blocks a tool.
63
65
  }
64
66
  }
67
+ /**
68
+ * #420 (P1 amended, owner decision of 2026-11-20): the quiet neighbours the planner may size at their
69
+ * stack plus their largest top-up (`PlanInput.quiet`). This game's kept turns (`readProfileTurns`) with
70
+ * the turns `boards` show observed afresh over them (`observeBoards`: the board just read included, so an
71
+ * attack on me last turn restores full sizing at once, before the hook keeps it), each opponent read by
72
+ * `quietNeighbour`. Nothing without a data directory, with `WARAPP_PLAYER_PROFILE=off`, or while the
73
+ * teams are unknown (any player may be my teammate). Never throws.
74
+ */
75
+ export async function quietNeighbours(a) {
76
+ if (!a.dataDir || !a.teamsKnown || !profileEnabled(a.env))
77
+ return [];
78
+ try {
79
+ const kept = await readProfileTurns(a.dataDir, a.gameId, a.me, a.env);
80
+ const fresh = observeBoards({
81
+ gameId: a.gameId,
82
+ me: a.me,
83
+ graph: a.graph,
84
+ settings: a.settings,
85
+ ...(a.cards !== undefined ? { cards: a.cards } : {}),
86
+ opponents: a.opponents,
87
+ boards: a.boards,
88
+ });
89
+ const out = [];
90
+ for (const player of [...a.opponents].sort((x, y) => x - y)) {
91
+ const byTurn = new Map((kept.get(player) ?? []).map((t) => [t.turn, t]));
92
+ for (const [turn, m] of fresh) {
93
+ const p = m.get(player);
94
+ if (p)
95
+ byTurn.set(turn, { turn, primitives: p });
96
+ }
97
+ const q = quietNeighbour([...byTurn.values()]);
98
+ if (q.quiet)
99
+ out.push({ player, contactTurns: q.contactTurns, attacks: q.attacks });
100
+ }
101
+ return out;
102
+ }
103
+ catch {
104
+ return [];
105
+ }
106
+ }
107
+ /**
108
+ * {@link foldFinishedGame} for a read that shows a game finished with no fold report (warapp_wait_for_turn's
109
+ * read, a game-ended notification): nothing for a lottery or no-show game (#437, {@link foldExclusion}).
110
+ * The files folded, as `foldFinishedGame` counts them.
111
+ */
112
+ export async function foldKeptProfile(dataDir, game, env) {
113
+ if (game.state !== 'Finished' || (await foldExclusion(dataDir, game)))
114
+ return 0;
115
+ return foldFinishedGame(dataDir, game, env);
116
+ }
65
117
  /** The note on a finished game with nothing to fold (#264). */
66
118
  export const NOTHING_TO_FOLD = 'Nothing of this game could be counted: counts start with games played on this build.';
67
119
  /** The note on a fold that failed (`failed`): the turns may well be kept, and the next read tries again. */
68
120
  export const FOLD_FAILED = "This game's turns could not be counted now (a profile store could not be read or written); the next read of the finished game tries again.";
69
121
  /** The note when there is no data directory (`no-data-dir`): nothing is kept, so nothing is counted. */
70
122
  export const NO_DATA_DIR = 'Nothing is kept without a data directory, so no game is counted.';
71
- const GAP_NOTES = { failed: FOLD_FAILED, 'no-data-dir': NO_DATA_DIR };
123
+ /** #437: the note on a lottery or no-show game (`excluded`). */
124
+ export const EXCLUDED_FOLD_NOTE = 'A lottery or no-show game teaches nothing of its players: it is counted apart, never folded.';
125
+ const GAP_NOTES = { failed: FOLD_FAILED, 'no-data-dir': NO_DATA_DIR, excluded: EXCLUDED_FOLD_NOTE };
72
126
  /** The opponents and turns the per-game file of `game` holds as `me` saw it. */
73
127
  async function foldedOpponents(dataDir, env, game, me) {
74
128
  const turns = await readProfileTurns(dataDir, game.id, me, env);
@@ -86,7 +140,9 @@ async function foldedOpponents(dataDir, env, game, me) {
86
140
  * `already-folded`). The backfilled file takes the board cache's age, so it is deleted when the board
87
141
  * cache would be (no id-bearing file outlives it). Nothing with profiling off. A fold that fails
88
142
  * (`failed`: an unreadable store, an error) and a missing data directory (`no-data-dir`) carry their
89
- * own notes; every other gap says counts start with games played on this build. Never throws.
143
+ * own notes, as does a lottery or no-show game (`excluded`, #437: {@link foldExclusion}, checked before
144
+ * any fold, so such a game is never folded whichever tool reads it first); every other gap says counts
145
+ * start with games played on this build. Never throws.
90
146
  */
91
147
  export async function foldFinished(dataDir, env, game) {
92
148
  if (!profileEnabled(env))
@@ -97,6 +153,9 @@ export async function foldFinished(dataDir, env, game) {
97
153
  try {
98
154
  if (game.state !== 'Finished')
99
155
  return nothing('not-finished');
156
+ // #437: a lottery or no-show game is counted apart by every fold, whichever tool reads it first.
157
+ if (await foldExclusion(dataDir, game))
158
+ return nothing('excluded');
100
159
  const me = await readCachedPlayer(dataDir, game.id);
101
160
  // A per-game file kept while it was played (any account of mine): the live fold.
102
161
  const live = await foldFinishedGame(dataDir, game, env);
@@ -12,6 +12,7 @@ import { foldFinished, recordProfile } from './profile-hook.js';
12
12
  import { counterOf, readOpponents } from './profile-reads.js';
13
13
  import { resolveTeamsFor } from './team-source.js';
14
14
  import { boardHistory, currentTurn, requireTurnPhase } from './turn.js';
15
+ import { captureObservation } from './decision-capture.js';
15
16
  const VIEWS = ['compact', 'full'];
16
17
  export function registerProfileOpponentsTool(server, ctx, deps = {}) {
17
18
  const env = deps.env ?? process.env;
@@ -70,6 +71,7 @@ export function registerProfileOpponentsTool(server, ctx, deps = {}) {
70
71
  const boards = turn !== null ? [...history.boards, { turn, board }] : [];
71
72
  if (ctx.dataDir && turn !== null) {
72
73
  await writeBoardCache(ctx.dataDir, game.id, me.id, turn, board);
74
+ await captureObservation(ctx, game.id, me.id, [{ turn, board, source: 'live' }]);
73
75
  await writeGameRecord(ctx.dataDir, game);
74
76
  await recordProfile(ctx.dataDir, env, game, me, boards, teamsKnown);
75
77
  }
@@ -5,7 +5,7 @@ import { callerWantsProgress, currentCallSignal, McpToolError, reportProgress }
5
5
  import { z } from 'zod';
6
6
  import { parseGameId } from '../client.js';
7
7
  import { activeGameIds } from '../my-games.js';
8
- import { foldFinishedGame } from '../profile-store.js';
8
+ import { foldKeptProfile } from './profile-hook.js';
9
9
  import { endOfGame } from './end-of-game.js';
10
10
  import { currentTurn, gameIdArg, readAnnotations, respond, untrustedDescription } from './common.js';
11
11
  import { lookupMeta, mintMeta } from './hints.js';
@@ -345,7 +345,7 @@ export function registerPushTools(server, ctx, push, deps = {}) {
345
345
  }
346
346
  // The first read that shows a game of mine finished folds its opponent profile (B2; best effort, no request).
347
347
  if (game.state === 'Finished' && ctx.dataDir)
348
- await foldFinishedGame(ctx.dataDir, game, env);
348
+ await foldKeptProfile(ctx.dataDir, game, env);
349
349
  // #312: its end-of-game pass, once (one history read; best effort, never throws).
350
350
  if (game.state === 'Finished')
351
351
  await endOfGame({ client: ctx.client, dataDir: ctx.dataDir, env }, id, token, game);
@@ -26,6 +26,7 @@ import { mapOf } from './map.js';
26
26
  import { recordProfile } from './profile-hook.js';
27
27
  import { resolveBonus, resolvePlayer, resolveTerritory } from './resolve.js';
28
28
  import { boardHistory, plannerSettings } from './turn.js';
29
+ import { captureObservation } from './decision-capture.js';
29
30
  import { resolveTeamsFor } from './team-source.js';
30
31
  const VIEWS = ['compact', 'full'];
31
32
  const MAX_SCOPE_ITEMS = 200;
@@ -373,6 +374,7 @@ export function registerRelationsTools(server, ctx, opts = {}) {
373
374
  live = true;
374
375
  if (ctx.dataDir) {
375
376
  await writeBoardCache(ctx.dataDir, game.id, me.id, turn, board);
377
+ await captureObservation(ctx, game.id, me.id, [{ turn, board, source: 'live' }]);
376
378
  await writeGameRecord(ctx.dataDir, game);
377
379
  await recordProfile(ctx.dataDir, env, game, me, boards, teamsKnown);
378
380
  }
@@ -9,6 +9,8 @@ import { gameIdArg, readAnnotations, respond, untrustedDescription } from './com
9
9
  import { lookupMeta } from './hints.js';
10
10
  import { metRead } from './profile-reads.js';
11
11
  import { resolvePlayer } from './resolve.js';
12
+ import { captureOpponentRead, turnOfGame } from './decision-capture.js';
13
+ import { decisionLogOwner, decisionLogPath } from '../decision-log.js';
12
14
  /**
13
15
  * The player's invite token (= GameFeed player id), looked up in a game or given raw, and the numeric
14
16
  * id the profile store keys it by (a raw token read as GameFeed ids are).
@@ -24,7 +26,7 @@ async function tokenOf(ctx, gameId, player) {
24
26
  }
25
27
  const game = await ctx.client.getGame(gameId, { map: false });
26
28
  const p = resolvePlayer(game.players, raw);
27
- return { token: p.feedId ?? String(p.id), id: p.id };
29
+ return { token: p.feedId ?? String(p.id), id: p.id, game };
28
30
  }
29
31
  async function page(ctx, url, what) {
30
32
  try {
@@ -60,7 +62,7 @@ export function registerScoutTool(server, ctx, opts = {}) {
60
62
  .describe('The player: a name (or part of one) in game_id, or their player id (GameFeed id / invite token).'),
61
63
  }),
62
64
  }, async ({ game_id, player }) => {
63
- const { token, id } = await tokenOf(ctx, game_id, player);
65
+ const { token, id, game } = await tokenOf(ctx, game_id, player);
64
66
  const [profileHtml, commonHtml] = await Promise.all([
65
67
  page(ctx, profileUrl(token), 'profile'),
66
68
  page(ctx, commonGamesUrl(token), 'common games'),
@@ -77,6 +79,18 @@ export function registerScoutTool(server, ctx, opts = {}) {
77
79
  const { name, ...stats } = profile;
78
80
  // Part D (docs/PLAN-PROFILES.md section 11): the cross-game read, when the record has the player.
79
81
  const met = await metRead(ctx.dataDir, env, id).catch(() => undefined);
82
+ // #437: with a game, what was read goes into its decision log (the log's own account; none: nothing kept).
83
+ if (game && ctx.dataDir) {
84
+ const owner = await decisionLogOwner(decisionLogPath(ctx.dataDir, game.id), game.id);
85
+ if (owner !== undefined && owner !== id && game.players.some((p) => p.id === owner)) {
86
+ await captureOpponentRead(ctx, game.id, owner, id, {
87
+ turn: turnOfGame(game),
88
+ level: stats.level,
89
+ ranked: stats.ranked,
90
+ bootRatePct: stats.bootRatePct,
91
+ });
92
+ }
93
+ }
80
94
  return respond(undefined, ['compact'], () => ({
81
95
  player: { id: token, name },
82
96
  profile: stats,
@@ -16,6 +16,7 @@
16
16
  // warapp_backfill_history: the warapp_my_games sweep (src/tools/end-of-game.ts) at a bigger batch —
17
17
  // up to 25 finished games not yet processed per call, each history read once, as the sweep reads it —
18
18
  // with an optional wider window. Writes only this server's state; nothing goes to war.app.
19
+ import { backfillWinnerCurves } from './map-curves.js';
19
20
  import { CONFIRM_INJECTION_RULE, McpToolError, toolAnnotations } from '@chrischall/mcp-utils';
20
21
  import { mintUploadSlot, resolveUploadSource } from '@chrischall/mcp-utils/export';
21
22
  import { z } from 'zod';
@@ -187,7 +188,8 @@ function registerBackfillTool(server, ctx, env) {
187
188
  'it) and kept name-free for the opponent profiles, map records and lessons — what warapp_my_games does two ' +
188
189
  'games per call. `window` widens how many of your newest finished games are considered (default 250, at ' +
189
190
  `most ${MAX_FINISHED_RECORDS}). Reports what it processed and how many remain; safe to call again until ` +
190
- '`remaining` is 0. Writes only this server\'s state and never writes to war.app. ' +
191
+ '`remaining` is 0. It also gives map records kept before the winners\' income curves were those curves, from the ' +
192
+ 'histories already kept (`winnerCurves`, no request). Writes only this server\'s state and never writes to war.app. ' +
191
193
  BRIDGE_NOTE,
192
194
  annotations: toolAnnotations({ title: 'Backfill finished war.app games', readOnly: false, destructive: false, idempotent: true, openWorld: true }),
193
195
  inputSchema: z.object({
@@ -215,7 +217,10 @@ function registerBackfillTool(server, ctx, env) {
215
217
  limit: limit ?? BACKFILL_DEFAULT,
216
218
  window: size,
217
219
  });
220
+ // #419: entries kept before the winners' curves were, given them from the kept histories (no request).
221
+ const winnerCurves = await backfillWinnerCurves(ctx.dataDir);
218
222
  return respond(undefined, ['compact'], () => ({
223
+ winnerCurves,
219
224
  processed: r.processed,
220
225
  processedCount: r.processed.length,
221
226
  remaining: r.pending,
@@ -12,7 +12,7 @@ import { cardClock } from '../strategy/card-clock.js';
12
12
  import { cardRules } from '../cards.js';
13
13
  import { gameIdArg, graphOf, readAnnotations, respond, untrustedDescription, viewArg, WARAPP_UNTRUSTED_NOTE } from './common.js';
14
14
  import { lookupMeta } from './hints.js';
15
- import { DEFAULT_TERRITORY_LIMIT, PICK_PHASE_STATE, pickSettings } from './picks.js';
15
+ import { PICK_PHASE_STATE, pickSettings, pickTerritoryLimit } from './picks.js';
16
16
  import { mapOf } from './map.js';
17
17
  import { currentTurn } from './turn.js';
18
18
  import { FROZEN_TAB_HINT, loadLiveGame } from './live-context.js';
@@ -57,7 +57,6 @@ const mapView = (map, n, full) => ({
57
57
  function gameMapNotes(game, map) {
58
58
  const picking = game.state === PICK_PHASE_STATE;
59
59
  const playing = game.players.filter((p) => (p.state ?? 'Playing') === 'Playing').length;
60
- const limit = game.settings?.territoryLimit;
61
60
  const board = game.standing?.territories ?? [];
62
61
  const pickable = board.filter((t) => t.owner.kind === 'available').map((t) => t.territoryId);
63
62
  const neutralArmies = new Map(board.flatMap((t) => (t.owner.kind === 'neutral' && t.armies !== null ? [[t.territoryId, t.armies]] : [])));
@@ -69,7 +68,8 @@ function gameMapNotes(game, map) {
69
68
  ? {
70
69
  opening: {
71
70
  players: Math.max(2, playing || game.players.length),
72
- territoryLimit: limit && limit > 0 ? limit : DEFAULT_TERRITORY_LIMIT,
71
+ // #428: the limit set, else the full-distribution share, else the default.
72
+ territoryLimit: pickTerritoryLimit(game.settings, game.players.length, pickable.length).limit,
73
73
  pickable,
74
74
  ...(neutralArmies.size ? { neutralArmies } : {}),
75
75
  },
@@ -50,11 +50,13 @@ export function stressOpponents(input) {
50
50
  symmetricStart: symmetricStart(game.settings),
51
51
  ...(unevenStart(game.settings) ? { unevenStart: unevenStart(game.settings) } : {}),
52
52
  ...(input.opening ? { opening: input.opening } : {}),
53
+ ...(input.mapPace ? { mapPace: input.mapPace } : {}),
53
54
  ...(game.settings?.fog !== undefined ? { fog: game.settings.fog } : {}),
54
55
  ...(opponentReinforcement(game.settings, hand) ? { reinforcement: opponentReinforcement(game.settings, hand) } : {}),
55
56
  },
56
57
  turn,
57
58
  ...(effect.sanctionsOnOthers.length ? { sanctions: effect.sanctionsOnOthers } : {}),
59
+ ...(input.known?.length && input.enemyDeploy === undefined ? { known: input.known } : {}),
58
60
  });
59
61
  const myTeam = carriesTeam(me.team) ? me.team : undefined;
60
62
  const teamOf = new Map(game.players.map((p) => [p.id, p.team]));
@@ -8,6 +8,7 @@ import { inGameOf } from '../live.js';
8
8
  import { Method, writeGameRefreshParams } from '../protocol/methods.js';
9
9
  import { pendingSurrenders, readGameDetailsSeats } from '../surrender-pending.js';
10
10
  import { untrustedText } from './common.js';
11
+ import { captureGameEvent, turnOfGame } from './decision-capture.js';
11
12
  /** Where the read comes from, for a result's note. */
12
13
  export const SURRENDER_PENDING_NOTE = "Read from the game details (the web client's GameRefresh), UNVERIFIED live: a list is what the details showed " +
13
14
  '(empty: no surrender pending); null means they could not be read, not that none is pending. A lobby, a finished ' +
@@ -62,7 +63,15 @@ export async function readPendingSurrenders(ctx, game, me, read = (id) => readDe
62
63
  if (id !== undefined)
63
64
  byInGame.set(id, p);
64
65
  }
65
- return pendingSurrenders(seats, inGameOf(me), (id) => byInGame.get(id)?.id ?? null).map((p) => {
66
+ const pending = pendingSurrenders(seats, inGameOf(me), (id) => byInGame.get(id)?.id ?? null);
67
+ // #437: each pending surrender seen goes into the decision log once (by GameFeed id; one without is not kept).
68
+ for (const p of pending) {
69
+ if (p.player === null)
70
+ continue;
71
+ const detail = p.owedByMe === true ? 'owed' : p.owedByMe === false ? 'not-owed' : 'unknown';
72
+ await captureGameEvent(ctx, game.id, me.id, { turn: turnOfGame(game), kind: 'surrender-pending', player: p.player, detail }, { create: true });
73
+ }
74
+ return pending.map((p) => {
66
75
  const player = byInGame.get(p.inGameId);
67
76
  return { ...p, name: player ? untrustedText(player.name) : null };
68
77
  });
@@ -14,6 +14,7 @@ import { gameIdArg, shownAccount, UNTRUSTED_PREVIEW_NOTE, untrustedText } from '
14
14
  import { noBrowserNote } from './session.js';
15
15
  import { mintMeta } from './hints.js';
16
16
  import { requireApprovedAccount, writeAccount } from './live-context.js';
17
+ import { captureGameEvent, mySurrenderDetail, turnOfGame } from './decision-capture.js';
17
18
  import { defineGatedWrite, mySeat, refuse, requireMe, requirePlaying, sendAndVerify, worded } from './write-kit.js';
18
19
  const PLAYING = 'Playing';
19
20
  const SURRENDERED = 'SurrenderAccepted';
@@ -126,6 +127,8 @@ export function registerSurrenderTool(server, ctx) {
126
127
  ? {
127
128
  turn: log.latest.turn,
128
129
  state: log.latest.state,
130
+ // #454: the income lean beside an even state (additive).
131
+ ...(log.latest.lean ? { lean: log.latest.lean } : {}),
129
132
  heldTurns: log.latest.heldTurns,
130
133
  basis: log.latest.basis,
131
134
  // #304: the incomes compared and each opponent's frontier read; `thin` when the state rested on little.
@@ -175,13 +178,20 @@ export function registerSurrenderTool(server, ctx) {
175
178
  untrusted: UNTRUSTED_PREVIEW_NOTE,
176
179
  },
177
180
  },
178
- state: { gameId, name, me, undo: takeBack, acceptanceNeeded: acceptance.needed },
181
+ state: {
182
+ gameId,
183
+ name,
184
+ me,
185
+ undo: takeBack,
186
+ acceptanceNeeded: acceptance.needed,
187
+ logged: { turn: turnOfGame(game), detail: (({ status: _s, ...rest }) => rest)(mySurrenderDetail('pending', log)) },
188
+ },
179
189
  };
180
190
  },
181
- async execute({ gameId, name, me, undo, acceptanceNeeded }) {
191
+ async execute({ gameId, name, me, undo, acceptanceNeeded, logged }) {
182
192
  await requireApprovedAccount(ctx, writeAccount(me));
183
193
  const game = { id: gameId, name };
184
- return sendAndVerify({
194
+ const result = await sendAndVerify({
185
195
  send: async () => {
186
196
  await ctx.rpc.call('Surrender', Method.Surrender, (w) => writeSurrenderParams(w, { gameId, surrender: !undo }));
187
197
  },
@@ -242,6 +252,11 @@ export function registerSurrenderTool(server, ctx) {
242
252
  };
243
253
  },
244
254
  });
255
+ // #437: my surrender, once war.app shows it taken (accepted, or pending the others), into the decision log.
256
+ if (!undo && logged && (result.status === 'surrendered' || result.status === 'pending')) {
257
+ await captureGameEvent(ctx, gameId, me, { turn: logged.turn, kind: 'my-surrender', detail: { status: result.status, ...logged.detail } }, { create: true });
258
+ }
259
+ return result;
245
260
  },
246
261
  });
247
262
  }