@chrischall/warapp-mcp 0.15.0 → 0.17.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.
@@ -7,7 +7,7 @@
7
7
  },
8
8
  "metadata": {
9
9
  "description": "MCP server for war.app (Warzone) — your games, players, settings, map bonuses and chokepoints, board analysis and route planning through war.app's per-player GameFeed API, plus the live board, territory picks, cards, turn planning and submission, turn notifications and game chat through your signed-in war.app tab (joining, leaving or surrendering a game, closing out a finished game, accepting another player's surrender, Begin on a speed first turn, picks, turn orders, withdrawing them, chat sends, marking notifications and chat read, deleting notifications, importing local history and linking a session are confirm-gated).",
10
- "version": "0.15.0"
10
+ "version": "0.17.0"
11
11
  },
12
12
  "plugins": [
13
13
  {
@@ -15,7 +15,7 @@
15
15
  "displayName": "war.app (Warzone)",
16
16
  "source": "./",
17
17
  "description": "war.app (Warzone) game advisor for Claude — games, maps, bonuses, routes, live board, picks, turns, cards and chat",
18
- "version": "0.15.0",
18
+ "version": "0.17.0",
19
19
  "author": {
20
20
  "name": "Chris Hall"
21
21
  },
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "warapp-mcp",
3
3
  "displayName": "war.app (Warzone)",
4
- "version": "0.15.0",
4
+ "version": "0.17.0",
5
5
  "description": "war.app (Warzone) game advisor for Claude — games, maps, bonuses, routes, live board, picks, turns, cards and chat",
6
6
  "author": {
7
7
  "name": "Chris Hall",
package/dist/bundle.js CHANGED
@@ -115386,6 +115386,7 @@ async function withPathLock(path, fn) {
115386
115386
  var MAX_STORED_MAPS = 40;
115387
115387
  var MAX_MAP_AGE_MS = 30 * 24 * 60 * 60 * 1e3;
115388
115388
  var MAX_GAME_INDEX = 500;
115389
+ var MAX_PINNED_GAMES = 1e3;
115389
115390
  var VERSION = 1;
115390
115391
  var MAP_FILE = /^\d+\.json$/;
115391
115392
  var isRec2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
@@ -115394,6 +115395,7 @@ var isIntArray = (v) => Array.isArray(v) && v.every(isInt);
115394
115395
  var mapsDir = (dir) => join5(dir, "maps");
115395
115396
  var mapStorePath = (dir, mapId) => join5(mapsDir(dir), `${mapId}.json`);
115396
115397
  var indexPath = (dir) => join5(mapsDir(dir), "games.json");
115398
+ var pinsPath = (dir) => join5(mapsDir(dir), "pinned.json");
115397
115399
  async function writeJsonAtomic(path, folder, body) {
115398
115400
  await mkdir(folder, { recursive: true, mode: 448 });
115399
115401
  const tmp = `${path}.${process.pid}.${randomBytes3(4).toString("hex")}.tmp`;
@@ -115470,9 +115472,10 @@ async function readStoredMapEntry(dir, mapId, opts = {}) {
115470
115472
  }
115471
115473
  async function evictMaps(dir, keep) {
115472
115474
  const folder = mapsDir(dir);
115475
+ const pinned = new Set((await readPins(dir)).map(([, m]) => `${m}.json`));
115473
115476
  const files = [];
115474
115477
  for (const name of await readdir(folder)) {
115475
- if (!MAP_FILE.test(name)) continue;
115478
+ if (!MAP_FILE.test(name) || pinned.has(name)) continue;
115476
115479
  try {
115477
115480
  files.push({ name, at: (await stat(join5(folder, name))).mtimeMs });
115478
115481
  } catch {
@@ -115545,6 +115548,44 @@ async function rememberGameMap(dir, gameId, mapId) {
115545
115548
  return false;
115546
115549
  }
115547
115550
  }
115551
+ async function readPins(dir) {
115552
+ try {
115553
+ const raw = JSON.parse(await readFile(pinsPath(dir), "utf8"));
115554
+ if (!isRec2(raw) || raw.version !== VERSION || !Array.isArray(raw.pins)) return [];
115555
+ return raw.pins.filter((e) => Array.isArray(e) && e.length === 2 && isInt(e[0]) && isInt(e[1]));
115556
+ } catch {
115557
+ return [];
115558
+ }
115559
+ }
115560
+ async function pinStoredMap(dir, mapId, gameId) {
115561
+ try {
115562
+ return await withPathLock(pinsPath(dir), async () => {
115563
+ const pins = await readPins(dir);
115564
+ if (pins.some(([g, m]) => g === gameId && m === mapId)) return false;
115565
+ const next = pins.filter(([g]) => g !== gameId);
115566
+ next.push([gameId, mapId]);
115567
+ await writeJsonAtomic(pinsPath(dir), mapsDir(dir), { version: VERSION, pins: next.slice(-MAX_PINNED_GAMES) });
115568
+ return true;
115569
+ });
115570
+ } catch {
115571
+ return false;
115572
+ }
115573
+ }
115574
+ async function unpinGames(dir, gameIds) {
115575
+ if (!gameIds.length) return false;
115576
+ const gone = new Set(gameIds);
115577
+ try {
115578
+ return await withPathLock(pinsPath(dir), async () => {
115579
+ const pins = await readPins(dir);
115580
+ const next = pins.filter(([g]) => !gone.has(g));
115581
+ if (next.length === pins.length) return false;
115582
+ await writeJsonAtomic(pinsPath(dir), mapsDir(dir), { version: VERSION, pins: next });
115583
+ return true;
115584
+ });
115585
+ } catch {
115586
+ return false;
115587
+ }
115588
+ }
115548
115589
 
115549
115590
  // src/build-id.ts
115550
115591
  import { createHash as createHash4 } from "node:crypto";
@@ -115630,7 +115671,7 @@ function serverBuild() {
115630
115671
  }
115631
115672
 
115632
115673
  // src/version.ts
115633
- var VERSION2 = "0.15.0";
115674
+ var VERSION2 = "0.17.0";
115634
115675
 
115635
115676
  // src/decision-log.ts
115636
115677
  var DECISION_LOG_VERSION = 1;
@@ -115746,6 +115787,10 @@ function encodeInput(input2) {
115746
115787
  }
115747
115788
  function loggedEstimates(estimates, tracks) {
115748
115789
  const methods = new Map((tracks ?? []).flatMap((t) => t.incomeMethod ? [[t.playerId, t.incomeMethod]] : []));
115790
+ const internals = new Map((tracks ?? []).flatMap((t) => {
115791
+ const logged2 = loggedTrack(t);
115792
+ return logged2 ? [[t.playerId, logged2]] : [];
115793
+ }));
115749
115794
  return [...estimates].sort((a, b) => a.playerId - b.playerId).map((e) => ({
115750
115795
  player: e.playerId,
115751
115796
  estimate: e.estimate,
@@ -115753,9 +115798,36 @@ function loggedEstimates(estimates, tracks) {
115753
115798
  coverage: e.coverage?.share ?? null,
115754
115799
  thin: !!e.thinEvidence,
115755
115800
  ...methods.has(e.playerId) ? { method: methods.get(e.playerId) } : {},
115756
- stages: estimateStages(e)
115801
+ stages: estimateStages(e),
115802
+ ...internals.has(e.playerId) ? { track: internals.get(e.playerId) } : {}
115757
115803
  }));
115758
115804
  }
115805
+ function loggedTrack(t) {
115806
+ if (t.income === void 0) return void 0;
115807
+ const window = new Set(t.incomeTurns ?? []);
115808
+ const turns = (t.turns ?? []).filter((x) => window.has(x.from));
115809
+ return {
115810
+ income: t.income,
115811
+ window: turns.map((x) => ({
115812
+ turn: x.from,
115813
+ observed: x.observed,
115814
+ raw: x.raw,
115815
+ low: x.low,
115816
+ high: x.high,
115817
+ cap: x.cap,
115818
+ coverage: x.coverage?.share ?? null,
115819
+ ...x.captureFloor !== void 0 ? { captureFloor: x.captureFloor } : {},
115820
+ ...x.accounted ? { accounted: true } : {},
115821
+ ...x.fogCaptures ? { fogCaptures: x.fogCaptures.income } : {}
115822
+ })),
115823
+ ...t.incomeLowered ? { lowered: t.incomeLowered } : {},
115824
+ ...t.incomeRise ? { rise: { ...t.incomeRise } } : {},
115825
+ ...t.observedLow ? { observedLow: { ...t.observedLow } } : {},
115826
+ ...t.incomeTrip ? { trip: { ...t.incomeTrip } } : {},
115827
+ ...t.incomeJump ? { jump: { turn: t.incomeJump.turn, observed: t.incomeJump.observed, before: t.incomeJump.before, verdict: t.incomeJump.verdict } } : {},
115828
+ ...typeof t.topUp === "number" ? { topUp: t.topUp } : {}
115829
+ };
115830
+ }
115759
115831
  function earnedIncome(input2) {
115760
115832
  const { income, cardArmies } = input2 ?? {};
115761
115833
  if (typeof income !== "number") return void 0;
@@ -115817,7 +115889,8 @@ function logOf(c, gameId) {
115817
115889
  ...isRec3(c.seats) ? { seats: c.seats } : {},
115818
115890
  ...isRec3(c.join) ? { join: c.join } : {},
115819
115891
  ...isRec3(c.opponents) ? { opponents: c.opponents } : {},
115820
- ...isRec3(c.picks) ? { picks: c.picks } : {}
115892
+ ...isRec3(c.picks) ? { picks: c.picks } : {},
115893
+ ...isInt2(c.mapId) ? { mapId: c.mapId } : {}
115821
115894
  };
115822
115895
  }
115823
115896
  var hasContent = (log) => Object.keys(log.turns).length > 0 || !!log.events?.length || !!log.join || !!log.seats || !!log.opponents || !!log.picks;
@@ -115906,7 +115979,7 @@ async function recordDecision(dir, gameId, playerId, rec2, opts = {}) {
115906
115979
  [String(rec2.turn)]: { ...entry, ...was?.chat ? { chat: was.chat } : {}, ...was?.checks ? { checks: was.checks } : {} }
115907
115980
  };
115908
115981
  encodeBoards(turns, boards);
115909
- return { ...log, turns };
115982
+ return { ...log, ...rec2.mapId !== void 0 ? { mapId: rec2.mapId } : {}, turns };
115910
115983
  },
115911
115984
  opts
115912
115985
  );
@@ -116441,6 +116514,7 @@ async function pruneDecisionLogs(dir, caps = {}) {
116441
116514
  } catch {
116442
116515
  }
116443
116516
  }
116517
+ await unpinGames(dir, removed);
116444
116518
  return removed;
116445
116519
  }
116446
116520
 
@@ -137565,6 +137639,7 @@ function gameIdsOf(body) {
137565
137639
 
137566
137640
  // src/tools/decision-capture.ts
137567
137641
  import { createHash as createHash7 } from "node:crypto";
137642
+ import { existsSync as existsSync3 } from "node:fs";
137568
137643
 
137569
137644
  // src/join-color.ts
137570
137645
  var GAME_COLOR = "warlight.shared.GameColor";
@@ -138634,12 +138709,14 @@ var bonusesOf = (graph) => new Map([...graph.bonusById.keys()].map((id) => [id,
138634
138709
  async function capturePlan(ctx, a) {
138635
138710
  if (!ctx.dataDir) return;
138636
138711
  const opts = modeOf2(ctx);
138637
- await recordDecision(
138712
+ const mapId = a.graph.map.id;
138713
+ const wrote = await recordDecision(
138638
138714
  ctx.dataDir,
138639
138715
  a.gameId,
138640
138716
  a.me,
138641
138717
  {
138642
138718
  turn: a.turn,
138719
+ mapId,
138643
138720
  board: a.board,
138644
138721
  ...a.plannedBoard ? { plannedBoard: a.plannedBoard } : {},
138645
138722
  input: a.input,
@@ -138654,6 +138731,7 @@ async function capturePlan(ctx, a) {
138654
138731
  },
138655
138732
  opts
138656
138733
  );
138734
+ if (wrote || existsSync3(decisionLogPath(ctx.dataDir, a.gameId))) await pinStoredMap(ctx.dataDir, mapId, a.gameId);
138657
138735
  if (a.turn < 2) return;
138658
138736
  try {
138659
138737
  await fillOutcome(
@@ -145010,6 +145088,7 @@ var finishedDir = (dir) => join24(dir, "finished");
145010
145088
  var finishedPath = (dir, salt, me, gameId) => join24(finishedDir(dir), `${finishedGameKey(salt, me, gameId)}.json`);
145011
145089
  var processedPath = (dir) => join24(finishedDir(dir), "processed.json");
145012
145090
  var KEY = /^[0-9a-f]{32}$/;
145091
+ var COLLECTOR_VERSION = 1;
145013
145092
  var END_STATS_VERSION = 3;
145014
145093
  var OWNER_NEUTRAL2 = -1;
145015
145094
  var OWNER_AVAILABLE = -2;
@@ -145032,6 +145111,33 @@ async function readFinishedState(path) {
145032
145111
  return "unreadable";
145033
145112
  }
145034
145113
  }
145114
+ async function readFinishedSummary(path) {
145115
+ let text;
145116
+ try {
145117
+ text = await readFile19(path, "utf8");
145118
+ } catch (e) {
145119
+ return e.code === "ENOENT" ? "missing" : "unreadable";
145120
+ }
145121
+ try {
145122
+ const v = JSON.parse(text);
145123
+ if (!isRec20(v) || v.version !== VERSION4 || typeof v.status !== "string" || !STATUSES.has(v.status)) return "unreadable";
145124
+ const r = v;
145125
+ const f = isRec20(r.failure) ? r.failure : void 0;
145126
+ const stats = isRec20(r.stats) ? r.stats : void 0;
145127
+ return {
145128
+ status: r.status,
145129
+ collector: typeof r.collector === "number" && Number.isInteger(r.collector) && r.collector >= 0 ? r.collector : 0,
145130
+ ...f && typeof f.reason === "string" ? { failure: { reason: f.reason, ..."kind" in f && typeof f.kind === "string" ? { kind: f.kind } : {} } } : {},
145131
+ ...Array.isArray(r.turns) ? { turns: r.turns.length } : {},
145132
+ ...Array.isArray(r.boards) ? { boards: r.boards.length } : {},
145133
+ ...stats && typeof stats.version === "number" ? { statsVersion: stats.version } : {},
145134
+ ...Array.isArray(r.kinds) ? { kinds: r.kinds.filter((k) => typeof k === "string") } : {},
145135
+ ...isRec20(r.outcome) && typeof r.outcome.result === "string" ? { result: r.outcome.result } : {}
145136
+ };
145137
+ } catch {
145138
+ return "unreadable";
145139
+ }
145140
+ }
145035
145141
  async function writeFinishedRecord(dir, path, body, keep = MAX_FINISHED_RECORDS, protect) {
145036
145142
  await writeJsonAtomic(path, finishedDir(dir), body);
145037
145143
  await pruneFinished(dir, keep, /* @__PURE__ */ new Set([...protect ?? [], path])).catch(() => void 0);
@@ -145110,6 +145216,7 @@ function finishedRecordOf(p) {
145110
145216
  const stored = kept ? storeBoards(kept.boards, p.game?.players.map((x) => x.id) ?? [p.me], key) : void 0;
145111
145217
  return {
145112
145218
  version: VERSION4,
145219
+ collector: COLLECTOR_VERSION,
145113
145220
  status: p.status,
145114
145221
  ...p.failure ? { failure: p.failure } : {},
145115
145222
  ...p.layout ? { layout: p.layout } : {},
@@ -156418,13 +156525,14 @@ async function endOfGame(deps, gameId, me, seen2, opts = {}) {
156418
156525
  await closeOnly();
156419
156526
  return { status: "record-unreadable" };
156420
156527
  }
156421
- if (state !== "missing" && state.status === "captured") return await keptOrBackfilled(dataDir2, path, salt, me, opts.history ?? seen2, opts.history);
156422
- if (state !== "missing" && (!opts.retry || !opts.history)) return { status: "already-processed" };
156528
+ const reread = opts.reread === true;
156529
+ if (state !== "missing" && state.status === "captured" && !reread) return await keptOrBackfilled(dataDir2, path, salt, me, opts.history ?? seen2, opts.history);
156530
+ if (state !== "missing" && !reread && (!opts.retry || !opts.history)) return { status: "already-processed" };
156423
156531
  let game = opts.history;
156424
156532
  let failure2;
156425
156533
  if (!game) {
156426
- if (state === "missing" && await isMarked(dataDir2, salt, me, gameId)) return { status: "already-processed" };
156427
- const key = attemptKey(dataDir2, me, gameId);
156534
+ if (state === "missing" && !reread && await isMarked(dataDir2, salt, me, gameId)) return { status: "already-processed" };
156535
+ const key = `${attemptKey(dataDir2, me, gameId)}${reread ? "|reread" : ""}`;
156428
156536
  if (attempted.has(key)) return { status: "attempted" };
156429
156537
  remember(attempted, key);
156430
156538
  try {
@@ -156446,6 +156554,8 @@ async function endOfGame(deps, gameId, me, seen2, opts = {}) {
156446
156554
  read = game;
156447
156555
  const shown2 = game ?? seen2;
156448
156556
  const { record: record4, history } = await buildRecord(dataDir2, salt, me, gameId, game, shown2, failure2);
156557
+ if (reread && state !== "missing" && state.status === "captured" && record4.status !== "captured")
156558
+ return { status: record4.status, keptPrevious: true, ...record4.failure ? { failure: record4.failure } : {} };
156449
156559
  kept = excludedKind(record4.kinds ?? []);
156450
156560
  try {
156451
156561
  const protect = opts.protectIds ? new Set(opts.protectIds.map((id) => finishedPath(dataDir2, salt, me, id))) : void 0;
@@ -156719,19 +156829,76 @@ var sweepWindow = (keep = MAX_FINISHED_RECORDS) => Math.max(1, Math.floor(keep /
156719
156829
  async function sweepFinished(deps, me, gameIds, {
156720
156830
  limit = END_OF_GAME_PER_CALL,
156721
156831
  keep = MAX_FINISHED_RECORDS,
156722
- window: size
156832
+ window: size,
156833
+ only,
156834
+ reread,
156835
+ report: report2
156723
156836
  } = {}) {
156724
156837
  const window = gameIds.slice(0, Math.max(1, Math.min(size ?? sweepWindow(keep), keep)));
156725
- if (deps.dataDir && !profileEnabled(deps.env)) await finishDecisionLogs(deps.dataDir, window, me, { mode: decisionLogModeOf(deps.env) });
156838
+ const scope = only ? gameIds.filter((id) => only.includes(id)) : window;
156839
+ if (deps.dataDir && !profileEnabled(deps.env)) await finishDecisionLogs(deps.dataDir, scope, me, { mode: decisionLogModeOf(deps.env) });
156840
+ const before = /* @__PURE__ */ new Map();
156841
+ if (report2 || reread) for (const id of scope) before.set(id, await gameStanding(deps, me, id));
156726
156842
  const todo = [];
156727
- for (const id of window) if (await needsEndOfGame(deps.dataDir, deps.env, id, me)) todo.push(id);
156843
+ for (const id of scope) {
156844
+ if (await needsEndOfGame(deps.dataDir, deps.env, id, me)) todo.push({ id, reread: false });
156845
+ else if (reread && rereadWanted(before.get(id), reread)) todo.push({ id, reread: true });
156846
+ }
156728
156847
  await refreshProcessed(deps, me, window).catch(() => void 0);
156729
156848
  const processed = [];
156730
- for (const id of todo.slice(0, limit)) {
156731
- const r = await endOfGame(deps, id, me, void 0, { fold: true, keep, protectIds: window });
156732
- processed.push({ gameId: id, status: r.status, ...r.turns !== void 0 ? { turns: r.turns } : {} });
156849
+ const protectIds = only ? [.../* @__PURE__ */ new Set([...window, ...scope])] : window;
156850
+ for (const t of todo.slice(0, limit)) {
156851
+ const r = await endOfGame(deps, t.id, me, void 0, { fold: true, keep, protectIds, ...t.reread ? { reread: true } : {} });
156852
+ processed.push({
156853
+ gameId: t.id,
156854
+ status: r.status,
156855
+ ...t.reread ? { reread: true } : {},
156856
+ ...r.turns !== void 0 ? { turns: r.turns } : {},
156857
+ ...r.failure ? { failure: failureCode(r.failure) } : {},
156858
+ ...r.keptPrevious ? { keptPrevious: true } : {}
156859
+ });
156860
+ }
156861
+ const out = { processed, pending: Math.max(0, todo.length - limit) };
156862
+ if (report2) {
156863
+ const thisCall = new Map(processed.map((p) => [p.gameId, p]));
156864
+ const waiting = new Set(todo.slice(limit).map((t) => t.id));
156865
+ const games = [];
156866
+ for (const id of scope) {
156867
+ const now = thisCall.has(id) ? await gameStanding(deps, me, id) : before.get(id);
156868
+ const p = thisCall.get(id);
156869
+ games.push({
156870
+ gameId: id,
156871
+ ...now,
156872
+ ...p ? { thisCall: p.reread ? "reread" : "read" } : waiting.has(id) ? { thisCall: "waiting" } : {}
156873
+ });
156874
+ }
156875
+ out.games = games;
156733
156876
  }
156734
- return { processed, pending: Math.max(0, todo.length - limit) };
156877
+ return out;
156878
+ }
156879
+ async function gameStanding(deps, me, gameId) {
156880
+ const { dataDir: dataDir2, env } = deps;
156881
+ if (!dataDir2 || !profileEnabled(env)) return { state: "unknown" };
156882
+ try {
156883
+ const salt = await playerRecordSalt(dataDir2);
156884
+ if (!salt) return { state: "not-processed" };
156885
+ const summary = await readFinishedSummary(finishedPath(dataDir2, salt, me, gameId));
156886
+ if (summary === "unreadable") return { state: "record-unreadable" };
156887
+ if (summary !== "missing") return { state: "recorded", outdated: summary.collector < COLLECTOR_VERSION, ...summary };
156888
+ return await isMarked(dataDir2, salt, me, gameId) ? { state: "processed-record-pruned" } : { state: "not-processed" };
156889
+ } catch {
156890
+ return { state: "unknown" };
156891
+ }
156892
+ }
156893
+ function rereadWanted(s, scope) {
156894
+ if (s.state === "processed-record-pruned") return scope === "all";
156895
+ if (s.state !== "recorded") return false;
156896
+ if (scope === "all") return true;
156897
+ if (scope === "failed") return s.status !== "captured";
156898
+ return s.outdated;
156899
+ }
156900
+ function failureCode(f) {
156901
+ return { reason: f.reason, ..."kind" in f && f.kind ? { kind: f.kind } : {} };
156735
156902
  }
156736
156903
  async function refreshProcessed(deps, me, window) {
156737
156904
  const { dataDir: dataDir2, env } = deps;
@@ -165127,14 +165294,18 @@ function registerBackfillTool(server, ctx, env) {
165127
165294
  {
165128
165295
  title: "Process more finished war.app games at once",
165129
165296
  _meta: mintMeta("change", ["backfill my war.app history", "process finished games", "catch up past games"]),
165130
- description: `Give the end-of-game pass to up to \`limit\` (default 10, at most 25) of your finished war.app games not yet processed, newest first: each game's history is read ONCE from GameFeed (never again, whatever comes of it) and kept name-free for the opponent profiles, map records and lessons \u2014 what warapp_my_games does two games per call. \`window\` widens how many of your newest finished games are considered (default 250, at most ${MAX_FINISHED_RECORDS}). Reports what it processed and how many remain; safe to call again until \`remaining\` is 0. It also gives map records kept before the winners' income curves were those curves, from the histories already kept (\`winnerCurves\`, no request). Writes only this server's state and never writes to war.app. ` + BRIDGE_NOTE,
165297
+ description: `Give the end-of-game pass to up to \`limit\` (default 10, at most 25) of your finished war.app games not yet processed, newest first: each game's history is read ONCE from GameFeed (never again, whatever comes of it) and kept name-free for the opponent profiles, map records and lessons \u2014 what warapp_my_games does two games per call. \`window\` widens how many of your newest finished games are considered (default 250, at most ${MAX_FINISHED_RECORDS}). Reports what it processed and how many remain; safe to call again until \`remaining\` is 0. \`games\` lists every game considered one by one, from this server's state (no request): recorded (captured, read-failed or history-unreadable, with the failure code, history turns, boards kept, stats version, collector version and \`outdated\` when kept under an older collector), not-processed, processed-record-pruned or record-unreadable, and what this call did to it (read, reread, waiting). \`game_ids\` limits it to those games. \`reread\` reads the history AGAIN (one more GameFeed request per game) for games already processed \u2014 \`failed\` (read-failed or history-unreadable), \`outdated\` (kept under an older collector version, so newer metrics get captured) or \`all\` \u2014 and rebuilds the record and what was processed from it (each store replaces the game's share; nothing counts twice); a re-read that fails never replaces a captured record (\`keptPrevious\`). It also gives map records kept before the winners' income curves were those curves, from the histories already kept (\`winnerCurves\`, no request). Writes only this server's state and never writes to war.app. ` + BRIDGE_NOTE,
165131
165298
  annotations: toolAnnotations({ title: "Backfill finished war.app games", readOnly: false, destructive: false, idempotent: true, openWorld: true }),
165132
165299
  inputSchema: external_exports.object({
165133
165300
  limit: external_exports.number().int().min(1).max(BACKFILL_MAX).optional().describe(`Games to process this call (default ${BACKFILL_DEFAULT}, max ${BACKFILL_MAX}).`),
165134
- window: external_exports.number().int().min(1).max(MAX_FINISHED_RECORDS).optional().describe(`How many of your newest finished games to consider (default ${sweepWindow()}, max ${MAX_FINISHED_RECORDS}).`)
165301
+ window: external_exports.number().int().min(1).max(MAX_FINISHED_RECORDS).optional().describe(`How many of your newest finished games to consider (default ${sweepWindow()}, max ${MAX_FINISHED_RECORDS}).`),
165302
+ game_ids: external_exports.array(external_exports.number().int().positive()).min(1).max(MAX_FINISHED_RECORDS).optional().describe("Only these games (each a finished game of yours; others are listed in `notFinishedOrNotMine`)."),
165303
+ reread: external_exports.enum(["failed", "outdated", "all"]).optional().describe(
165304
+ "Read again the history of games already processed: `failed` (read-failed or history-unreadable), `outdated` (kept under an older collector version) or `all`. One GameFeed request per game; default none."
165305
+ )
165135
165306
  })
165136
165307
  },
165137
- async ({ limit, window }) => {
165308
+ async ({ limit, window, game_ids, reread }) => {
165138
165309
  if (!ctx.dataDir) refuse("This server has no data directory, so no history can be kept.", "Nothing to do here.");
165139
165310
  if (!profileEnabled(env)) refuse("The end-of-game pass is off (WARAPP_PLAYER_PROFILE=off), so nothing was read.", "Turn profiling on to backfill.");
165140
165311
  const { me, games } = await fetchMyGames(ctx);
@@ -165144,8 +165315,13 @@ function registerBackfillTool(server, ctx, env) {
165144
165315
  const size = Math.min(window ?? sweepWindow(), MAX_FINISHED_RECORDS);
165145
165316
  const r = await sweepFinished({ client: ctx.client, dataDir: ctx.dataDir, env }, token2, ids2, {
165146
165317
  limit: limit ?? BACKFILL_DEFAULT,
165147
- window: size
165318
+ window: size,
165319
+ report: true,
165320
+ ...game_ids ? { only: game_ids } : {},
165321
+ ...reread ? { reread } : {}
165148
165322
  });
165323
+ const finished = new Set(ids2);
165324
+ const notMine = game_ids ? [...new Set(game_ids)].filter((id) => !finished.has(id)) : [];
165149
165325
  const winnerCurves = await backfillWinnerCurves(ctx.dataDir);
165150
165326
  return respond(void 0, ["compact"], () => ({
165151
165327
  winnerCurves,
@@ -165154,7 +165330,10 @@ function registerBackfillTool(server, ctx, env) {
165154
165330
  remaining: r.pending,
165155
165331
  finishedGames: ids2.length,
165156
165332
  window: size,
165157
- ...ids2.length > size ? { outsideWindow: ids2.length - size } : {}
165333
+ ...ids2.length > size && !game_ids ? { outsideWindow: ids2.length - size } : {},
165334
+ collectorVersion: COLLECTOR_VERSION,
165335
+ games: r.games ?? [],
165336
+ ...notMine.length ? { notFinishedOrNotMine: notMine } : {}
165158
165337
  }));
165159
165338
  }
165160
165339
  );
@@ -57,7 +57,7 @@
57
57
  import { open, readdir, readFile, stat, unlink } from 'node:fs/promises';
58
58
  import { join } from 'node:path';
59
59
  import { estimateOff } from './analysis/decision-truth.js';
60
- import { writeJsonAtomic } from './map-store.js';
60
+ import { unpinGames, writeJsonAtomic } from './map-store.js';
61
61
  import { withPathLock } from './path-lock.js';
62
62
  import { serverBuild } from './build-id.js';
63
63
  import { VERSION } from './version.js';
@@ -241,6 +241,10 @@ export function decodeInput(logged, board, graph) {
241
241
  /** The estimates as logged: ids, figures and flags only. */
242
242
  export function loggedEstimates(estimates, tracks) {
243
243
  const methods = new Map((tracks ?? []).flatMap((t) => (t.incomeMethod ? [[t.playerId, t.incomeMethod]] : [])));
244
+ const internals = new Map((tracks ?? []).flatMap((t) => {
245
+ const logged = loggedTrack(t);
246
+ return logged ? [[t.playerId, logged]] : [];
247
+ }));
244
248
  return [...estimates]
245
249
  .sort((a, b) => a.playerId - b.playerId)
246
250
  .map((e) => ({
@@ -251,8 +255,39 @@ export function loggedEstimates(estimates, tracks) {
251
255
  thin: !!e.thinEvidence,
252
256
  ...(methods.has(e.playerId) ? { method: methods.get(e.playerId) } : {}),
253
257
  stages: estimateStages(e),
258
+ ...(internals.has(e.playerId) ? { track: internals.get(e.playerId) } : {}),
254
259
  }));
255
260
  }
261
+ /** #586: {@link LoggedTrack} of one track; `undefined` for a track with no income field (one built by hand). */
262
+ export function loggedTrack(t) {
263
+ if (t.income === undefined)
264
+ return undefined;
265
+ const window = new Set(t.incomeTurns ?? []);
266
+ const turns = (t.turns ?? []).filter((x) => window.has(x.from));
267
+ return {
268
+ income: t.income,
269
+ window: turns.map((x) => ({
270
+ turn: x.from,
271
+ observed: x.observed,
272
+ raw: x.raw,
273
+ low: x.low,
274
+ high: x.high,
275
+ cap: x.cap,
276
+ coverage: x.coverage?.share ?? null,
277
+ ...(x.captureFloor !== undefined ? { captureFloor: x.captureFloor } : {}),
278
+ ...(x.accounted ? { accounted: true } : {}),
279
+ ...(x.fogCaptures ? { fogCaptures: x.fogCaptures.income } : {}),
280
+ })),
281
+ ...(t.incomeLowered ? { lowered: t.incomeLowered } : {}),
282
+ ...(t.incomeRise ? { rise: { ...t.incomeRise } } : {}),
283
+ ...(t.observedLow ? { observedLow: { ...t.observedLow } } : {}),
284
+ ...(t.incomeTrip ? { trip: { ...t.incomeTrip } } : {}),
285
+ ...(t.incomeJump
286
+ ? { jump: { turn: t.incomeJump.turn, observed: t.incomeJump.observed, before: t.incomeJump.before, verdict: t.incomeJump.verdict } }
287
+ : {}),
288
+ ...(typeof t.topUp === 'number' ? { topUp: t.topUp } : {}),
289
+ };
290
+ }
256
291
  /** My income as `input` gives it, card armies out; `undefined` when it holds none. */
257
292
  function earnedIncome(input) {
258
293
  const { income, cardArmies } = (input ?? {});
@@ -330,6 +365,7 @@ function logOf(c, gameId) {
330
365
  ...(isRec(c.join) ? { join: c.join } : {}),
331
366
  ...(isRec(c.opponents) ? { opponents: c.opponents } : {}),
332
367
  ...(isRec(c.picks) ? { picks: c.picks } : {}),
368
+ ...(isInt(c.mapId) ? { mapId: c.mapId } : {}),
333
369
  };
334
370
  }
335
371
  /** Whether a log holds anything: a turn, or per-game context (#437). */
@@ -442,7 +478,7 @@ export async function recordDecision(dir, gameId, playerId, rec, opts = {}) {
442
478
  [String(rec.turn)]: { ...entry, ...(was?.chat ? { chat: was.chat } : {}), ...(was?.checks ? { checks: was.checks } : {}) },
443
479
  };
444
480
  encodeBoards(turns, boards);
445
- return { ...log, turns };
481
+ return { ...log, ...(rec.mapId !== undefined ? { mapId: rec.mapId } : {}), turns };
446
482
  }, opts);
447
483
  }
448
484
  catch {
@@ -1128,5 +1164,7 @@ export async function pruneDecisionLogs(dir, caps = {}) {
1128
1164
  // Gone already, or not removable: leave it.
1129
1165
  }
1130
1166
  }
1167
+ // #586: a pruned log no longer keeps its map pinned.
1168
+ await unpinGames(dir, removed);
1131
1169
  return removed;
1132
1170
  }
@@ -53,6 +53,13 @@ export const finishedPath = (dir, salt, me, gameId) => join(finishedDir(dir), `$
53
53
  /** The processed marks: not a record (its name is no key), so the prune and the record list skip it. */
54
54
  export const processedPath = (dir) => join(finishedDir(dir), 'processed.json');
55
55
  const KEY = /^[0-9a-f]{32}$/;
56
+ /**
57
+ * The version of what the end-of-game pass collects and processes from a history. Bump it whenever the capture
58
+ * or its processing (profiles, map record, lessons, decision-log truth, stats) gains or changes a metric:
59
+ * warapp_backfill_history's `reread: 'outdated'` then reads again the history of every game whose record was
60
+ * kept under an older one (a record kept before this field reads as 0). 1: the first versioned capture.
61
+ */
62
+ export const COLLECTOR_VERSION = 1;
56
63
  /**
57
64
  * #541/#542: the version of the stats computation. 2: seat lines stop and resume as the client's (a return to
58
65
  * Playing resumes; an AI takeover runs on under the seat with `aiFrom`). 3 (#542 follow-up): a seat ordering after
@@ -90,6 +97,39 @@ export async function readFinishedState(path) {
90
97
  return 'unreadable';
91
98
  }
92
99
  }
100
+ /** The record at `path` summarised: `missing`, `unreadable` (as {@link readFinishedState}), or its summary. Never throws. */
101
+ export async function readFinishedSummary(path) {
102
+ let text;
103
+ try {
104
+ text = await readFile(path, 'utf8');
105
+ }
106
+ catch (e) {
107
+ return e.code === 'ENOENT' ? 'missing' : 'unreadable';
108
+ }
109
+ try {
110
+ const v = JSON.parse(text);
111
+ if (!isRec(v) || v.version !== VERSION || typeof v.status !== 'string' || !STATUSES.has(v.status))
112
+ return 'unreadable';
113
+ const r = v;
114
+ const f = isRec(r.failure) ? r.failure : undefined;
115
+ const stats = isRec(r.stats) ? r.stats : undefined;
116
+ return {
117
+ status: r.status,
118
+ collector: typeof r.collector === 'number' && Number.isInteger(r.collector) && r.collector >= 0 ? r.collector : 0,
119
+ ...(f && typeof f.reason === 'string'
120
+ ? { failure: { reason: f.reason, ...('kind' in f && typeof f.kind === 'string' ? { kind: f.kind } : {}) } }
121
+ : {}),
122
+ ...(Array.isArray(r.turns) ? { turns: r.turns.length } : {}),
123
+ ...(Array.isArray(r.boards) ? { boards: r.boards.length } : {}),
124
+ ...(stats && typeof stats.version === 'number' ? { statsVersion: stats.version } : {}),
125
+ ...(Array.isArray(r.kinds) ? { kinds: r.kinds.filter((k) => typeof k === 'string') } : {}),
126
+ ...(isRec(r.outcome) && typeof r.outcome.result === 'string' ? { result: r.outcome.result } : {}),
127
+ };
128
+ }
129
+ catch {
130
+ return 'unreadable';
131
+ }
132
+ }
93
133
  /**
94
134
  * Write a record atomically (0600), then keep the newest {@link MAX_FINISHED_RECORDS}: never a path in
95
135
  * `protect` (the sweep's window, src/tools/end-of-game.ts), nor the one just written. Throws on a failed write.
@@ -199,6 +239,7 @@ export function finishedRecordOf(p) {
199
239
  const stored = kept ? storeBoards(kept.boards, p.game?.players.map((x) => x.id) ?? [p.me], key) : undefined;
200
240
  return {
201
241
  version: VERSION,
242
+ collector: COLLECTOR_VERSION,
202
243
  status: p.status,
203
244
  ...(p.failure ? { failure: p.failure } : {}),
204
245
  ...(p.layout ? { layout: p.layout } : {}),
package/dist/map-store.js CHANGED
@@ -20,6 +20,10 @@
20
20
  // - `<dataDir>/maps/games.json`: `{ version: 1, games: [[gameId, mapId], …] }`, newest last, at most
21
21
  // MAX_GAME_INDEX entries — which map a game is on, so a game seen before a restart is still asked
22
22
  // `GetMap=false`.
23
+ // - `<dataDir>/maps/pinned.json` (#586): `{ version: 1, pins: [[gameId, mapId], …] }`, newest last, at most
24
+ // MAX_PINNED_GAMES entries — the maps of games with a decision log (src/decision-log.ts), pinned when a turn
25
+ // is planned and unpinned when the log is pruned. A pinned map is never evicted and does not count toward
26
+ // MAX_STORED_MAPS, so a logged game can still be replayed offline after many other maps were used.
23
27
  //
24
28
  // Files are 0600 in a 0700 folder and written atomically; every read is loose (a bad file is ignored,
25
29
  // and replaced by the next write) and nothing here throws. Another process sharing the data directory
@@ -34,6 +38,8 @@ export const MAX_STORED_MAPS = 40;
34
38
  export const MAX_MAP_AGE_MS = 30 * 24 * 60 * 60 * 1000;
35
39
  /** Game → map entries kept in the index; the oldest goes first. */
36
40
  export const MAX_GAME_INDEX = 500;
41
+ /** #586: games whose map is pinned; the oldest pin goes first. As many as the decision log keeps games (1000). */
42
+ export const MAX_PINNED_GAMES = 1000;
37
43
  const VERSION = 1;
38
44
  const MAP_FILE = /^\d+\.json$/;
39
45
  const isRec = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
@@ -42,6 +48,7 @@ const isIntArray = (v) => Array.isArray(v) && v.every(isInt);
42
48
  export const mapsDir = (dir) => join(dir, 'maps');
43
49
  export const mapStorePath = (dir, mapId) => join(mapsDir(dir), `${mapId}.json`);
44
50
  const indexPath = (dir) => join(mapsDir(dir), 'games.json');
51
+ const pinsPath = (dir) => join(mapsDir(dir), 'pinned.json');
45
52
  /** Write `body` as JSON at `path` atomically (0600; folder 0700). */
46
53
  export async function writeJsonAtomic(path, folder, body) {
47
54
  await mkdir(folder, { recursive: true, mode: 0o700 });
@@ -140,12 +147,16 @@ export async function readStoredMapEntry(dir, mapId, opts = {}) {
140
147
  return undefined;
141
148
  }
142
149
  }
143
- /** Delete the least recently used maps beyond {@link MAX_STORED_MAPS}, keeping `keep`. Best effort. */
150
+ /**
151
+ * Delete the least recently used maps beyond {@link MAX_STORED_MAPS}, keeping `keep` and every pinned map (#586),
152
+ * which do not count toward the cap. Best effort.
153
+ */
144
154
  async function evictMaps(dir, keep) {
145
155
  const folder = mapsDir(dir);
156
+ const pinned = new Set((await readPins(dir)).map(([, m]) => `${m}.json`));
146
157
  const files = [];
147
158
  for (const name of await readdir(folder)) {
148
- if (!MAP_FILE.test(name))
159
+ if (!MAP_FILE.test(name) || pinned.has(name))
149
160
  continue;
150
161
  try {
151
162
  files.push({ name, at: (await stat(join(folder, name))).mtimeMs });
@@ -240,3 +251,59 @@ export async function rememberGameMap(dir, gameId, mapId) {
240
251
  return false;
241
252
  }
242
253
  }
254
+ /** #586: the pins, loosely: unusable entries are dropped. */
255
+ async function readPins(dir) {
256
+ try {
257
+ const raw = JSON.parse(await readFile(pinsPath(dir), 'utf8'));
258
+ if (!isRec(raw) || raw.version !== VERSION || !Array.isArray(raw.pins))
259
+ return [];
260
+ return raw.pins.filter((e) => Array.isArray(e) && e.length === 2 && isInt(e[0]) && isInt(e[1]));
261
+ }
262
+ catch {
263
+ return [];
264
+ }
265
+ }
266
+ /** #586: the map ids pinned by a game's decision log. Never throws. */
267
+ export async function pinnedMapIds(dir) {
268
+ return new Set((await readPins(dir)).map(([, m]) => m));
269
+ }
270
+ /**
271
+ * #586: pin `mapId` for `gameId` (a game with a decision log), so the stored map is never evicted while the log is
272
+ * kept; an existing pin for the game is moved to the newest. `true` when written (`false` when already pinned so,
273
+ * or on failure); never throws.
274
+ */
275
+ export async function pinStoredMap(dir, mapId, gameId) {
276
+ try {
277
+ return await withPathLock(pinsPath(dir), async () => {
278
+ const pins = await readPins(dir);
279
+ if (pins.some(([g, m]) => g === gameId && m === mapId))
280
+ return false;
281
+ const next = pins.filter(([g]) => g !== gameId);
282
+ next.push([gameId, mapId]);
283
+ await writeJsonAtomic(pinsPath(dir), mapsDir(dir), { version: VERSION, pins: next.slice(-MAX_PINNED_GAMES) });
284
+ return true;
285
+ });
286
+ }
287
+ catch {
288
+ return false;
289
+ }
290
+ }
291
+ /** #586: drop the pins of `gameIds` (their decision logs were pruned). `true` when written; never throws. */
292
+ export async function unpinGames(dir, gameIds) {
293
+ if (!gameIds.length)
294
+ return false;
295
+ const gone = new Set(gameIds);
296
+ try {
297
+ return await withPathLock(pinsPath(dir), async () => {
298
+ const pins = await readPins(dir);
299
+ const next = pins.filter(([g]) => !gone.has(g));
300
+ if (next.length === pins.length)
301
+ return false;
302
+ await writeJsonAtomic(pinsPath(dir), mapsDir(dir), { version: VERSION, pins: next });
303
+ return true;
304
+ });
305
+ }
306
+ catch {
307
+ return false;
308
+ }
309
+ }
@@ -97,7 +97,7 @@ export async function reviewGame(dir, gameId, opts = {}) {
97
97
  const found = await findFinished(dir, salt, gameId, cached, game);
98
98
  const me = cached ?? found.me;
99
99
  const finished = typeof found.record === 'object' ? found.record : null;
100
- const mapId = finished?.mapId ?? game?.settings?.mapId;
100
+ const mapId = finished?.mapId ?? game?.settings?.mapId ?? log?.mapId;
101
101
  const stored = mapId !== undefined ? await readStoredMap(dir, mapId, { maxAgeMs: Number.POSITIVE_INFINITY }) : undefined;
102
102
  const key = salt && me !== undefined ? finishedGameKey(salt, me, gameId) : undefined;
103
103
  const mapRecord = mapId !== undefined ? keyedEntry(mapRecordPath(dir, mapId), await readMapRecord(dir, mapId), key) : { state: 'missing', value: null };
@@ -19,9 +19,11 @@
19
19
  // `pickWarningCode`), `capturePicksSent` (warapp_submit_picks after a send) and `capturePicksAward` (the award
20
20
  // `loadAward` reads on turn 1, once).
21
21
  import { createHash } from 'node:crypto';
22
+ import { existsSync } from 'node:fs';
22
23
  import { parseFeedTime } from '../normalize.js';
23
24
  import { bonusTerritories } from '../analysis/bonuses.js';
24
25
  import { policyChecks } from '../open-games.js';
26
+ import { pinStoredMap } from '../map-store.js';
25
27
  import { nameFreeSettings } from '../replay.js';
26
28
  import { readSeenTurn } from '../turn-orders.js';
27
29
  import { recordPicksAdvice, recordPicksAward, recordPicksSent, decisionLogMode, decisionLogOwner, decisionLogPath, decisionOutcome, recordGameEvent, recordJoin, recordOpponentRead, recordSeats, fillOutcome, recordChat, recordCheck, recordDecision, recordObservations, recordSeenTurn, recordSubmission, } from '../decision-log.js';
@@ -36,8 +38,10 @@ export async function capturePlan(ctx, a) {
36
38
  if (!ctx.dataDir)
37
39
  return;
38
40
  const opts = modeOf(ctx);
39
- await recordDecision(ctx.dataDir, a.gameId, a.me, {
41
+ const mapId = a.graph.map.id;
42
+ const wrote = await recordDecision(ctx.dataDir, a.gameId, a.me, {
40
43
  turn: a.turn,
44
+ mapId,
41
45
  board: a.board,
42
46
  ...(a.plannedBoard ? { plannedBoard: a.plannedBoard } : {}),
43
47
  input: a.input,
@@ -50,6 +54,9 @@ export async function capturePlan(ctx, a) {
50
54
  ...(a.cards ? { cards: a.cards } : {}),
51
55
  ...(a.times ? { times: a.times } : {}),
52
56
  }, opts);
57
+ // #586: keep the map of every game with a decision log, so its turns can be replayed offline.
58
+ if (wrote || existsSync(decisionLogPath(ctx.dataDir, a.gameId)))
59
+ await pinStoredMap(ctx.dataDir, mapId, a.gameId);
53
60
  if (a.turn < 2)
54
61
  return;
55
62
  try {
@@ -28,7 +28,7 @@ import { profileFormatOf } from '../analysis/opponent-profile.js';
28
28
  import { trackGame } from '../analysis/opponents.js';
29
29
  import { recordLessons, recordLessonsExcluded, recordMapExcluded, recordMapGame } from '../lessons-store.js';
30
30
  import { endingOf, foldGame, markHistoryFolded, profileFileState } from '../profile-store.js';
31
- import { END_STATS_VERSION, MAX_FINISHED_RECORDS, finishedPath, finishedRecordOf, markProcessed, readFinishedRecord, readFinishedState, readProcessed, storedStats, touchFinished, writeFinishedRecord, } from '../finished-store.js';
31
+ import { COLLECTOR_VERSION, END_STATS_VERSION, MAX_FINISHED_RECORDS, finishedPath, finishedRecordOf, markProcessed, readFinishedRecord, readFinishedState, readFinishedSummary, readProcessed, storedStats, touchFinished, writeFinishedRecord, } from '../finished-store.js';
32
32
  import { playerKey } from '../player-record-store.js';
33
33
  import { withPathLock } from '../path-lock.js';
34
34
  import { finalOutlookOf, readOutlookLog } from '../outlook-log.js';
@@ -145,18 +145,19 @@ export async function endOfGame(deps, gameId, me, seen, opts = {}) {
145
145
  await closeOnly();
146
146
  return { status: 'record-unreadable' };
147
147
  }
148
- if (state !== 'missing' && state.status === 'captured')
148
+ const reread = opts.reread === true;
149
+ if (state !== 'missing' && state.status === 'captured' && !reread)
149
150
  return await keptOrBackfilled(dataDir, path, salt, me, opts.history ?? seen, opts.history);
150
- if (state !== 'missing' && (!opts.retry || !opts.history))
151
+ if (state !== 'missing' && !reread && (!opts.retry || !opts.history))
151
152
  return { status: 'already-processed' };
152
153
  // The one history read: the caller's, else one request, sent once (no transport retry) and never retried.
153
154
  let game = opts.history;
154
155
  let failure;
155
156
  if (!game) {
156
- if (state === 'missing' && (await isMarked(dataDir, salt, me, gameId)))
157
+ if (state === 'missing' && !reread && (await isMarked(dataDir, salt, me, gameId)))
157
158
  return { status: 'already-processed' };
158
- // The request is spent from here on, whatever follows: never again in this process.
159
- const key = attemptKey(dataDir, me, gameId);
159
+ // The request is spent from here on, whatever follows: never again in this process (a re-read once).
160
+ const key = `${attemptKey(dataDir, me, gameId)}${reread ? '|reread' : ''}`;
160
161
  if (attempted.has(key))
161
162
  return { status: 'attempted' };
162
163
  remember(attempted, key);
@@ -192,6 +193,9 @@ export async function endOfGame(deps, gameId, me, seen, opts = {}) {
192
193
  read = game;
193
194
  const shown = game ?? seen;
194
195
  const { record, history } = await buildRecord(dataDir, salt, me, gameId, game, shown, failure);
196
+ // A re-read that failed never replaces a capture kept before it.
197
+ if (reread && state !== 'missing' && state.status === 'captured' && record.status !== 'captured')
198
+ return { status: record.status, keptPrevious: true, ...(record.failure ? { failure: record.failure } : {}) };
195
199
  kept = excludedKind(record.kinds ?? []);
196
200
  try {
197
201
  const protect = opts.protectIds ? new Set(opts.protectIds.map((id) => finishedPath(dataDir, salt, me, id))) : undefined;
@@ -537,24 +541,92 @@ export const sweepWindow = (keep = MAX_FINISHED_RECORDS) => Math.max(1, Math.flo
537
541
  * sweep processed is so never read again (P2). `window` widens (or narrows) it for warapp_backfill_history,
538
542
  * at most `keep` games.
539
543
  */
540
- export async function sweepFinished(deps, me, gameIds, { limit = END_OF_GAME_PER_CALL, keep = MAX_FINISHED_RECORDS, window: size, } = {}) {
544
+ export async function sweepFinished(deps, me, gameIds, { limit = END_OF_GAME_PER_CALL, keep = MAX_FINISHED_RECORDS, window: size, only, reread, report, } = {}) {
541
545
  // warapp_backfill_history may widen the window, never past the record bound (every game in it is protected).
542
546
  const window = gameIds.slice(0, Math.max(1, Math.min(size ?? sweepWindow(keep), keep)));
547
+ const scope = only ? gameIds.filter((id) => only.includes(id)) : window;
543
548
  // #412: with profiling off no pass runs, but these games are over: their decision logs leave `active`
544
549
  // (no request; a log already closed costs one head read).
545
550
  if (deps.dataDir && !profileEnabled(deps.env))
546
- await finishDecisionLogs(deps.dataDir, window, me, { mode: decisionLogModeOf(deps.env) });
551
+ await finishDecisionLogs(deps.dataDir, scope, me, { mode: decisionLogModeOf(deps.env) });
552
+ const before = new Map();
553
+ if (report || reread)
554
+ for (const id of scope)
555
+ before.set(id, await gameStanding(deps, me, id));
547
556
  const todo = [];
548
- for (const id of window)
557
+ for (const id of scope) {
549
558
  if (await needsEndOfGame(deps.dataDir, deps.env, id, me))
550
- todo.push(id);
559
+ todo.push({ id, reread: false });
560
+ else if (reread && rereadWanted(before.get(id), reread))
561
+ todo.push({ id, reread: true });
562
+ }
551
563
  await refreshProcessed(deps, me, window).catch(() => undefined);
552
564
  const processed = [];
553
- for (const id of todo.slice(0, limit)) {
554
- const r = await endOfGame(deps, id, me, undefined, { fold: true, keep, protectIds: window });
555
- processed.push({ gameId: id, status: r.status, ...(r.turns !== undefined ? { turns: r.turns } : {}) });
565
+ const protectIds = only ? [...new Set([...window, ...scope])] : window;
566
+ for (const t of todo.slice(0, limit)) {
567
+ const r = await endOfGame(deps, t.id, me, undefined, { fold: true, keep, protectIds, ...(t.reread ? { reread: true } : {}) });
568
+ processed.push({
569
+ gameId: t.id,
570
+ status: r.status,
571
+ ...(t.reread ? { reread: true } : {}),
572
+ ...(r.turns !== undefined ? { turns: r.turns } : {}),
573
+ ...(r.failure ? { failure: failureCode(r.failure) } : {}),
574
+ ...(r.keptPrevious ? { keptPrevious: true } : {}),
575
+ });
576
+ }
577
+ const out = { processed, pending: Math.max(0, todo.length - limit) };
578
+ if (report) {
579
+ const thisCall = new Map(processed.map((p) => [p.gameId, p]));
580
+ const waiting = new Set(todo.slice(limit).map((t) => t.id));
581
+ const games = [];
582
+ for (const id of scope) {
583
+ const now = thisCall.has(id) ? await gameStanding(deps, me, id) : before.get(id);
584
+ const p = thisCall.get(id);
585
+ games.push({
586
+ gameId: id,
587
+ ...now,
588
+ ...(p ? { thisCall: p.reread ? 'reread' : 'read' } : waiting.has(id) ? { thisCall: 'waiting' } : {}),
589
+ });
590
+ }
591
+ out.games = games;
592
+ }
593
+ return out;
594
+ }
595
+ /** One game's standing from this server's state alone (no request). Never throws. */
596
+ export async function gameStanding(deps, me, gameId) {
597
+ const { dataDir, env } = deps;
598
+ if (!dataDir || !profileEnabled(env))
599
+ return { state: 'unknown' };
600
+ try {
601
+ const salt = await playerRecordSalt(dataDir);
602
+ if (!salt)
603
+ return { state: 'not-processed' };
604
+ const summary = await readFinishedSummary(finishedPath(dataDir, salt, me, gameId));
605
+ if (summary === 'unreadable')
606
+ return { state: 'record-unreadable' };
607
+ if (summary !== 'missing')
608
+ return { state: 'recorded', outdated: summary.collector < COLLECTOR_VERSION, ...summary };
609
+ return (await isMarked(dataDir, salt, me, gameId)) ? { state: 'processed-record-pruned' } : { state: 'not-processed' };
556
610
  }
557
- return { processed, pending: Math.max(0, todo.length - limit) };
611
+ catch {
612
+ return { state: 'unknown' };
613
+ }
614
+ }
615
+ /** Whether `reread` names a game in this standing. */
616
+ function rereadWanted(s, scope) {
617
+ if (s.state === 'processed-record-pruned')
618
+ return scope === 'all';
619
+ if (s.state !== 'recorded')
620
+ return false;
621
+ if (scope === 'all')
622
+ return true;
623
+ if (scope === 'failed')
624
+ return s.status !== 'captured';
625
+ return s.outdated;
626
+ }
627
+ /** A failure as the sweep reports it: codes only. */
628
+ function failureCode(f) {
629
+ return { reason: f.reason, ...('kind' in f && f.kind ? { kind: f.kind } : {}) };
558
630
  }
559
631
  /** Mark the window's records most recently used, so a prune drops a record outside the window first. */
560
632
  async function refreshProcessed(deps, me, window) {
@@ -20,7 +20,7 @@ import { backfillWinnerCurves } from './map-curves.js';
20
20
  import { CONFIRM_INJECTION_RULE, McpToolError, toolAnnotations } from '@chrischall/mcp-utils';
21
21
  import { mintUploadSlot, resolveUploadSource } from '@chrischall/mcp-utils/export';
22
22
  import { z } from 'zod';
23
- import { MAX_FINISHED_RECORDS } from '../finished-store.js';
23
+ import { COLLECTOR_VERSION, MAX_FINISHED_RECORDS } from '../finished-store.js';
24
24
  import { profileEnabled } from '../profile-store.js';
25
25
  import { applyImport, decodeBundle, MAX_BUNDLE_BYTES, planImport, StateBundleError, } from '../state-bundle.js';
26
26
  import { respond } from './common.js';
@@ -188,7 +188,15 @@ function registerBackfillTool(server, ctx, env) {
188
188
  'it) and kept name-free for the opponent profiles, map records and lessons — what warapp_my_games does two ' +
189
189
  'games per call. `window` widens how many of your newest finished games are considered (default 250, at ' +
190
190
  `most ${MAX_FINISHED_RECORDS}). Reports what it processed and how many remain; safe to call again until ` +
191
- '`remaining` is 0. It also gives map records kept before the winners\' income curves were those curves, from the ' +
191
+ '`remaining` is 0. `games` lists every game considered one by one, from this server\'s state (no request): ' +
192
+ 'recorded (captured, read-failed or history-unreadable, with the failure code, history turns, boards kept, ' +
193
+ 'stats version, collector version and `outdated` when kept under an older collector), not-processed, ' +
194
+ 'processed-record-pruned or record-unreadable, and what this call did to it (read, reread, waiting). ' +
195
+ '`game_ids` limits it to those games. `reread` reads the history AGAIN (one more GameFeed request per game) ' +
196
+ 'for games already processed — `failed` (read-failed or history-unreadable), `outdated` (kept under an older ' +
197
+ 'collector version, so newer metrics get captured) or `all` — and rebuilds the record and what was processed ' +
198
+ 'from it (each store replaces the game\'s share; nothing counts twice); a re-read that fails never replaces a ' +
199
+ 'captured record (`keptPrevious`). It also gives map records kept before the winners\' income curves were those curves, from the ' +
192
200
  'histories already kept (`winnerCurves`, no request). Writes only this server\'s state and never writes to war.app. ' +
193
201
  BRIDGE_NOTE,
194
202
  annotations: toolAnnotations({ title: 'Backfill finished war.app games', readOnly: false, destructive: false, idempotent: true, openWorld: true }),
@@ -201,8 +209,18 @@ function registerBackfillTool(server, ctx, env) {
201
209
  .max(MAX_FINISHED_RECORDS)
202
210
  .optional()
203
211
  .describe(`How many of your newest finished games to consider (default ${sweepWindow()}, max ${MAX_FINISHED_RECORDS}).`),
212
+ game_ids: z
213
+ .array(z.number().int().positive())
214
+ .min(1)
215
+ .max(MAX_FINISHED_RECORDS)
216
+ .optional()
217
+ .describe('Only these games (each a finished game of yours; others are listed in `notFinishedOrNotMine`).'),
218
+ reread: z
219
+ .enum(['failed', 'outdated', 'all'])
220
+ .optional()
221
+ .describe("Read again the history of games already processed: `failed` (read-failed or history-unreadable), `outdated` (kept under an older collector version) or `all`. One GameFeed request per game; default none."),
204
222
  }),
205
- }, async ({ limit, window }) => {
223
+ }, async ({ limit, window, game_ids, reread }) => {
206
224
  if (!ctx.dataDir)
207
225
  refuse('This server has no data directory, so no history can be kept.', 'Nothing to do here.');
208
226
  if (!profileEnabled(env))
@@ -216,7 +234,12 @@ function registerBackfillTool(server, ctx, env) {
216
234
  const r = await sweepFinished({ client: ctx.client, dataDir: ctx.dataDir, env }, token, ids, {
217
235
  limit: limit ?? BACKFILL_DEFAULT,
218
236
  window: size,
237
+ report: true,
238
+ ...(game_ids ? { only: game_ids } : {}),
239
+ ...(reread ? { reread } : {}),
219
240
  });
241
+ const finished = new Set(ids);
242
+ const notMine = game_ids ? [...new Set(game_ids)].filter((id) => !finished.has(id)) : [];
220
243
  // #419: entries kept before the winners' curves were, given them from the kept histories (no request).
221
244
  const winnerCurves = await backfillWinnerCurves(ctx.dataDir);
222
245
  return respond(undefined, ['compact'], () => ({
@@ -226,7 +249,10 @@ function registerBackfillTool(server, ctx, env) {
226
249
  remaining: r.pending,
227
250
  finishedGames: ids.length,
228
251
  window: size,
229
- ...(ids.length > size ? { outsideWindow: ids.length - size } : {}),
252
+ ...(ids.length > size && !game_ids ? { outsideWindow: ids.length - size } : {}),
253
+ collectorVersion: COLLECTOR_VERSION,
254
+ games: r.games ?? [],
255
+ ...(notMine.length ? { notFinishedOrNotMine: notMine } : {}),
230
256
  }));
231
257
  });
232
258
  }
package/dist/version.js CHANGED
@@ -1,4 +1,4 @@
1
1
  // Single source of truth for the server version. release-please bumps the
2
2
  // literal on the marked line (registered in release-please-config.json
3
3
  // extra-files); every other module imports VERSION from here.
4
- export const VERSION = '0.15.0'; // x-release-please-version
4
+ export const VERSION = '0.17.0'; // x-release-please-version
package/manifest.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "manifest_version": "0.3",
4
4
  "name": "warapp-mcp",
5
5
  "display_name": "war.app (Warzone)",
6
- "version": "0.15.0",
6
+ "version": "0.17.0",
7
7
  "description": "war.app (Warzone) game advisor for Claude — your games, maps, bonuses, board analysis and routes via the GameFeed API, plus your games list (waiting on you first), opponent scouting with your head-to-head, the live board, territory picks, cards, turn planning and submission, turn notifications, and chat through your signed-in war.app tab (ContextMint Bridge). Joining, leaving or surrendering a game, closing out a finished game, accepting another player's surrender, Begin on a speed first turn, picks, turn orders, withdrawing them, chat sends, marking notifications and chat read, deleting notifications, importing local history into a hosted server and linking a session (local only) are confirm-gated.",
8
8
  "author": {
9
9
  "name": "Chris Hall",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chrischall/warapp-mcp",
3
- "version": "0.15.0",
3
+ "version": "0.17.0",
4
4
  "mcpName": "io.github.chrischall/warapp-mcp",
5
5
  "description": "war.app (Warzone) game advisor MCP server for Claude — games, maps, bonuses and board analysis via the GameFeed API, plus your games list, opponent scouting, the live board, territory picks, cards, turn planning and submission, turn notifications and chat through your signed-in war.app tab. Developed and maintained by AI (Claude Code).",
6
6
  "author": "Claude Code (AI) <https://www.anthropic.com/claude>",
package/server.json CHANGED
@@ -6,12 +6,12 @@
6
6
  "url": "https://github.com/chrischall/warapp-mcp",
7
7
  "source": "github"
8
8
  },
9
- "version": "0.15.0",
9
+ "version": "0.17.0",
10
10
  "packages": [
11
11
  {
12
12
  "registryType": "npm",
13
13
  "identifier": "@chrischall/warapp-mcp",
14
- "version": "0.15.0",
14
+ "version": "0.17.0",
15
15
  "transport": {
16
16
  "type": "stdio"
17
17
  },