@chrischall/warapp-mcp 0.0.0-stage → 0.1.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 (179) hide show
  1. package/.claude-plugin/marketplace.json +34 -0
  2. package/.claude-plugin/plugin.json +21 -0
  3. package/.mcp.json +11 -0
  4. package/LICENSE +21 -0
  5. package/README.md +264 -2
  6. package/dist/analysis/award.js +159 -0
  7. package/dist/analysis/bonuses.js +98 -0
  8. package/dist/analysis/breach.js +62 -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/graph.js +82 -0
  19. package/dist/analysis/guard-off.js +54 -0
  20. package/dist/analysis/guess.js +351 -0
  21. package/dist/analysis/headroom.js +241 -0
  22. package/dist/analysis/hold-diff.js +64 -0
  23. package/dist/analysis/how-lost.js +130 -0
  24. package/dist/analysis/index.js +14 -0
  25. package/dist/analysis/local-deploy.js +159 -0
  26. package/dist/analysis/lookahead.js +108 -0
  27. package/dist/analysis/opponent-profile.js +551 -0
  28. package/dist/analysis/opponents.js +1245 -0
  29. package/dist/analysis/outlook.js +633 -0
  30. package/dist/analysis/overrides.js +60 -0
  31. package/dist/analysis/picks.js +1879 -0
  32. package/dist/analysis/plan/after-leftover.js +140 -0
  33. package/dist/analysis/plan/cap-spend.js +242 -0
  34. package/dist/analysis/plan/captures.js +1195 -0
  35. package/dist/analysis/plan/commander.js +236 -0
  36. package/dist/analysis/plan/completed.js +29 -0
  37. package/dist/analysis/plan/conceded-out.js +131 -0
  38. package/dist/analysis/plan/estimates.js +715 -0
  39. package/dist/analysis/plan/guard-off.js +232 -0
  40. package/dist/analysis/plan/holds.js +1631 -0
  41. package/dist/analysis/plan/leftover.js +760 -0
  42. package/dist/analysis/plan/move-order.js +319 -0
  43. package/dist/analysis/plan/orders.js +317 -0
  44. package/dist/analysis/plan/relations.js +702 -0
  45. package/dist/analysis/plan/report.js +672 -0
  46. package/dist/analysis/plan/shared.js +1218 -0
  47. package/dist/analysis/plan/stand-still.js +823 -0
  48. package/dist/analysis/plan/state.js +44 -0
  49. package/dist/analysis/plan/strike.js +1416 -0
  50. package/dist/analysis/plan/targets.js +651 -0
  51. package/dist/analysis/plan/team.js +299 -0
  52. package/dist/analysis/plan/threats.js +927 -0
  53. package/dist/analysis/plan/transfers.js +328 -0
  54. package/dist/analysis/plan/util.js +5 -0
  55. package/dist/analysis/plan/vacated.js +285 -0
  56. package/dist/analysis/planner.js +2922 -0
  57. package/dist/analysis/player-record.js +144 -0
  58. package/dist/analysis/player.js +268 -0
  59. package/dist/analysis/profile.js +347 -0
  60. package/dist/analysis/relations.js +1030 -0
  61. package/dist/analysis/schedule.js +88 -0
  62. package/dist/analysis/since-last.js +50 -0
  63. package/dist/analysis/static-seats.js +71 -0
  64. package/dist/analysis/stress.js +577 -0
  65. package/dist/analysis/team-brief.js +151 -0
  66. package/dist/analysis/tripwire.js +644 -0
  67. package/dist/analysis/turn-sim.js +259 -0
  68. package/dist/analysis/whereabouts.js +1109 -0
  69. package/dist/board.js +105 -0
  70. package/dist/bundle.js +143479 -0
  71. package/dist/cards.js +435 -0
  72. package/dist/chat-cursor.js +135 -0
  73. package/dist/chat.js +192 -0
  74. package/dist/client.js +361 -0
  75. package/dist/config.js +62 -0
  76. package/dist/direct/link.js +102 -0
  77. package/dist/direct/session.js +267 -0
  78. package/dist/direct/transport.js +424 -0
  79. package/dist/guess-salt.js +65 -0
  80. package/dist/hosted.js +24 -0
  81. package/dist/index.js +33 -0
  82. package/dist/join-color.js +140 -0
  83. package/dist/live.js +278 -0
  84. package/dist/map-stats.js +152 -0
  85. package/dist/map-store.js +204 -0
  86. package/dist/move-order.js +141 -0
  87. package/dist/my-games.js +180 -0
  88. package/dist/normalize.js +411 -0
  89. package/dist/open-games.js +537 -0
  90. package/dist/outlook-log.js +138 -0
  91. package/dist/path-lock.js +22 -0
  92. package/dist/pick-list.js +193 -0
  93. package/dist/player-record-store.js +229 -0
  94. package/dist/player-states.js +31 -0
  95. package/dist/profile-store.js +677 -0
  96. package/dist/protocol/bundle.js +375 -0
  97. package/dist/protocol/codec.js +556 -0
  98. package/dist/protocol/decoded.js +12 -0
  99. package/dist/protocol/interp.js +1904 -0
  100. package/dist/protocol/methods.js +531 -0
  101. package/dist/protocol/rpc.js +202 -0
  102. package/dist/push/listener.js +393 -0
  103. package/dist/push/packets.js +66 -0
  104. package/dist/push/socketio.js +333 -0
  105. package/dist/push/websocket.js +179 -0
  106. package/dist/redact.js +62 -0
  107. package/dist/relations-store.js +242 -0
  108. package/dist/replay.js +215 -0
  109. package/dist/scalars.js +28 -0
  110. package/dist/scout.js +346 -0
  111. package/dist/stats.js +269 -0
  112. package/dist/strategy/card-clock.js +185 -0
  113. package/dist/strategy/map-notes.js +128 -0
  114. package/dist/strategy/notes.js +2168 -0
  115. package/dist/team-cards.js +84 -0
  116. package/dist/team-orders.js +150 -0
  117. package/dist/teams.js +19 -0
  118. package/dist/tools/award.js +206 -0
  119. package/dist/tools/begin-turn.js +162 -0
  120. package/dist/tools/board.js +77 -0
  121. package/dist/tools/card-advice.js +256 -0
  122. package/dist/tools/card-effects.js +49 -0
  123. package/dist/tools/card-plays.js +434 -0
  124. package/dist/tools/card-support-advice.js +140 -0
  125. package/dist/tools/chat-inbox.js +146 -0
  126. package/dist/tools/chat.js +483 -0
  127. package/dist/tools/check-plan.js +688 -0
  128. package/dist/tools/commander-check.js +102 -0
  129. package/dist/tools/commitments.js +216 -0
  130. package/dist/tools/common.js +143 -0
  131. package/dist/tools/diplomacy.js +342 -0
  132. package/dist/tools/game.js +126 -0
  133. package/dist/tools/guess-view.js +56 -0
  134. package/dist/tools/healthcheck.js +90 -0
  135. package/dist/tools/hints.js +34 -0
  136. package/dist/tools/how-lost.js +154 -0
  137. package/dist/tools/index.js +142 -0
  138. package/dist/tools/join-game.js +327 -0
  139. package/dist/tools/leave-game.js +181 -0
  140. package/dist/tools/live-context.js +339 -0
  141. package/dist/tools/live.js +404 -0
  142. package/dist/tools/map-stats.js +117 -0
  143. package/dist/tools/map.js +133 -0
  144. package/dist/tools/my-games.js +123 -0
  145. package/dist/tools/open-games.js +104 -0
  146. package/dist/tools/opponents.js +151 -0
  147. package/dist/tools/order-options.js +135 -0
  148. package/dist/tools/picks.js +292 -0
  149. package/dist/tools/profile-hook.js +156 -0
  150. package/dist/tools/profile-opponents.js +121 -0
  151. package/dist/tools/profile-reads.js +99 -0
  152. package/dist/tools/push.js +385 -0
  153. package/dist/tools/relations.js +611 -0
  154. package/dist/tools/resolve.js +45 -0
  155. package/dist/tools/route.js +36 -0
  156. package/dist/tools/scout.js +87 -0
  157. package/dist/tools/session.js +163 -0
  158. package/dist/tools/strategy.js +200 -0
  159. package/dist/tools/stress-opponents.js +83 -0
  160. package/dist/tools/surrender.js +240 -0
  161. package/dist/tools/survival.js +189 -0
  162. package/dist/tools/team-brief.js +266 -0
  163. package/dist/tools/team-source.js +222 -0
  164. package/dist/tools/team.js +182 -0
  165. package/dist/tools/turn.js +2761 -0
  166. package/dist/tools/uncommit.js +160 -0
  167. package/dist/tools/where.js +275 -0
  168. package/dist/tools/write-kit.js +158 -0
  169. package/dist/transport-bridge.js +33 -0
  170. package/dist/trend.js +452 -0
  171. package/dist/version.js +4 -0
  172. package/manifest.json +247 -0
  173. package/mint.yaml +140 -0
  174. package/package.json +68 -4
  175. package/server.json +72 -0
  176. package/skills/warapp-api/SKILL.md +226 -0
  177. package/skills/warapp-api/references/scout.mjs +348 -0
  178. package/skills/warapp-api/scripts/warapp.sh +228 -0
  179. package/skills/warapp-mcp/SKILL.md +1011 -0
package/dist/trend.js ADDED
@@ -0,0 +1,452 @@
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
+ function standingOf(entry) {
33
+ if (!isRec(entry))
34
+ return entry;
35
+ for (const k of STANDING_KEYS)
36
+ if (entry[k] !== undefined)
37
+ return entry[k];
38
+ return entry;
39
+ }
40
+ /** History entries as (completed turns, raw standing), in any of the plausible layouts. */
41
+ function entriesOf(history, out = []) {
42
+ if (Array.isArray(history)) {
43
+ history.forEach((e, i) => {
44
+ let n;
45
+ if (isRec(e))
46
+ for (const k of NUMBER_KEYS)
47
+ n ??= asInt(e[k]);
48
+ out.push([n ?? i, standingOf(e)]);
49
+ });
50
+ return out;
51
+ }
52
+ if (!isRec(history))
53
+ return out;
54
+ const turns = history.turns ?? history.Turns;
55
+ if (turns !== undefined)
56
+ return entriesOf(turns, out);
57
+ for (const [k, v] of Object.entries(history)) {
58
+ const m = /^(?:turn|standing)?_?(\d+)$/i.exec(k);
59
+ if (m)
60
+ out.push([Number(m[1]), standingOf(v)]);
61
+ }
62
+ return out;
63
+ }
64
+ /**
65
+ * The standing after `completedTurns` turns from a raw `GetHistory` payload,
66
+ * with owners keyed by GameFeed player id; `undefined` when it is absent or
67
+ * unusable. An entry's number is read as the count of completed turns its
68
+ * standing reflects (an assumption: the in-progress shape is unverified).
69
+ * Never throws.
70
+ */
71
+ export function boardFromHistory(history, completedTurns, players) {
72
+ try {
73
+ const raw = entriesOf(history).find(([n]) => n === completedTurns)?.[1];
74
+ return feedOwners(boardFromStanding(raw), players);
75
+ }
76
+ catch {
77
+ return undefined;
78
+ }
79
+ }
80
+ /** A parsed board with in-game owner ids mapped back to GameFeed player ids. */
81
+ function feedOwners(board, players) {
82
+ if (!board)
83
+ return undefined;
84
+ const byInGame = playersByInGameId(players);
85
+ const feedIds = new Set(players.map((p) => p.id));
86
+ return {
87
+ ...board,
88
+ territories: board.territories.map((t) => {
89
+ if (t.owner.kind !== 'player' || feedIds.has(t.owner.playerId))
90
+ return t;
91
+ const p = byInGame.get(t.owner.playerId);
92
+ return p ? { ...t, owner: { kind: 'player', playerId: p.id } } : t;
93
+ }),
94
+ };
95
+ }
96
+ /**
97
+ * Every usable standing in a raw `GetHistory` payload, ascending by entry
98
+ * number (completed turns, as {@link boardFromHistory} reads it), owners keyed
99
+ * by GameFeed player id. Entries that do not parse are left out; the first of
100
+ * two entries with one number wins. Never throws.
101
+ */
102
+ export function historyBoards(history, players) {
103
+ try {
104
+ const seen = new Set();
105
+ const out = [];
106
+ for (const [turn, raw] of entriesOf(history)) {
107
+ if (seen.has(turn))
108
+ continue;
109
+ const board = feedOwners(boardFromStanding(raw), players);
110
+ if (!board)
111
+ continue;
112
+ seen.add(turn);
113
+ out.push({ turn, board });
114
+ }
115
+ return out.sort((a, b) => a.turn - b.turn);
116
+ }
117
+ catch {
118
+ return [];
119
+ }
120
+ }
121
+ /** Where the last planned boards of a game are cached. */
122
+ export const boardCachePath = (dir, gameId) => join(dir, 'boards', `${gameId}.json`);
123
+ /**
124
+ * Turns kept per game: enough history for opponent tracking (an estimate over the
125
+ * last three observed turns needs four boards; more shows where the armies went
126
+ * since an opponent was first seen), and a turn planned again (another goal, or
127
+ * after a hand override) still finds the board of the turn before it.
128
+ */
129
+ export const CACHED_TURNS = 10;
130
+ /**
131
+ * Turns of the survival store's estimates kept per game (#275 review): every turn of a game, not only the
132
+ * boards' newest {@link CACHED_TURNS}, since the tripwire's stock bound reads every turn's kept estimate
133
+ * from turn 1 (and reads no stock with a turn missing). Numbers only, a few per turn.
134
+ */
135
+ export const SURVIVAL_TURNS = 200;
136
+ /** A game's cached boards not written for this long are deleted (finished or abandoned games). */
137
+ export const BOARD_CACHE_MAX_AGE_MS = 60 * 86_400_000;
138
+ const BOARD_FILE = /^\d+\.json$/;
139
+ /** Board directories pruned by this process: once is enough. */
140
+ const pruned = new Set();
141
+ /** Delete the board caches of games not written for {@link BOARD_CACHE_MAX_AGE_MS}. Best effort. */
142
+ async function pruneBoardCaches(dir) {
143
+ const boards = join(dir, 'boards');
144
+ if (pruned.has(boards))
145
+ return;
146
+ pruned.add(boards);
147
+ const cutoff = Date.now() - BOARD_CACHE_MAX_AGE_MS;
148
+ try {
149
+ for (const name of await readdir(boards)) {
150
+ if (!BOARD_FILE.test(name))
151
+ continue;
152
+ const file = join(boards, name);
153
+ try {
154
+ if ((await stat(file)).mtimeMs < cutoff)
155
+ await unlink(file);
156
+ }
157
+ catch {
158
+ // Gone already, or unreadable: leave it.
159
+ }
160
+ }
161
+ }
162
+ catch {
163
+ // No board directory yet.
164
+ }
165
+ }
166
+ const EMPTY = () => ({ turns: {}, orders: {}, expected: {}, estimates: {}, tripwires: [] });
167
+ /** The raw cache for `gameId` as `playerId` saw it: boards, orders and expected incomes by turn; empty when absent or unusable. */
168
+ async function readCache(dir, gameId, playerId) {
169
+ try {
170
+ const c = JSON.parse(await readFile(boardCachePath(dir, gameId), 'utf8'));
171
+ if (!isRec(c) || c.gameId !== gameId || c.playerId !== playerId)
172
+ return EMPTY();
173
+ const rest = {
174
+ orders: isRec(c.orders) ? c.orders : {},
175
+ expected: isRec(c.expected) ? c.expected : {},
176
+ estimates: isRec(c.estimates) ? c.estimates : {},
177
+ tripwires: Array.isArray(c.tripwires) ? c.tripwires : [],
178
+ };
179
+ if (isRec(c.turns))
180
+ return { turns: c.turns, ...rest };
181
+ // A single-board cache written before turns were kept.
182
+ if (typeof c.turn === 'number')
183
+ return { turns: { [String(c.turn)]: c.board }, ...rest };
184
+ return { turns: {}, ...rest };
185
+ }
186
+ catch {
187
+ return EMPTY();
188
+ }
189
+ }
190
+ /** The cache's optional parts as written back: the orders, expected incomes and survival store, when any are kept. */
191
+ function extras(cache) {
192
+ return {
193
+ ...(Object.keys(cache.orders).length ? { orders: cache.orders } : {}),
194
+ ...(Object.keys(cache.expected).length ? { expected: cache.expected } : {}),
195
+ ...(Object.keys(cache.estimates).length ? { estimates: cache.estimates } : {}),
196
+ ...(cache.tripwires.length ? { tripwires: cache.tripwires } : {}),
197
+ };
198
+ }
199
+ /** The cached boards by turn for `gameId` as `playerId` saw them; `{}` when absent or unusable. */
200
+ async function readCachedTurns(dir, gameId, playerId) {
201
+ return (await readCache(dir, gameId, playerId)).turns;
202
+ }
203
+ /** The newest `keep` ({@link CACHED_TURNS} by default) numeric keys of `rec` at or below `upTo`, ascending. */
204
+ function newestTurns(rec, upTo = Infinity, keep = CACHED_TURNS) {
205
+ return Object.keys(rec)
206
+ .filter((k) => /^\d+$/.test(k) && Number(k) <= upTo)
207
+ .map(Number)
208
+ .sort((a, b) => b - a)
209
+ .slice(0, keep)
210
+ .sort((a, b) => a - b);
211
+ }
212
+ /** Write a game's cache file atomically, then prune old games. */
213
+ async function writeCache(dir, body) {
214
+ const path = boardCachePath(dir, body.gameId);
215
+ await mkdir(join(dir, 'boards'), { recursive: true, mode: 0o700 });
216
+ const tmp = `${path}.${process.pid}.tmp`;
217
+ await writeFile(tmp, JSON.stringify(body), { mode: 0o600 });
218
+ await rename(tmp, path);
219
+ await pruneBoardCaches(dir);
220
+ }
221
+ const isNum = (v) => typeof v === 'number' && Number.isFinite(v);
222
+ /** Cached orders, loosely: unusable entries are dropped, never thrown on. */
223
+ function ordersOf(o) {
224
+ if (!isRec(o) || !Array.isArray(o.deploys) || !Array.isArray(o.moves))
225
+ return undefined;
226
+ return {
227
+ deploys: o.deploys
228
+ .filter((d) => isRec(d) && isNum(d.territoryId) && isNum(d.armies))
229
+ .map((d) => ({ territoryId: d.territoryId, armies: d.armies })),
230
+ moves: o.moves
231
+ .filter((m) => isRec(m) && isNum(m.from) && isNum(m.to) && isNum(m.armies))
232
+ .map((m) => ({ from: m.from, to: m.to, armies: m.armies, ...(m.commander === true ? { commander: true } : {}) })),
233
+ ...(Array.isArray(o.sent)
234
+ ? {
235
+ sent: o.sent
236
+ .filter((m) => isRec(m) && isNum(m.from) && isNum(m.to))
237
+ .map((m) => ({
238
+ from: m.from,
239
+ to: m.to,
240
+ ...(m.transferOnly === true ? { transferOnly: true } : {}),
241
+ ...(m.commander === true ? { commander: true } : {}),
242
+ })),
243
+ }
244
+ : {}),
245
+ ...(Array.isArray(o.cards)
246
+ ? {
247
+ cards: o.cards
248
+ .filter((c) => isRec(c) && typeof c.card === 'string')
249
+ .map((c) => ({
250
+ card: c.card,
251
+ ...(isNum(c.from) ? { from: c.from } : {}),
252
+ ...(isNum(c.to) ? { to: c.to } : {}),
253
+ ...(isNum(c.target) ? { target: c.target } : {}),
254
+ })),
255
+ }
256
+ : {}),
257
+ };
258
+ }
259
+ /** The orders this server sent for `gameId` as `playerId`, by turn (#119); empty when none. Never throws. */
260
+ export async function readCachedOrders(dir, gameId, playerId) {
261
+ const { orders } = await readCache(dir, gameId, playerId);
262
+ const out = new Map();
263
+ for (const turn of newestTurns(orders)) {
264
+ const o = ordersOf(orders[String(turn)]);
265
+ if (o)
266
+ out.set(turn, o);
267
+ }
268
+ return out;
269
+ }
270
+ /**
271
+ * Cache the deploys and moves this server sent for turn `turn` of `gameId` as `playerId` (#119),
272
+ * keeping the newest {@link CACHED_TURNS} turns of orders and every cached board; the newest send
273
+ * for a turn wins. Never throws.
274
+ */
275
+ export async function writeOrdersCache(dir, gameId, playerId, turn, orders) {
276
+ try {
277
+ const cache = await readCache(dir, gameId, playerId);
278
+ const all = { ...cache.orders, [String(turn)]: { deploys: orders.deploys, moves: orders.moves, ...(orders.sent ? { sent: orders.sent } : {}), ...(orders.cards ? { cards: orders.cards } : {}) } };
279
+ const kept = {};
280
+ for (const n of newestTurns(all))
281
+ kept[String(n)] = all[String(n)];
282
+ await writeCache(dir, { gameId, playerId, turns: cache.turns, ...extras(cache), orders: kept });
283
+ return true;
284
+ }
285
+ catch {
286
+ return false;
287
+ }
288
+ }
289
+ /**
290
+ * Forget the orders cached for turn `turn` of `gameId` as `playerId` (they were withdrawn with
291
+ * warapp_uncommit_turn, so they may never run and no longer measure that turn), keeping every
292
+ * other turn and every board. Writes nothing when none are cached. Never throws.
293
+ */
294
+ export async function dropOrdersCache(dir, gameId, playerId, turn) {
295
+ try {
296
+ const cache = await readCache(dir, gameId, playerId);
297
+ if (!(String(turn) in cache.orders))
298
+ return true;
299
+ const orders = { ...cache.orders };
300
+ delete orders[String(turn)];
301
+ await writeCache(dir, { gameId, playerId, turns: cache.turns, ...extras(cache), orders });
302
+ return true;
303
+ }
304
+ catch {
305
+ return false;
306
+ }
307
+ }
308
+ /**
309
+ * The board this server planned on for `gameId`, only when it was planned for
310
+ * `playerId` on exactly turn `turn`; `undefined` otherwise. Never throws.
311
+ */
312
+ export async function readBoardCache(dir, gameId, playerId, turn) {
313
+ return boardOf((await readCachedTurns(dir, gameId, playerId))[String(turn)]);
314
+ }
315
+ /** A cached board, loosely: unusable entries are dropped, never thrown on. */
316
+ function boardOf(b) {
317
+ if (!isRec(b) || !Array.isArray(b.territories))
318
+ return undefined;
319
+ const territories = b.territories.filter((t) => isRec(t) &&
320
+ typeof t.territoryId === 'number' &&
321
+ isRec(t.owner) &&
322
+ (typeof t.armies === 'number' || t.armies === null));
323
+ return { source: b.source === 'gamefeed' ? 'gamefeed' : 'browser', verified: b.verified === true, territories };
324
+ }
325
+ /**
326
+ * Every board cached for `gameId` as `playerId` saw it, oldest turn first, only turns below
327
+ * `before` when given; `[]` when there are none. Never throws.
328
+ */
329
+ export async function readBoardHistory(dir, gameId, playerId, before) {
330
+ const turns = await readCachedTurns(dir, gameId, playerId);
331
+ const out = [];
332
+ for (const [k, v] of Object.entries(turns)) {
333
+ if (!/^\d+$/.test(k))
334
+ continue;
335
+ const turn = Number(k);
336
+ if (before !== undefined && turn >= before)
337
+ continue;
338
+ const board = boardOf(v);
339
+ if (board)
340
+ out.push({ turn, board });
341
+ }
342
+ return out.sort((a, b) => a.turn - b.turn);
343
+ }
344
+ /**
345
+ * The next income the plan of turn `turn` of `gameId` expected (#194), as `playerId` planned it;
346
+ * `undefined` when that turn was not planned here or the figure is unusable. Never throws.
347
+ */
348
+ export async function readExpectedIncome(dir, gameId, playerId, turn) {
349
+ const v = (await readCache(dir, gameId, playerId)).expected[String(turn)];
350
+ return isNum(v) && v >= 0 ? v : undefined;
351
+ }
352
+ /**
353
+ * Cache the board just planned on (turn `turn` of `gameId`, as `playerId` sees
354
+ * it), keeping the newest {@link CACHED_TURNS} turns; a different player's
355
+ * cache is replaced. With `expectedNextIncome` (a plan's `expected.nextIncome`,
356
+ * #194), that figure is kept for the turn too, the newest plan of a turn winning;
357
+ * without it, the turn's figure already kept stays. Never throws.
358
+ */
359
+ export async function writeBoardCache(dir, gameId, playerId, turn, board, expectedNextIncome) {
360
+ try {
361
+ const cache = await readCache(dir, gameId, playerId);
362
+ // A team game's teammate orders are this turn's entries, not the board: never cached (C1).
363
+ const { teammateOrders: _entries, ...plain } = board;
364
+ const kept = { ...cache.turns, [String(turn)]: plain };
365
+ const turns = {};
366
+ for (const n of newestTurns(kept, turn))
367
+ turns[String(n)] = kept[String(n)];
368
+ const allExpected = { ...cache.expected, ...(expectedNextIncome !== undefined ? { [String(turn)]: expectedNextIncome } : {}) };
369
+ const expected = {};
370
+ for (const n of newestTurns(allExpected, turn))
371
+ expected[String(n)] = allExpected[String(n)];
372
+ await writeCache(dir, { gameId, playerId, turns, ...extras({ ...cache, expected }) });
373
+ return true;
374
+ }
375
+ catch {
376
+ return false;
377
+ }
378
+ }
379
+ /**
380
+ * The player whose view is cached for `gameId` (the file keeps one account's boards), for offline
381
+ * replay (src/replay.ts); `undefined` when there is no usable cache. Never throws.
382
+ */
383
+ export async function readCachedPlayer(dir, gameId) {
384
+ try {
385
+ const c = JSON.parse(await readFile(boardCachePath(dir, gameId), 'utf8'));
386
+ return isRec(c) && c.gameId === gameId && typeof c.playerId === 'number' ? c.playerId : undefined;
387
+ }
388
+ catch {
389
+ return undefined;
390
+ }
391
+ }
392
+ const TRIP_KINDS = new Set(['fog-stack', 'capture', 'held-attack']);
393
+ /** A kept tripwire, loosely: `undefined` when unusable. */
394
+ function tripwireOf(w) {
395
+ if (!isRec(w) || typeof w.kind !== 'string' || !TRIP_KINDS.has(w.kind))
396
+ return undefined;
397
+ const nums = ['player', 'since', 'until', 'territory', 'observed', 'allowed', 'implied'];
398
+ if (!nums.every((k) => isNum(w[k])))
399
+ return undefined;
400
+ return {
401
+ player: w.player,
402
+ since: w.since,
403
+ until: w.until,
404
+ kind: w.kind,
405
+ territory: w.territory,
406
+ observed: w.observed,
407
+ allowed: w.allowed,
408
+ implied: w.implied,
409
+ };
410
+ }
411
+ /** The survival side store (#275 b) kept for `gameId` as `playerId`; empty when none. Never throws. */
412
+ export async function readSurvival(dir, gameId, playerId) {
413
+ const cache = await readCache(dir, gameId, playerId);
414
+ const estimates = new Map();
415
+ for (const turn of newestTurns(cache.estimates, Infinity, SURVIVAL_TURNS)) {
416
+ const rec = cache.estimates[String(turn)];
417
+ if (!isRec(rec))
418
+ continue;
419
+ const row = new Map();
420
+ for (const [k, v] of Object.entries(rec))
421
+ if (/^\d+$/.test(k) && isNum(v) && v >= 0)
422
+ row.set(Number(k), v);
423
+ if (row.size)
424
+ estimates.set(turn, row);
425
+ }
426
+ const tripwires = cache.tripwires.map(tripwireOf).filter((w) => w !== undefined);
427
+ return { estimates, tripwires };
428
+ }
429
+ /**
430
+ * Keep turn `turn`'s opponent estimates and the untrusted marks now running (#275 b) for `gameId` as
431
+ * `playerId`, with the newest {@link SURVIVAL_TURNS} turns of estimates; the marks replace those kept.
432
+ * Never throws.
433
+ */
434
+ export async function writeSurvival(dir, gameId, playerId, turn, s) {
435
+ try {
436
+ const cache = await readCache(dir, gameId, playerId);
437
+ const all = { ...cache.estimates, [String(turn)]: Object.fromEntries([...s.estimates].map(([p, e]) => [String(p), e])) };
438
+ const estimates = {};
439
+ for (const n of newestTurns(all, Infinity, SURVIVAL_TURNS))
440
+ estimates[String(n)] = all[String(n)];
441
+ await writeCache(dir, {
442
+ gameId,
443
+ playerId,
444
+ turns: cache.turns,
445
+ ...extras({ ...cache, estimates, tripwires: [...s.tripwires] }),
446
+ });
447
+ return true;
448
+ }
449
+ catch {
450
+ return false;
451
+ }
452
+ }
@@ -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.1.0'; // x-release-please-version