@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,484 @@
1
+ // warapp_get_notifications, warapp_dismiss_notification and warapp_delete_notification (#311): war.app's
2
+ // in-app notifications (the client's "In App Notifications" screen), read with GetInAppNotifications (317),
3
+ // marked read with AcknowledgeInAppNotifications (319) and deleted with DeleteInAppNotification (318, the
4
+ // client's Delete button). All read from the client bundle, UNVERIFIED live (docs/WEB-PROTOCOL.md,
5
+ // Notifications and read marks).
6
+ //
7
+ // The list is name-free beyond ids: a notification's title and data are war.app's text with other
8
+ // players' names in it, read only to classify the notification and find the game its link names.
9
+ // A game-ended notification runs the end-of-game pass on that game (#312, src/tools/end-of-game.ts:
10
+ // idempotent, one history read per game, at most END_OF_GAME_PER_CALL per call), which folds its live
11
+ // profile too; then any kept opponent profile still unfolded is folded (B2, `foldFinishedGame`) — one
12
+ // GameFeed read (no map) only when one is kept unfolded, none otherwise.
13
+ //
14
+ // Dismissing marks read and never deletes; deleting is its own tool, one 318 per id, error 699 read as
15
+ // already gone. Neither sends anything to any player. Automated chat stays off (D2): neither is a send.
16
+ import { CONFIRM_INJECTION_RULE, toolAnnotations } from '@chrischall/mcp-utils';
17
+ import { z } from 'zod';
18
+ import { classifyNotification, readInAppNotifications } from '../notifications.js';
19
+ import { foldFinishedGame, hasUnfoldedProfile, profileEnabled } from '../profile-store.js';
20
+ import { END_OF_GAME_PER_CALL, endOfGame, finishedAccount, needsEndOfGame } from './end-of-game.js';
21
+ import { Method, NOTIFICATION_ID, NOTIFICATION_NOT_FOUND, NOTIFICATIONS_PAGE_SIZE, writeAcknowledgeInAppNotificationsParams, writeDeleteInAppNotificationParams, writeGetInAppNotificationsParams, } from '../protocol/methods.js';
22
+ import { notSent, WarappServerError } from '../protocol/rpc.js';
23
+ import { readAnnotations, respond, untrustedDescription } from './common.js';
24
+ import { mintMeta } from './hints.js';
25
+ import { requireApprovedAccount, writeAccount } from './live-context.js';
26
+ import { BRIDGE_NOTE } from './live.js';
27
+ import { defineGatedWrite, refuse, requireMe, sendAndVerify } from './write-kit.js';
28
+ /** Every answer says so: nothing here has been checked against a real reply. */
29
+ export const NOTIFICATIONS_UNVERIFIED = "Read from war.app's client code, UNVERIFIED live: the notification list, its fields and how a game-ended " +
30
+ 'notification is recognised have not been checked against a real reply yet.';
31
+ /** The most games one list call reads from GameFeed to fold a kept profile. */
32
+ export const FOLD_LOOKUPS = 5;
33
+ /** The most pages a dismissal reads to find its ids (and to read them back). */
34
+ export const MAX_FIND_PAGES = 5;
35
+ /** The most ids one dismissal (or deletion) takes. */
36
+ export const MAX_DISMISS_IDS = NOTIFICATIONS_PAGE_SIZE;
37
+ /** One page of the account's notifications, from `start`. */
38
+ async function listPage(ctx, start) {
39
+ const env = await ctx.rpc.call('GetInAppNotifications', Method.GetInAppNotifications, (w) => writeGetInAppNotificationsParams(w, start));
40
+ return readInAppNotifications(await ctx.bundle(), env.body);
41
+ }
42
+ /** The notifications among `ids` the list holds, read page by page until all are found (at most MAX_FIND_PAGES). */
43
+ async function findNotifications(ctx, ids) {
44
+ const want = new Set(ids);
45
+ const found = new Map();
46
+ const positions = new Map();
47
+ let start = 0;
48
+ let total = 0;
49
+ let complete = false;
50
+ for (let page = 0; page < MAX_FIND_PAGES; page++) {
51
+ const listed = await listPage(ctx, start);
52
+ total = listed.total;
53
+ listed.items.forEach((n, i) => {
54
+ if (want.has(n.id) && !found.has(n.id)) {
55
+ found.set(n.id, n);
56
+ positions.set(n.id, start + i);
57
+ }
58
+ });
59
+ start += listed.items.length;
60
+ if (listed.items.length === 0 || start >= total) {
61
+ complete = true;
62
+ break;
63
+ }
64
+ if (found.size === want.size)
65
+ break;
66
+ }
67
+ return { found, positions, readTo: start, total, complete };
68
+ }
69
+ /**
70
+ * An id the read-back did not find is seen gone only when the pages read cover the whole list, or
71
+ * reach past where it stood when planned by as many notifications as the list has grown since (new
72
+ * ones arrive at the top and push it down). Otherwise it is simply not seen: never confirmed.
73
+ */
74
+ export function seenGone(after, position, totalBefore) {
75
+ if (after.complete)
76
+ return true;
77
+ if (position === undefined)
78
+ return false;
79
+ return after.readTo > position + Math.max(0, after.total - totalBefore);
80
+ }
81
+ /**
82
+ * The end-of-game pass on each game a game-ended notification names (#312: the fourth trigger, beside
83
+ * warapp_get_game, warapp_wait_for_turn's read and the warapp_my_games sweep), through the same idempotent
84
+ * `endOfGame`: a game with a record or a processed mark costs nothing; at most `END_OF_GAME_PER_CALL` games
85
+ * that still need it per call, in the list's order (the rest are `pending`, for a later list call), each
86
+ * ONE history read (P2), folding its live profile too. The account is the board cache's, else the
87
+ * signed-in one (read at most once per call). Never throws.
88
+ */
89
+ async function passEndedGames(ctx, env, games) {
90
+ const dir = ctx.dataDir;
91
+ const processed = [];
92
+ let pending = 0;
93
+ if (!dir || !profileEnabled(env))
94
+ return { processed, pending };
95
+ let token;
96
+ const identity = () => (token ??= ctx.myInviteToken().catch(() => undefined));
97
+ for (const gameId of games) {
98
+ const me = await finishedAccount(dir, env, gameId, identity);
99
+ if (me === undefined || !(await needsEndOfGame(dir, env, gameId, me)))
100
+ continue;
101
+ if (processed.length >= END_OF_GAME_PER_CALL) {
102
+ pending++;
103
+ continue;
104
+ }
105
+ const r = await endOfGame({ client: ctx.client, dataDir: dir, env }, gameId, me, undefined, { fold: true });
106
+ processed.push({ gameId, status: r.status, ...(r.turns !== undefined ? { turns: r.turns } : {}), ...(r.profileFold ? { profileFold: r.profileFold.status } : {}) });
107
+ }
108
+ return { processed, pending };
109
+ }
110
+ /**
111
+ * Fold the kept opponent profile of each game a game-ended notification names (B2): only where a
112
+ * per-game file is kept unfolded, one GameFeed read (no map) per such game, at most FOLD_LOOKUPS.
113
+ * Runs after the end-of-game pass, which folds a game it reads itself (so that game costs no read here).
114
+ * Best effort: a failed read folds nothing and is never an error.
115
+ */
116
+ async function foldEndedGames(ctx, env, games) {
117
+ const dir = ctx.dataDir;
118
+ if (!dir || !profileEnabled(env))
119
+ return [];
120
+ const out = [];
121
+ let lookups = 0;
122
+ for (const gameId of games) {
123
+ if (lookups >= FOLD_LOOKUPS)
124
+ break;
125
+ if (!(await hasUnfoldedProfile(dir, gameId)))
126
+ continue;
127
+ lookups++;
128
+ try {
129
+ const game = await ctx.client.getGame(gameId, { map: false });
130
+ const files = game.state === 'Finished' ? await foldFinishedGame(dir, game, env) : 0;
131
+ if (files > 0)
132
+ out.push({ gameId, files });
133
+ }
134
+ catch {
135
+ // Best effort: the next read that shows the game finished folds it.
136
+ }
137
+ }
138
+ return out;
139
+ }
140
+ /** The games the game-ended notifications name, once each, in the list's order. */
141
+ const endedGames = (notes) => [
142
+ ...new Set(notes.filter((n) => n.kind === 'game-ended' && n.gameId !== null).map((n) => n.gameId)),
143
+ ];
144
+ const idArg = z.union([z.string(), z.number().int().nonnegative()]);
145
+ /** Clean, validated notification ids, or a refusal naming the bad ones. */
146
+ function askedIds(ids) {
147
+ const asked = [...new Set(ids.map((id) => String(id).trim()))];
148
+ const bad = asked.filter((id) => !NOTIFICATION_ID.test(id));
149
+ if (bad.length) {
150
+ refuse(`Not a notification id: ${bad.slice(0, 5).join(', ')}. Nothing was sent.`, 'Use the ids warapp_get_notifications lists.');
151
+ }
152
+ return asked;
153
+ }
154
+ export function registerNotificationTools(server, ctx, opts = {}) {
155
+ const env = opts.env ?? process.env;
156
+ server.registerTool('warapp_get_notifications', {
157
+ title: 'List my war.app notifications',
158
+ description: untrustedDescription("Your war.app (Warzone) in-app notifications (the client's notifications screen, war.app's " +
159
+ 'GetInAppNotifications), 30 per page, by id only: each with `id` (what warapp_dismiss_notification takes), ' +
160
+ '`kind` (`game-ended` when the title is war.app\'s "Game … has ended." line, else `other`), `gameId` (the ' +
161
+ 'game its link names, or null), `time` and `unread`. The title and body are never shown (they carry other ' +
162
+ "players' names). " +
163
+ '`total` is how many notifications war.app holds; pass `next` back as `start` for the next page; ' +
164
+ '`unread_only` keeps the unread ones of the page. A game-ended notification runs the end-of-game pass on ' +
165
+ 'that game once (`endOfGame`: its history read once from GameFeed and kept name-free for later games, at most ' +
166
+ 'two games per call, `pending` counting the rest; a game already processed costs nothing) and folds the ' +
167
+ 'opponent profile kept for it (`profilesFolded`, or the pass entry\'s `profileFold`). Chat is not here: warapp_chat_inbox reads it. ' +
168
+ `${BRIDGE_NOTE} Read-only. ${NOTIFICATIONS_UNVERIFIED}`),
169
+ _meta: mintMeta('whats-new', ['notifications', 'war.app notifications', 'my alerts', 'did a game end']),
170
+ annotations: readAnnotations('List war.app notifications'),
171
+ inputSchema: z.object({
172
+ start: z.number().int().min(0).max(1_000_000).optional().describe('The paging offset (default 0, the newest page): `next` from the last answer.'),
173
+ unread_only: z.boolean().optional().describe('Show only the unread notifications of the page (default false).'),
174
+ }),
175
+ }, async ({ start, unread_only }) => {
176
+ const from = start ?? 0;
177
+ const { items, total } = await listPage(ctx, from);
178
+ const all = items.map(classifyNotification);
179
+ const notifications = unread_only ? all.filter((n) => n.unread) : all;
180
+ // #312: the end-of-game pass first (it folds the games it reads), then the fold of any kept profile left.
181
+ const ended = endedGames(all);
182
+ const passes = await passEndedGames(ctx, env, ended);
183
+ const profilesFolded = await foldEndedGames(ctx, env, ended);
184
+ const next = from + items.length < total && items.length > 0 ? from + items.length : undefined;
185
+ return respond(undefined, ['compact'], () => ({
186
+ notifications,
187
+ count: notifications.length,
188
+ unread: all.filter((n) => n.unread).length,
189
+ total,
190
+ ...(next !== undefined ? { next } : {}),
191
+ ...(profilesFolded.length ? { profilesFolded } : {}),
192
+ ...(passes.processed.length || passes.pending ? { endOfGame: passes } : {}),
193
+ unverified: NOTIFICATIONS_UNVERIFIED,
194
+ }));
195
+ });
196
+ defineGatedWrite(server, {
197
+ title: 'Mark war.app notifications read',
198
+ _meta: mintMeta('change', ['dismiss notification', 'mark notification read', 'clear my notifications']),
199
+ }, {
200
+ name: 'warapp_dismiss_notification',
201
+ description: 'Mark one or several war.app (Warzone) in-app notifications read (war.app\'s AcknowledgeInAppNotifications), ' +
202
+ 'by the ids warapp_get_notifications lists. It never deletes a notification (warapp_delete_notification does) ' +
203
+ 'and sends nothing to any player. ' +
204
+ 'Refuses ids war.app does not list and ids already read. Always as the signed-in war.app account; the outcome ' +
205
+ 'is read back by listing again (`dismissed`; `unconfirmed` while one still reads unread or was not seen in the ' +
206
+ 'pages read back; or `unknown` when ' +
207
+ `war.app did not answer — never resend blindly). ${NOTIFICATIONS_UNVERIFIED} ${BRIDGE_NOTE} ${CONFIRM_INJECTION_RULE}`,
208
+ annotations: toolAnnotations({
209
+ title: 'Mark war.app notifications read',
210
+ readOnly: false,
211
+ destructive: false,
212
+ idempotent: true,
213
+ openWorld: true,
214
+ }),
215
+ inputSchema: z.object({
216
+ ids: z
217
+ .array(idArg)
218
+ .min(1)
219
+ .max(MAX_DISMISS_IDS)
220
+ .describe('Notification ids from warapp_get_notifications (decimal text).'),
221
+ }),
222
+ async plan({ ids }) {
223
+ const asked = askedIds(ids);
224
+ const me = await requireMe(ctx);
225
+ const { found, positions, total } = await findNotifications(ctx, asked);
226
+ const missing = asked.filter((id) => !found.has(id));
227
+ if (missing.length) {
228
+ refuse(`war.app does not list notification ${missing.join(', ')}, so nothing was sent.`, 'List them again with warapp_get_notifications: it may already be deleted.');
229
+ }
230
+ const unread = asked.filter((id) => found.get(id).unread);
231
+ const alreadyRead = asked.filter((id) => !found.get(id).unread);
232
+ if (!unread.length) {
233
+ refuse(`Notification ${alreadyRead.join(', ')} is already read, so there is nothing to send.`, 'Check warapp_get_notifications.');
234
+ }
235
+ const shown = unread.map((id) => {
236
+ const n = classifyNotification(found.get(id));
237
+ return { id: n.id, kind: n.kind, gameId: n.gameId, time: n.time };
238
+ });
239
+ const label = unread.length === 1 ? `notification ${unread[0]}` : `${unread.length} notifications (${unread.join(', ')})`;
240
+ return {
241
+ gate: {
242
+ action: 'warapp.dismiss_notification',
243
+ // By id only: a notification's title and body are war.app's text with other players' names.
244
+ summary: `Mark war.app ${label} read`,
245
+ account: writeAccount(me),
246
+ target: unread.join(','),
247
+ payload: { method: 'AcknowledgeInAppNotifications', ids: unread },
248
+ willSend: { ids: unread },
249
+ preview: {
250
+ warning: `This marks ${label} read on war.app. Nothing is deleted and nothing reaches another player.`,
251
+ account: `war.app account ${me}`,
252
+ notifications: shown,
253
+ ...(alreadyRead.length ? { alreadyRead } : {}),
254
+ unverified: NOTIFICATIONS_UNVERIFIED,
255
+ },
256
+ },
257
+ state: {
258
+ me,
259
+ ids: unread,
260
+ alreadyRead,
261
+ positions: Object.fromEntries(unread.map((id) => [id, positions.get(id)])),
262
+ totalBefore: total,
263
+ },
264
+ };
265
+ },
266
+ async execute({ me, ids, alreadyRead, positions, totalBefore }) {
267
+ await requireApprovedAccount(ctx, writeAccount(me));
268
+ const base = { ids, ...(alreadyRead.length ? { alreadyRead } : {}) };
269
+ const check = 'Check warapp_get_notifications before doing anything else.';
270
+ return sendAndVerify({
271
+ send: async () => {
272
+ await ctx.rpc.call('AcknowledgeInAppNotifications', Method.AcknowledgeInAppNotifications, (w) => writeAcknowledgeInAppNotificationsParams(w, ids));
273
+ },
274
+ unanswered: (failure) => ({
275
+ status: 'unknown',
276
+ outcome: 'unknown',
277
+ ...base,
278
+ warning: `war.app did not confirm (${failure}), so the notifications may already be marked read. ${check}`,
279
+ }),
280
+ readBack: () => findNotifications(ctx, ids),
281
+ unreadable: (failure) => ({
282
+ status: 'unconfirmed',
283
+ outcome: 'unconfirmed',
284
+ ...base,
285
+ warning: `war.app accepted the request, but the list could not be read back (${failure}). ${check}`,
286
+ }),
287
+ classify: (after) => {
288
+ // Read on the list, or seen gone from it (deleted): no longer unread. Not found where the pages
289
+ // read could not tell: not seen, so never confirmed.
290
+ const stillUnread = ids.filter((id) => after.found.get(id)?.unread === true);
291
+ const dismissed = ids.filter((id) => after.found.get(id)?.unread === false);
292
+ const missing = ids.filter((id) => !after.found.has(id));
293
+ const gone = missing.filter((id) => seenGone(after, positions[id], totalBefore));
294
+ const notSeen = missing.filter((id) => !gone.includes(id));
295
+ const parts = {
296
+ ...(dismissed.length ? { dismissed } : {}),
297
+ ...(gone.length ? { gone } : {}),
298
+ };
299
+ if (!stillUnread.length && !notSeen.length) {
300
+ return { status: 'dismissed', outcome: 'confirmed', ...base, ...parts };
301
+ }
302
+ const problems = [
303
+ ...(stillUnread.length ? [`the list still shows ${stillUnread.join(', ')} unread`] : []),
304
+ ...(notSeen.length
305
+ ? [`${notSeen.join(', ')} ${notSeen.length === 1 ? 'was' : 'were'} not seen in the pages read (${after.readTo} of ${after.total})`]
306
+ : []),
307
+ ];
308
+ return {
309
+ status: 'unconfirmed',
310
+ outcome: 'unconfirmed',
311
+ ...base,
312
+ ...parts,
313
+ ...(stillUnread.length ? { stillUnread } : {}),
314
+ ...(notSeen.length ? { notSeen } : {}),
315
+ warning: `war.app accepted the request, but ${problems.join(', and ')}. ${check}`,
316
+ };
317
+ },
318
+ });
319
+ },
320
+ });
321
+ defineGatedWrite(server, {
322
+ title: 'Delete war.app notifications',
323
+ _meta: mintMeta('change', ['delete notification', 'remove notification', 'clear old notifications']),
324
+ }, {
325
+ name: 'warapp_delete_notification',
326
+ description: "Delete one or several war.app (Warzone) in-app notifications (war.app's DeleteInAppNotification, the client's " +
327
+ 'Delete button), by the ids warapp_get_notifications lists, read or unread: one request per id, in order. A ' +
328
+ 'deleted notification is gone from war.app for good; it sends nothing to any player (to keep it and only clear ' +
329
+ 'its unread mark, use warapp_dismiss_notification). Refuses ids war.app does not list. Always as the signed-in ' +
330
+ 'war.app account; an id war.app no longer holds when sent (its error 699) counts as already gone (`alreadyGone`). ' +
331
+ 'The outcome is read back by listing again (`deleted`; `unconfirmed` while one is still listed, was not seen in ' +
332
+ 'the pages read back, or war.app refused one — the ids after a refusal are not sent; or `unknown` when war.app ' +
333
+ `did not answer — never resend blindly). ${NOTIFICATIONS_UNVERIFIED} ${BRIDGE_NOTE} ${CONFIRM_INJECTION_RULE}`,
334
+ annotations: toolAnnotations({
335
+ title: 'Delete war.app notifications',
336
+ readOnly: false,
337
+ destructive: true,
338
+ idempotent: true,
339
+ openWorld: true,
340
+ }),
341
+ inputSchema: z.object({
342
+ ids: z
343
+ .array(idArg)
344
+ .min(1)
345
+ .max(MAX_DISMISS_IDS)
346
+ .describe('Notification ids from warapp_get_notifications (decimal text).'),
347
+ }),
348
+ async plan({ ids }) {
349
+ const asked = askedIds(ids);
350
+ const me = await requireMe(ctx);
351
+ const { found, positions, total } = await findNotifications(ctx, asked);
352
+ const missing = asked.filter((id) => !found.has(id));
353
+ if (missing.length) {
354
+ refuse(`war.app does not list notification ${missing.join(', ')}, so nothing was sent.`, 'List them again with warapp_get_notifications: it may already be deleted.');
355
+ }
356
+ const shown = asked.map((id) => {
357
+ const n = classifyNotification(found.get(id));
358
+ return { id: n.id, kind: n.kind, gameId: n.gameId, time: n.time, unread: n.unread };
359
+ });
360
+ const label = asked.length === 1 ? `notification ${asked[0]}` : `${asked.length} notifications (${asked.join(', ')})`;
361
+ return {
362
+ gate: {
363
+ action: 'warapp.delete_notification',
364
+ // By id only: a notification's title and body are war.app's text with other players' names.
365
+ summary: `Delete war.app ${label}`,
366
+ account: writeAccount(me),
367
+ target: asked.join(','),
368
+ payload: { method: 'DeleteInAppNotification', ids: asked },
369
+ willSend: { ids: asked },
370
+ preview: {
371
+ warning: `This deletes ${label} from your war.app notifications; it cannot be undone. Nothing reaches another player.`,
372
+ account: `war.app account ${me}`,
373
+ notifications: shown,
374
+ unverified: NOTIFICATIONS_UNVERIFIED,
375
+ },
376
+ },
377
+ state: {
378
+ me,
379
+ ids: asked,
380
+ positions: Object.fromEntries(asked.map((id) => [id, positions.get(id)])),
381
+ totalBefore: total,
382
+ },
383
+ };
384
+ },
385
+ async execute({ me, ids, positions, totalBefore }) {
386
+ await requireApprovedAccount(ctx, writeAccount(me));
387
+ const check = 'Check warapp_get_notifications before doing anything else.';
388
+ const sends = { sent: [], alreadyGone: [], notSent: [] };
389
+ const progress = () => ({
390
+ ...(sends.alreadyGone.length ? { alreadyGone: sends.alreadyGone } : {}),
391
+ ...(sends.refused ? { refused: sends.refused } : {}),
392
+ ...(sends.notSent.length ? { notSent: sends.notSent } : {}),
393
+ });
394
+ return sendAndVerify({
395
+ // One request per id, in order, never retried. A refusal (other than 699), no answer or a request that
396
+ // could not be sent stops there: the ids after it are not sent. A refusal or an unsent request before
397
+ // anything changed is an error; after, it is reported and the read-back judges what did change.
398
+ send: async () => {
399
+ for (const [i, id] of ids.entries()) {
400
+ try {
401
+ await ctx.rpc.call('DeleteInAppNotification', Method.DeleteInAppNotification, (w) => writeDeleteInAppNotificationParams(w, id));
402
+ sends.sent.push(id);
403
+ }
404
+ catch (e) {
405
+ if (e instanceof WarappServerError && e.code === NOTIFICATION_NOT_FOUND) {
406
+ sends.alreadyGone.push(id);
407
+ continue;
408
+ }
409
+ sends.notSent = ids.slice(i + 1);
410
+ const changed = sends.sent.length + sends.alreadyGone.length > 0;
411
+ if (changed && notSent(e)) {
412
+ // Never "nothing changed": earlier ids went. This one never left, so it is not sent either.
413
+ sends.unsent = id;
414
+ sends.notSent = ids.slice(i);
415
+ return;
416
+ }
417
+ if (e instanceof WarappServerError) {
418
+ if (!changed)
419
+ throw e;
420
+ sends.refused = { id, code: e.code };
421
+ return;
422
+ }
423
+ sends.unanswered = id;
424
+ throw e;
425
+ }
426
+ }
427
+ },
428
+ unanswered: (failure) => ({
429
+ status: 'unknown',
430
+ outcome: 'unknown',
431
+ ids,
432
+ ...(sends.sent.length ? { sent: sends.sent } : {}),
433
+ ...(sends.unanswered ? { unanswered: sends.unanswered } : {}),
434
+ ...progress(),
435
+ warning: `war.app did not confirm (${failure}), so notification ${sends.unanswered ?? ids[0]} may already be deleted` +
436
+ `${sends.notSent.length ? `; ${sends.notSent.join(', ')} ${sends.notSent.length === 1 ? 'was' : 'were'} not sent` : ''}. ${check}`,
437
+ }),
438
+ readBack: () => findNotifications(ctx, ids),
439
+ unreadable: (failure) => ({
440
+ status: 'unconfirmed',
441
+ outcome: 'unconfirmed',
442
+ ids,
443
+ ...(sends.sent.length ? { sent: sends.sent } : {}),
444
+ ...progress(),
445
+ warning: `war.app accepted the request, but the list could not be read back (${failure}). ${check}`,
446
+ }),
447
+ classify: (after) => {
448
+ // Each id sent (or already gone) is deleted only once seen gone; one still listed, or not found where
449
+ // the pages read could not tell, is not confirmed.
450
+ const tried = [...sends.sent, ...sends.alreadyGone];
451
+ const stillListed = tried.filter((id) => after.found.has(id));
452
+ const missing = tried.filter((id) => !after.found.has(id));
453
+ const gone = missing.filter((id) => seenGone(after, positions[id], totalBefore));
454
+ const notSeen = missing.filter((id) => !gone.includes(id));
455
+ const deleted = gone.filter((id) => sends.sent.includes(id));
456
+ const parts = { ids, ...(deleted.length ? { deleted } : {}), ...progress() };
457
+ if (!stillListed.length && !notSeen.length && !sends.refused && !sends.unsent) {
458
+ return { status: 'deleted', outcome: 'confirmed', ...parts };
459
+ }
460
+ const problems = [
461
+ ...(sends.refused
462
+ ? [`war.app refused ${sends.refused.id} (error ${sends.refused.code})${sends.notSent.length ? `, so ${sends.notSent.join(', ')} ${sends.notSent.length === 1 ? 'was' : 'were'} not sent` : ''}`]
463
+ : []),
464
+ ...(sends.unsent
465
+ ? [sends.notSent.length > 1 ? `${sends.unsent} could not be sent, so ${sends.notSent.slice(1).join(', ')} ${sends.notSent.length === 2 ? 'was' : 'were'} not sent either` : `${sends.unsent} could not be sent`]
466
+ : []),
467
+ ...(stillListed.length ? [`the list still holds ${stillListed.join(', ')}`] : []),
468
+ ...(notSeen.length
469
+ ? [`${notSeen.join(', ')} ${notSeen.length === 1 ? 'was' : 'were'} not seen in the pages read (${after.readTo} of ${after.total})`]
470
+ : []),
471
+ ];
472
+ return {
473
+ status: 'unconfirmed',
474
+ outcome: 'unconfirmed',
475
+ ...parts,
476
+ ...(stillListed.length ? { stillListed } : {}),
477
+ ...(notSeen.length ? { notSeen } : {}),
478
+ warning: `${problems.join(', and ')}. ${check}`,
479
+ };
480
+ },
481
+ });
482
+ },
483
+ });
484
+ }
@@ -8,6 +8,8 @@ import { lookupMeta } from './hints.js';
8
8
  import { loadLiveGame } from './live-context.js';
9
9
  import { BRIDGE_NOTE, playerArg, resolveMe } from './live.js';
10
10
  import { mapOf } from './map.js';
11
+ import { pastGamesFor } from './past-games.js';
12
+ import { profileFormatOf } from '../analysis/opponent-profile.js';
11
13
  import { recordProfile } from './profile-hook.js';
12
14
  import { boardHistory, currentTurn, plannerSettings, requireTurnPhase } from './turn.js';
13
15
  import { resolveTeamsFor } from './team-source.js';
@@ -35,13 +37,16 @@ export function registerOpponentsTool(server, ctx, deps = {}) {
35
37
  'earnedAtLeast (its starting armies plus the base income every turn so far: a lower bound on armies received, ' +
36
38
  'not held) and a warning when that beats your largest stack or your total visible armies. Notes say how ' +
37
39
  'confident each figure is (turns used, missing turns, caps, fog reveals). Only consecutive turns are ' +
38
- `compared. Refuses outside a turn phase. ${BRIDGE_NOTE} Read-only on war.app; it caches the board it read.`),
40
+ 'compared. "full" adds `pastGames` when you have finished games: per format the games, results, how the lost ones were lost, the mean turn ' +
41
+ 'your income went flat, and the calibration — this tracker\'s income estimate ÷ the true income from each finished history, by format and ' +
42
+ 'by coverage band (how much of the frontier was read), with the shares read under half and over 1.5× (reported only; nothing reads it). ' +
43
+ `Refuses outside a turn phase. ${BRIDGE_NOTE} Read-only on war.app; it caches the board it read.`),
39
44
  _meta: lookupMeta(['track opponents', 'enemy income', 'what is my opponent earning', 'hidden bonuses']),
40
45
  annotations: readAnnotations('Track war.app opponents'),
41
46
  inputSchema: z.object({
42
47
  game_id: gameIdArg,
43
48
  player: playerArg,
44
- view: viewArg(VIEWS, 'compact (default) gives each opponent\'s per-turn deploys (with a low–high range when ambiguous), income, unexplained armies, inferred bonuses and notes; "full" adds the territories each turn counted, captured (and which captures came out of the fog, were reinforced, or were mine emptied), grew next to the fog, and skipped as fog reveals, and its army change, losses and likely combat deaths.'),
49
+ view: viewArg(VIEWS, 'compact (default) gives each opponent\'s per-turn deploys (with a low–high range when ambiguous), income, unexplained armies, inferred bonuses and notes; "full" adds the territories each turn counted, captured (and which captures came out of the fog, were reinforced, or were mine emptied), grew next to the fog, and skipped as fog reveals, and its army change, losses and likely combat deaths, and `pastGames` (the lessons of your finished games).'),
45
50
  }),
46
51
  }, async ({ game_id, player, view }) => {
47
52
  const feed = await ctx.client.getGame(game_id, { settings: true });
@@ -63,6 +68,8 @@ export function registerOpponentsTool(server, ctx, deps = {}) {
63
68
  await writeGameRecord(ctx.dataDir, game);
64
69
  await recordProfile(ctx.dataDir, deps.env, game, me, boards, teamsKnown);
65
70
  }
71
+ // #312 E3: what my finished games teach (full only; reported only, no track or plan reads it).
72
+ const pastGames = view === 'full' ? await pastGamesFor(ctx.dataDir, deps.env, profileFormatOf(game.players)) : undefined;
66
73
  const name = namer(map);
67
74
  const players = new Map(game.players.map((p) => [p.id, p.name]));
68
75
  const bonusOf = (id) => {
@@ -75,6 +82,8 @@ export function registerOpponentsTool(server, ctx, deps = {}) {
75
82
  deploy: x.observed,
76
83
  ...(x.raw !== x.observed ? { uncapped: x.raw, cap: x.cap } : {}),
77
84
  visibleIncome: x.visibleIncome,
85
+ // #294: how much of its frontier the turn read.
86
+ ...(x.coverage ? { coverage: x.coverage } : {}),
78
87
  // #119: what my own orders that turn measured (defenders my failed attacks killed, …).
79
88
  ...(x.measured ? { measured: x.measured } : {}),
80
89
  ...(x.broken.length ? { brokenBonuses: x.broken.map(bonusOf) } : {}),
@@ -106,6 +115,7 @@ export function registerOpponentsTool(server, ctx, deps = {}) {
106
115
  game: { id: game.id, name: game.name ?? null, turn },
107
116
  player: { id: me.id, name: me.name },
108
117
  turns: boards.map((b) => b.turn).sort((a, b) => a - b),
118
+ ...(rung === 'full' && pastGames ? { pastGames } : {}),
109
119
  // #94: every opponent out of sight whose received armies beat my largest stack or my total.
110
120
  warnings: tracks.flatMap((t) => t.warnings),
111
121
  opponents: tracks.map((t) => ({
@@ -127,6 +137,8 @@ export function registerOpponentsTool(server, ctx, deps = {}) {
127
137
  method: t.incomeMethod,
128
138
  ...(t.incomeLowered ? { lowered: t.incomeLowered } : {}),
129
139
  observedRange: t.observedRange,
140
+ // #294: how much of its frontier the window's turns read.
141
+ ...(t.coverage ? { coverage: t.coverage } : {}),
130
142
  usedByPlanner: t.income !== null && t.turns.length >= TRACKED_MIN_TURNS,
131
143
  // #250: set by one turn far above the turns before it, with what the boards say of it.
132
144
  ...(t.incomeJump ? { jump: t.incomeJump } : {}),
@@ -0,0 +1,94 @@
1
+ import { PACE_TURNS, startRegion } from '../analysis/game-lessons.js';
2
+ import { lessonsSummary, mapRecordStarts, mapRecordSummary, readLessons, readMapRecord } from '../lessons-store.js';
3
+ import { profileEnabled } from '../profile-store.js';
4
+ /** The note every view carries: where it comes from, and that no plan reads it. */
5
+ export const PAST_GAMES_NOTE = 'From your own finished games (their histories, read once at the end of each game): reported only — no plan, ranking or estimate reads it.';
6
+ /** Start bonuses listed on the compact views. */
7
+ export const MAP_RECORD_COMPACT = 8;
8
+ /** The record of `mapId` when it holds a game; `unreadable` when it cannot be parsed; `undefined` otherwise (off, no data dir, no map, none kept). Never throws. */
9
+ export async function mapRecordFor(dataDir, env, mapId) {
10
+ if (!dataDir || mapId === undefined || !profileEnabled(env ?? process.env))
11
+ return undefined;
12
+ try {
13
+ const rec = await readMapRecord(dataDir, mapId);
14
+ return rec === 'unreadable' || rec.games > 0 ? rec : undefined;
15
+ }
16
+ catch {
17
+ return undefined;
18
+ }
19
+ }
20
+ /**
21
+ * The map record as warapp_plan_picks and warapp_map_stats show it: games, my results, my results per
22
+ * bonus my start touched (`inPrimary` when the given picks touch it too), the bonuses winners started
23
+ * in, and the pace (medians of the winners' and my income after turns 4 and 8). Pure.
24
+ */
25
+ export function mapRecordView(rec, o) {
26
+ const { mine, winners } = mapRecordStarts(rec);
27
+ const summary = mapRecordSummary(rec);
28
+ const primary = o.graph && o.picks ? new Set(startRegion(o.graph, o.picks).bonuses) : undefined;
29
+ const cap = (xs) => (o.full ? xs : xs.slice(0, MAP_RECORD_COMPACT));
30
+ return {
31
+ games: summary.games,
32
+ outcomes: summary.outcomes,
33
+ myStarts: cap(mine).map((m) => ({ bonus: o.bonusName(m.bonusId), games: m.games, outcomes: m.outcomes, ...(primary ? { inPrimary: primary.has(m.bonusId) } : {}) })),
34
+ winnerStarts: cap(winners).map((w) => ({ bonus: o.bonusName(w.bonusId), games: w.games })),
35
+ pace: Object.fromEntries(PACE_TURNS.map((t) => [
36
+ `afterTurn${t}`,
37
+ { winners: t === 4 ? summary.pace.winners.income4 : summary.pace.winners.income8, mine: t === 4 ? summary.pace.mine.income4 : summary.pace.mine.income8 },
38
+ ])),
39
+ ...(!o.full && (mine.length > MAP_RECORD_COMPACT || winners.length > MAP_RECORD_COMPACT) ? { more: 'view "full" lists every start bonus' } : {}),
40
+ note: PAST_GAMES_NOTE,
41
+ };
42
+ }
43
+ /**
44
+ * The pace beside my income on the boards after turns 4 and 8 (warapp_plan_turn): with `turnsCompleted`
45
+ * one of {@link PACE_TURNS} and a record with a figure for it, my income now beside the median winner's
46
+ * and my own past median there; `undefined` otherwise. Pure.
47
+ */
48
+ export function paceView(rec, turnsCompleted, myIncome) {
49
+ if (turnsCompleted === null || !PACE_TURNS.includes(turnsCompleted))
50
+ return undefined;
51
+ const s = mapRecordSummary(rec);
52
+ const four = turnsCompleted === 4;
53
+ const winners = four ? s.pace.winners.income4 : s.pace.winners.income8;
54
+ const myPast = four ? s.pace.mine.income4 : s.pace.mine.income8;
55
+ if (winners === null && myPast === null)
56
+ return undefined;
57
+ return {
58
+ afterTurn: turnsCompleted,
59
+ mine: myIncome,
60
+ winners,
61
+ myPast,
62
+ games: s.games,
63
+ ...(winners !== null ? { behindWinners: myIncome < winners } : {}),
64
+ note: PAST_GAMES_NOTE,
65
+ };
66
+ }
67
+ /**
68
+ * The lessons summarized (warapp_track_opponents full): per format the games, results, how the lost ones
69
+ * were lost, the mean turn my income went flat, and the tracker's estimate ÷ the true income by coverage
70
+ * band; `thisFormat` names the game's. `unreadable` when the store cannot be parsed; `undefined` when
71
+ * off, without a data dir, or with no game kept. Never throws.
72
+ */
73
+ export async function pastGamesFor(dataDir, env, format) {
74
+ if (!dataDir || !profileEnabled(env ?? process.env))
75
+ return undefined;
76
+ try {
77
+ const file = await readLessons(dataDir);
78
+ if (file === 'unreadable')
79
+ return 'unreadable';
80
+ const s = lessonsSummary(file);
81
+ if (s.games <= 0)
82
+ return undefined;
83
+ return {
84
+ thisFormat: format,
85
+ ...s,
86
+ readAs: 'calibration: per coverage band (the share of its frontier the track read, #294), n turns × opponents scored, the mean and geometric mean of ' +
87
+ 'the tracked income ÷ the true income from the history, and the shares read under half (low) and over 1.5× (high).',
88
+ note: PAST_GAMES_NOTE,
89
+ };
90
+ }
91
+ catch {
92
+ return undefined;
93
+ }
94
+ }