@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
@@ -0,0 +1,165 @@
1
+ // The outlook log (#178): per game, the strength ratio of every turn this server planned and the
2
+ // latest outlook, plus the final result once a game this server logs is seen finished and, when
3
+ // it was lost, how (#274: `loss`, read from the cached boards; a log may hold only that). Local
4
+ // only, at `<dataDir>/outlook/<gameId>.json`, and name-free (player ids and figures, no names):
5
+ // it is the data the outlook's thresholds are to be calibrated from (OUTLOOK_RATIO is borrowed).
6
+ // Best effort: never throws.
7
+ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
8
+ import { randomUUID } from 'node:crypto';
9
+ import { join } from 'node:path';
10
+ const isRec = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
11
+ /** Turns kept per game (a long game is still a small file). */
12
+ const OUTLOOK_LOG_TURNS = 500;
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
+ });
19
+ /** The log of `gameId` as `playerId` played it; `undefined` when absent, another player's, or unusable. */
20
+ export async function readOutlookLog(dir, gameId, playerId) {
21
+ try {
22
+ const c = JSON.parse(await readFile(outlookLogPath(dir, gameId), 'utf8'));
23
+ if (!isRec(c) || c.gameId !== gameId || c.playerId !== playerId || !isRec(c.turns))
24
+ return undefined;
25
+ return c;
26
+ }
27
+ catch {
28
+ return undefined;
29
+ }
30
+ }
31
+ async function write(dir, log) {
32
+ const path = outlookLogPath(dir, log.gameId);
33
+ await mkdir(join(dir, 'outlook'), { recursive: true, mode: 0o700 });
34
+ // Unique per write: two plans of one game in this process must not share (and race on) a temp file.
35
+ const tmp = `${path}.${process.pid}.${randomUUID()}.tmp`;
36
+ await writeFile(tmp, JSON.stringify(log), { mode: 0o600 });
37
+ await rename(tmp, path);
38
+ }
39
+ /** Add the outlook's turns to the log and make it the latest. Best effort. */
40
+ export async function recordOutlook(dir, gameId, playerId, outlook) {
41
+ try {
42
+ const log = (await readOutlookLog(dir, gameId, playerId)) ?? { gameId, playerId, turns: {} };
43
+ for (const t of outlook.turns)
44
+ log.turns[String(t.turn)] = {
45
+ mine: t.mine,
46
+ low: t.strongest?.low ?? null,
47
+ high: t.strongest?.high ?? null,
48
+ ratio: t.ratio,
49
+ state: t.state,
50
+ ...(t.estimated ? { estimated: true } : {}),
51
+ ...(t.figures
52
+ ? {
53
+ figures: {
54
+ mine: { ...t.figures.mine },
55
+ strongest: t.figures.strongest && t.strongest
56
+ ? {
57
+ playerId: t.strongest.playerId,
58
+ ...(t.strongest.team !== undefined ? { team: t.strongest.team } : {}),
59
+ ...t.figures.strongest,
60
+ }
61
+ : null,
62
+ },
63
+ }
64
+ : {}),
65
+ ...(t.evidence ? { evidence: logged(t.evidence) } : {}),
66
+ };
67
+ const keep = Object.keys(log.turns)
68
+ .map(Number)
69
+ .sort((a, b) => b - a)
70
+ .slice(0, OUTLOOK_LOG_TURNS);
71
+ log.turns = Object.fromEntries(keep.sort((a, b) => a - b).map((k) => [String(k), log.turns[String(k)]]));
72
+ const last = outlook.turns.at(-1);
73
+ if (last)
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
+ };
81
+ await write(dir, log);
82
+ }
83
+ catch {
84
+ // The log is optional.
85
+ }
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
+ }
101
+ /** Record the final result of a game the log already holds; `true` when written. Best effort. */
102
+ export async function recordResult(dir, gameId, playerId, result) {
103
+ try {
104
+ const log = await readOutlookLog(dir, gameId, playerId);
105
+ if (!log)
106
+ return false;
107
+ if (log.result === result)
108
+ return true;
109
+ await write(dir, { ...log, result });
110
+ return true;
111
+ }
112
+ catch {
113
+ return false;
114
+ }
115
+ }
116
+ /** The player whose log `gameId` is; `undefined` when there is none. Never throws. */
117
+ export async function readOutlookPlayer(dir, gameId) {
118
+ try {
119
+ const c = JSON.parse(await readFile(outlookLogPath(dir, gameId), 'utf8'));
120
+ return isRec(c) && c.gameId === gameId && typeof c.playerId === 'number' ? c.playerId : undefined;
121
+ }
122
+ catch {
123
+ return undefined;
124
+ }
125
+ }
126
+ /**
127
+ * Keep how `gameId` was lost (#274) in its log, starting one when this server logged no outlook for
128
+ * it (the boards were cached by another tool); `true` when written, `false` (nothing written) when the
129
+ * log is another account's. Name-free: ids and figures. Best effort.
130
+ */
131
+ export async function recordLoss(dir, gameId, playerId, loss) {
132
+ try {
133
+ // Another account's log (its calibration turns) is never replaced.
134
+ const owner = await readOutlookPlayer(dir, gameId);
135
+ if (owner !== undefined && owner !== playerId)
136
+ return false;
137
+ const log = (await readOutlookLog(dir, gameId, playerId)) ?? { gameId, playerId, turns: {} };
138
+ if (JSON.stringify(log.loss) === JSON.stringify(loss))
139
+ return true;
140
+ await write(dir, { ...log, loss });
141
+ return true;
142
+ }
143
+ catch {
144
+ return false;
145
+ }
146
+ }
147
+ /**
148
+ * When `game` is finished and this server logs it, record the logged player's final GameFeed state
149
+ * as the result; `true` when written. Best effort.
150
+ */
151
+ export async function recordFinalResult(dir, game) {
152
+ if (game.state !== 'Finished')
153
+ return false;
154
+ try {
155
+ const c = JSON.parse(await readFile(outlookLogPath(dir, game.id), 'utf8'));
156
+ if (!isRec(c) || typeof c.playerId !== 'number')
157
+ return false;
158
+ const playerId = c.playerId;
159
+ const state = game.players.find((p) => p.id === playerId)?.state;
160
+ return state === undefined ? false : await recordResult(dir, game.id, playerId, state);
161
+ }
162
+ catch {
163
+ return false;
164
+ }
165
+ }
@@ -0,0 +1,22 @@
1
+ // An in-process lock per file path, for the read-modify-write stores (the agreement ledger and the
2
+ // cross-game player record): two tool calls in this process that read, change and write the same
3
+ // file run one after the other, so neither write loses the other's change. It serialises this
4
+ // process only; another process sharing the data directory is not covered (writes stay atomic, so a
5
+ // file is never torn, but the later writer wins).
6
+ const tails = new Map();
7
+ /** Run `fn` once every earlier section on `path` in this process has finished (thrown or not). */
8
+ export async function withPathLock(path, fn) {
9
+ const previous = tails.get(path) ?? Promise.resolve();
10
+ let release;
11
+ const tail = previous.then(() => new Promise((resolve) => (release = resolve)));
12
+ tails.set(path, tail);
13
+ await previous;
14
+ try {
15
+ return await fn();
16
+ }
17
+ finally {
18
+ release();
19
+ if (tails.get(path) === tail)
20
+ tails.delete(path);
21
+ }
22
+ }
@@ -0,0 +1,193 @@
1
+ // My pick list of a game, kept so the award can be read from it (#166, src/analysis/award.ts).
2
+ //
3
+ // war.app serves a player's picks while territories are being distributed; whether it still does
4
+ // afterwards is not verified, and the award can only be read against the list it used. So the
5
+ // list is written here when this server reads it back from war.app (after warapp_submit_picks,
6
+ // or by warapp_get_my_picks during distribution), at `<dataDir>/picks/<gameId>.json`, with the
7
+ // award read from it on the first board after distribution. The same file keeps the territories
8
+ // the live board showed as pickable during distribution (written by warapp_plan_picks and by
9
+ // warapp_submit_picks' preview): once the game starts nothing says where a player could have
10
+ // started, and warapp_locate_opponents needs it. #201: beside them, the neutrals the picking board
11
+ // showed and their armies, so a neutral the fog hides later (a wasteland) keeps a known size for the
12
+ // turn planner. A record may hold any of these. Territory ids
13
+ // only: no names, no other player's data. Best effort and never throws; a game's file not
14
+ // written for 60 days is deleted on the first write of a process.
15
+ import { mkdir, readdir, readFile, rename, stat, unlink, writeFile } from 'node:fs/promises';
16
+ import { join } from 'node:path';
17
+ import { OWNER_NEUTRAL } from './live.js';
18
+ /** Where a game's pick list is kept. */
19
+ export const pickListPath = (dir, gameId) => join(dir, 'picks', `${gameId}.json`);
20
+ /** A game's pick list not written for this long is deleted (finished or abandoned games). */
21
+ export const PICK_LIST_MAX_AGE_MS = 60 * 86_400_000;
22
+ const PICK_FILE = /^\d+\.json$/;
23
+ /** Pick directories pruned by this process: once is enough. */
24
+ const pruned = new Set();
25
+ const isRec = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
26
+ const isId = (v) => typeof v === 'number' && Number.isSafeInteger(v) && v > 0;
27
+ const isIds = (v) => Array.isArray(v) && v.every(isId);
28
+ const isArmies = (v) => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0;
29
+ /** `[territory, armies]` pairs, the malformed dropped, each territory once (the first), ascending. */
30
+ function neutralsOf(v) {
31
+ if (!Array.isArray(v))
32
+ return undefined;
33
+ const seen = new Map();
34
+ for (const e of v)
35
+ if (Array.isArray(e) && e.length === 2 && isId(e[0]) && isArmies(e[1]) && !seen.has(e[0]))
36
+ seen.set(e[0], e[1]);
37
+ return seen.size ? [...seen].sort((a, b) => a[0] - b[0]) : undefined;
38
+ }
39
+ /** A stored award, loosely: anything that does not look like one is dropped. */
40
+ function awardOf(v) {
41
+ if (v === null)
42
+ return null;
43
+ if (!isRec(v) || !isIds(v.granted) || !isIds(v.unlisted) || !isIds(v.opponentStarts))
44
+ return undefined;
45
+ if (typeof v.allStartsKnown !== 'boolean')
46
+ return undefined;
47
+ if (v.role !== null && v.role !== 'first' && v.role !== 'second')
48
+ return undefined;
49
+ if (v.opponentFirstAward !== null && !isId(v.opponentFirstAward))
50
+ return undefined;
51
+ return {
52
+ granted: v.granted,
53
+ unlisted: v.unlisted,
54
+ opponentStarts: v.opponentStarts,
55
+ allStartsKnown: v.allStartsKnown,
56
+ role: v.role,
57
+ opponentFirstAward: v.opponentFirstAward,
58
+ // A team game's (C2): kept only when it reads as ids.
59
+ ...(isIds(v.teammateStarts) ? { teammateStarts: v.teammateStarts } : {}),
60
+ };
61
+ }
62
+ /**
63
+ * The record kept for `gameId` when it is `playerId`'s: the pick list, the pickable territories, or
64
+ * both; `undefined` when absent or when it holds neither. An award is read only beside a list.
65
+ * Never throws.
66
+ */
67
+ export async function readPickRecord(dir, gameId, playerId) {
68
+ try {
69
+ const c = JSON.parse(await readFile(pickListPath(dir, gameId), 'utf8'));
70
+ if (!isRec(c) || c.gameId !== gameId || c.playerId !== playerId)
71
+ return undefined;
72
+ const list = isIds(c.list) && c.list.length ? c.list : undefined;
73
+ const pickable = isIds(c.pickable) && c.pickable.length ? c.pickable : undefined;
74
+ const neutrals = neutralsOf(c.neutrals);
75
+ if (!list && !pickable)
76
+ return undefined;
77
+ const award = list ? awardOf(c.award) : undefined;
78
+ return {
79
+ gameId,
80
+ playerId,
81
+ ...(list ? { list } : {}),
82
+ ...(pickable ? { pickable } : {}),
83
+ ...(neutrals ? { neutrals } : {}),
84
+ ...(award !== undefined ? { award } : {}),
85
+ };
86
+ }
87
+ catch {
88
+ return undefined;
89
+ }
90
+ }
91
+ /** Delete the pick lists of games not written for {@link PICK_LIST_MAX_AGE_MS}. Best effort. */
92
+ async function prunePickLists(dir) {
93
+ const picks = join(dir, 'picks');
94
+ if (pruned.has(picks))
95
+ return;
96
+ pruned.add(picks);
97
+ const cutoff = Date.now() - PICK_LIST_MAX_AGE_MS;
98
+ try {
99
+ for (const name of await readdir(picks)) {
100
+ if (!PICK_FILE.test(name))
101
+ continue;
102
+ const file = join(picks, name);
103
+ try {
104
+ if ((await stat(file)).mtimeMs < cutoff)
105
+ await unlink(file);
106
+ }
107
+ catch {
108
+ // Gone already, or unreadable: leave it.
109
+ }
110
+ }
111
+ }
112
+ catch {
113
+ // No pick directory yet.
114
+ }
115
+ }
116
+ async function writeRecord(dir, record) {
117
+ try {
118
+ const path = pickListPath(dir, record.gameId);
119
+ await mkdir(join(dir, 'picks'), { recursive: true, mode: 0o700 });
120
+ const tmp = `${path}.${process.pid}.tmp`;
121
+ await writeFile(tmp, JSON.stringify(record), { mode: 0o600 });
122
+ await rename(tmp, path);
123
+ await prunePickLists(dir);
124
+ return true;
125
+ }
126
+ catch {
127
+ return false;
128
+ }
129
+ }
130
+ const sameIds = (a, b) => a !== undefined && a.length === b.length && a.every((t, i) => t === b[i]);
131
+ /**
132
+ * Keep `list` as `playerId`'s picks for `gameId`. The same list already kept stays as it is (its
133
+ * award too); a different one replaces it and drops the award read from the old one. The pickable
134
+ * territories kept beside it stay. Never throws.
135
+ */
136
+ export async function writePickList(dir, gameId, playerId, list) {
137
+ if (!list.length || !isIds([...list]))
138
+ return false;
139
+ const kept = await readPickRecord(dir, gameId, playerId);
140
+ if (sameIds(kept?.list, list))
141
+ return true;
142
+ return writeRecord(dir, {
143
+ gameId,
144
+ playerId,
145
+ list: [...list],
146
+ ...(kept?.pickable ? { pickable: kept.pickable } : {}),
147
+ ...(kept?.neutrals ? { neutrals: kept.neutrals } : {}),
148
+ });
149
+ }
150
+ /** Keep the award read from the stored list (`null`: nothing could be read). False when no list is kept for this player. */
151
+ export async function writeAward(dir, gameId, playerId, award) {
152
+ const kept = await readPickRecord(dir, gameId, playerId);
153
+ if (!kept?.list)
154
+ return false;
155
+ return writeRecord(dir, {
156
+ gameId,
157
+ playerId,
158
+ list: kept.list,
159
+ ...(kept.pickable ? { pickable: kept.pickable } : {}),
160
+ ...(kept.neutrals ? { neutrals: kept.neutrals } : {}),
161
+ award,
162
+ });
163
+ }
164
+ /**
165
+ * Keep the territories the live board showed as pickable for `gameId` (ascending, each once),
166
+ * beside `playerId`'s list and its award when those are kept, and (#201) the picking board's
167
+ * neutrals with their armies when given (else those already kept stay). The same sets already
168
+ * kept stay as they are. Never throws.
169
+ */
170
+ export async function writePickable(dir, gameId, playerId, pickable, neutralArmies) {
171
+ if (!pickable.length || !isIds([...pickable]))
172
+ return false;
173
+ const ids = [...new Set(pickable)].sort((a, b) => a - b);
174
+ const kept = await readPickRecord(dir, gameId, playerId);
175
+ const neutrals = neutralsOf(neutralArmies) ?? kept?.neutrals;
176
+ if (sameIds(kept?.pickable, ids) && JSON.stringify(kept?.neutrals) === JSON.stringify(neutrals))
177
+ return true;
178
+ return writeRecord(dir, {
179
+ gameId,
180
+ playerId,
181
+ ...(kept?.list ? { list: kept.list } : {}),
182
+ pickable: ids,
183
+ ...(neutrals ? { neutrals } : {}),
184
+ ...(kept?.list && kept.award !== undefined ? { award: kept.award } : {}),
185
+ });
186
+ }
187
+ /** #201: the neutrals a live board shows with their armies (fogged ones left out), ascending by territory. */
188
+ export function pickingNeutrals(board) {
189
+ return board
190
+ .filter((t) => !t.fogged && t.owner === OWNER_NEUTRAL && t.armies !== null)
191
+ .map((t) => [t.territoryId, t.armies])
192
+ .sort((a, b) => a[0] - b[0]);
193
+ }
@@ -0,0 +1,231 @@
1
+ // The cross-game player record on disk (docs/PLAN-TEAMS.md A2, owner decision D5 of 2026-11-14: ON,
2
+ // local and hosted — a hosted child keeps it in its per-user data dir, `state.dataDir` in mint.yaml).
3
+ // At `<dataDir>/relations/players.json` (version 3): per player, the name-free entries and the
4
+ // tallies of `src/analysis/player-record.ts`, and when they last changed. The player is keyed by an
5
+ // HMAC of its GameFeed id under a local secret salt (`<dataDir>/relations/players.salt`, 0600), and
6
+ // each entry by an HMAC of my account, the game and the agreement (the ledger is per account, so two
7
+ // accounts sharing a data dir never collide; entries written before the account was in the key are
8
+ // read as they are, `legacyEntryKey`): the file holds no player id, game id or name, and without the
9
+ // salt it cannot be joined to a game or a player.
10
+ //
11
+ // The salt is made only on the write path, never by a read; a salt file that exists but is
12
+ // malformed is never replaced (that would orphan every key on record): reads say `unreadable` and
13
+ // writes fail until the owner fixes or removes it. A record file that exists but cannot be read or
14
+ // parsed (bad JSON, not an object, no `players` object) is treated the same way — never moved aside,
15
+ // never overwritten, since writing over it would drop every other player's data: reads say
16
+ // `unreadable` and writes fail until the owner fixes or removes it. A missing file is empty.
17
+ //
18
+ // Bounded (`MAX_RECORD_ENTRIES` per player, `MAX_RECORD_PLAYERS` players). Isolated so it can be
19
+ // switched off: `WARAPP_PLAYER_RECORD=off` (or `0` / `false` / `no`) and nothing here reads or
20
+ // writes. Reads are loose (versions 1 and 2 are read too; an unusable player or entry is dropped);
21
+ // every write is atomic and runs under the in-process path lock (src/path-lock.ts). Never throws.
22
+ import { createHmac, randomBytes, randomUUID } from 'node:crypto';
23
+ import { link, mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
24
+ import { join } from 'node:path';
25
+ import { readEnvVar } from '@chrischall/mcp-utils';
26
+ import { addCounts, COUNT_KEYS, MAX_RECORD_PLAYERS, talliesOf, upsertEntry, ZERO_COUNTS, } from './analysis/player-record.js';
27
+ import { withPathLock } from './path-lock.js';
28
+ import { relationsDir } from './relations-store.js';
29
+ const isRec = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
30
+ const SALT = /^[0-9a-f]{32}$/;
31
+ const HASH = /^[0-9a-f]{32}$/;
32
+ const OUTCOMES = new Set(['open', 'not-agreed', 'kept', 'ended-with-notice', 'broken-by-them', 'broken-by-me']);
33
+ export const playerRecordPath = (dir) => join(relationsDir(dir), 'players.json');
34
+ export const playerRecordSaltPath = (dir) => join(relationsDir(dir), 'players.salt');
35
+ /** Whether the cross-game record is on: yes (local and hosted) unless `WARAPP_PLAYER_RECORD` is `off`, `0`, `false` or `no`. */
36
+ export function playerRecordEnabled(env = process.env) {
37
+ const v = readEnvVar('WARAPP_PLAYER_RECORD', { env });
38
+ return v === undefined || !/^(off|0|false|no)$/i.test(v.trim());
39
+ }
40
+ async function readSalt(dir) {
41
+ let text;
42
+ try {
43
+ text = await readFile(playerRecordSaltPath(dir), 'utf8');
44
+ }
45
+ catch (e) {
46
+ return e.code === 'ENOENT' ? 'missing' : 'malformed';
47
+ }
48
+ const salt = text.trim();
49
+ return SALT.test(salt) ? { salt } : 'malformed';
50
+ }
51
+ /** The salt on record for `dir`; `undefined` when there is none yet or it is malformed. Never makes one. */
52
+ export async function playerRecordSalt(dir) {
53
+ const s = await readSalt(dir);
54
+ return typeof s === 'object' ? s.salt : undefined;
55
+ }
56
+ /**
57
+ * The salt for a write: the one on record, else a new one (never over an existing file); `undefined`
58
+ * when malformed. The one "read or make" for every store keyed by `playerKey` (this record and the
59
+ * opponent profiles, src/profile-store.ts), so two salts can never exist. Throws when it cannot be
60
+ * written (callers run it inside their own never-throw guard).
61
+ */
62
+ export async function playerSaltForWrite(dir) {
63
+ const s = await readSalt(dir);
64
+ if (typeof s === 'object')
65
+ return s.salt;
66
+ if (s === 'malformed')
67
+ return undefined;
68
+ const path = playerRecordSaltPath(dir);
69
+ await mkdir(relationsDir(dir), { recursive: true, mode: 0o700 });
70
+ const tmp = `${path}.${process.pid}.${randomUUID()}.tmp`;
71
+ await writeFile(tmp, randomBytes(16).toString('hex'), { mode: 0o600 });
72
+ try {
73
+ // `link` fails when the file exists: another writer's salt is never replaced.
74
+ await link(tmp, path);
75
+ }
76
+ catch (e) {
77
+ if (e.code !== 'EEXIST')
78
+ throw e;
79
+ }
80
+ finally {
81
+ await unlink(tmp).catch(() => undefined);
82
+ }
83
+ const again = await readSalt(dir);
84
+ return typeof again === 'object' ? again.salt : undefined;
85
+ }
86
+ const hmac = (salt, text) => createHmac('sha256', salt).update(text).digest('hex').slice(0, 32);
87
+ /** A player's key in the record: never the id itself. */
88
+ export const playerKey = (salt, playerId) => hmac(salt, `player:${playerId}`);
89
+ /** A game's key in the opponent profiles: my account and the game, never the ids themselves. */
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}`);
93
+ /** An agreement's key in the record: my account, the game and the agreement, never the ids themselves. */
94
+ export const entryKey = (salt, myId, gameId, agreementId) => hmac(salt, `agreement:${myId}:${gameId}:${agreementId}`);
95
+ /** The key entries were written under before my account was part of it: still read, and updated in place. */
96
+ export const legacyEntryKey = (salt, gameId, agreementId) => hmac(salt, `agreement:${gameId}:${agreementId}`);
97
+ const count = (v) => typeof v === 'number' && Number.isInteger(v) && v >= 0;
98
+ const intOrNull = (v) => v === null || (typeof v === 'number' && Number.isInteger(v));
99
+ function talliesFrom(v) {
100
+ if (!isRec(v) || !COUNT_KEYS.every((k) => count(v[k])))
101
+ return undefined;
102
+ const out = { ...ZERO_COUNTS };
103
+ for (const k of COUNT_KEYS)
104
+ out[k] = v[k];
105
+ return out;
106
+ }
107
+ function entryOf(v) {
108
+ // Entries are this module's own writes: checked for shape, not re-derived.
109
+ if (!isRec(v) || typeof v.key !== 'string' || !HASH.test(v.key) || !OUTCOMES.has(v.outcome) || typeof v.updated !== 'number')
110
+ return undefined;
111
+ if (!isRec(v.format) || !isRec(v.terms) || !intOrNull(v.agreedTurn) || !intOrNull(v.endedTurn))
112
+ return undefined;
113
+ return v;
114
+ }
115
+ /** One player as stored, in any version this module wrote; `undefined` when unusable. */
116
+ function playerOf(v) {
117
+ if (!isRec(v))
118
+ return undefined;
119
+ const entries = Array.isArray(v.entries) ? v.entries.map(entryOf).filter((e) => e !== undefined) : [];
120
+ // Version 3 keeps `tallies`, version 2 kept `counts` only, version 1 entries only.
121
+ const tallies = talliesFrom(v.tallies) ?? talliesFrom(v.counts) ?? (entries.length ? talliesOf(entries) : undefined);
122
+ if (!tallies)
123
+ return undefined;
124
+ const updated = typeof v.updated === 'number' ? v.updated : entries.reduce((m, e) => Math.max(m, e.updated), 0);
125
+ return { tallies, entries, updated };
126
+ }
127
+ /** The file on record: empty when there is none; `'unreadable'` when one exists but cannot be read or parsed. */
128
+ async function readFileRecord(dir) {
129
+ let text;
130
+ try {
131
+ text = await readFile(playerRecordPath(dir), 'utf8');
132
+ }
133
+ catch (e) {
134
+ return e.code === 'ENOENT' ? { version: 3, players: {} } : 'unreadable';
135
+ }
136
+ let c;
137
+ try {
138
+ c = JSON.parse(text);
139
+ }
140
+ catch {
141
+ return 'unreadable';
142
+ }
143
+ if (!isRec(c) || !isRec(c.players))
144
+ return 'unreadable';
145
+ const players = {};
146
+ for (const [k, v] of Object.entries(c.players)) {
147
+ const p = HASH.test(k) ? playerOf(v) : undefined;
148
+ if (p)
149
+ players[k] = p;
150
+ }
151
+ return { version: 3, players };
152
+ }
153
+ async function writeFileRecord(dir, file) {
154
+ const keys = Object.keys(file.players)
155
+ .sort((a, b) => file.players[b].updated - file.players[a].updated || (a < b ? -1 : 1))
156
+ .slice(0, MAX_RECORD_PLAYERS)
157
+ .sort();
158
+ const bounded = { version: 3, players: Object.fromEntries(keys.map((k) => [k, file.players[k]])) };
159
+ const path = playerRecordPath(dir);
160
+ await mkdir(relationsDir(dir), { recursive: true, mode: 0o700 });
161
+ const tmp = `${path}.${process.pid}.${randomUUID()}.tmp`;
162
+ await writeFile(tmp, JSON.stringify(bounded), { mode: 0o600 });
163
+ await rename(tmp, path);
164
+ }
165
+ /**
166
+ * What is on record for `playerId`: its tallies and entries; `null` when nothing is (no salt yet
167
+ * included); `'unreadable'` when the salt file is malformed or the record file cannot be parsed;
168
+ * `'off'` when the record is off. Never throws, never writes.
169
+ */
170
+ export async function readPlayerRecord(dir, playerId, env) {
171
+ if (!playerRecordEnabled(env))
172
+ return 'off';
173
+ try {
174
+ const s = await readSalt(dir);
175
+ if (s === 'malformed')
176
+ return 'unreadable';
177
+ if (s === 'missing')
178
+ return null;
179
+ const file = await readFileRecord(dir);
180
+ if (file === 'unreadable')
181
+ return 'unreadable';
182
+ const p = file.players[playerKey(s.salt, playerId)];
183
+ return p ? { tallies: p.tallies, entries: p.entries } : null;
184
+ }
185
+ catch {
186
+ return null;
187
+ }
188
+ }
189
+ /** The record's state for a tool result: `on`, `off`, or `unreadable` (a malformed salt file or a record file that cannot be parsed). */
190
+ export async function playerRecordState(dir, env) {
191
+ if (!playerRecordEnabled(env))
192
+ return 'off';
193
+ if (!dir)
194
+ return 'on';
195
+ if ((await readSalt(dir).catch(() => 'missing')) === 'malformed')
196
+ return 'unreadable';
197
+ return (await readFileRecord(dir).catch(() => 'unreadable')) === 'unreadable' ? 'unreadable' : 'on';
198
+ }
199
+ /**
200
+ * Update `playerId`'s part of the record: `update` gets the salt (to key entries) and what is on
201
+ * record, and returns the tallies to add (`recordDelta`) and the entries to upsert. Read, change and
202
+ * write run under the in-process lock for the file. `updated` when written; `off` when the record is
203
+ * off; `failed` when it could not be (a malformed salt or an unparseable record file included: neither
204
+ * is ever overwritten). Never throws.
205
+ */
206
+ export async function updatePlayerRecord(dir, playerId, update, env, now = Date.now()) {
207
+ if (!playerRecordEnabled(env))
208
+ return 'off';
209
+ try {
210
+ return await withPathLock(playerRecordPath(dir), async () => {
211
+ const file = await readFileRecord(dir);
212
+ if (file === 'unreadable')
213
+ return 'failed';
214
+ const salt = await playerSaltForWrite(dir);
215
+ if (!salt)
216
+ return 'failed';
217
+ const key = playerKey(salt, playerId);
218
+ const current = file.players[key] ?? { tallies: { ...ZERO_COUNTS }, entries: [], updated: 0 };
219
+ const { delta, entries } = update(salt, { tallies: current.tallies, entries: current.entries });
220
+ let next = current.entries;
221
+ for (const e of entries)
222
+ next = upsertEntry(next, e);
223
+ file.players[key] = { tallies: addCounts(current.tallies, delta), entries: next, updated: now };
224
+ await writeFileRecord(dir, file);
225
+ return 'updated';
226
+ });
227
+ }
228
+ catch {
229
+ return 'failed';
230
+ }
231
+ }
@@ -0,0 +1,31 @@
1
+ // A player's state in a game, and the one test of whether it holds a seat.
2
+ //
3
+ // GameFeed names the state (`"Playing"`, `"Declined"`, …); the web client's
4
+ // records carry the GamePlayerState code. Both are named here, so the open-games
5
+ // list, the join read-back and the game profile all ask the same question (#133).
6
+ /** GamePlayerState: the web client's codes, named as GameFeed names them. */
7
+ export const PLAYER_STATE_NAMES = {
8
+ 1: 'Invited',
9
+ 2: 'Playing',
10
+ 3: 'Eliminated',
11
+ 4: 'Won',
12
+ 5: 'Declined',
13
+ 6: 'RemovedByHost',
14
+ 7: 'SurrenderAccepted',
15
+ 8: 'Booted',
16
+ 9: 'EndedByVote',
17
+ };
18
+ /** A GamePlayerState code's name; the code itself when it has none. */
19
+ export function playerStateName(code) {
20
+ return PLAYER_STATE_NAMES[code] ?? String(code);
21
+ }
22
+ /**
23
+ * States of a player who does not hold a seat: an invitation not yet accepted, one declined, and a
24
+ * removal by the host. Such a player never started the game. Every other state held a seat — the
25
+ * finished ones (eliminated, surrendered, booted, …) included.
26
+ */
27
+ const NOT_SEATED = new Set(['Invited', 'Declined', 'RemovedByHost']);
28
+ /** Whether a player in `state` (a GameFeed state name; absent reads as Playing) holds a seat. */
29
+ export function holdsSeat(state) {
30
+ return !NOT_SEATED.has(state ?? 'Playing');
31
+ }