@chrischall/warapp-mcp 0.1.0 → 0.3.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 (86) hide show
  1. package/.claude-plugin/marketplace.json +3 -3
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +49 -20
  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 +13214 -9759
  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/direct/link.js +9 -5
  22. package/dist/direct/session.js +60 -6
  23. package/dist/direct/sign-in.js +296 -0
  24. package/dist/direct/transport.js +59 -24
  25. package/dist/finished-store.js +357 -0
  26. package/dist/hosted.js +6 -4
  27. package/dist/index.js +1 -1
  28. package/dist/lessons-store.js +356 -0
  29. package/dist/live.js +9 -0
  30. package/dist/map-details.js +127 -0
  31. package/dist/map-stats.js +14 -6
  32. package/dist/map-store.js +44 -6
  33. package/dist/my-games.js +44 -6
  34. package/dist/normalize.js +34 -2
  35. package/dist/notifications.js +143 -0
  36. package/dist/outlook-log.js +28 -1
  37. package/dist/player-record-store.js +2 -0
  38. package/dist/profile-store.js +61 -11
  39. package/dist/protocol/methods.js +86 -2
  40. package/dist/replay.js +16 -4
  41. package/dist/stats.js +26 -4
  42. package/dist/strategy/notes.js +64 -9
  43. package/dist/surrender-pending.js +126 -0
  44. package/dist/tools/accept-surrender.js +311 -0
  45. package/dist/tools/chat-inbox.js +17 -5
  46. package/dist/tools/chat-read-mark.js +179 -0
  47. package/dist/tools/chat.js +50 -8
  48. package/dist/tools/check-plan.js +1 -0
  49. package/dist/tools/commander-check.js +1 -0
  50. package/dist/tools/end-of-game.js +384 -0
  51. package/dist/tools/game.js +31 -6
  52. package/dist/tools/healthcheck.js +7 -1
  53. package/dist/tools/index.js +24 -8
  54. package/dist/tools/join-game.js +1 -1
  55. package/dist/tools/live-context.js +3 -1
  56. package/dist/tools/map-details.js +88 -0
  57. package/dist/tools/map-stats.js +15 -2
  58. package/dist/tools/map.js +10 -2
  59. package/dist/tools/my-games.js +78 -8
  60. package/dist/tools/notifications.js +484 -0
  61. package/dist/tools/open-games.js +5 -2
  62. package/dist/tools/opponents.js +14 -2
  63. package/dist/tools/past-games.js +94 -0
  64. package/dist/tools/picks.js +15 -2
  65. package/dist/tools/profile-opponents.js +1 -1
  66. package/dist/tools/profile-reads.js +3 -3
  67. package/dist/tools/push.js +72 -12
  68. package/dist/tools/session.js +50 -18
  69. package/dist/tools/sign-in.js +56 -0
  70. package/dist/tools/strategy.js +65 -8
  71. package/dist/tools/stress-opponents.js +1 -1
  72. package/dist/tools/surrender-pending.js +74 -0
  73. package/dist/tools/surrender.js +10 -3
  74. package/dist/tools/team-brief.js +1 -1
  75. package/dist/tools/team.js +2 -6
  76. package/dist/tools/turn.js +79 -15
  77. package/dist/tools/where.js +42 -17
  78. package/dist/tools/write-kit.js +16 -3
  79. package/dist/trend.js +145 -20
  80. package/dist/version.js +1 -1
  81. package/docs/examples/warapp-auth-flow.json +31 -0
  82. package/manifest.json +22 -2
  83. package/mint.yaml +44 -22
  84. package/package.json +3 -2
  85. package/server.json +2 -2
  86. package/skills/warapp-mcp/SKILL.md +141 -14
package/dist/my-games.js CHANGED
@@ -14,13 +14,15 @@ import { carriesTeam } from './teams.js';
14
14
  export const MY_GAMES_RETURN = 'warlight.shared.MyGamesReturn';
15
15
  export const GAME_INFO = 'warlight.shared.GameInfo';
16
16
  export const GAME_INFO_PLAYER = 'warlight.shared.GameInfoPlayer';
17
- /** GameState. */
18
- const GAME_STATE_NAMES = {
17
+ /** GameState: the web client's codes, named as GameFeed names them. */
18
+ export const GAME_STATE_NAMES = {
19
19
  2: 'WaitingForPlayers',
20
20
  3: 'Playing',
21
21
  4: 'Finished',
22
22
  5: 'DistributingTerritories',
23
23
  };
24
+ /** A GameState code's name; the code itself when it has none. */
25
+ export const gameStateName = (code) => GAME_STATE_NAMES[code] ?? String(code);
24
26
  const GAME_WAITING = 2;
25
27
  const GAME_PLAYING = 3;
26
28
  const GAME_DISTRIBUTING = 5;
@@ -28,10 +30,31 @@ const GAME_FINISHED = 4;
28
30
  const PLAYER_PLAYING = 2;
29
31
  /** GameInfo field positions in read order, and its whole field count (src/open-games.ts reads the same record). */
30
32
  const GI = { gameId: 7, name: 13, lastTurn: 14, players: 16, state: 22 };
33
+ /**
34
+ * GameInfo's four "unread … messages" flags (#311, docs/WEB-PROTOCOL.md "Marking a game's chat read"): read from
35
+ * the client bundle, UNVERIFIED live. The read-back for RegisterChatView.
36
+ */
37
+ const GI_UNREAD = { group: 8, private: 17, public: 18, team: 23 };
31
38
  export const GAME_INFO_FIELDS = 27;
32
39
  /** GameInfoPlayer field positions in read order, and its whole field count. */
33
40
  const GP = { committed: 2, name: 5, id: 6, state: 7, team: 8 };
34
41
  export const GAME_INFO_PLAYER_FIELDS = 10;
42
+ /** Whether any of the flags is set. */
43
+ export const anyUnreadChat = (f) => f !== undefined && (f.group || f.private || f.public || f.team);
44
+ /** The game's unread-chat flags in the list, or undefined (not listed, or the flags did not read). */
45
+ export function unreadChatOf(games, gameId) {
46
+ return games.find((g) => g.id === gameId)?.unreadChat;
47
+ }
48
+ /** The flags, read loosely: a field that is not a boolean leaves them all unknown, never refuses the list. */
49
+ function unreadFlagsOf(f) {
50
+ const group = f[GI_UNREAD.group];
51
+ const priv = f[GI_UNREAD.private];
52
+ const pub = f[GI_UNREAD.public];
53
+ const team = f[GI_UNREAD.team];
54
+ if (typeof group !== 'boolean' || typeof priv !== 'boolean' || typeof pub !== 'boolean' || typeof team !== 'boolean')
55
+ return undefined;
56
+ return { group, private: priv, public: pub, team };
57
+ }
35
58
  /** The GetMyGames reply arrived in a shape this server does not understand. */
36
59
  export class MyGamesFormatError extends McpToolError {
37
60
  constructor(detail) {
@@ -92,12 +115,14 @@ function gameOf(g) {
92
115
  !isInt(state)) {
93
116
  throw new MyGamesFormatError('a GameInfo lacks its fields');
94
117
  }
118
+ const unreadChat = unreadFlagsOf(f);
95
119
  return {
96
120
  id,
97
121
  name: name ?? '',
98
122
  lastTurn,
99
123
  stateCode: state,
100
124
  players: (players ?? []).filter((p) => p !== null).map(playerOf),
125
+ ...(unreadChat ? { unreadChat } : {}),
101
126
  };
102
127
  }
103
128
  /** Read a GetMyGames result (the body positioned at the result-present flag). */
@@ -128,7 +153,7 @@ export function summarizeMyGames(games, myInGameId) {
128
153
  return {
129
154
  id: g.id,
130
155
  name: g.name,
131
- state: GAME_STATE_NAMES[g.stateCode] ?? String(g.stateCode),
156
+ state: gameStateName(g.stateCode),
132
157
  turn: g.lastTurn < 0 ? null : g.lastTurn + 1,
133
158
  waitingOnYou: active && me !== undefined && me.stateCode === PLAYER_PLAYING && !me.committed,
134
159
  players: g.players.map((p) => ({
@@ -152,12 +177,25 @@ export function activeGameIds(games, myInGameId) {
152
177
  }
153
178
  /**
154
179
  * Games whose chat is live (#256): lobbies, games being picked and games being played — every
155
- * game in the list but a finished one, whatever my seat's state. Ascending id order, so a cursor
156
- * (the last id read) resumes the list even when games join or leave it between calls.
180
+ * game in the list but a finished one, whatever my seat's state — plus a finished game whose chat
181
+ * war.app flags unread, or whose flags did not read at all (#311, GameInfo's unread flags: UNVERIFIED
182
+ * live — a misread position must not hide a finished game's chat without a word; `unflaggedFinished`
183
+ * names those). Ascending id order, so a cursor (the last id read) resumes the list even when games
184
+ * join or leave it between calls.
157
185
  */
158
186
  export function chatGameIds(games) {
159
187
  return games
160
- .filter((g) => g.stateCode === GAME_WAITING || g.stateCode === GAME_PLAYING || g.stateCode === GAME_DISTRIBUTING)
188
+ .filter((g) => g.stateCode === GAME_WAITING ||
189
+ g.stateCode === GAME_PLAYING ||
190
+ g.stateCode === GAME_DISTRIBUTING ||
191
+ (g.stateCode === GAME_FINISHED && (g.unreadChat === undefined || anyUnreadChat(g.unreadChat))))
192
+ .map((g) => g.id)
193
+ .sort((a, b) => a - b);
194
+ }
195
+ /** Finished games whose unread-chat flags did not read (#311): `chatGameIds` keeps them, unjudged. Ascending ids. */
196
+ export function unflaggedFinished(games) {
197
+ return games
198
+ .filter((g) => g.stateCode === GAME_FINISHED && g.unreadChat === undefined)
161
199
  .map((g) => g.id)
162
200
  .sort((a, b) => a - b);
163
201
  }
package/dist/normalize.js CHANGED
@@ -301,8 +301,9 @@ export function normalizeGame(raw) {
301
301
  const standing = boardFromStanding(g.standing ?? g.standings ?? g.latestStanding);
302
302
  if (standing)
303
303
  game.standing = standing;
304
- if (g.history !== undefined)
305
- game.history = g.history;
304
+ const history = historyOf(g);
305
+ if (history !== undefined)
306
+ game.history = history;
306
307
  if (g.chat !== undefined)
307
308
  game.chat = g.chat;
308
309
  const settings = isRec(g.settings) ? g.settings : undefined;
@@ -313,6 +314,37 @@ export function normalizeGame(raw) {
313
314
  game.description = description;
314
315
  return game;
315
316
  }
317
+ /** A top-level key that carries a turn of the history (#302): `standing<N>`, `turn<N>`, `distributionStanding`. */
318
+ const HISTORY_KEY = /^(?:(?:standing|turn)_?\d+|distributionStanding)$/i;
319
+ /**
320
+ * The game's history as sent (#302): `history` / `History` (a JSON string parsed when it parses), else
321
+ * the history-like top-level keys gathered into one object, else a per-turn `standings` / `turns` list
322
+ * — `standings` only when it does not read as the current board. `undefined` when none came.
323
+ */
324
+ function historyOf(g) {
325
+ const named = g.history ?? g.History;
326
+ if (named !== undefined) {
327
+ if (typeof named !== 'string')
328
+ return named;
329
+ try {
330
+ return JSON.parse(named);
331
+ }
332
+ catch {
333
+ return named;
334
+ }
335
+ }
336
+ const out = {};
337
+ for (const [k, v] of Object.entries(g))
338
+ if (HISTORY_KEY.test(k))
339
+ out[k] = v;
340
+ if (Object.keys(out).length)
341
+ return out;
342
+ if (Array.isArray(g.turns))
343
+ return { turns: g.turns };
344
+ if ((Array.isArray(g.standings) || isRec(g.standings)) && !boardFromStanding(g.standings))
345
+ return { standings: g.standings };
346
+ return undefined;
347
+ }
316
348
  const INSTANT_WORDS = new Set(['instant', 'instantly', 'immediate', 'yes']);
317
349
  const NOT_INSTANT_WORDS = new Set(['notinstant', 'noninstant', 'notimmediate', 'requireacceptance', 'requiresacceptance', 'vote', 'no', 'never']);
318
350
  /** {@link EndRules} from a raw settings object; never throws. */
@@ -0,0 +1,143 @@
1
+ // war.app's in-app notifications (#311): a GetInAppNotifications reply (method 317), decoded by the
2
+ // client bundle's own readers by stable type name, like GetMyGames — fields by read order, checked by
3
+ // type, never by their minified names (docs/WEB-PROTOCOL.md, Notifications and read marks).
4
+ // UNVERIFIED live: read from the bundle, nothing here has been checked against a real reply.
5
+ //
6
+ // What a tool reports is name-free beyond ids: a notification's id, time, unread flag, a kind and the
7
+ // game id its link names. Its title and data are text war.app writes (with other players' names in
8
+ // them): they are read only to classify it, never passed on. The record's fourth field, a string the
9
+ // client never reads (perhaps a type name), is unverified free text: it is neither reported nor used.
10
+ import { McpToolError } from '@chrischall/mcp-utils';
11
+ import { fields, isObj } from './protocol/decoded.js';
12
+ import { NOTIFICATION_ID } from './protocol/methods.js';
13
+ export { NOTIFICATIONS_PAGE_SIZE } from './protocol/methods.js';
14
+ export const IN_APP_NOTIFICATIONS_RETURN = 'warlight.shared.GetInAppNotificationsReturn';
15
+ export const IN_APP_NOTIFICATION = 'warlight.shared.InAppNotification';
16
+ /** InAppNotification field positions in read order, and its whole field count. */
17
+ const NF = { sent: 0, data: 1, id: 2, n3: 3, n4: 4, title: 5, unread: 6 };
18
+ export const IN_APP_NOTIFICATION_FIELDS = 7;
19
+ /** The GetInAppNotifications reply arrived in a shape this server does not understand. */
20
+ export class NotificationsFormatError extends McpToolError {
21
+ constructor(detail) {
22
+ super(`war.app's notification list arrived in an unexpected shape (${detail}).`, {
23
+ kind: 'unknown',
24
+ hint: 'The war.app client may have changed; the notifications can still be read in the war.app tab.',
25
+ });
26
+ this.name = 'NotificationsFormatError';
27
+ }
28
+ }
29
+ const isInt = (v) => typeof v === 'number' && Number.isInteger(v);
30
+ const isStr = (v) => v === null || typeof v === 'string';
31
+ function notificationOf(n) {
32
+ if (!isObj(n) || n.$type !== IN_APP_NOTIFICATION)
33
+ throw new NotificationsFormatError('a notification is not an InAppNotification');
34
+ const f = fields(n);
35
+ if (f.length !== IN_APP_NOTIFICATION_FIELDS) {
36
+ throw new NotificationsFormatError(`an InAppNotification has ${f.length} fields, not ${IN_APP_NOTIFICATION_FIELDS}`);
37
+ }
38
+ const sent = f[NF.sent];
39
+ const data = f[NF.data];
40
+ const rawId = f[NF.id];
41
+ const n3 = f[NF.n3];
42
+ const n4 = f[NF.n4];
43
+ const title = f[NF.title];
44
+ const unread = f[NF.unread];
45
+ if (!(sent === null || sent instanceof Date) || !isStr(data) || !isInt(n3) || !isStr(n4) || !isStr(title) || typeof unread !== 'boolean') {
46
+ throw new NotificationsFormatError('an InAppNotification lacks its fields');
47
+ }
48
+ // The client parses the id text as a number; the interpreter may hand back either.
49
+ const id = typeof rawId === 'string' ? rawId.trim() : isInt(rawId) && rawId >= 0 ? String(rawId) : undefined;
50
+ if (id === undefined || !NOTIFICATION_ID.test(id))
51
+ throw new NotificationsFormatError('a notification id is not a number');
52
+ return { id, sent: sent !== null && Number.isFinite(sent.getTime()) ? sent : null, data, n3, n4, title, unread };
53
+ }
54
+ /** Read a GetInAppNotifications result (the body positioned at the result-present flag). */
55
+ export function readInAppNotifications(bundle, body) {
56
+ if (!body.bool())
57
+ return { items: [], total: 0 };
58
+ const ret = bundle.readClass(IN_APP_NOTIFICATIONS_RETURN, body);
59
+ if (!isObj(ret) || ret.$type !== IN_APP_NOTIFICATIONS_RETURN)
60
+ throw new NotificationsFormatError('no GetInAppNotificationsReturn');
61
+ const f = fields(ret);
62
+ if (f.length !== 2)
63
+ throw new NotificationsFormatError(`a GetInAppNotificationsReturn has ${f.length} fields, not 2`);
64
+ const [list, total] = f;
65
+ if (!(list === null || Array.isArray(list)) || !isInt(total))
66
+ throw new NotificationsFormatError('no notification list');
67
+ const items = (list ?? []).filter((n) => n !== null).map(notificationOf);
68
+ return { items, total: Math.max(total, items.length) };
69
+ }
70
+ /** The most data text read for a link: anything longer is not looked at. */
71
+ const MAX_DATA = 64 * 1024;
72
+ /** Hosts a game link may name (war.app, and the old Warzone domain the site still answers on). */
73
+ const GAME_HOSTS = new Set(['war.app', 'www.war.app', 'warzone.com', 'www.warzone.com']);
74
+ /** The game id one link names (`GameID=` on a war.app page, or a relative path), else null. */
75
+ function gameIdOfUrl(url) {
76
+ if (typeof url !== 'string' || url.length > 2048)
77
+ return null;
78
+ let parsed;
79
+ try {
80
+ parsed = new URL(url, 'https://war.app/');
81
+ }
82
+ catch {
83
+ return null;
84
+ }
85
+ if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:')
86
+ return null;
87
+ if (!GAME_HOSTS.has(parsed.hostname.toLowerCase()))
88
+ return null;
89
+ for (const [k, v] of parsed.searchParams) {
90
+ if (k.toLowerCase() === 'gameid' && /^\d{1,10}$/.test(v)) {
91
+ const id = Number(v);
92
+ if (id > 0 && id <= 0x7fffffff)
93
+ return id;
94
+ }
95
+ }
96
+ return null;
97
+ }
98
+ /** The game a notification's data links to: its `Url`, else the first of its `Urls` that names one. */
99
+ export function gameIdFromData(data) {
100
+ if (data === null || data.length > MAX_DATA)
101
+ return null;
102
+ let obj;
103
+ try {
104
+ obj = JSON.parse(data);
105
+ }
106
+ catch {
107
+ return null;
108
+ }
109
+ if (!isObj(obj))
110
+ return null;
111
+ const direct = gameIdOfUrl(obj.Url);
112
+ if (direct !== null)
113
+ return direct;
114
+ if (Array.isArray(obj.Urls)) {
115
+ for (const u of obj.Urls.slice(0, 20)) {
116
+ const id = isObj(u) ? gameIdOfUrl(u.Url) : null;
117
+ if (id !== null)
118
+ return id;
119
+ }
120
+ }
121
+ return null;
122
+ }
123
+ /**
124
+ * The title of a game-ended notification, in the client's own wording (an owner's screenshot,
125
+ * 2026-11-16): `Game "<name>" has ended. You can now view its history`. Matched on that structure,
126
+ * anchored at both the leading `Game "` and the `" has ended.` after the name, never on a bare
127
+ * "ended" or "finished" anywhere in the text (another notification can quote a player's words).
128
+ * The name may itself hold quotes, so it is matched greedily up to the last `" has ended.`.
129
+ */
130
+ const ENDED_TITLE = /^Game ".*" has ended\.(\s|$)/s;
131
+ /** The longest title looked at. */
132
+ const MAX_TITLE = 500;
133
+ /** A notification as a tool reports it: ids, time, flags and its kind, never its text. */
134
+ export function classifyNotification(n) {
135
+ const ended = n.title !== null && n.title.length <= MAX_TITLE && ENDED_TITLE.test(n.title);
136
+ return {
137
+ id: n.id,
138
+ kind: ended ? 'game-ended' : 'other',
139
+ gameId: gameIdFromData(n.data),
140
+ time: n.sent ? n.sent.toISOString() : null,
141
+ unread: n.unread,
142
+ };
143
+ }
@@ -11,6 +11,11 @@ const isRec = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
11
11
  /** Turns kept per game (a long game is still a small file). */
12
12
  const OUTLOOK_LOG_TURNS = 500;
13
13
  export const outlookLogPath = (dir, gameId) => join(dir, 'outlook', `${gameId}.json`);
14
+ const logged = (e) => ({
15
+ incomes: e.incomes ? { ...e.incomes, ...(e.incomes.players ? { players: [...e.incomes.players] } : {}) } : null,
16
+ opponents: e.opponents.map(({ playerId, income, source, coverage, thin }) => ({ playerId, income, source, coverage, thin })),
17
+ thin: e.thin,
18
+ });
14
19
  /** The log of `gameId` as `playerId` played it; `undefined` when absent, another player's, or unusable. */
15
20
  export async function readOutlookLog(dir, gameId, playerId) {
16
21
  try {
@@ -42,6 +47,7 @@ export async function recordOutlook(dir, gameId, playerId, outlook) {
42
47
  high: t.strongest?.high ?? null,
43
48
  ratio: t.ratio,
44
49
  state: t.state,
50
+ ...(t.estimated ? { estimated: true } : {}),
45
51
  ...(t.figures
46
52
  ? {
47
53
  figures: {
@@ -56,6 +62,7 @@ export async function recordOutlook(dir, gameId, playerId, outlook) {
56
62
  },
57
63
  }
58
64
  : {}),
65
+ ...(t.evidence ? { evidence: logged(t.evidence) } : {}),
59
66
  };
60
67
  const keep = Object.keys(log.turns)
61
68
  .map(Number)
@@ -64,13 +71,33 @@ export async function recordOutlook(dir, gameId, playerId, outlook) {
64
71
  log.turns = Object.fromEntries(keep.sort((a, b) => a - b).map((k) => [String(k), log.turns[String(k)]]));
65
72
  const last = outlook.turns.at(-1);
66
73
  if (last)
67
- log.latest = { turn: last.turn, state: outlook.state, heldTurns: outlook.heldTurns, basis: outlook.basis };
74
+ log.latest = {
75
+ turn: last.turn,
76
+ state: outlook.state,
77
+ heldTurns: outlook.heldTurns,
78
+ basis: outlook.basis,
79
+ ...(outlook.evidence ? { evidence: logged(outlook.evidence) } : {}),
80
+ };
68
81
  await write(dir, log);
69
82
  }
70
83
  catch {
71
84
  // The log is optional.
72
85
  }
73
86
  }
87
+ export function finalOutlookOf(log) {
88
+ const l = log.latest;
89
+ if (!l || typeof l.turn !== 'number')
90
+ return undefined;
91
+ const t = log.turns[String(l.turn)];
92
+ return {
93
+ turn: l.turn,
94
+ state: l.state ?? null,
95
+ heldTurns: typeof l.heldTurns === 'number' ? l.heldTurns : 0,
96
+ ...(t?.ratio ? { ratio: { low: t.ratio.low, high: t.ratio.high } } : {}),
97
+ ...(t?.estimated ? { estimated: true } : {}),
98
+ ...(l.evidence?.thin ? { thin: true } : {}),
99
+ };
100
+ }
74
101
  /** Record the final result of a game the log already holds; `true` when written. Best effort. */
75
102
  export async function recordResult(dir, gameId, playerId, result) {
76
103
  try {
@@ -88,6 +88,8 @@ const hmac = (salt, text) => createHmac('sha256', salt).update(text).digest('hex
88
88
  export const playerKey = (salt, playerId) => hmac(salt, `player:${playerId}`);
89
89
  /** A game's key in the opponent profiles: my account and the game, never the ids themselves. */
90
90
  export const profileGameKey = (salt, myId, gameId) => hmac(salt, `profile-game:${myId}:${gameId}`);
91
+ /** A finished game's end-of-game record (#312, src/finished-store.ts): my account and the game, never the ids themselves. */
92
+ export const finishedGameKey = (salt, myId, gameId) => hmac(salt, `finished-game:${myId}:${gameId}`);
91
93
  /** An agreement's key in the record: my account, the game and the agreement, never the ids themselves. */
92
94
  export const entryKey = (salt, myId, gameId, agreementId) => hmac(salt, `agreement:${myId}:${gameId}:${agreementId}`);
93
95
  /** The key entries were written under before my account was part of it: still read, and updated in place. */
@@ -29,23 +29,26 @@
29
29
  // seats go to the pool only; a human who became an AI is left out of the game altogether (no turn of
30
30
  // the change is known, V4). A finished game is folded by `foldFinishedGame` on the first read that
31
31
  // shows it finished (warapp_get_game, warapp_wait_for_turn's re-read); its per-game file is then
32
- // marked `folded: 'live'` and kept until the age rule deletes it (part C, which would read the
33
- // game's history first, is not built), and a file reaching that age unfolded is folded with every
34
- // ending `unknown`, then deleted. A store or salt that exists but is not JSON, not an object or not
32
+ // marked `folded: 'live'` and kept until the age rule deletes it, and a file reaching that age
33
+ // unfolded is folded with every ending `unknown`, then deleted. Part C (#312 E2): the end-of-game
34
+ // pass folds the game again from its history (`source: 'history'`, src/tools/end-of-game.ts), which
35
+ // replaces the live entry and marks a per-game file not yet folded `folded: 'history'`. A store or salt that exists but is not JSON, not an object or not
35
36
  // version 1 is never overwritten: reads say `unreadable`, folds fail. Inside a version-1 store the
36
37
  // read is loose, like the board cache's: a malformed player record, entry or total is dropped (an
37
38
  // `entries` that is not an array reads as none), and the next fold writes the store back without it.
38
39
  //
39
40
  // Folding is idempotent only while the game's entry is still stored: `foldGame` finds "this game
40
41
  // again" among a player's last `MAX_PROFILE_ENTRIES` entries and the population's last
41
- // `MAX_POPULATION_ENTRIES`. A game folded again after its entry was dropped (part C's history
42
- // replacement arriving that late) is faded and counted a second time. Likewise the
42
+ // `MAX_POPULATION_ENTRIES`. A live fold after its entry was dropped is faded and counted a second
43
+ // time. The history fold guards it (#312 E2): when the game was folded before (the population holds
44
+ // it, or the caller says the per-game file is marked), a player with no entry for it is skipped
45
+ // whenever its entry list is full (an entry may have been dropped), and the population is skipped
46
+ // when it no longer holds the game. Likewise the
43
47
  // `MAX_PROFILE_GAME_FILES` bound can fold a game still in progress (endings `unknown`) and delete
44
48
  // its file; if play goes on, `recordBehaviour` starts a new file with the later turns only, and the
45
49
  // fold at the finish replaces the earlier entry with that shorter one, so the turns before the
46
- // eviction leave the totals. Both are rare today (30 games with one opponent, 200 games in play);
47
- // part C must guard them (a kept tombstone of folded keys, or merging into the stored entry) before
48
- // it relies on refolding.
50
+ // eviction leave the totals (the history fold then replaces that shorter entry with the whole game's).
51
+ // Both are rare today (30 games with one opponent, 200 games in play).
49
52
  import { mkdir, readdir, readFile, rename, stat, unlink, writeFile } from 'node:fs/promises';
50
53
  import { join } from 'node:path';
51
54
  import { randomUUID } from 'node:crypto';
@@ -440,6 +443,12 @@ export async function foldGame(dir, input, env = process.env) {
440
443
  return 'failed';
441
444
  const key = profileGameKey(salt, input.me, input.gameId);
442
445
  const seats = [...input.seats].sort((a, b) => a.id - b.id);
446
+ const oldPopulation = population.entries.find((e) => e.key === key);
447
+ // #312 E2: a history fold replaces what a live fold counted, and must never count it twice. The
448
+ // game was folded before when the population still holds it or the caller knows it was; then a
449
+ // player with no entry for it is counted only when its entry list never dropped one (not full).
450
+ const history = input.source === 'history';
451
+ const foldedBefore = history && (oldPopulation !== undefined || input.foldedBefore === true);
443
452
  // Each human seat, under its player key.
444
453
  for (const seat of seats) {
445
454
  if (seat.ai)
@@ -449,6 +458,8 @@ export async function foldGame(dir, input, env = process.env) {
449
458
  const old = p.entries.find((e) => e.key === key);
450
459
  if (old?.source === 'history' && input.source === 'live')
451
460
  continue;
461
+ if (!old && foldedBefore && p.entries.length >= MAX_PROFILE_ENTRIES)
462
+ continue;
452
463
  if (!old) {
453
464
  // A game new to this player: everything before it fades once.
454
465
  for (const f of PROFILE_FORMATS)
@@ -479,8 +490,8 @@ export async function foldGame(dir, input, env = process.env) {
479
490
  // The population: humans by format, AIs pooled; replaced as a whole for a game folded again.
480
491
  const humans = sumOf(seats.filter((s) => !s.ai).map((s) => s.habits));
481
492
  const ai = sumOf(seats.filter((s) => s.ai).map((s) => s.habits));
482
- const old = population.entries.find((e) => e.key === key);
483
- if (!(old?.source === 'history' && input.source === 'live')) {
493
+ const old = oldPopulation;
494
+ if (!(old?.source === 'history' && input.source === 'live') && !(history && !old && foldedBefore)) {
484
495
  if (old) {
485
496
  bump(population.totals, old.format, old.humans, -1);
486
497
  population.ai = addHabits(population.ai, old.ai, -1);
@@ -541,8 +552,12 @@ export async function readProfileHistory(dir, ids, game, env = process.env) {
541
552
  if (own)
542
553
  past = addHabits(past, own.habits, -own.weight);
543
554
  const games = p.games - (own ? 1 : 0);
555
+ let fromHistory = emptyHabits();
556
+ for (const e of p.entries)
557
+ if (e.source === 'history' && e !== own)
558
+ fromHistory = addHabits(fromHistory, e.habits, e.weight);
544
559
  if (games > 0 || !isEmpty(past))
545
- out.players.set(id, { games, past });
560
+ out.players.set(id, { games, past, fromHistory });
546
561
  }
547
562
  return out;
548
563
  }
@@ -638,6 +653,26 @@ export async function foldFinishedGame(dir, game, env = process.env) {
638
653
  }
639
654
  return folded;
640
655
  }
656
+ /**
657
+ * After a history fold (#312 E2): mark the per-game file of `gameId` as `playerId` saw it `folded:
658
+ * 'history'`, so the live fold at the next finished read leaves it alone. Nothing when there is no
659
+ * file or it is already folded. Never throws.
660
+ */
661
+ export async function markHistoryFolded(dir, gameId, playerId) {
662
+ const path = profileGamePath(dir, gameId, playerId);
663
+ try {
664
+ await stat(path);
665
+ }
666
+ catch {
667
+ return;
668
+ }
669
+ await withPathLock(path, async () => {
670
+ const file = await readGameFile(dir, gameId, playerId);
671
+ if (file.folded)
672
+ return;
673
+ await writeGameFile(path, { version: 1, gameId, playerId, ...file, folded: 'history' });
674
+ }).catch(() => undefined);
675
+ }
641
676
  /**
642
677
  * The per-game file of `gameId` as `playerId` saw it (#264): `none` when there is none, `folded` when
643
678
  * it was folded, else `kept`. Never throws (an unreadable file reads as `kept`: never backfilled over).
@@ -651,6 +686,21 @@ export async function profileFileState(dir, gameId, playerId) {
651
686
  }
652
687
  return (await readGameFile(dir, gameId, playerId)).folded ? 'folded' : 'kept';
653
688
  }
689
+ /**
690
+ * Whether any account of mine keeps a per-game file of `gameId` not folded yet (#311): what makes a fold
691
+ * worth a GameFeed read when a notification says the game ended. Never throws, never writes.
692
+ */
693
+ export async function hasUnfoldedProfile(dir, gameId) {
694
+ const prefix = `${gameId}-`;
695
+ const names = await readdir(profileGamesDir(dir)).catch(() => []);
696
+ for (const name of names) {
697
+ if (!name.startsWith(prefix) || !/^\d+-\d+\.json$/.test(name))
698
+ continue;
699
+ if ((await profileFileState(dir, gameId, Number(name.slice(prefix.length, -'.json'.length)))) === 'kept')
700
+ return true;
701
+ }
702
+ return false;
703
+ }
654
704
  /**
655
705
  * Whether the cross-game stores already hold `gameId` as folded by `me` (#264: a per-game file the
656
706
  * age rule or the file bound removed after its fold). Reads the population's entries under the game's
@@ -8,6 +8,7 @@ export const Method = {
8
8
  GameRefresh: 39,
9
9
  GetLatestGameInfo: 40,
10
10
  SendChat: 42,
11
+ RegisterChatView: 43,
11
12
  GetGameSettings: 48,
12
13
  GetMyGames: 50,
13
14
  AcceptGame: 60,
@@ -16,6 +17,7 @@ export const Method = {
16
17
  GetOpenAutoGame: 63,
17
18
  DeclineGame: 64,
18
19
  Surrender: 67,
20
+ AcceptSurrender: 68,
19
21
  GetMapDetails: 73,
20
22
  SendOrders: 74,
21
23
  SendInProgressOrders: 75,
@@ -27,6 +29,9 @@ export const Method = {
27
29
  GetTurns: 81,
28
30
  Subscribe: 238,
29
31
  GameUpdated: 241,
32
+ GetInAppNotifications: 317,
33
+ DeleteInAppNotification: 318,
34
+ AcknowledgeInAppNotifications: 319,
30
35
  };
31
36
  const NAMES = new Map(Object.entries(Method).map(([name, id]) => [id, name]));
32
37
  /** The method's name for a known id, or undefined. */
@@ -115,6 +120,15 @@ export function readAcceptOpenSeatReturn(body) {
115
120
  export function writeSurrenderParams(w, p) {
116
121
  w.int32(p.gameId).bool(p.surrender).bool(false);
117
122
  }
123
+ /**
124
+ * AcceptSurrender(auth, …) — accept another player's pending surrender (#317). READ FROM THE CLIENT
125
+ * BUNDLE's writer, NOT VERIFIED LIVE: after the auth block the int32 game id, the int32 in-game id of
126
+ * the surrendering player, the accept flag (false takes an acceptance back), then the per-method
127
+ * "a mod hooks this method" bool, sent false. No result payload: the outcome is read from game state.
128
+ */
129
+ export function writeAcceptSurrenderParams(w, p) {
130
+ w.int32(p.gameId).int32(p.playerId).bool(p.accept).bool(false);
131
+ }
118
132
  /**
119
133
  * BeginFirstTurn(auth, gameId) — the web client's Begin button in a game whose
120
134
  * first turn is a speed race (MoveOrder `NoLuckCycle`): war.app withholds the
@@ -136,6 +150,44 @@ export function writeBeginFirstTurnParams(w, gameId) {
136
150
  export function writeUnCommitParams(w, gameId) {
137
151
  w.int32(gameId);
138
152
  }
153
+ /** The page size the client always asks GetInAppNotifications for. */
154
+ export const NOTIFICATIONS_PAGE_SIZE = 30;
155
+ /**
156
+ * GetInAppNotifications(auth, start, count) — the client's notifications screen (#311). READ FROM THE
157
+ * CLIENT BUNDLE's writer, NOT VERIFIED LIVE: after the auth block the int32 start index (the paging
158
+ * offset), then the int32 page size (the client always sends 30). Reply: GetInAppNotificationsReturn.
159
+ */
160
+ export function writeGetInAppNotificationsParams(w, start, count = NOTIFICATIONS_PAGE_SIZE) {
161
+ w.int32(start).int32(count);
162
+ }
163
+ /** A notification id as war.app sends it back: decimal text. */
164
+ export const NOTIFICATION_ID = /^\d{1,20}$/;
165
+ /**
166
+ * AcknowledgeInAppNotifications(auth, ids) — marks notifications read (#311). READ FROM THE CLIENT
167
+ * BUNDLE's writer, NOT VERIFIED LIVE: after the auth block a present list (int32 count) of the ids, each
168
+ * a string of decimal text. No result payload: the effect is read back from a later list.
169
+ */
170
+ export function writeAcknowledgeInAppNotificationsParams(w, ids) {
171
+ if (ids.length === 0)
172
+ throw new RangeError('no notification ids');
173
+ for (const id of ids)
174
+ if (!NOTIFICATION_ID.test(id))
175
+ throw new RangeError(`not a notification id: ${JSON.stringify(id)}`);
176
+ w.bool(true).list(ids, (ww, id) => ww.string(id));
177
+ }
178
+ /**
179
+ * DeleteInAppNotification(auth, id) — deletes one notification (#311), the client's Delete button. READ
180
+ * FROM THE CLIENT BUNDLE's writer, NOT VERIFIED LIVE: after the auth block one string, the id as decimal
181
+ * text. No result payload; the client treats server error 699 (`InAppNotificationKeyNotFound`) as already
182
+ * deleted. The effect is read back from a later list.
183
+ */
184
+ export function writeDeleteInAppNotificationParams(w, id) {
185
+ if (!NOTIFICATION_ID.test(id))
186
+ throw new RangeError(`not a notification id: ${JSON.stringify(id)}`);
187
+ w.string(id);
188
+ }
189
+ /** The server error DeleteInAppNotification answers for an id it does not hold: already deleted. */
190
+ export const NOTIFICATION_NOT_FOUND = 699;
139
191
  /**
140
192
  * DeclineGame(auth, gameId, modHook) — the lobby's Decline button, which is also how a seated
141
193
  * player leaves a game still `WaitingForPlayers` (#217). READ FROM THE CLIENT BUNDLE's writer,
@@ -221,6 +273,33 @@ export function writeGameRefreshParams(w, p) {
221
273
  .bool(false)
222
274
  .bool(false);
223
275
  }
276
+ /** A chat read mark: a message id as decimal text, or `-1` (the client's "no mark"). */
277
+ export const CHAT_MARK = /^(-1|\d{1,20})$/;
278
+ function writeMarkDict(w, marks) {
279
+ if (!marks || marks.size === 0) {
280
+ w.bool(false);
281
+ return;
282
+ }
283
+ w.bool(true).dict(marks, (ww, k) => ww.int32(k), (ww, v) => ww.string(v));
284
+ }
285
+ /**
286
+ * RegisterChatView(auth, …) — marks a game's chat read (#311). READ FROM THE CLIENT BUNDLE's writer, NOT
287
+ * VERIFIED LIVE: the int32 game id, the public and team marks (strings of decimal text: the highest message
288
+ * id seen on that channel; the client sends `-1` for a channel it is not marking), then two optional dicts
289
+ * (present flag, int32 count, int32 key, string mark): per private counterpart (in-game id), and per game
290
+ * group. No result payload: the effect is read back from GetMyGames' unread flags.
291
+ */
292
+ export function writeRegisterChatViewParams(w, p) {
293
+ const marks = [p.publicMark, p.teamMark, ...(p.privateMarks?.values() ?? []), ...(p.groupMarks?.values() ?? [])];
294
+ for (const m of marks)
295
+ if (m !== undefined && !CHAT_MARK.test(m))
296
+ throw new RangeError(`not a chat mark: ${JSON.stringify(m)}`);
297
+ w.int32(p.gameId)
298
+ .string(p.publicMark ?? NO_CHAT_MARKER)
299
+ .string(p.teamMark ?? NO_CHAT_MARKER);
300
+ writeMarkDict(w, p.privateMarks);
301
+ writeMarkDict(w, p.groupMarks);
302
+ }
224
303
  /**
225
304
  * SendChat(auth, …) per docs/WEB-PROTOCOL.md (read from the client's
226
305
  * serializer; the owner verifies it live): game id, text, channel, optional
@@ -309,8 +388,8 @@ const CardPlayTag = {
309
388
  Blockade: 18,
310
389
  Bomb: 20,
311
390
  };
312
- /** The card plays whose encoding is read from the bundle but not yet sent live (V9). */
313
- export const UNVERIFIED_CARD_PLAYS = new Set([
391
+ /** The card plays that take targets (PLAN-TEAMS part D): `warapp_submit_turn` resolves their fields. */
392
+ export const TARGETED_CARD_PLAYS = new Set([
314
393
  'Spy',
315
394
  'Airlift',
316
395
  'Gift',
@@ -321,6 +400,11 @@ export const UNVERIFIED_CARD_PLAYS = new Set([
321
400
  'Bomb',
322
401
  'EmergencyBlockade',
323
402
  ]);
403
+ /**
404
+ * The card plays whose encoding is read from the bundle but not yet sent live (V9): the preview warns
405
+ * and the result carries `cardPlayCheck`. Airlift left it once verified live 2026-11-16 (#296).
406
+ */
407
+ export const UNVERIFIED_CARD_PLAYS = new Set([...TARGETED_CARD_PLAYS].filter((kind) => kind !== 'Airlift'));
324
408
  function need(v, card, what) {
325
409
  if (v === undefined)
326
410
  throw new Error(`A ${card} card play needs ${what}.`);