@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
@@ -1,8 +1,31 @@
1
- import { captureFinished } from '../analysis/finished-game.js';
1
+ // The end-of-game pass (#312 E1; owner decisions P2–P4 of 2026-11-16): once per finished game the
2
+ // account played, read the game's history ONCE (GameFeed GetHistory with its settings and GetMap=false:
3
+ // a cached map is attached by its id, and the client's refresh of a map that lacks land never runs, and
4
+ // with `noRetry` the client does not re-send it on a 429 or 5xx, so the history is never read twice; with no map cached, one map-only read without the history follows),
5
+ // capture what it teaches (src/analysis/finished-game.ts) and keep it name-free (src/finished-store.ts).
6
+ // The record is the "processed" mark, and a separate bounded list of hashed keys (`markProcessed`, ten
7
+ // times the record bound) outlives its prune: a game with either is never read again by a trigger,
8
+ // whatever its status — a failed read is recorded and NOT retried automatically; an explicit
9
+ // warapp_get_game with `include_history` re-runs a failed pass from the history that call already read
10
+ // (no further request); a pass from a caller's history leaves the lasting mark too. A reply showing the game still in play leaves no lasting mark (it may end later).
11
+ //
12
+ // Triggers: any read that shows the game finished (warapp_get_game, warapp_wait_for_turn's read), a
13
+ // game-ended in-app notification (warapp_get_notifications, at most `END_OF_GAME_PER_CALL` per call), and
14
+ // the sweep in warapp_my_games over the account's finished games not yet processed, at most
15
+ // `END_OF_GAME_PER_CALL` per call (the marks are its cursor: each attempt leaves one, so the next call
16
+ // moves on). A pass that spent its request but left no record is remembered for the life of the process
17
+ // too (`attempted`), so no trigger reads that game's history twice (P2: never retried in a loop).
18
+ // Off with `WARAPP_PLAYER_PROFILE=off`; nothing without a data directory.
19
+ // Profiles inform only (P1): no planner decision reads any of this. Never throws.
20
+ import { readEnvVar } from '@chrischall/mcp-utils';
21
+ import { decisionTruth } from '../analysis/decision-truth.js';
22
+ import { captureFinished, excludedKind, outcomeOf } from '../analysis/finished-game.js';
23
+ import { compactDecisionLog, decisionLogMode, finishDecisionLogs, recordTruth } from '../decision-log.js';
24
+ import { teammatesOf } from '../teams.js';
2
25
  import { aggregateCalibration, calibrationSamples, flatTurn, historyHabits, incomeCurve, lessonLoss, mapFacts, } from '../analysis/game-lessons.js';
3
26
  import { profileFormatOf } from '../analysis/opponent-profile.js';
4
27
  import { trackGame } from '../analysis/opponents.js';
5
- import { recordLessons, recordMapGame } from '../lessons-store.js';
28
+ import { recordLessons, recordLessonsExcluded, recordMapExcluded, recordMapGame } from '../lessons-store.js';
6
29
  import { endingOf, foldGame, markHistoryFolded, profileFileState } from '../profile-store.js';
7
30
  import { MAX_FINISHED_RECORDS, finishedPath, finishedRecordOf, markProcessed, readFinishedState, readProcessed, touchFinished, writeFinishedRecord, } from '../finished-store.js';
8
31
  import { withPathLock } from '../path-lock.js';
@@ -14,8 +37,10 @@ import { profileEnabled } from '../profile-store.js';
14
37
  import { nameFreeSettings } from '../replay.js';
15
38
  import { historyBoards, historyReport, readBoardHistory, readCachedOrders, readCachedPlayer } from '../trend.js';
16
39
  import { graphOf } from './common.js';
40
+ import { settingsKey } from './decision-capture.js';
17
41
  import { mapOf } from './map.js';
18
- import { cardsInPlay, foldFinished, observeSettings, profiledOpponents } from './profile-hook.js';
42
+ import { keptFacts, kindsOf } from './game-kind.js';
43
+ import { cardsInPlay, EXCLUDED_FOLD_NOTE, foldFinished, observeSettings, profiledOpponents } from './profile-hook.js';
19
44
  import { keptTeams } from './team-source.js';
20
45
  import { plannerSettings } from './turn.js';
21
46
  /** Finished games the warapp_my_games sweep processes per call (each one GameFeed history read). */
@@ -29,6 +54,8 @@ function remember(set, key) {
29
54
  while (set.size > MEMO_LIMIT)
30
55
  set.delete(set.values().next().value);
31
56
  }
57
+ /** The decision log's mode as `env` sets it. */
58
+ const decisionLogModeOf = (env) => decisionLogMode({ WARAPP_DECISION_LOG: readEnvVar('WARAPP_DECISION_LOG', { env }) });
32
59
  /**
33
60
  * Games (per data dir and account) whose history request this process already spent, whatever came
34
61
  * of it: a game in here is never read again by any trigger in this process, even when no record
@@ -70,8 +97,13 @@ export async function needsEndOfGame(dataDir, env, gameId, me) {
70
97
  */
71
98
  export async function endOfGame(deps, gameId, me, seen, opts = {}) {
72
99
  const { dataDir, env } = deps;
73
- if (!profileEnabled(env))
100
+ if (!profileEnabled(env)) {
101
+ // #412: no pass runs, but the game is over: its decision log leaves `active` (the prune never deletes
102
+ // an active log), dropping nothing. The account may be unknown here (none is read with profiling off).
103
+ if (dataDir && seen?.state === 'Finished')
104
+ await finishDecisionLogs(dataDir, [gameId], me, { mode: decisionLogModeOf(env) });
74
105
  return { status: 'off' };
106
+ }
75
107
  if (!dataDir)
76
108
  return { status: 'no-data-dir' };
77
109
  if (me === undefined)
@@ -80,16 +112,24 @@ export async function endOfGame(deps, gameId, me, seen, opts = {}) {
80
112
  return { status: 'not-finished' };
81
113
  if (seen && !seen.players.some((p) => p.id === me && holdsSeat(p.state)))
82
114
  return { status: 'not-a-player' };
115
+ // #412: an exit that runs no truth or compaction for a game over still takes its decision log out of
116
+ // `active` (the prune never deletes an active log, and the lasting mark may already stop any later
117
+ // pass), dropping nothing: an `include_history` retry can still write the truth and compact.
118
+ const closeOnly = () => finishDecisionLogs(dataDir, [gameId], me, { mode: decisionLogModeOf(env) });
119
+ let read;
120
+ // #437: the kind this pass keeps the game apart for (no profile fold either).
121
+ let kept;
83
122
  try {
84
123
  const salt = await playerSaltForWrite(dataDir);
85
124
  if (!salt)
86
125
  return { status: 'unavailable' };
87
126
  const path = finishedPath(dataDir, salt, me, gameId);
88
- let read;
89
127
  const result = await withPathLock(path, async () => {
90
128
  const state = await readFinishedState(path);
91
- if (state === 'unreadable')
129
+ if (state === 'unreadable') {
130
+ await closeOnly();
92
131
  return { status: 'record-unreadable' };
132
+ }
93
133
  if (state !== 'missing' && (!opts.retry || state.status === 'captured' || !opts.history))
94
134
  return { status: 'already-processed' };
95
135
  // The one history read: the caller's, else one request, sent once (no transport retry) and never retried.
@@ -135,14 +175,18 @@ export async function endOfGame(deps, gameId, me, seen, opts = {}) {
135
175
  read = game;
136
176
  const shown = game ?? seen;
137
177
  const { record, history } = await buildRecord(dataDir, salt, me, gameId, game, shown, failure);
178
+ kept = excludedKind(record.kinds ?? []);
138
179
  try {
139
180
  const protect = opts.protectIds ? new Set(opts.protectIds.map((id) => finishedPath(dataDir, salt, me, id))) : undefined;
140
181
  await writeFinishedRecord(dataDir, path, record, opts.keep, protect);
141
182
  }
142
183
  catch {
184
+ await closeOnly();
143
185
  return { status: 'failed' };
144
186
  }
145
187
  const processed = history && game ? await processHistory(dataDir, env, salt, me, gameId, game, history) : undefined;
188
+ // #412: the decision log's truth (from the full history, before any cut) and its compaction.
189
+ await closeDecisionLog(dataDir, env, me, gameId, game ?? shown, history && game ? history : undefined);
146
190
  return {
147
191
  status: record.status,
148
192
  ...(record.turns ? { turns: record.turns.length } : {}),
@@ -152,12 +196,17 @@ export async function endOfGame(deps, gameId, me, seen, opts = {}) {
152
196
  });
153
197
  if (opts.fold && (result.status === 'captured' || result.status === 'history-unreadable')) {
154
198
  const game = read ?? seen;
155
- if (game)
199
+ if (kept)
200
+ result.profileFold = { status: 'nothing', reason: 'excluded', note: EXCLUDED_FOLD_NOTE };
201
+ else if (game)
156
202
  result.profileFold = await foldFinished(dataDir, env, game);
157
203
  }
158
204
  return result;
159
205
  }
160
206
  catch {
207
+ // Shown finished (or, with no read, passed as finished by the sweep or a game-ended notice).
208
+ if (((read ?? seen)?.state ?? 'Finished') === 'Finished')
209
+ await closeOnly();
161
210
  return { status: 'failed' };
162
211
  }
163
212
  }
@@ -177,28 +226,35 @@ async function buildRecord(dataDir, salt, me, gameId, read, shown, failure) {
177
226
  mapId: shown?.settings?.mapId ?? shown?.map?.id,
178
227
  picks,
179
228
  };
180
- if (!read)
181
- return { record: finishedRecordOf({ ...common, status: 'read-failed', failure, capture: capture(shown, me, [], new Map(), undefined) }) };
229
+ // #437: what this server kept of the game: its kind, and the turn my seat left.
230
+ const facts = await keptFacts(dataDir, gameId, me);
231
+ if (!read) {
232
+ const c = capture(shown, me, [], new Map(), undefined, facts.leftTurn);
233
+ return { record: finishedRecordOf({ ...common, status: 'read-failed', failure, capture: c, kinds: kindsOf(shown, me, c, facts) }) };
234
+ }
182
235
  const report = historyReport(read);
183
- const orders = (await readCachedPlayer(dataDir, gameId)) === me ? await readCachedOrders(dataDir, gameId, me) : new Map();
236
+ const orders = facts.orders;
184
237
  const map = read.map ? mapOf(read) : undefined;
185
238
  if ('unreadable' in report) {
186
239
  const u = report.unreadable;
240
+ const c = capture(read, me, [], orders, undefined, facts.leftTurn);
187
241
  return {
188
242
  record: finishedRecordOf({
189
243
  ...common,
190
244
  status: 'history-unreadable',
191
245
  failure: { reason: u.reason, keys: u.keys, ...(u.layout ? { layout: u.layout } : {}), ...(u.shape ? { shape: u.shape } : {}), ...(u.turns !== undefined ? { turns: u.turns } : {}) },
192
- capture: capture(read, me, [], orders, undefined),
246
+ capture: c,
247
+ kinds: kindsOf(read, me, c, facts),
193
248
  }),
194
249
  };
195
250
  }
196
251
  const boards = historyBoards(read.history, read.players, read.numberOfTurns !== undefined ? { numberOfTurns: read.numberOfTurns } : {});
197
252
  const graph = map ? graphOf(map) : undefined;
198
- const captured = capture(read, me, boards, orders, graph);
253
+ const captured = capture(read, me, boards, orders, graph, facts.leftTurn);
254
+ const kinds = kindsOf(read, me, captured, facts);
199
255
  return {
200
- record: finishedRecordOf({ ...common, status: 'captured', layout: report.read.layout, noMap: !map, capture: captured, boards }),
201
- history: { capture: captured, boards, orders, graph },
256
+ record: finishedRecordOf({ ...common, status: 'captured', layout: report.read.layout, noMap: !map, capture: captured, boards, kinds }),
257
+ history: { capture: captured, boards, orders, graph, kinds },
202
258
  };
203
259
  }
204
260
  /**
@@ -209,6 +265,15 @@ async function buildRecord(dataDir, salt, me, gameId, read, shown, failure) {
209
265
  * boards scored against the truth by coverage). Never throws.
210
266
  */
211
267
  async function processHistory(dataDir, env, salt, me, gameId, game, h) {
268
+ const key = finishedGameKey(salt, me, gameId);
269
+ const mapId = game.settings?.mapId ?? game.map?.id;
270
+ // #437: a lottery or no-show game is counted apart: never in the lessons, the map record or the profiles.
271
+ const apart = excludedKind(h.kinds);
272
+ if (apart) {
273
+ const map = mapId !== undefined ? await recordMapExcluded(dataDir, mapId, key, apart) : 'excluded';
274
+ const lessons = await recordLessonsExcluded(dataDir, key, apart);
275
+ return { profiles: 'excluded', map, lessons };
276
+ }
212
277
  const out = { profiles: 'no-map', map: 'no-map', lessons: 'no-map' };
213
278
  const g = h.graph;
214
279
  if (!g)
@@ -219,7 +284,6 @@ async function processHistory(dataDir, env, salt, me, gameId, game, h) {
219
284
  const seated = resolved.players.filter((p) => holdsSeat(p.state));
220
285
  const format = profileFormatOf(resolved.players);
221
286
  const opponents = mine ? profiledOpponents(resolved, mine) : resolved.players.filter((p) => p.id !== me).map((p) => p.id);
222
- const key = finishedGameKey(salt, me, gameId);
223
287
  const c = h.capture;
224
288
  try {
225
289
  out.profiles = !teams?.known || !mine ? 'teams-unknown' : await foldHistory(dataDir, env, me, gameId, resolved, opponents, format, seated.length, h);
@@ -227,8 +291,8 @@ async function processHistory(dataDir, env, salt, me, gameId, game, h) {
227
291
  catch {
228
292
  out.profiles = 'failed';
229
293
  }
230
- const mapId = game.settings?.mapId ?? game.map?.id;
231
294
  if (mapId !== undefined) {
295
+ const s = game.settings;
232
296
  out.map = await recordMapGame(dataDir, mapId, {
233
297
  key,
234
298
  format,
@@ -236,6 +300,13 @@ async function processHistory(dataDir, env, salt, me, gameId, game, h) {
236
300
  result: c.outcome.result,
237
301
  turns: c.outcome.turn,
238
302
  ...mapFacts(g, me, c.outcome.winners, c.starts, c.turns),
303
+ kinds: h.kinds,
304
+ // #437: the views read only the games of the current game's format and settings.
305
+ settings: {
306
+ key: settingsKey(game),
307
+ ...(s?.localDeployments !== undefined ? { localDeployments: s.localDeployments } : {}),
308
+ ...(s?.commanders !== undefined ? { commanders: s.commanders } : {}),
309
+ },
239
310
  });
240
311
  }
241
312
  try {
@@ -270,9 +341,11 @@ async function processHistory(dataDir, env, salt, me, gameId, game, h) {
270
341
  graph: g,
271
342
  settings: game.settings,
272
343
  numberOfTurns: c.outcome.turn,
273
- outTurn: c.outcome.outTurn,
344
+ // #437: a surrender's or a boot's turn is the one my seat left (the log's events), not only the history's.
345
+ outTurn: c.outcome.leftTurn ?? c.outcome.outTurn,
274
346
  }),
275
347
  calibration: aggregateCalibration(samples),
348
+ kinds: h.kinds,
276
349
  });
277
350
  }
278
351
  catch {
@@ -280,6 +353,56 @@ async function processHistory(dataDir, env, salt, me, gameId, game, h) {
280
353
  }
281
354
  return out;
282
355
  }
356
+ /**
357
+ * The decision log of a finished game (#412 task 3): with the history captured, every turn's truth and
358
+ * every logged turn's accuracy from the FULL history boards (`h.boards`, before the finished record's
359
+ * head/tail cut: no-gaps rule (c)); then the log is compacted (no-gaps rule (b); `full` keeps it whole).
360
+ * Without a captured history the log is only marked `finished` (whole, but no longer protected from the
361
+ * prune): the retry that brings it writes the truth, then compacts. Nothing with `WARAPP_DECISION_LOG=off`.
362
+ * Never throws.
363
+ */
364
+ async function closeDecisionLog(dataDir, env, me, gameId, game, h) {
365
+ const mode = decisionLogModeOf(env);
366
+ if (mode === 'off')
367
+ return;
368
+ try {
369
+ if (h?.graph && game) {
370
+ const graph = h.graph;
371
+ const teams = await keptTeams(dataDir, game).catch(() => undefined);
372
+ const resolved = teams?.game ?? game;
373
+ const mine = resolved.players.find((p) => p.id === me);
374
+ const allies = new Set(mine ? teammatesOf(resolved.players, mine).map((p) => p.id) : []);
375
+ const opponents = resolved.players.filter((p) => p.id !== me && !allies.has(p.id)).map((p) => p.id);
376
+ // Every seat as still playing: a final state would read a seat out on every earlier board.
377
+ const asPlaying = resolved.players.map(({ state: _state, ...p }) => p);
378
+ await recordTruth(dataDir, gameId, me, (logged) => decisionTruth({
379
+ graph,
380
+ me,
381
+ opponents,
382
+ history: h.boards,
383
+ ...(game.numberOfTurns !== undefined ? { numberOfTurns: game.numberOfTurns } : {}),
384
+ incomeSettings: game.settings,
385
+ plannerSettings: plannerSettings(game.settings),
386
+ game: trackGame(asPlaying, game.settings, game.map),
387
+ logged,
388
+ }), { mode });
389
+ }
390
+ // Compaction follows the truth (its choice of turns reads the accuracy): with no history captured, a
391
+ // retry (warapp_get_game include_history) can still bring it, so the log stays whole until then — but
392
+ // marked `finished` (the game is over), so the prune may drop it: an `active` log is never pruned, and
393
+ // no trigger retries the read by itself. The retry's truth and compaction accept a `finished` log. A
394
+ // captured history with no map can never give a truth (a captured pass is not run again): compact.
395
+ if (!h) {
396
+ await finishDecisionLogs(dataDir, [gameId], me, { mode });
397
+ return;
398
+ }
399
+ const lost = game ? ['lost', 'surrendered', 'eliminated', 'booted'].includes(outcomeOf(game.players, me)) : false;
400
+ await compactDecisionLog(dataDir, gameId, me, { mode, lost });
401
+ }
402
+ catch {
403
+ // Best effort.
404
+ }
405
+ }
283
406
  /** Part C: fold the opponents' habits read off the history, as `history` (replacing a live entry). */
284
407
  async function foldHistory(dataDir, env, me, gameId, game, opponents, format, players, h) {
285
408
  const byId = new Map(game.players.map((p) => [p.id, p]));
@@ -304,7 +427,7 @@ async function foldHistory(dataDir, env, me, gameId, game, opponents, format, pl
304
427
  await markHistoryFolded(dataDir, gameId, me);
305
428
  return 'folded';
306
429
  }
307
- function capture(game, me, boards, orders, graph) {
430
+ function capture(game, me, boards, orders, graph, leftTurn) {
308
431
  if (!game)
309
432
  return undefined;
310
433
  return captureFinished({
@@ -315,6 +438,7 @@ function capture(game, me, boards, orders, graph) {
315
438
  numberOfTurns: game.numberOfTurns,
316
439
  boards,
317
440
  orders,
441
+ leftTurn,
318
442
  });
319
443
  }
320
444
  /**
@@ -361,6 +485,10 @@ export const sweepWindow = (keep = MAX_FINISHED_RECORDS) => Math.max(1, Math.flo
361
485
  export async function sweepFinished(deps, me, gameIds, { limit = END_OF_GAME_PER_CALL, keep = MAX_FINISHED_RECORDS, window: size, } = {}) {
362
486
  // warapp_backfill_history may widen the window, never past the record bound (every game in it is protected).
363
487
  const window = gameIds.slice(0, Math.max(1, Math.min(size ?? sweepWindow(keep), keep)));
488
+ // #412: with profiling off no pass runs, but these games are over: their decision logs leave `active`
489
+ // (no request; a log already closed costs one head read).
490
+ if (deps.dataDir && !profileEnabled(deps.env))
491
+ await finishDecisionLogs(deps.dataDir, window, me, { mode: decisionLogModeOf(deps.env) });
364
492
  const todo = [];
365
493
  for (const id of window)
366
494
  if (await needsEndOfGame(deps.dataDir, deps.env, id, me))
@@ -0,0 +1,92 @@
1
+ // #437: a finished game's kind (lottery, no-show, legacy, team) from what was read and what this server
2
+ // kept of it, shared by the end-of-game pass (the record's `kinds`) and every profile fold (`foldFinished`),
3
+ // so a lottery or no-show game is kept out of the profiles whichever tool reads it first. Never throws.
4
+ import { excludedKind, gameKinds, leftTurnOf, outcomeOf } from '../analysis/finished-game.js';
5
+ import { profileFormatOf } from '../analysis/opponent-profile.js';
6
+ import { readDecisionLog } from '../decision-log.js';
7
+ import { finishedPath, readFinishedRecord } from '../finished-store.js';
8
+ import { LOTTERY_MAX_TERRITORIES } from '../open-games.js';
9
+ import { playerRecordSalt } from '../player-record-store.js';
10
+ import { readCachedOrders, readCachedPlayer } from '../trend.js';
11
+ const LEAVING = new Set(['surrender-accepted', 'booted']);
12
+ /**
13
+ * Whether a logged event is my seat leaving. My own surrender counts only once war.app shows it taken
14
+ * (`status: 'surrendered'`): a pending one leaves the seat playing until the others accept (logged then as
15
+ * the seat's `surrender-accepted`), and it may be undone, so its turn is not the turn my seat left.
16
+ */
17
+ function isLeaving(e, me) {
18
+ if (e.kind === 'my-surrender')
19
+ return typeof e.detail === 'object' && e.detail.status === 'surrendered' && (e.player === undefined || e.player === me);
20
+ return LEAVING.has(e.kind) && e.player === me;
21
+ }
22
+ export async function keptFacts(dataDir, gameId, me) {
23
+ const hasBoards = (await readCachedPlayer(dataDir, gameId).catch(() => undefined)) === me;
24
+ const orders = hasBoards ? await readCachedOrders(dataDir, gameId, me).catch(() => new Map()) : new Map();
25
+ const log = await readDecisionLog(dataDir, gameId, me).catch(() => undefined);
26
+ const left = (log?.events ?? [])
27
+ .filter((e) => isLeaving(e, me))
28
+ .map((e) => e.turn)
29
+ .filter((t) => Number.isInteger(t));
30
+ return { log, hasBoards, orders, leftTurn: left.length ? Math.min(...left) : undefined };
31
+ }
32
+ /** The game's kinds (#437) from what was read and what this server kept. */
33
+ export function kindsOf(game, me, capture, facts) {
34
+ const committed = new Set(facts.orders.keys());
35
+ for (const [k, e] of Object.entries(facts.log?.turns ?? {}))
36
+ if (e.sent)
37
+ committed.add(Number(k));
38
+ const s = game?.settings;
39
+ const result = capture?.outcome.result ?? (game ? outcomeOf(game.players, me) : 'unknown');
40
+ const outTurn = capture?.outcome.outTurn ?? null;
41
+ return gameKinds({
42
+ result,
43
+ team: game ? profileFormatOf(game.players) === 'team' : false,
44
+ territories: game?.map?.territories.length,
45
+ joinLottery: facts.log?.join?.lottery,
46
+ lotteryShape: s?.minimumArmyBonus === 0 && (s.overriddenBonuses?.size ?? 0) > 0,
47
+ lotteryMaxTerritories: LOTTERY_MAX_TERRITORIES,
48
+ hasLog: facts.log !== undefined,
49
+ hasBoards: facts.hasBoards,
50
+ committedTurns: committed.size,
51
+ leftTurn: capture?.outcome.leftTurn ?? leftTurnOf(result, outTurn, facts.leftTurn),
52
+ numberOfTurns: game?.numberOfTurns ?? null,
53
+ });
54
+ }
55
+ /**
56
+ * Whether a finished game is kept out of the profile folds (#437): the kinds its end-of-game record keeps
57
+ * when there is one (the pass's own verdict), else the kinds read now from the game and what this server
58
+ * kept of it as the cached account. With no cached account (a per-game file kept by another account of
59
+ * mine) only the game itself is read: its map's size, or the lottery settings shape. Read-only (never makes
60
+ * the salt), no request; `undefined` on any failure, so a fold is never blocked by this check.
61
+ */
62
+ export async function foldExclusion(dataDir, game) {
63
+ try {
64
+ const me = await readCachedPlayer(dataDir, game.id).catch(() => undefined);
65
+ if (me !== undefined) {
66
+ const salt = await playerRecordSalt(dataDir);
67
+ if (salt) {
68
+ const rec = await readFinishedRecord(finishedPath(dataDir, salt, me, game.id));
69
+ if (typeof rec === 'object' && rec.kinds)
70
+ return excludedKind(rec.kinds);
71
+ }
72
+ return excludedKind(kindsOf(game, me, undefined, await keptFacts(dataDir, game.id, me)));
73
+ }
74
+ const s = game.settings;
75
+ return excludedKind(gameKinds({
76
+ result: 'unknown',
77
+ team: false,
78
+ territories: game.map?.territories.length,
79
+ lotteryShape: s?.minimumArmyBonus === 0 && (s.overriddenBonuses?.size ?? 0) > 0,
80
+ lotteryMaxTerritories: LOTTERY_MAX_TERRITORIES,
81
+ // Nothing kept as a known account: never a no-show from here.
82
+ hasLog: false,
83
+ hasBoards: false,
84
+ committedTurns: 0,
85
+ leftTurn: null,
86
+ numberOfTurns: null,
87
+ }));
88
+ }
89
+ catch {
90
+ return undefined;
91
+ }
92
+ }
@@ -83,7 +83,10 @@ function seatOut(result, byState, last, game) {
83
83
  const head = `${byState.line} The last turn played here was turn ${turn}`;
84
84
  if (!entry)
85
85
  return { result, ...byState, turn, line: `${head}; no outlook was logged for it.` };
86
- const held = log.latest && log.latest.turn === loggedTurn && log.latest.state !== null ? { state: log.latest.state, turns: log.latest.heldTurns } : undefined;
86
+ const latest = log.latest;
87
+ const held = latest && latest.turn === loggedTurn && latest.state !== null
88
+ ? { state: latest.state, ...(latest.lean ? { lean: latest.lean } : {}), turns: latest.heldTurns }
89
+ : undefined;
87
90
  const f = entry.figures;
88
91
  const s = f?.strongest;
89
92
  const who = s
@@ -94,11 +97,13 @@ function seatOut(result, byState, last, game) {
94
97
  const outlook = {
95
98
  turn: loggedTurn,
96
99
  state: entry.state,
100
+ // #454: the income lean beside an even state (additive).
101
+ ...(entry.lean ? { lean: entry.lean } : {}),
97
102
  ...(held ? { held } : {}),
98
103
  ...(f ? { mine: f.mine } : {}),
99
104
  ...(s ? { strongest: { id: s.playerId, ...(s.team !== undefined ? { team: s.team } : {}), name: who, armies: s.armies, income: s.income } } : {}),
100
105
  };
101
- const read = `${loggedTurn === turn ? 'its outlook' : `the last outlook logged (turn ${loggedTurn})`} read ${entry.state}${held ? ` (held ${held.turns} turn${held.turns === 1 ? '' : 's'})` : ''}`;
106
+ 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'})` : ''}`;
102
107
  const figures = !f
103
108
  ? ' (the armies and income behind it were not logged then)'
104
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'}`;
@@ -1,4 +1,5 @@
1
1
  import { defaultMapCache, WarappClient } from '../client.js';
2
+ import { captureSeats } from './decision-capture.js';
2
3
  import { dataDir } from '../config.js';
3
4
  import { StatsCollector } from '../stats.js';
4
5
  import { registerBeginTurnTool } from './begin-turn.js';
@@ -79,6 +80,8 @@ export function registerAllTools(server, deps = {}) {
79
80
  // The cached signed-in account is discarded whenever the account behind the router may have changed.
80
81
  identity: () => bridge.identityState(),
81
82
  });
83
+ // #437: every game read diffs the seats into the game's decision log (no request of its own).
84
+ client.observeGames((game) => captureSeats(live, game));
82
85
  registerHealthcheckTool(server, fetchproxy, bridge, { ...deps, standIn: () => live.decoderReport()?.standIn });
83
86
  // The signed-in account names a finished game's player for its end-of-game pass when no board was cached (#312).
84
87
  registerGameTool(server, client, () => dataDir(deps.env), deps.env, () => live.myInviteToken());
@@ -13,6 +13,7 @@ import { GAME_COLOR_COUNT, Method, readAcceptOpenSeatReturn, writeAcceptOpenSeat
13
13
  import { WarappServerError } from '../protocol/rpc.js';
14
14
  import { gameIdArg, UNTRUSTED_PREVIEW_NOTE, untrustedText } from './common.js';
15
15
  import { noBrowserNote } from './session.js';
16
+ import { captureJoin, joinContextLog } from './decision-capture.js';
16
17
  import { mintMeta } from './hints.js';
17
18
  import { requireApprovedAccount, writeAccount } from './live-context.js';
18
19
  import { fetchMyGames } from './my-games.js';
@@ -138,8 +139,8 @@ async function lobbyScreen(ctx, gameId) {
138
139
  const game = await ctx.client.getGame(gameId, { settings: true, map: false });
139
140
  const { screen, gaps } = feedScreen(game.settings ?? { cards: [], raw: {} });
140
141
  return screen
141
- ? { screen, gaps }
142
- : { screen: null, gaps, note: "GameFeed's settings name no neutral size, so the neutral-cost screen was skipped." };
142
+ ? { screen, gaps, game }
143
+ : { screen: null, gaps, game, note: "GameFeed's settings name no neutral size, so the neutral-cost screen was skipped." };
143
144
  }
144
145
  catch (e) {
145
146
  return {
@@ -282,10 +283,11 @@ export function registerJoinGameTool(server, ctx) {
282
283
  team,
283
284
  color,
284
285
  account: String(token),
286
+ join: joinContextLog(game, screened.game, screened.screen),
285
287
  },
286
288
  };
287
289
  },
288
- async execute({ gameId, name, url, team, color, account }) {
290
+ async execute({ gameId, name, url, team, color, account, join }) {
289
291
  await requireApprovedAccount(ctx, account);
290
292
  const game = { id: gameId, name, url };
291
293
  let vacationEnded = false;
@@ -298,7 +300,7 @@ export function registerJoinGameTool(server, ctx) {
298
300
  warning: 'war.app accepted the join, but neither GameFeed nor your games list shows you in the game yet, so ' +
299
301
  'this could not confirm it. Check warapp_my_games shortly.',
300
302
  });
301
- return sendAndVerify({
303
+ const result = await sendAndVerify({
302
304
  send: async () => {
303
305
  const env = await ctx.rpc.call('AcceptOpenSeat', Method.AcceptOpenSeat, (w) => writeAcceptOpenSeatParams(w, { gameId, team, color }));
304
306
  vacationEnded = readAcceptOpenSeatReturn(env.body)?.vacationEnded ?? false;
@@ -322,6 +324,10 @@ export function registerJoinGameTool(server, ctx) {
322
324
  unreadable: () => notShown(),
323
325
  classify: (seated) => (seated ? { status: 'joined', outcome: 'confirmed', game, ...extra() } : notShown()),
324
326
  });
327
+ // #437: the lobby joined, once confirmed, into the game's decision log (name-free).
328
+ if (result.outcome === 'confirmed' && join)
329
+ await captureJoin(ctx, gameId, Number(account), join);
330
+ return result;
325
331
  },
326
332
  });
327
333
  }
@@ -2,7 +2,9 @@
2
2
  // chat), the web-client RPC channel through the bridge (board, picks, sends),
3
3
  // and the client bundle whose readers decode the board.
4
4
  import { McpToolError } from '@chrischall/mcp-utils';
5
+ import { chatAutomationMode, chatBlocksTurnMode } from '../chat-automation.js';
5
6
  import { dataDir } from '../config.js';
7
+ import { decisionLogMode } from '../decision-log.js';
6
8
  import { inGameId, LiveBoardFormatError, readLatestGameInfo, standingFromInfo } from '../live.js';
7
9
  import { BUNDLE_FETCH_TIMEOUT_MS, BUNDLE_MAX_BYTES, BundleProvider } from '../protocol/bundle.js';
8
10
  import { ProtocolError } from '../protocol/codec.js';
@@ -220,8 +222,12 @@ export function createLiveContext(opts) {
220
222
  cached = undefined;
221
223
  settled = started;
222
224
  },
225
+ cachedInviteToken: () => (cached && now() - cached.at < IDENTITY_TTL_MS ? Number(cached.token) : undefined),
223
226
  fetchPage: fetchText,
224
227
  dataDir: dir,
228
+ decisionLog: decisionLogMode(opts.env ?? process.env),
229
+ chatAutomation: chatAutomationMode(opts.env ?? process.env),
230
+ chatBlocksTurn: chatBlocksTurnMode(opts.env ?? process.env),
225
231
  hosted: isHosted(opts.env ?? process.env),
226
232
  hostSignIn: hostedSession(opts.env ?? process.env) !== null,
227
233
  client: opts.client,
@@ -16,6 +16,7 @@ import { mapOf } from './map.js';
16
16
  import { resolvePlayer, resolveTerritory } from './resolve.js';
17
17
  import { defineGatedWrite, requireMySeat, sendAndVerify } from './write-kit.js';
18
18
  import { resolveTeamsFor } from './team-source.js';
19
+ import { capturePicksSent } from './decision-capture.js';
19
20
  const VIEWS = ['compact', 'full'];
20
21
  const MAX_PICK_ARGS = 200;
21
22
  export const BRIDGE_NOTE = 'Reads through your signed-in war.app tab (ContextMint Bridge), so it sees exactly what you see — fog included.';
@@ -356,7 +357,7 @@ export function registerLiveTools(server, ctx) {
356
357
  await requireApprovedAccount(ctx, writeAccount(me));
357
358
  const ids = picks.map((p) => p.id);
358
359
  const base = { game: gameId, picks };
359
- return sendAndVerify({
360
+ const result = await sendAndVerify({
360
361
  send: async () => {
361
362
  await ctx.rpc.call('SendTerritoryPicks', Method.SendTerritoryPicks, (w) => writeSendTerritoryPicksParams(w, gameId, ids));
362
363
  },
@@ -399,6 +400,14 @@ export function registerLiveTools(server, ctx) {
399
400
  };
400
401
  },
401
402
  });
403
+ // #437 task 3: what was sent and read back into the game's decision log (ids only; the latest send wins).
404
+ await capturePicksSent(ctx, gameId, me, {
405
+ sent: ids,
406
+ readBack: result.readBack ?? null,
407
+ verified: result.verified,
408
+ outcome: result.outcome,
409
+ });
410
+ return result;
402
411
  },
403
412
  });
404
413
  }
@@ -0,0 +1,73 @@
1
+ // #419: map-record entries kept before #419 hold no winner income curve, so they count for no fog pace. The end-of-game
2
+ // records (src/finished-store.ts) keep each captured game's history boards (the first and last 30), from which the
3
+ // winners' curves are read again here: no request, this server's state only. Run by warapp_backfill_history. Name-free
4
+ // like the stores: a record's players are labelled by position (`anonymousHistoryOfRecord`), winners matched to the
5
+ // map entry by their start territories. Never throws.
6
+ import { basename } from 'node:path';
7
+ import { curvePoints } from '../analysis/game-lessons.js';
8
+ import { turnIncomes } from '../analysis/finished-game.js';
9
+ import { applyBonusOverrides } from '../analysis/overrides.js';
10
+ import { anonymousHistoryOfRecord, listFinishedRecords, readFinishedRecord } from '../finished-store.js';
11
+ import { fillWinnerCurves, readMapRecord } from '../lessons-store.js';
12
+ import { readStoredMap } from '../map-store.js';
13
+ import { normalizeSettings } from '../normalize.js';
14
+ import { graphOf } from './common.js';
15
+ /** Fill the winners' curves of every map-record entry kept without them, from the end-of-game records. Never throws. */
16
+ export async function backfillWinnerCurves(dataDir) {
17
+ const out = { filled: 0, unfilled: 0 };
18
+ let paths;
19
+ try {
20
+ paths = await listFinishedRecords(dataDir);
21
+ }
22
+ catch {
23
+ return out;
24
+ }
25
+ for (const path of paths) {
26
+ try {
27
+ const rec = await readFinishedRecord(path);
28
+ if (typeof rec === 'string' || rec.status !== 'captured')
29
+ continue;
30
+ const settings = rec.settings ? normalizeSettings(rec.settings) : undefined;
31
+ const mapId = rec.mapId ?? settings?.mapId;
32
+ if (mapId === undefined)
33
+ continue;
34
+ const key = basename(path, '.json');
35
+ const mr = await readMapRecord(dataDir, mapId);
36
+ const entry = mr === 'unreadable' ? undefined : mr.entries.find((e) => e.key === key);
37
+ if (!entry || entry.winners.every((w) => w.income))
38
+ continue;
39
+ const h = anonymousHistoryOfRecord(rec);
40
+ const map = await readStoredMap(dataDir, mapId, { maxAgeMs: Number.POSITIVE_INFINITY });
41
+ if (typeof h === 'string' || !map || !settings) {
42
+ out.unfilled++;
43
+ continue;
44
+ }
45
+ const graph = graphOf(applyBonusOverrides(map, settings));
46
+ const winners = h.players.filter((p) => p.state === 'Won').map((p) => p.id);
47
+ const boards = [...h.boards].sort((a, b) => a.turn - b.turn);
48
+ const ids = h.players.map((p) => p.id);
49
+ const curves = new Map(winners.map((w) => [w, []]));
50
+ for (const b of boards) {
51
+ const inc = turnIncomes(graph, b.board, ids, settings);
52
+ for (const w of winners) {
53
+ const x = inc.get(w);
54
+ if (x)
55
+ curves.get(w).push({ afterTurn: b.turn, income: x.income });
56
+ }
57
+ }
58
+ const start = boards[0];
59
+ const startOf = (w) => start && start.turn === 0
60
+ ? start.board.territories.flatMap((t) => (t.owner.kind === 'player' && t.owner.playerId === w ? [t.territoryId] : []))
61
+ : [];
62
+ const r = await fillWinnerCurves(dataDir, mapId, key, winners.map((w) => ({ territories: startOf(w), income: curvePoints(curves.get(w)) })));
63
+ if (r === 'filled')
64
+ out.filled++;
65
+ else if (r !== 'missing')
66
+ out.unfilled++;
67
+ }
68
+ catch {
69
+ out.unfilled++;
70
+ }
71
+ }
72
+ return out;
73
+ }