@chrischall/warapp-mcp 0.0.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 (194) hide show
  1. package/.claude-plugin/marketplace.json +4 -4
  2. package/.claude-plugin/plugin.json +2 -2
  3. package/README.md +211 -9
  4. package/dist/analysis/accept-surrender.js +56 -0
  5. package/dist/analysis/award.js +159 -0
  6. package/dist/analysis/bonuses.js +98 -0
  7. package/dist/analysis/breach.js +62 -0
  8. package/dist/analysis/calibrate.js +239 -0
  9. package/dist/analysis/card-support.js +329 -0
  10. package/dist/analysis/card-threats.js +234 -0
  11. package/dist/analysis/cards-in-effect.js +130 -0
  12. package/dist/analysis/chains.js +59 -0
  13. package/dist/analysis/chokepoints.js +140 -0
  14. package/dist/analysis/combat.js +231 -0
  15. package/dist/analysis/commander-safety.js +149 -0
  16. package/dist/analysis/commitments.js +338 -0
  17. package/dist/analysis/exchange.js +155 -0
  18. package/dist/analysis/finished-game.js +136 -0
  19. package/dist/analysis/game-lessons.js +217 -0
  20. package/dist/analysis/graph.js +82 -0
  21. package/dist/analysis/guard-off.js +54 -0
  22. package/dist/analysis/guess.js +351 -0
  23. package/dist/analysis/headroom.js +241 -0
  24. package/dist/analysis/hold-diff.js +64 -0
  25. package/dist/analysis/how-lost.js +130 -0
  26. package/dist/analysis/index.js +14 -0
  27. package/dist/analysis/local-deploy.js +179 -0
  28. package/dist/analysis/lookahead.js +108 -0
  29. package/dist/analysis/opponent-profile.js +552 -0
  30. package/dist/analysis/opponents.js +1253 -0
  31. package/dist/analysis/outlook.js +695 -0
  32. package/dist/analysis/overrides.js +60 -0
  33. package/dist/analysis/picks.js +1879 -0
  34. package/dist/analysis/plan/after-leftover.js +140 -0
  35. package/dist/analysis/plan/cap-spend.js +242 -0
  36. package/dist/analysis/plan/captures.js +1195 -0
  37. package/dist/analysis/plan/commander.js +236 -0
  38. package/dist/analysis/plan/completed.js +29 -0
  39. package/dist/analysis/plan/conceded-out.js +131 -0
  40. package/dist/analysis/plan/estimates.js +715 -0
  41. package/dist/analysis/plan/guard-off.js +232 -0
  42. package/dist/analysis/plan/holds.js +1631 -0
  43. package/dist/analysis/plan/leftover.js +760 -0
  44. package/dist/analysis/plan/move-order.js +319 -0
  45. package/dist/analysis/plan/orders.js +317 -0
  46. package/dist/analysis/plan/relations.js +702 -0
  47. package/dist/analysis/plan/report.js +672 -0
  48. package/dist/analysis/plan/shared.js +1405 -0
  49. package/dist/analysis/plan/stand-still.js +823 -0
  50. package/dist/analysis/plan/state.js +44 -0
  51. package/dist/analysis/plan/strike.js +1416 -0
  52. package/dist/analysis/plan/targets.js +651 -0
  53. package/dist/analysis/plan/team.js +299 -0
  54. package/dist/analysis/plan/threats.js +1001 -0
  55. package/dist/analysis/plan/transfers.js +328 -0
  56. package/dist/analysis/plan/util.js +5 -0
  57. package/dist/analysis/plan/vacated.js +285 -0
  58. package/dist/analysis/planner.js +2927 -0
  59. package/dist/analysis/player-record.js +144 -0
  60. package/dist/analysis/player.js +268 -0
  61. package/dist/analysis/profile.js +347 -0
  62. package/dist/analysis/relations.js +1030 -0
  63. package/dist/analysis/schedule.js +88 -0
  64. package/dist/analysis/since-last.js +50 -0
  65. package/dist/analysis/static-seats.js +71 -0
  66. package/dist/analysis/stress.js +584 -0
  67. package/dist/analysis/team-brief.js +151 -0
  68. package/dist/analysis/tripwire.js +644 -0
  69. package/dist/analysis/turn-sim.js +259 -0
  70. package/dist/analysis/whereabouts.js +1112 -0
  71. package/dist/board.js +105 -0
  72. package/dist/bundle.js +121082 -36148
  73. package/dist/calibration-source.js +75 -0
  74. package/dist/cards.js +435 -0
  75. package/dist/chat-cursor.js +135 -0
  76. package/dist/chat.js +265 -0
  77. package/dist/client.js +439 -0
  78. package/dist/config.js +62 -0
  79. package/dist/direct/link.js +102 -0
  80. package/dist/direct/session.js +267 -0
  81. package/dist/direct/transport.js +424 -0
  82. package/dist/finished-store.js +357 -0
  83. package/dist/guess-salt.js +65 -0
  84. package/dist/hosted.js +24 -0
  85. package/dist/index.js +33 -0
  86. package/dist/join-color.js +140 -0
  87. package/dist/lessons-store.js +356 -0
  88. package/dist/live.js +287 -0
  89. package/dist/map-details.js +127 -0
  90. package/dist/map-stats.js +160 -0
  91. package/dist/map-store.js +242 -0
  92. package/dist/move-order.js +141 -0
  93. package/dist/my-games.js +218 -0
  94. package/dist/normalize.js +443 -0
  95. package/dist/notifications.js +143 -0
  96. package/dist/open-games.js +537 -0
  97. package/dist/outlook-log.js +165 -0
  98. package/dist/path-lock.js +22 -0
  99. package/dist/pick-list.js +193 -0
  100. package/dist/player-record-store.js +231 -0
  101. package/dist/player-states.js +31 -0
  102. package/dist/profile-store.js +727 -0
  103. package/dist/protocol/bundle.js +375 -0
  104. package/dist/protocol/codec.js +556 -0
  105. package/dist/protocol/decoded.js +12 -0
  106. package/dist/protocol/interp.js +1904 -0
  107. package/dist/protocol/methods.js +615 -0
  108. package/dist/protocol/rpc.js +202 -0
  109. package/dist/push/listener.js +393 -0
  110. package/dist/push/packets.js +66 -0
  111. package/dist/push/socketio.js +333 -0
  112. package/dist/push/websocket.js +179 -0
  113. package/dist/redact.js +62 -0
  114. package/dist/relations-store.js +242 -0
  115. package/dist/replay.js +227 -0
  116. package/dist/scalars.js +28 -0
  117. package/dist/scout.js +346 -0
  118. package/dist/stats.js +291 -0
  119. package/dist/strategy/card-clock.js +185 -0
  120. package/dist/strategy/map-notes.js +128 -0
  121. package/dist/strategy/notes.js +2223 -0
  122. package/dist/surrender-pending.js +126 -0
  123. package/dist/team-cards.js +84 -0
  124. package/dist/team-orders.js +150 -0
  125. package/dist/teams.js +19 -0
  126. package/dist/tools/accept-surrender.js +311 -0
  127. package/dist/tools/award.js +206 -0
  128. package/dist/tools/begin-turn.js +162 -0
  129. package/dist/tools/board.js +77 -0
  130. package/dist/tools/card-advice.js +256 -0
  131. package/dist/tools/card-effects.js +49 -0
  132. package/dist/tools/card-plays.js +434 -0
  133. package/dist/tools/card-support-advice.js +140 -0
  134. package/dist/tools/chat-inbox.js +158 -0
  135. package/dist/tools/chat-read-mark.js +179 -0
  136. package/dist/tools/chat.js +525 -0
  137. package/dist/tools/check-plan.js +689 -0
  138. package/dist/tools/commander-check.js +103 -0
  139. package/dist/tools/commitments.js +216 -0
  140. package/dist/tools/common.js +143 -0
  141. package/dist/tools/diplomacy.js +342 -0
  142. package/dist/tools/end-of-game.js +384 -0
  143. package/dist/tools/game.js +151 -0
  144. package/dist/tools/guess-view.js +56 -0
  145. package/dist/tools/healthcheck.js +90 -0
  146. package/dist/tools/hints.js +34 -0
  147. package/dist/tools/how-lost.js +154 -0
  148. package/dist/tools/index.js +152 -0
  149. package/dist/tools/join-game.js +327 -0
  150. package/dist/tools/leave-game.js +181 -0
  151. package/dist/tools/live-context.js +339 -0
  152. package/dist/tools/live.js +404 -0
  153. package/dist/tools/map-details.js +88 -0
  154. package/dist/tools/map-stats.js +130 -0
  155. package/dist/tools/map.js +141 -0
  156. package/dist/tools/my-games.js +193 -0
  157. package/dist/tools/notifications.js +484 -0
  158. package/dist/tools/open-games.js +104 -0
  159. package/dist/tools/opponents.js +163 -0
  160. package/dist/tools/order-options.js +135 -0
  161. package/dist/tools/past-games.js +94 -0
  162. package/dist/tools/picks.js +305 -0
  163. package/dist/tools/profile-hook.js +156 -0
  164. package/dist/tools/profile-opponents.js +121 -0
  165. package/dist/tools/profile-reads.js +99 -0
  166. package/dist/tools/push.js +445 -0
  167. package/dist/tools/relations.js +611 -0
  168. package/dist/tools/resolve.js +45 -0
  169. package/dist/tools/route.js +36 -0
  170. package/dist/tools/scout.js +87 -0
  171. package/dist/tools/session.js +163 -0
  172. package/dist/tools/strategy.js +257 -0
  173. package/dist/tools/stress-opponents.js +83 -0
  174. package/dist/tools/surrender-pending.js +74 -0
  175. package/dist/tools/surrender.js +247 -0
  176. package/dist/tools/survival.js +189 -0
  177. package/dist/tools/team-brief.js +266 -0
  178. package/dist/tools/team-source.js +222 -0
  179. package/dist/tools/team.js +178 -0
  180. package/dist/tools/turn.js +2825 -0
  181. package/dist/tools/uncommit.js +160 -0
  182. package/dist/tools/where.js +300 -0
  183. package/dist/tools/write-kit.js +164 -0
  184. package/dist/transport-bridge.js +33 -0
  185. package/dist/trend.js +577 -0
  186. package/dist/version.js +4 -0
  187. package/manifest.json +194 -4
  188. package/mint.yaml +106 -14
  189. package/package.json +11 -6
  190. package/server.json +40 -3
  191. package/skills/warapp-api/SKILL.md +95 -4
  192. package/skills/warapp-api/references/scout.mjs +348 -0
  193. package/skills/warapp-api/scripts/warapp.sh +69 -8
  194. package/skills/warapp-mcp/SKILL.md +1096 -21
package/dist/trend.js ADDED
@@ -0,0 +1,577 @@
1
+ // The previous turn's board, for the planner's threat trend. Best effort and
2
+ // never throws: GameFeed's `GetHistory` standing for the previous turn when the
3
+ // feed sends one (UNVERIFIED for games in progress — see docs/WARAPP-API.md),
4
+ // else the board this server planned on for the previous turn, cached on disk
5
+ // (the newest CACHED_TURNS turns per game, planned or tracked: opponent tracking
6
+ // reads the whole history).
7
+ //
8
+ // The cache holds only the player's own fogged view (what the live board
9
+ // showed them), at `<dataDir>/boards/<gameId>.json`; a game's file not written for
10
+ // 60 days is deleted on the first write of a process.
11
+ //
12
+ // Beside the boards, the same file keeps the orders this server sent for a turn
13
+ // (`warapp_submit_turn`, #119): my own orders are measurements of what an opponent
14
+ // deployed (analysis/opponents.ts `measureOrders`). Orders sent from the web client
15
+ // stay unknown, which changes nothing; a confirmed `warapp_uncommit_turn` drops the
16
+ // turn's cached orders, so a resend from the web client does not leave them standing.
17
+ //
18
+ // And, by turn, the next income the plan of that turn expected (`expected.nextIncome`, #194): the
19
+ // next turn's plan compares its income with it ("since last turn").
20
+ //
21
+ // And (#275 b) the survival side store: by turn, the deploy estimate each opponent was planned
22
+ // against (`estimates`), and the opponents whose estimate a tripwire marked untrusted
23
+ // (`tripwires`, src/analysis/tripwire.ts). Player ids and numbers only, never a name.
24
+ import { mkdir, readdir, readFile, rename, stat, unlink, writeFile } from 'node:fs/promises';
25
+ import { join } from 'node:path';
26
+ import { boardFromStanding } from './board.js';
27
+ import { playersByInGameId } from './live.js';
28
+ import { asInt } from './scalars.js';
29
+ const isRec = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
30
+ const STANDING_KEYS = ['standing', 'standings', 'latestStanding', 'Standing'];
31
+ const NUMBER_KEYS = ['turnNumber', 'turn', 'number', 'TurnNumber'];
32
+ /** Keys that wrap a history's turns (#302: GameFeed's spelling is unverified). */
33
+ const WRAPPER_KEYS = ['turns', 'Turns', 'history', 'History', 'standings', 'Standings'];
34
+ const DISTRIBUTION_KEYS = ['distributionStanding', 'DistributionStanding'];
35
+ const STANDING_KEY = /^standing_?(\d+)$/i;
36
+ function standingOf(entry) {
37
+ if (!isRec(entry))
38
+ return entry;
39
+ for (const k of STANDING_KEYS)
40
+ if (entry[k] !== undefined)
41
+ return entry[k];
42
+ return entry;
43
+ }
44
+ /** Whether a raw standing shows any territory held by a player (a pre-pick board shows none). */
45
+ const playerLand = (raw) => boardFromStanding(standingOf(raw))?.territories.some((t) => t.owner.kind === 'player') ?? false;
46
+ const ORDER_LIST_KEYS = ['orders', 'Orders'];
47
+ const ORDER_TYPE_KEYS = ['type', 'Type', 'orderType', 'OrderType'];
48
+ /**
49
+ * Whether a history entry carries a turn's orders rather than a standing: a record with an `orders`
50
+ * list and no standing key, or a list whose records name an order type (`type` / `orderType`).
51
+ */
52
+ function carriesOrders(entry) {
53
+ if (Array.isArray(entry))
54
+ return entry.some((e) => isRec(e) && ORDER_TYPE_KEYS.some((k) => typeof e[k] === 'string'));
55
+ if (!isRec(entry))
56
+ return false;
57
+ return ORDER_LIST_KEYS.some((k) => entry[k] !== undefined) && !STANDING_KEYS.some((k) => entry[k] !== undefined);
58
+ }
59
+ /** History entries in any of the plausible layouts (#302). Throws only on a hostile getter (callers catch). */
60
+ function parseHistory(history, opts = {}) {
61
+ if (typeof history === 'string') {
62
+ let parsed;
63
+ try {
64
+ parsed = JSON.parse(history);
65
+ }
66
+ catch {
67
+ return { entries: [], layout: 'none', shape: 'string' };
68
+ }
69
+ const inner = parseHistory(parsed, opts);
70
+ return { ...inner, layout: `json>${inner.layout}` };
71
+ }
72
+ if (Array.isArray(history)) {
73
+ const entries = history.map((e, i) => {
74
+ let n;
75
+ if (isRec(e))
76
+ for (const k of NUMBER_KEYS)
77
+ n ??= asInt(e[k]);
78
+ return [n ?? i, standingOf(e)];
79
+ });
80
+ return { entries, layout: 'array', shape: 'array' };
81
+ }
82
+ if (!isRec(history))
83
+ return { entries: [], layout: 'none', shape: history === null ? 'null' : typeof history };
84
+ for (const k of WRAPPER_KEYS) {
85
+ const v = history[k];
86
+ if (v === undefined)
87
+ continue;
88
+ const inner = parseHistory(v, opts);
89
+ return { ...inner, layout: `wrapper:${k}>${inner.layout}`, shape: 'object' };
90
+ }
91
+ let dist;
92
+ for (const k of DISTRIBUTION_KEYS)
93
+ dist ??= history[k];
94
+ const standings = [];
95
+ for (const [k, v] of Object.entries(history)) {
96
+ const m = STANDING_KEY.exec(k);
97
+ if (m)
98
+ standings.push([Number(m[1]), standingOf(v)]);
99
+ }
100
+ if (standings.length) {
101
+ // Top-level `standing<N>` keys (#302), `turn<N>` beside them being orders: is standing0 the
102
+ // start, or the board after the first turn? UNVERIFIED. A distribution standing beside them
103
+ // decides: one on which no player holds land is the board before picks, so standing0 is the
104
+ // start (the board after picks); one with player land is the start itself, so standing0 is one
105
+ // turn on. Without one, the game's completed turns decide when the last N reaches them or
106
+ // falls one short.
107
+ const last = Math.max(...standings.map(([n]) => n));
108
+ const t = opts.numberOfTurns;
109
+ const offset = dist !== undefined
110
+ ? playerLand(dist)
111
+ ? 1
112
+ : 0
113
+ : t !== undefined && last === t - 1
114
+ ? 1
115
+ : 0;
116
+ const entries = standings.map(([n, v]) => [n + offset, v]);
117
+ if (dist !== undefined && !entries.some(([n]) => n === 0))
118
+ entries.push([0, standingOf(dist)]);
119
+ return {
120
+ entries,
121
+ layout: `standing-keys${offset ? '+1' : ''}${dist !== undefined ? '+distribution' : ''}`,
122
+ shape: 'object',
123
+ };
124
+ }
125
+ // Turn-numbered keys (`turn<N>` / `<N>`): an entry that carries orders is never a board (the
126
+ // Warlight-era `turn<N>` is the turn's orders). A distribution standing is entry 0 only when a
127
+ // player holds land on it: a land-free one is the board before picks, never turn 1's previous board.
128
+ const entries = [];
129
+ for (const [k, v] of Object.entries(history)) {
130
+ const m = /^(?:turn)?_?(\d+)$/i.exec(k);
131
+ if (m && !carriesOrders(v))
132
+ entries.push([Number(m[1]), standingOf(v)]);
133
+ }
134
+ if (dist !== undefined && playerLand(dist) && !entries.some(([n]) => n === 0))
135
+ entries.push([0, standingOf(dist)]);
136
+ return { entries, layout: 'numbered-keys', shape: 'object' };
137
+ }
138
+ /**
139
+ * The standing after `completedTurns` turns from a raw `GetHistory` payload,
140
+ * with owners keyed by GameFeed player id; `undefined` when it is absent or
141
+ * unusable. An entry's number is read as the count of completed turns its
142
+ * standing reflects (an assumption: the shape is unverified, #302). The first
143
+ * entry of that number that parses wins. Never throws.
144
+ */
145
+ export function boardFromHistory(history, completedTurns, players, opts = {}) {
146
+ try {
147
+ for (const [n, raw] of parseHistory(history, opts).entries) {
148
+ if (n !== completedTurns)
149
+ continue;
150
+ const board = feedOwners(boardFromStanding(raw), players);
151
+ if (board)
152
+ return board;
153
+ }
154
+ return undefined;
155
+ }
156
+ catch {
157
+ return undefined;
158
+ }
159
+ }
160
+ /** A parsed board with in-game owner ids mapped back to GameFeed player ids. */
161
+ function feedOwners(board, players) {
162
+ if (!board)
163
+ return undefined;
164
+ const byInGame = playersByInGameId(players);
165
+ const feedIds = new Set(players.map((p) => p.id));
166
+ return {
167
+ ...board,
168
+ territories: board.territories.map((t) => {
169
+ if (t.owner.kind !== 'player' || feedIds.has(t.owner.playerId))
170
+ return t;
171
+ const p = byInGame.get(t.owner.playerId);
172
+ return p ? { ...t, owner: { kind: 'player', playerId: p.id } } : t;
173
+ }),
174
+ };
175
+ }
176
+ /**
177
+ * Every usable standing in a raw `GetHistory` payload, ascending by entry
178
+ * number (completed turns, as {@link boardFromHistory} reads it), owners keyed
179
+ * by GameFeed player id. Entries that do not parse are left out; the first of
180
+ * two entries with one number that parses wins. Never throws.
181
+ */
182
+ export function historyBoards(history, players, opts = {}) {
183
+ try {
184
+ const seen = new Set();
185
+ const out = [];
186
+ for (const [turn, raw] of parseHistory(history, opts).entries) {
187
+ if (seen.has(turn))
188
+ continue;
189
+ const board = feedOwners(boardFromStanding(raw), players);
190
+ if (!board)
191
+ continue;
192
+ seen.add(turn);
193
+ out.push({ turn, board });
194
+ }
195
+ return out.sort((a, b) => a.turn - b.turn);
196
+ }
197
+ catch {
198
+ return [];
199
+ }
200
+ }
201
+ /** At most this many key names go into a report (#302). */
202
+ const MAX_REPORTED_KEYS = 40;
203
+ /** A key name that may be reported: an identifier, never free text. */
204
+ const SAFE_KEY = /^[A-Za-z][A-Za-z0-9_]{0,39}$/;
205
+ /** The key names of a reply or entry worth reporting: identifiers only, capped (#302). */
206
+ export function safeKeys(keys) {
207
+ return keys.filter((k) => SAFE_KEY.test(k)).slice(0, MAX_REPORTED_KEYS);
208
+ }
209
+ /**
210
+ * Whether a game's history reads, and if not why (#302): one live call then shows GameFeed's real
211
+ * shape. `needPlayerLand` (map statistics) also asks that some board shows a player of the game
212
+ * holding land. Name-free; never throws.
213
+ */
214
+ export function historyReport(game, opts = {}) {
215
+ const keys = safeKeys(game.feedKeys ?? []);
216
+ if (game.history === undefined)
217
+ return { unreadable: { reason: 'absent', keys } };
218
+ let parsed;
219
+ try {
220
+ parsed = parseHistory(game.history, game.numberOfTurns !== undefined ? { numberOfTurns: game.numberOfTurns } : {});
221
+ }
222
+ catch {
223
+ parsed = { entries: [], layout: 'none', shape: 'object' };
224
+ }
225
+ const { entries, shape, layout } = parsed;
226
+ if (shape === 'string')
227
+ return { unreadable: { reason: 'not-json', keys, shape } };
228
+ if (!entries.length) {
229
+ const own = isRec(game.history) ? { historyKeys: safeKeys(Object.keys(game.history)) } : {};
230
+ return { unreadable: { reason: 'no-turns', keys, shape, ...own } };
231
+ }
232
+ const boards = historyBoards(game.history, game.players, game.numberOfTurns !== undefined ? { numberOfTurns: game.numberOfTurns } : {});
233
+ if (!boards.length) {
234
+ const first = entries[0][1];
235
+ const entryKeys = isRec(first) ? { entryKeys: safeKeys(Object.keys(first)) } : {};
236
+ return { unreadable: { reason: 'no-standing', keys, shape, turns: entries.length, ...entryKeys } };
237
+ }
238
+ if (opts.needPlayerLand) {
239
+ const ids = new Set(game.players.map((p) => p.id));
240
+ const land = boards.some(({ board }) => board.territories.some((t) => t.owner.kind === 'player' && ids.has(t.owner.playerId)));
241
+ if (!land)
242
+ return { unreadable: { reason: 'no-player-land', keys, shape, turns: boards.length } };
243
+ }
244
+ return { read: { turns: boards.length, first: boards[0].turn, last: boards[boards.length - 1].turn, layout } };
245
+ }
246
+ /** Where the last planned boards of a game are cached. */
247
+ export const boardCachePath = (dir, gameId) => join(dir, 'boards', `${gameId}.json`);
248
+ /**
249
+ * Turns kept per game: enough history for opponent tracking (an estimate over the
250
+ * last three observed turns needs four boards; more shows where the armies went
251
+ * since an opponent was first seen), and a turn planned again (another goal, or
252
+ * after a hand override) still finds the board of the turn before it.
253
+ */
254
+ export const CACHED_TURNS = 10;
255
+ /**
256
+ * Turns of the survival store's estimates kept per game (#275 review): every turn of a game, not only the
257
+ * boards' newest {@link CACHED_TURNS}, since the tripwire's stock bound reads every turn's kept estimate
258
+ * from turn 1 (and reads no stock with a turn missing). Numbers only, a few per turn.
259
+ */
260
+ export const SURVIVAL_TURNS = 200;
261
+ /** A game's cached boards not written for this long are deleted (finished or abandoned games). */
262
+ export const BOARD_CACHE_MAX_AGE_MS = 60 * 86_400_000;
263
+ const BOARD_FILE = /^\d+\.json$/;
264
+ /** Board directories pruned by this process: once is enough. */
265
+ const pruned = new Set();
266
+ /** Delete the board caches of games not written for {@link BOARD_CACHE_MAX_AGE_MS}. Best effort. */
267
+ async function pruneBoardCaches(dir) {
268
+ const boards = join(dir, 'boards');
269
+ if (pruned.has(boards))
270
+ return;
271
+ pruned.add(boards);
272
+ const cutoff = Date.now() - BOARD_CACHE_MAX_AGE_MS;
273
+ try {
274
+ for (const name of await readdir(boards)) {
275
+ if (!BOARD_FILE.test(name))
276
+ continue;
277
+ const file = join(boards, name);
278
+ try {
279
+ if ((await stat(file)).mtimeMs < cutoff)
280
+ await unlink(file);
281
+ }
282
+ catch {
283
+ // Gone already, or unreadable: leave it.
284
+ }
285
+ }
286
+ }
287
+ catch {
288
+ // No board directory yet.
289
+ }
290
+ }
291
+ const EMPTY = () => ({ turns: {}, orders: {}, expected: {}, estimates: {}, tripwires: [] });
292
+ /** The raw cache for `gameId` as `playerId` saw it: boards, orders and expected incomes by turn; empty when absent or unusable. */
293
+ async function readCache(dir, gameId, playerId) {
294
+ try {
295
+ const c = JSON.parse(await readFile(boardCachePath(dir, gameId), 'utf8'));
296
+ if (!isRec(c) || c.gameId !== gameId || c.playerId !== playerId)
297
+ return EMPTY();
298
+ const rest = {
299
+ orders: isRec(c.orders) ? c.orders : {},
300
+ expected: isRec(c.expected) ? c.expected : {},
301
+ estimates: isRec(c.estimates) ? c.estimates : {},
302
+ tripwires: Array.isArray(c.tripwires) ? c.tripwires : [],
303
+ };
304
+ if (isRec(c.turns))
305
+ return { turns: c.turns, ...rest };
306
+ // A single-board cache written before turns were kept.
307
+ if (typeof c.turn === 'number')
308
+ return { turns: { [String(c.turn)]: c.board }, ...rest };
309
+ return { turns: {}, ...rest };
310
+ }
311
+ catch {
312
+ return EMPTY();
313
+ }
314
+ }
315
+ /** The cache's optional parts as written back: the orders, expected incomes and survival store, when any are kept. */
316
+ function extras(cache) {
317
+ return {
318
+ ...(Object.keys(cache.orders).length ? { orders: cache.orders } : {}),
319
+ ...(Object.keys(cache.expected).length ? { expected: cache.expected } : {}),
320
+ ...(Object.keys(cache.estimates).length ? { estimates: cache.estimates } : {}),
321
+ ...(cache.tripwires.length ? { tripwires: cache.tripwires } : {}),
322
+ };
323
+ }
324
+ /** The cached boards by turn for `gameId` as `playerId` saw them; `{}` when absent or unusable. */
325
+ async function readCachedTurns(dir, gameId, playerId) {
326
+ return (await readCache(dir, gameId, playerId)).turns;
327
+ }
328
+ /** The newest `keep` ({@link CACHED_TURNS} by default) numeric keys of `rec` at or below `upTo`, ascending. */
329
+ function newestTurns(rec, upTo = Infinity, keep = CACHED_TURNS) {
330
+ return Object.keys(rec)
331
+ .filter((k) => /^\d+$/.test(k) && Number(k) <= upTo)
332
+ .map(Number)
333
+ .sort((a, b) => b - a)
334
+ .slice(0, keep)
335
+ .sort((a, b) => a - b);
336
+ }
337
+ /** Write a game's cache file atomically, then prune old games. */
338
+ async function writeCache(dir, body) {
339
+ const path = boardCachePath(dir, body.gameId);
340
+ await mkdir(join(dir, 'boards'), { recursive: true, mode: 0o700 });
341
+ const tmp = `${path}.${process.pid}.tmp`;
342
+ await writeFile(tmp, JSON.stringify(body), { mode: 0o600 });
343
+ await rename(tmp, path);
344
+ await pruneBoardCaches(dir);
345
+ }
346
+ const isNum = (v) => typeof v === 'number' && Number.isFinite(v);
347
+ /** Cached orders, loosely: unusable entries are dropped, never thrown on. */
348
+ function ordersOf(o) {
349
+ if (!isRec(o) || !Array.isArray(o.deploys) || !Array.isArray(o.moves))
350
+ return undefined;
351
+ return {
352
+ deploys: o.deploys
353
+ .filter((d) => isRec(d) && isNum(d.territoryId) && isNum(d.armies))
354
+ .map((d) => ({ territoryId: d.territoryId, armies: d.armies })),
355
+ moves: o.moves
356
+ .filter((m) => isRec(m) && isNum(m.from) && isNum(m.to) && isNum(m.armies))
357
+ .map((m) => ({ from: m.from, to: m.to, armies: m.armies, ...(m.commander === true ? { commander: true } : {}) })),
358
+ ...(Array.isArray(o.sent)
359
+ ? {
360
+ sent: o.sent
361
+ .filter((m) => isRec(m) && isNum(m.from) && isNum(m.to))
362
+ .map((m) => ({
363
+ from: m.from,
364
+ to: m.to,
365
+ ...(m.transferOnly === true ? { transferOnly: true } : {}),
366
+ ...(m.commander === true ? { commander: true } : {}),
367
+ })),
368
+ }
369
+ : {}),
370
+ ...(Array.isArray(o.cards)
371
+ ? {
372
+ cards: o.cards
373
+ .filter((c) => isRec(c) && typeof c.card === 'string')
374
+ .map((c) => ({
375
+ card: c.card,
376
+ ...(isNum(c.from) ? { from: c.from } : {}),
377
+ ...(isNum(c.to) ? { to: c.to } : {}),
378
+ ...(isNum(c.target) ? { target: c.target } : {}),
379
+ })),
380
+ }
381
+ : {}),
382
+ };
383
+ }
384
+ /** The orders this server sent for `gameId` as `playerId`, by turn (#119); empty when none. Never throws. */
385
+ export async function readCachedOrders(dir, gameId, playerId) {
386
+ const { orders } = await readCache(dir, gameId, playerId);
387
+ const out = new Map();
388
+ for (const turn of newestTurns(orders)) {
389
+ const o = ordersOf(orders[String(turn)]);
390
+ if (o)
391
+ out.set(turn, o);
392
+ }
393
+ return out;
394
+ }
395
+ /**
396
+ * Cache the deploys and moves this server sent for turn `turn` of `gameId` as `playerId` (#119),
397
+ * keeping the newest {@link CACHED_TURNS} turns of orders and every cached board; the newest send
398
+ * for a turn wins. Never throws.
399
+ */
400
+ export async function writeOrdersCache(dir, gameId, playerId, turn, orders) {
401
+ try {
402
+ const cache = await readCache(dir, gameId, playerId);
403
+ const all = { ...cache.orders, [String(turn)]: { deploys: orders.deploys, moves: orders.moves, ...(orders.sent ? { sent: orders.sent } : {}), ...(orders.cards ? { cards: orders.cards } : {}) } };
404
+ const kept = {};
405
+ for (const n of newestTurns(all))
406
+ kept[String(n)] = all[String(n)];
407
+ await writeCache(dir, { gameId, playerId, turns: cache.turns, ...extras(cache), orders: kept });
408
+ return true;
409
+ }
410
+ catch {
411
+ return false;
412
+ }
413
+ }
414
+ /**
415
+ * Forget the orders cached for turn `turn` of `gameId` as `playerId` (they were withdrawn with
416
+ * warapp_uncommit_turn, so they may never run and no longer measure that turn), keeping every
417
+ * other turn and every board. Writes nothing when none are cached. Never throws.
418
+ */
419
+ export async function dropOrdersCache(dir, gameId, playerId, turn) {
420
+ try {
421
+ const cache = await readCache(dir, gameId, playerId);
422
+ if (!(String(turn) in cache.orders))
423
+ return true;
424
+ const orders = { ...cache.orders };
425
+ delete orders[String(turn)];
426
+ await writeCache(dir, { gameId, playerId, turns: cache.turns, ...extras(cache), orders });
427
+ return true;
428
+ }
429
+ catch {
430
+ return false;
431
+ }
432
+ }
433
+ /**
434
+ * The board this server planned on for `gameId`, only when it was planned for
435
+ * `playerId` on exactly turn `turn`; `undefined` otherwise. Never throws.
436
+ */
437
+ export async function readBoardCache(dir, gameId, playerId, turn) {
438
+ return boardOf((await readCachedTurns(dir, gameId, playerId))[String(turn)]);
439
+ }
440
+ /** A cached board, loosely: unusable entries are dropped, never thrown on. */
441
+ function boardOf(b) {
442
+ if (!isRec(b) || !Array.isArray(b.territories))
443
+ return undefined;
444
+ const territories = b.territories.filter((t) => isRec(t) &&
445
+ typeof t.territoryId === 'number' &&
446
+ isRec(t.owner) &&
447
+ (typeof t.armies === 'number' || t.armies === null));
448
+ return { source: b.source === 'gamefeed' ? 'gamefeed' : 'browser', verified: b.verified === true, territories };
449
+ }
450
+ /**
451
+ * Every board cached for `gameId` as `playerId` saw it, oldest turn first, only turns below
452
+ * `before` when given; `[]` when there are none. Never throws.
453
+ */
454
+ export async function readBoardHistory(dir, gameId, playerId, before) {
455
+ const turns = await readCachedTurns(dir, gameId, playerId);
456
+ const out = [];
457
+ for (const [k, v] of Object.entries(turns)) {
458
+ if (!/^\d+$/.test(k))
459
+ continue;
460
+ const turn = Number(k);
461
+ if (before !== undefined && turn >= before)
462
+ continue;
463
+ const board = boardOf(v);
464
+ if (board)
465
+ out.push({ turn, board });
466
+ }
467
+ return out.sort((a, b) => a.turn - b.turn);
468
+ }
469
+ /**
470
+ * The next income the plan of turn `turn` of `gameId` expected (#194), as `playerId` planned it;
471
+ * `undefined` when that turn was not planned here or the figure is unusable. Never throws.
472
+ */
473
+ export async function readExpectedIncome(dir, gameId, playerId, turn) {
474
+ const v = (await readCache(dir, gameId, playerId)).expected[String(turn)];
475
+ return isNum(v) && v >= 0 ? v : undefined;
476
+ }
477
+ /**
478
+ * Cache the board just planned on (turn `turn` of `gameId`, as `playerId` sees
479
+ * it), keeping the newest {@link CACHED_TURNS} turns; a different player's
480
+ * cache is replaced. With `expectedNextIncome` (a plan's `expected.nextIncome`,
481
+ * #194), that figure is kept for the turn too, the newest plan of a turn winning;
482
+ * without it, the turn's figure already kept stays. Never throws.
483
+ */
484
+ export async function writeBoardCache(dir, gameId, playerId, turn, board, expectedNextIncome) {
485
+ try {
486
+ const cache = await readCache(dir, gameId, playerId);
487
+ // A team game's teammate orders are this turn's entries, not the board: never cached (C1).
488
+ const { teammateOrders: _entries, ...plain } = board;
489
+ const kept = { ...cache.turns, [String(turn)]: plain };
490
+ const turns = {};
491
+ for (const n of newestTurns(kept, turn))
492
+ turns[String(n)] = kept[String(n)];
493
+ const allExpected = { ...cache.expected, ...(expectedNextIncome !== undefined ? { [String(turn)]: expectedNextIncome } : {}) };
494
+ const expected = {};
495
+ for (const n of newestTurns(allExpected, turn))
496
+ expected[String(n)] = allExpected[String(n)];
497
+ await writeCache(dir, { gameId, playerId, turns, ...extras({ ...cache, expected }) });
498
+ return true;
499
+ }
500
+ catch {
501
+ return false;
502
+ }
503
+ }
504
+ /**
505
+ * The player whose view is cached for `gameId` (the file keeps one account's boards), for offline
506
+ * replay (src/replay.ts); `undefined` when there is no usable cache. Never throws.
507
+ */
508
+ export async function readCachedPlayer(dir, gameId) {
509
+ try {
510
+ const c = JSON.parse(await readFile(boardCachePath(dir, gameId), 'utf8'));
511
+ return isRec(c) && c.gameId === gameId && typeof c.playerId === 'number' ? c.playerId : undefined;
512
+ }
513
+ catch {
514
+ return undefined;
515
+ }
516
+ }
517
+ const TRIP_KINDS = new Set(['fog-stack', 'capture', 'held-attack']);
518
+ /** A kept tripwire, loosely: `undefined` when unusable. */
519
+ function tripwireOf(w) {
520
+ if (!isRec(w) || typeof w.kind !== 'string' || !TRIP_KINDS.has(w.kind))
521
+ return undefined;
522
+ const nums = ['player', 'since', 'until', 'territory', 'observed', 'allowed', 'implied'];
523
+ if (!nums.every((k) => isNum(w[k])))
524
+ return undefined;
525
+ return {
526
+ player: w.player,
527
+ since: w.since,
528
+ until: w.until,
529
+ kind: w.kind,
530
+ territory: w.territory,
531
+ observed: w.observed,
532
+ allowed: w.allowed,
533
+ implied: w.implied,
534
+ };
535
+ }
536
+ /** The survival side store (#275 b) kept for `gameId` as `playerId`; empty when none. Never throws. */
537
+ export async function readSurvival(dir, gameId, playerId) {
538
+ const cache = await readCache(dir, gameId, playerId);
539
+ const estimates = new Map();
540
+ for (const turn of newestTurns(cache.estimates, Infinity, SURVIVAL_TURNS)) {
541
+ const rec = cache.estimates[String(turn)];
542
+ if (!isRec(rec))
543
+ continue;
544
+ const row = new Map();
545
+ for (const [k, v] of Object.entries(rec))
546
+ if (/^\d+$/.test(k) && isNum(v) && v >= 0)
547
+ row.set(Number(k), v);
548
+ if (row.size)
549
+ estimates.set(turn, row);
550
+ }
551
+ const tripwires = cache.tripwires.map(tripwireOf).filter((w) => w !== undefined);
552
+ return { estimates, tripwires };
553
+ }
554
+ /**
555
+ * Keep turn `turn`'s opponent estimates and the untrusted marks now running (#275 b) for `gameId` as
556
+ * `playerId`, with the newest {@link SURVIVAL_TURNS} turns of estimates; the marks replace those kept.
557
+ * Never throws.
558
+ */
559
+ export async function writeSurvival(dir, gameId, playerId, turn, s) {
560
+ try {
561
+ const cache = await readCache(dir, gameId, playerId);
562
+ const all = { ...cache.estimates, [String(turn)]: Object.fromEntries([...s.estimates].map(([p, e]) => [String(p), e])) };
563
+ const estimates = {};
564
+ for (const n of newestTurns(all, Infinity, SURVIVAL_TURNS))
565
+ estimates[String(n)] = all[String(n)];
566
+ await writeCache(dir, {
567
+ gameId,
568
+ playerId,
569
+ turns: cache.turns,
570
+ ...extras({ ...cache, estimates, tripwires: [...s.tripwires] }),
571
+ });
572
+ return true;
573
+ }
574
+ catch {
575
+ return false;
576
+ }
577
+ }
@@ -0,0 +1,4 @@
1
+ // Single source of truth for the server version. release-please bumps the
2
+ // literal on the marked line (registered in release-please-config.json
3
+ // extra-files); every other module imports VERSION from here.
4
+ export const VERSION = '0.2.0'; // x-release-please-version