@chrischall/warapp-mcp 0.1.0 → 0.2.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 (74) hide show
  1. package/.claude-plugin/marketplace.json +3 -3
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +28 -17
  4. package/dist/analysis/accept-surrender.js +56 -0
  5. package/dist/analysis/calibrate.js +239 -0
  6. package/dist/analysis/finished-game.js +136 -0
  7. package/dist/analysis/game-lessons.js +217 -0
  8. package/dist/analysis/local-deploy.js +37 -17
  9. package/dist/analysis/opponent-profile.js +6 -5
  10. package/dist/analysis/opponents.js +10 -2
  11. package/dist/analysis/outlook.js +63 -1
  12. package/dist/analysis/plan/shared.js +194 -7
  13. package/dist/analysis/plan/threats.js +103 -29
  14. package/dist/analysis/planner.js +10 -5
  15. package/dist/analysis/stress.js +14 -7
  16. package/dist/analysis/whereabouts.js +3 -0
  17. package/dist/bundle.js +12392 -9245
  18. package/dist/calibration-source.js +75 -0
  19. package/dist/chat.js +73 -0
  20. package/dist/client.js +85 -7
  21. package/dist/finished-store.js +357 -0
  22. package/dist/index.js +1 -1
  23. package/dist/lessons-store.js +356 -0
  24. package/dist/live.js +9 -0
  25. package/dist/map-details.js +127 -0
  26. package/dist/map-stats.js +14 -6
  27. package/dist/map-store.js +44 -6
  28. package/dist/my-games.js +44 -6
  29. package/dist/normalize.js +34 -2
  30. package/dist/notifications.js +143 -0
  31. package/dist/outlook-log.js +28 -1
  32. package/dist/player-record-store.js +2 -0
  33. package/dist/profile-store.js +61 -11
  34. package/dist/protocol/methods.js +86 -2
  35. package/dist/replay.js +16 -4
  36. package/dist/stats.js +26 -4
  37. package/dist/strategy/notes.js +64 -9
  38. package/dist/surrender-pending.js +126 -0
  39. package/dist/tools/accept-surrender.js +311 -0
  40. package/dist/tools/chat-inbox.js +17 -5
  41. package/dist/tools/chat-read-mark.js +179 -0
  42. package/dist/tools/chat.js +50 -8
  43. package/dist/tools/check-plan.js +1 -0
  44. package/dist/tools/commander-check.js +1 -0
  45. package/dist/tools/end-of-game.js +384 -0
  46. package/dist/tools/game.js +31 -6
  47. package/dist/tools/index.js +15 -5
  48. package/dist/tools/live-context.js +1 -1
  49. package/dist/tools/map-details.js +88 -0
  50. package/dist/tools/map-stats.js +15 -2
  51. package/dist/tools/map.js +10 -2
  52. package/dist/tools/my-games.js +77 -7
  53. package/dist/tools/notifications.js +484 -0
  54. package/dist/tools/opponents.js +14 -2
  55. package/dist/tools/past-games.js +94 -0
  56. package/dist/tools/picks.js +15 -2
  57. package/dist/tools/profile-opponents.js +1 -1
  58. package/dist/tools/profile-reads.js +3 -3
  59. package/dist/tools/push.js +72 -12
  60. package/dist/tools/strategy.js +65 -8
  61. package/dist/tools/stress-opponents.js +1 -1
  62. package/dist/tools/surrender-pending.js +74 -0
  63. package/dist/tools/surrender.js +10 -3
  64. package/dist/tools/team.js +1 -5
  65. package/dist/tools/turn.js +79 -15
  66. package/dist/tools/where.js +42 -17
  67. package/dist/tools/write-kit.js +6 -0
  68. package/dist/trend.js +145 -20
  69. package/dist/version.js +1 -1
  70. package/manifest.json +22 -2
  71. package/mint.yaml +14 -9
  72. package/package.json +1 -1
  73. package/server.json +2 -2
  74. package/skills/warapp-mcp/SKILL.md +141 -14
@@ -0,0 +1,357 @@
1
+ // The end-of-game records (#312 E1; owner decisions P2–P4 of 2026-11-16): one file per finished game
2
+ // the account played, `<dataDir>/finished/<key>.json`, the key an HMAC of my account and the game
3
+ // under the one shared salt (`finishedGameKey`, src/player-record-store.ts), so no file name holds an
4
+ // id. NAME-FREE inside too: players by the deal record's `playerKey` under the same salt, never an id
5
+ // or a name; territory, bonus and map ids are the map's own, public data. No clock is kept.
6
+ // A captured record also keeps the history's boards (owners by key, delta-encoded), which the calibration
7
+ // harness (#318, scripts/calibrate.mjs) reads as its truth: it never reads a history of its own.
8
+ //
9
+ // The file is also the "processed" mark: the end-of-game pass (src/tools/end-of-game.ts) runs once per
10
+ // game, and a file of any status means it ran. `captured` holds the history's capture; `history-unreadable`
11
+ // (with #315's reason) and `read-failed` (the request failed) record a pass whose history did not come,
12
+ // and are never retried automatically (an explicit warapp_get_game with `include_history` may).
13
+ //
14
+ // The record bound would drop a processed mark, so every pass that spent its history read (its own
15
+ // request, or the history a caller read and handed it) also leaves a mark in
16
+ // `<dataDir>/finished/processed.json` (`markProcessed`): the record keys only (hashed, no id),
17
+ // at most `MAX_PROCESSED_KEYS` (ten times the record bound), the least recently marked dropped first. A
18
+ // game with a mark is never read again by a trigger even once its record is pruned (P2). The one
19
+ // remaining exception: a game whose record AND mark have both aged out (over 5000 later passes) reads
20
+ // again if a trigger names it. A marks file that does not parse is never overwritten (marks then rely
21
+ // on the records alone).
22
+ //
23
+ // A captured record keeps at most `MAX_RECORD_BOARDS_HEAD` opening boards and `MAX_RECORD_BOARDS_TAIL`
24
+ // closing ones (the opening benchmark reads the first, the calibration the turns the board cache kept,
25
+ // the last ten); `boardsOmitted` counts the boards between them that were left out.
26
+ //
27
+ // Same guarantees as the profile stores: 0600 files in a 0700 folder, atomic writes, best effort; at
28
+ // most `MAX_FINISHED_RECORDS` files, the least recently written (or refreshed by the sweep) dropped first, never
29
+ // one the writer protects (the sweep's window: its newest finished games, half the bound, so a processed
30
+ // game it lists never loses its mark and is never read again); a file that exists but
31
+ // does not parse (not JSON, not an object, another version) is never overwritten. `WARAPP_PLAYER_PROFILE=off`
32
+ // switches the pass off (nothing read or written).
33
+ import { readdir, readFile, stat, unlink, utimes } from 'node:fs/promises';
34
+ import { join } from 'node:path';
35
+ import { profileFormatOf } from './analysis/opponent-profile.js';
36
+ import { writeJsonAtomic } from './map-store.js';
37
+ import { finishedGameKey, playerKey } from './player-record-store.js';
38
+ import { holdsSeat } from './player-states.js';
39
+ import { withPathLock } from './path-lock.js';
40
+ export const MAX_FINISHED_RECORDS = 500;
41
+ /** The processed marks kept: ten times the record bound. */
42
+ export const MAX_PROCESSED_KEYS = 5000;
43
+ /** The opening boards a captured record keeps. */
44
+ export const MAX_RECORD_BOARDS_HEAD = 30;
45
+ /** The closing boards a captured record keeps. */
46
+ export const MAX_RECORD_BOARDS_TAIL = 30;
47
+ const VERSION = 1;
48
+ const FILE = /^[0-9a-f]{32}\.json$/;
49
+ export const finishedDir = (dir) => join(dir, 'finished');
50
+ export const finishedPath = (dir, salt, me, gameId) => join(finishedDir(dir), `${finishedGameKey(salt, me, gameId)}.json`);
51
+ /** The processed marks: not a record (its name is no key), so the prune and the record list skip it. */
52
+ export const processedPath = (dir) => join(finishedDir(dir), 'processed.json');
53
+ const KEY = /^[0-9a-f]{32}$/;
54
+ export const OWNER_NEUTRAL = -1;
55
+ export const OWNER_AVAILABLE = -2;
56
+ /** Fogged, or an owner that is no seated player's (its raw value is never kept). */
57
+ export const OWNER_UNKNOWN = -3;
58
+ const FOG_WORD = /^[A-Za-z0-9]{1,20}$/;
59
+ const isRec = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
60
+ const STATUSES = new Set(['captured', 'history-unreadable', 'read-failed']);
61
+ /**
62
+ * The record at `path`: `missing`, `unreadable` (exists, but not JSON, not an object, another version
63
+ * or an unknown status: never overwritten), or its status. Never throws.
64
+ */
65
+ export async function readFinishedState(path) {
66
+ let text;
67
+ try {
68
+ text = await readFile(path, 'utf8');
69
+ }
70
+ catch (e) {
71
+ return e.code === 'ENOENT' ? 'missing' : 'unreadable';
72
+ }
73
+ try {
74
+ const v = JSON.parse(text);
75
+ if (!isRec(v) || v.version !== VERSION || typeof v.status !== 'string' || !STATUSES.has(v.status))
76
+ return 'unreadable';
77
+ return { status: v.status };
78
+ }
79
+ catch {
80
+ return 'unreadable';
81
+ }
82
+ }
83
+ /**
84
+ * Write a record atomically (0600), then keep the newest {@link MAX_FINISHED_RECORDS}: never a path in
85
+ * `protect` (the sweep's window, src/tools/end-of-game.ts), nor the one just written. Throws on a failed write.
86
+ */
87
+ export async function writeFinishedRecord(dir, path, body, keep = MAX_FINISHED_RECORDS, protect) {
88
+ await writeJsonAtomic(path, finishedDir(dir), body);
89
+ await pruneFinished(dir, keep, new Set([...(protect ?? []), path])).catch(() => undefined);
90
+ }
91
+ /** Mark a record most recently used (a prune drops the least recently written or touched first). Never throws. */
92
+ export async function touchFinished(path) {
93
+ const now = new Date();
94
+ await utimes(path, now, now).catch(() => undefined);
95
+ }
96
+ /**
97
+ * The processed marks: the record keys of every game whose pass spent its history read, oldest first.
98
+ * Missing: none. `unreadable`: the file exists but does not parse (never overwritten). Never throws.
99
+ */
100
+ export async function readProcessed(dir) {
101
+ const keys = await readProcessedKeys(dir);
102
+ return keys === 'unreadable' ? keys : new Set(keys);
103
+ }
104
+ async function readProcessedKeys(dir) {
105
+ let text;
106
+ try {
107
+ text = await readFile(processedPath(dir), 'utf8');
108
+ }
109
+ catch (e) {
110
+ return e.code === 'ENOENT' ? [] : 'unreadable';
111
+ }
112
+ try {
113
+ const v = JSON.parse(text);
114
+ if (!isRec(v) || v.version !== VERSION || !Array.isArray(v.keys) || !v.keys.every((k) => typeof k === 'string' && KEY.test(k)))
115
+ return 'unreadable';
116
+ return v.keys;
117
+ }
118
+ catch {
119
+ return 'unreadable';
120
+ }
121
+ }
122
+ /**
123
+ * Mark `key` (a `finishedGameKey`) processed, newest, keeping at most `limit` marks (0600, atomic,
124
+ * under the path lock). `false` when the marks file does not parse (left as it is) or the write failed. Never throws.
125
+ */
126
+ export async function markProcessed(dir, key, limit = MAX_PROCESSED_KEYS) {
127
+ if (!KEY.test(key))
128
+ return false;
129
+ const path = processedPath(dir);
130
+ try {
131
+ return await withPathLock(path, async () => {
132
+ const keys = await readProcessedKeys(dir);
133
+ if (keys === 'unreadable')
134
+ return false;
135
+ const next = [...keys.filter((k) => k !== key), key];
136
+ await writeJsonAtomic(path, finishedDir(dir), { version: VERSION, keys: next.slice(Math.max(0, next.length - limit)) });
137
+ return true;
138
+ });
139
+ }
140
+ catch {
141
+ return false;
142
+ }
143
+ }
144
+ /** Every record file under `dir` (the marks file aside), by path, sorted. Never throws. */
145
+ export async function listFinishedRecords(dir) {
146
+ const names = await readdir(finishedDir(dir)).catch(() => []);
147
+ return names
148
+ .filter((n) => FILE.test(n))
149
+ .sort()
150
+ .map((n) => join(finishedDir(dir), n));
151
+ }
152
+ async function pruneFinished(dir, keep, protect) {
153
+ const folder = finishedDir(dir);
154
+ const files = [];
155
+ for (const name of await readdir(folder)) {
156
+ if (!FILE.test(name))
157
+ continue;
158
+ const path = join(folder, name);
159
+ try {
160
+ files.push({ path, at: (await stat(path)).mtimeMs });
161
+ }
162
+ catch {
163
+ // Gone already.
164
+ }
165
+ }
166
+ if (files.length <= keep)
167
+ return;
168
+ files.sort((a, b) => b.at - a.at || a.path.localeCompare(b.path));
169
+ let over = files.length - keep;
170
+ for (const f of [...files].reverse()) {
171
+ if (over <= 0)
172
+ break;
173
+ if (protect.has(f.path))
174
+ continue;
175
+ await unlink(f.path).catch(() => undefined);
176
+ over--;
177
+ }
178
+ }
179
+ /** The stored record: every player id replaced by its `playerKey`. Pure. */
180
+ export function finishedRecordOf(p) {
181
+ const key = (id) => playerKey(p.salt, id);
182
+ const owner = (o) => (typeof o === 'number' ? key(o) : o);
183
+ const keyed = (m) => Object.fromEntries([...m].map(([id, v]) => [key(id), v]));
184
+ const game = p.game;
185
+ const c = p.capture;
186
+ // The history's own parts only when it read.
187
+ const h = p.status === 'captured' ? c : undefined;
188
+ const kept = p.status === 'captured' && p.boards ? boundedBoards(p.boards) : undefined;
189
+ const stored = kept ? storeBoards(kept.boards, p.game?.players.map((x) => x.id) ?? [p.me], key) : undefined;
190
+ return {
191
+ version: VERSION,
192
+ status: p.status,
193
+ ...(p.failure ? { failure: p.failure } : {}),
194
+ ...(p.layout ? { layout: p.layout } : {}),
195
+ ...(p.mapId !== undefined ? { mapId: p.mapId } : {}),
196
+ ...(p.noMap ? { noMap: true } : {}),
197
+ ...(game ? { format: profileFormatOf(game.players), seats: game.players.filter((x) => holdsSeat(x.state)).length } : {}),
198
+ ...(p.settings ? { settings: p.settings } : {}),
199
+ me: key(p.me),
200
+ ...(game
201
+ ? {
202
+ players: game.players
203
+ .filter((x) => holdsSeat(x.state))
204
+ .map((x) => ({
205
+ key: key(x.id),
206
+ ai: x.isAI,
207
+ ...(x.humanTurnedIntoAI ? { turnedAI: true } : {}),
208
+ ...(x.team !== undefined && x.team !== null ? { team: x.team } : {}),
209
+ ...(x.state ? { state: x.state } : {}),
210
+ })),
211
+ }
212
+ : {}),
213
+ ...(c ? { outcome: { ...c.outcome, winners: c.outcome.winners.map(key) } } : {}),
214
+ ...(p.outlook ? { outlook: p.outlook } : {}),
215
+ ...(p.picks !== undefined ? { picks: p.picks } : {}),
216
+ ...(h ? { starts: keyed(h.starts) } : {}),
217
+ ...(h ? { turns: h.turns.map((t) => ({ afterTurn: t.afterTurn, players: keyed(t.players) })) } : {}),
218
+ ...(h
219
+ ? {
220
+ failedAttacks: h.failedAttacks.map((f) => ({
221
+ ...f,
222
+ before: { owner: owner(f.before.owner), armies: f.before.armies },
223
+ after: { owner: owner(f.after.owner), armies: f.after.armies },
224
+ })),
225
+ }
226
+ : {}),
227
+ ...(stored ?? {}),
228
+ ...(kept?.omitted ? { boardsOmitted: kept.omitted } : {}),
229
+ };
230
+ }
231
+ /** The opening and closing boards a record keeps, and how many between them it leaves out. Pure. */
232
+ function boundedBoards(boards) {
233
+ const max = MAX_RECORD_BOARDS_HEAD + MAX_RECORD_BOARDS_TAIL;
234
+ if (boards.length <= max)
235
+ return { boards, omitted: 0 };
236
+ return { boards: [...boards.slice(0, MAX_RECORD_BOARDS_HEAD), ...boards.slice(boards.length - MAX_RECORD_BOARDS_TAIL)], omitted: boards.length - max };
237
+ }
238
+ /** The boards in their stored shape: owners by key (only the game's players; any other owner is unknown). Pure. */
239
+ function storeBoards(boards, ids, key) {
240
+ const known = new Set(ids);
241
+ const index = new Map();
242
+ const owners = [];
243
+ const ownerOf = (o) => {
244
+ if (o.kind === 'neutral')
245
+ return OWNER_NEUTRAL;
246
+ if (o.kind === 'available')
247
+ return OWNER_AVAILABLE;
248
+ if (o.kind !== 'player' || !known.has(o.playerId))
249
+ return OWNER_UNKNOWN;
250
+ let i = index.get(o.playerId);
251
+ if (i === undefined) {
252
+ i = owners.push(key(o.playerId)) - 1;
253
+ index.set(o.playerId, i);
254
+ }
255
+ return i;
256
+ };
257
+ const rowOf = (x) => {
258
+ const row = [x.territoryId, ownerOf(x.owner), x.armies];
259
+ return x.fogLevel && x.fogLevel !== 'Visible' && FOG_WORD.test(x.fogLevel) ? [...row, x.fogLevel] : row;
260
+ };
261
+ let prev;
262
+ const out = [];
263
+ for (const { turn, board } of boards) {
264
+ const rows = board.territories.map(rowOf);
265
+ const before = prev;
266
+ const sameList = before !== undefined && before.length === rows.length && rows.every((r, i) => r[0] === before[i][0]);
267
+ out.push(sameList ? { turn, d: true, t: rows.filter((r, i) => JSON.stringify(r) !== JSON.stringify(before[i])) } : { turn, t: rows });
268
+ prev = rows;
269
+ }
270
+ return { boardOwners: owners, boards: out };
271
+ }
272
+ /**
273
+ * The record at `path`: `missing`, `unreadable` (as {@link readFinishedState}), or the record itself.
274
+ * Never throws. The harness's reader (scripts/calibrate.mjs); the pass needs only the state.
275
+ */
276
+ export async function readFinishedRecord(path) {
277
+ const state = await readFinishedState(path);
278
+ if (typeof state === 'string')
279
+ return state;
280
+ try {
281
+ return JSON.parse(await readFile(path, 'utf8'));
282
+ }
283
+ catch {
284
+ return 'unreadable';
285
+ }
286
+ }
287
+ /**
288
+ * The history a captured record keeps, its keys matched against `ids` (the players the caller already
289
+ * knows by id: a key is never reversed). `no-boards`: not captured, or captured without its boards;
290
+ * `unmatched`: my key is none of `ids`. A seat matching none is left out, and land it owned reads as
291
+ * an unknown owner. Pure.
292
+ */
293
+ export function historyOfRecord(rec, salt, ids) {
294
+ if (!hasBoards(rec))
295
+ return 'no-boards';
296
+ const byKey = new Map(ids.map((id) => [playerKey(salt, id), id]));
297
+ if (!byKey.has(rec.me))
298
+ return 'unmatched';
299
+ return decodeHistory(rec, byKey);
300
+ }
301
+ /**
302
+ * The history a captured record keeps when the ids of its game are not known (#318: the game's settings
303
+ * record aged out): each player labelled by position, me 1, then the seats in the record's order, then
304
+ * any other board owner. A key is never reversed: the labels say who is who within the record only. Pure.
305
+ */
306
+ export function anonymousHistoryOfRecord(rec) {
307
+ if (!hasBoards(rec))
308
+ return 'no-boards';
309
+ const byKey = new Map();
310
+ for (const k of [rec.me, ...(rec.players ?? []).map((p) => p.key), ...rec.boardOwners])
311
+ if (!byKey.has(k))
312
+ byKey.set(k, byKey.size + 1);
313
+ const h = decodeHistory(rec, byKey);
314
+ // Me first among the players.
315
+ h.players.sort((a, b) => a.id - b.id);
316
+ return h;
317
+ }
318
+ const hasBoards = (rec) => rec.status === 'captured' && Array.isArray(rec.boards) && Array.isArray(rec.boardOwners);
319
+ function decodeHistory(rec, byKey) {
320
+ const me = byKey.get(rec.me);
321
+ const owners = rec.boardOwners.map((k) => byKey.get(k));
322
+ const ownerOf = (o) => {
323
+ if (o === OWNER_NEUTRAL)
324
+ return { kind: 'neutral' };
325
+ if (o === OWNER_AVAILABLE)
326
+ return { kind: 'available' };
327
+ const id = owners[o];
328
+ return id === undefined ? { kind: 'unknown' } : { kind: 'player', playerId: id };
329
+ };
330
+ const players = [];
331
+ for (const p of rec.players ?? []) {
332
+ const id = byKey.get(p.key);
333
+ if (id === undefined)
334
+ continue;
335
+ players.push({ id, isAI: p.ai, ...(p.team !== undefined ? { team: p.team } : {}), ...(p.state !== undefined ? { state: p.state } : {}) });
336
+ }
337
+ const territoryOf = ([territoryId, owner, armies, fogLevel]) => ({
338
+ territoryId,
339
+ owner: ownerOf(owner),
340
+ armies,
341
+ ...(fogLevel !== undefined ? { fogLevel } : {}),
342
+ });
343
+ const boards = [];
344
+ let prev;
345
+ for (const { turn, d, t } of rec.boards) {
346
+ let territories;
347
+ if (d && prev) {
348
+ const changed = new Map(t.map((row) => [row[0], territoryOf(row)]));
349
+ territories = prev.map((x) => changed.get(x.territoryId) ?? { ...x });
350
+ }
351
+ else
352
+ territories = t.map(territoryOf);
353
+ boards.push({ turn, board: { source: 'gamefeed', verified: false, territories } });
354
+ prev = territories;
355
+ }
356
+ return { me, numberOfTurns: rec.outcome?.turn ?? null, players, boards };
357
+ }
package/dist/index.js CHANGED
@@ -28,6 +28,6 @@ await runMcp({
28
28
  version: VERSION,
29
29
  tools: [(server) => registerAllTools(server, { bridge })],
30
30
  shutdown: { onSignal: () => bridge.transport().close() },
31
- banner: `[warapp-mcp] v${VERSION} — war.app (Warzone) advisor; joining, leaving or surrendering a game, Begin, picks, turn orders, withdrawing them, chat and linking a session are confirm-gated. Set WARAPP_EMAIL and WARAPP_API_TOKEN. ` +
31
+ banner: `[warapp-mcp] v${VERSION} — war.app (Warzone) advisor; joining, leaving or surrendering a game, accepting a surrender, Begin, picks, turn orders, withdrawing them, chat, marking notifications and chat read, deleting notifications and linking a session are confirm-gated. Set WARAPP_EMAIL and WARAPP_API_TOKEN. ` +
32
32
  'This project was developed and is maintained by AI (Claude). Use at your own discretion.',
33
33
  });