@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,242 @@
1
+ // The agreement ledger on disk (docs/PLAN-TEAMS.md A2): per game and account, at
2
+ // `<dataDir>/relations/<gameId>-<playerId>.json` (a second account in the same game has its own file),
3
+ // the agreements the player recorded with `warapp_record_agreement` — name-free (player, territory
4
+ // and bonus ids, turns, statuses; never a name or a message), 0600 in a 0700 directory, written
5
+ // atomically. It is the only file `warapp_record_agreement` writes besides the cross-game player
6
+ // record (src/player-record-store.ts); nothing is sent to war.app. Reads are loose: an unusable
7
+ // file or entry is dropped, never thrown on.
8
+ //
9
+ // `commitments` (part B4): what my chat messages promised (warapp_send_chat's declared commitments,
10
+ // never the text), recorded once a message is sent; warapp_submit_turn warns when orders break one.
11
+ //
12
+ // `usage` (part B2): per planned turn, what each honoured truce freed and what a break would have
13
+ // cost (rule T6: the armies and the income); warapp_plan_turn calls `recordTruceUsage`.
14
+ import { randomUUID } from 'node:crypto';
15
+ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
16
+ import { join } from 'node:path';
17
+ import { withPathLock } from './path-lock.js';
18
+ import { AGREEMENT_STATUSES, MAX_NOTICE_TURNS, } from './analysis/relations.js';
19
+ import { COMMITMENT_KINDS } from './analysis/commitments.js';
20
+ const isRec = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
21
+ const isInt = (v) => typeof v === 'number' && Number.isInteger(v);
22
+ const ints = (v) => (Array.isArray(v) && v.every(isInt) ? [...v] : undefined);
23
+ /** Agreements kept per game (the oldest over ones dropped first). */
24
+ export const MAX_AGREEMENTS = 50;
25
+ /** Planned turns of usage kept per game (the newest). */
26
+ export const MAX_USAGE_TURNS = 200;
27
+ /** Commitments kept per game (the newest). */
28
+ export const MAX_COMMITMENTS = 200;
29
+ export const relationsDir = (dir) => join(dir, 'relations');
30
+ export const relationsPath = (dir, gameId, playerId) => join(relationsDir(dir), `${gameId}-${playerId}.json`);
31
+ const AGREEMENT_ID = /^a(\d{1,9})$/;
32
+ /** An agreement id's number (`a7` is 7); ids are made by {@link nextAgreementId}. */
33
+ const idNumber = (id) => Number(AGREEMENT_ID.exec(id)?.[1] ?? 0);
34
+ function scopeOf(v) {
35
+ if (v === 'all')
36
+ return 'all';
37
+ if (!isRec(v))
38
+ return undefined;
39
+ const t = ints(v.territories);
40
+ if (t)
41
+ return { territories: t };
42
+ const b = ints(v.bonuses);
43
+ return b ? { bonuses: b } : undefined;
44
+ }
45
+ const isStatus = (v) => typeof v === 'string' && AGREEMENT_STATUSES.includes(v);
46
+ function termsOf(v) {
47
+ if (!isRec(v))
48
+ return undefined;
49
+ const scope = scopeOf(v.scope);
50
+ if (!scope || !isInt(v.noticeTurns) || v.noticeTurns < 0 || v.noticeTurns > MAX_NOTICE_TURNS)
51
+ return undefined;
52
+ const t = { scope, noticeTurns: v.noticeTurns };
53
+ if (isInt(v.borderCap))
54
+ t.borderCap = v.borderCap;
55
+ if (isInt(v.untilTurn))
56
+ t.untilTurn = v.untilTurn;
57
+ if (isInt(v.untilPlayerOut))
58
+ t.untilPlayerOut = v.untilPlayerOut;
59
+ if (isInt(v.against))
60
+ t.against = v.against;
61
+ return t;
62
+ }
63
+ /** An agreement read back, or `undefined` when it is unusable. */
64
+ export function agreementOf(v) {
65
+ if (!isRec(v) || typeof v.id !== 'string' || !AGREEMENT_ID.test(v.id) || !isInt(v.with) || v.kind !== 'truce' || !isStatus(v.status) || !isInt(v.createdTurn))
66
+ return undefined;
67
+ const terms = termsOf(v.terms);
68
+ if (!terms || !Array.isArray(v.history))
69
+ return undefined;
70
+ const history = v.history.filter((h) => isRec(h) && isInt(h.turn) && isStatus(h.status));
71
+ const a = { id: v.id, with: v.with, kind: 'truce', status: v.status, createdTurn: v.createdTurn, terms, history };
72
+ if (isInt(v.agreedTurn))
73
+ a.agreedTurn = v.agreedTurn;
74
+ if (isInt(v.noticeTurn))
75
+ a.noticeTurn = v.noticeTurn;
76
+ if (isInt(v.endedTurn))
77
+ a.endedTurn = v.endedTurn;
78
+ if (typeof v.enforced === 'boolean')
79
+ a.enforced = v.enforced;
80
+ if (typeof v.retaliated === 'boolean')
81
+ a.retaliated = v.retaliated;
82
+ return a;
83
+ }
84
+ const COMMITMENT_ID = /^c(\d{1,9})$/;
85
+ /** A commitment read back, or `undefined` when it is unusable. */
86
+ export function commitmentOf(v) {
87
+ if (!isRec(v) || typeof v.id !== 'string' || !COMMITMENT_ID.test(v.id) || !isInt(v.sentTurn))
88
+ return undefined;
89
+ if (typeof v.kind !== 'string' || !COMMITMENT_KINDS.includes(v.kind))
90
+ return undefined;
91
+ const base = { id: v.id, sentTurn: v.sentTurn };
92
+ switch (v.kind) {
93
+ case 'no-attack': {
94
+ const scope = scopeOf(v.scope);
95
+ if (!scope || !isInt(v.with) || !isInt(v.fromTurn) || !isInt(v.toTurn))
96
+ return undefined;
97
+ return { ...base, kind: 'no-attack', with: v.with, scope, fromTurn: v.fromTurn, toTurn: v.toTurn };
98
+ }
99
+ case 'will-attack':
100
+ if (!isInt(v.turn) || (!isInt(v.with) && !isInt(v.territory)))
101
+ return undefined;
102
+ return { ...base, kind: 'will-attack', turn: v.turn, ...(isInt(v.with) ? { with: v.with } : {}), ...(isInt(v.territory) ? { territory: v.territory } : {}) };
103
+ case 'notice':
104
+ if (typeof v.agreement !== 'string' || !isInt(v.with) || !isInt(v.endsTurn))
105
+ return undefined;
106
+ return { ...base, kind: 'notice', agreement: v.agreement, with: v.with, endsTurn: v.endsTurn };
107
+ default:
108
+ if (typeof v.agreement !== 'string' || !isInt(v.with))
109
+ return undefined;
110
+ return { ...base, kind: v.kind, agreement: v.agreement, with: v.with };
111
+ }
112
+ }
113
+ /** The commitments of a ledger file, the unusable dropped; absent when none. */
114
+ function commitmentsOf(v) {
115
+ if (!Array.isArray(v))
116
+ return {};
117
+ const list = v.map(commitmentOf).filter((c) => c !== undefined);
118
+ return list.length ? { commitments: list } : {};
119
+ }
120
+ /** The next commitment id in `ledger`: `c1`, `c2`, … */
121
+ export function nextCommitmentId(ledger) {
122
+ const n = (ledger.commitments ?? []).reduce((m, c) => Math.max(m, Number(COMMITMENT_ID.exec(c.id)?.[1] ?? 0)), 0);
123
+ return `c${n + 1}`;
124
+ }
125
+ function usageOf(v) {
126
+ if (!isRec(v))
127
+ return {};
128
+ const out = {};
129
+ for (const [k, list] of Object.entries(v)) {
130
+ if (!/^\d+$/.test(k) || !Array.isArray(list))
131
+ continue;
132
+ const num = (x) => (typeof x === 'number' && Number.isFinite(x) ? x : null);
133
+ out[k] = list
134
+ .filter((u) => isRec(u) && typeof u.agreementId === 'string')
135
+ .map((u) => ({
136
+ agreementId: u.agreementId,
137
+ armiesFreed: num(u.armiesFreed),
138
+ lossIfBroken: num(u.lossIfBroken),
139
+ ...('incomeLostIfBroken' in u ? { incomeLostIfBroken: num(u.incomeLostIfBroken) } : {}),
140
+ }));
141
+ }
142
+ return out;
143
+ }
144
+ /** An empty ledger for `gameId` as `playerId`. */
145
+ export const emptyLedger = (gameId, playerId) => ({ gameId, playerId, agreements: [], usage: {} });
146
+ /**
147
+ * The ledger of `gameId` as `playerId` recorded it; `undefined` when there is none, it is another
148
+ * account's, or it is unusable. Never throws.
149
+ */
150
+ export async function readLedger(dir, gameId, playerId) {
151
+ try {
152
+ const c = JSON.parse(await readFile(relationsPath(dir, gameId, playerId), 'utf8'));
153
+ if (!isRec(c) || c.gameId !== gameId || c.playerId !== playerId || !Array.isArray(c.agreements))
154
+ return undefined;
155
+ const agreements = c.agreements.map(agreementOf).filter((a) => a !== undefined);
156
+ return { gameId, playerId, agreements, usage: usageOf(c.usage), ...commitmentsOf(c.commitments) };
157
+ }
158
+ catch {
159
+ return undefined;
160
+ }
161
+ }
162
+ /**
163
+ * The ledger for a write: `null` when there is no file yet, `'unreadable'` when a file exists but
164
+ * cannot be read as this game's and account's ledger (bad JSON, another shape, a read error), so a
165
+ * caller never replaces recorded agreements with an empty ledger.
166
+ */
167
+ export async function readLedgerForWrite(dir, gameId, playerId) {
168
+ let text;
169
+ try {
170
+ text = await readFile(relationsPath(dir, gameId, playerId), 'utf8');
171
+ }
172
+ catch (e) {
173
+ return e.code === 'ENOENT' ? null : 'unreadable';
174
+ }
175
+ try {
176
+ const c = JSON.parse(text);
177
+ if (!isRec(c) || c.gameId !== gameId || c.playerId !== playerId || !Array.isArray(c.agreements))
178
+ return 'unreadable';
179
+ const agreements = c.agreements.map(agreementOf).filter((a) => a !== undefined);
180
+ return { gameId, playerId, agreements, usage: usageOf(c.usage), ...commitmentsOf(c.commitments) };
181
+ }
182
+ catch {
183
+ return 'unreadable';
184
+ }
185
+ }
186
+ /**
187
+ * The ledger with its agreements in id order, at most {@link MAX_AGREEMENTS} of them (over ones
188
+ * dropped oldest first), and at most {@link MAX_USAGE_TURNS} usage turns.
189
+ */
190
+ export function boundLedger(ledger) {
191
+ let agreements = [...ledger.agreements].sort((a, b) => idNumber(a.id) - idNumber(b.id) || (a.id < b.id ? -1 : 1));
192
+ if (agreements.length > MAX_AGREEMENTS) {
193
+ const over = agreements.filter((a) => a.endedTurn !== undefined).sort((a, b) => a.endedTurn - b.endedTurn || (a.id < b.id ? -1 : 1));
194
+ const drop = new Set(over.slice(0, agreements.length - MAX_AGREEMENTS).map((a) => a.id));
195
+ agreements = agreements.filter((a) => !drop.has(a.id)).slice(-MAX_AGREEMENTS);
196
+ }
197
+ const turns = Object.keys(ledger.usage)
198
+ .map(Number)
199
+ .sort((a, b) => b - a)
200
+ .slice(0, MAX_USAGE_TURNS)
201
+ .sort((a, b) => a - b);
202
+ const commitments = ledger.commitments?.length ? { commitments: ledger.commitments.slice(-MAX_COMMITMENTS) } : {};
203
+ const { commitments: _all, ...rest } = ledger;
204
+ return { ...rest, agreements, usage: Object.fromEntries(turns.map((t) => [String(t), ledger.usage[String(t)]])), ...commitments };
205
+ }
206
+ /** Write the ledger (bounded), atomically, 0600. `true` when written; never throws. */
207
+ export async function writeLedger(dir, ledger) {
208
+ try {
209
+ const path = relationsPath(dir, ledger.gameId, ledger.playerId);
210
+ await mkdir(relationsDir(dir), { recursive: true, mode: 0o700 });
211
+ const tmp = `${path}.${process.pid}.${randomUUID()}.tmp`;
212
+ await writeFile(tmp, JSON.stringify(boundLedger(ledger)), { mode: 0o600 });
213
+ await rename(tmp, path);
214
+ return true;
215
+ }
216
+ catch {
217
+ return false;
218
+ }
219
+ }
220
+ /** The next agreement id in `ledger`: `a1`, `a2`, … */
221
+ export function nextAgreementId(ledger) {
222
+ const n = ledger.agreements.reduce((m, a) => Math.max(m, idNumber(a.id)), 0);
223
+ return `a${n + 1}`;
224
+ }
225
+ /**
226
+ * Part B2: record what each truce freed and would cost on `turn`. Writes only when a ledger
227
+ * exists for the game. `true` when written; never throws.
228
+ */
229
+ export async function recordTruceUsage(dir, gameId, playerId, turn, usage) {
230
+ return withLedgerLock(dir, gameId, playerId, async () => {
231
+ const ledger = await readLedger(dir, gameId, playerId);
232
+ if (!ledger)
233
+ return false;
234
+ return writeLedger(dir, { ...ledger, usage: { ...ledger.usage, [String(turn)]: [...usage] } });
235
+ });
236
+ }
237
+ /**
238
+ * Run a read-modify-write of one ledger under the in-process lock for its file (src/path-lock.ts),
239
+ * so two calls in this process never lose each other's change. Not re-entrant: never nest it on
240
+ * the same ledger.
241
+ */
242
+ export const withLedgerLock = (dir, gameId, playerId, fn) => withPathLock(relationsPath(dir, gameId, playerId), fn);
package/dist/replay.js ADDED
@@ -0,0 +1,227 @@
1
+ // Offline replay of a planned game: the settings a plan needs, kept per game beside the board cache,
2
+ // and a loader that rebuilds the planner's inputs from the data directory alone (no request).
3
+ //
4
+ // `<dataDir>/games/<gameId>.json` is written wherever the board cache is (warapp_plan_turn,
5
+ // warapp_track_opponents, warapp_locate_opponents, warapp_get_relations): `{ version: 1, gameId,
6
+ // mapId, state, numberOfTurns, players, settings, derived }`. NAME-FREE: players are kept by id
7
+ // (with their team, state and AI flags), never by name; the settings are GameFeed's raw settings
8
+ // filtered by `sanitizeSettings` (numbers, booleans, numeric strings, a few enum settings and a
9
+ // card's `Mode`; no free text such as the creator's message, no mod entries, nothing equal to a
10
+ // player's or the game's name), with the overridden bonuses re-written in their verified shape. Read back through
11
+ // `normalizeSettings`, they give the planner the same income, kill rates, luck, rounding, fog,
12
+ // move order, teams, Local Deployment, commanders, cards and overrides. 0600 in a 0700 folder,
13
+ // atomic, best effort (never throws); the newest MAX_GAME_RECORDS games are kept, and a game not
14
+ // written for BOARD_CACHE_MAX_AGE_MS is deleted, as its boards are.
15
+ //
16
+ // The map comes from the persistent map store (src/map-store.ts, base values: `mapOf(game)` applies
17
+ // the game's overrides) and the boards and orders from the board cache (src/trend.ts).
18
+ import { readdir, readFile, stat, unlink } from 'node:fs/promises';
19
+ import { join } from 'node:path';
20
+ import { readStoredMap, writeJsonAtomic } from './map-store.js';
21
+ import { normalizeSettings, parseEndRules } from './normalize.js';
22
+ import { BOARD_CACHE_MAX_AGE_MS, readBoardHistory, readCachedOrders, readCachedPlayer } from './trend.js';
23
+ /** Games whose settings are kept; the least recently written goes first. */
24
+ export const MAX_GAME_RECORDS = 200;
25
+ const VERSION = 1;
26
+ const GAME_FILE = /^\d+\.json$/;
27
+ const isRec = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
28
+ const isInt = (v) => typeof v === 'number' && Number.isInteger(v);
29
+ export const gamesDir = (dir) => join(dir, 'games');
30
+ export const gameRecordPath = (dir, gameId) => join(gamesDir(dir), `${gameId}.json`);
31
+ /** Top-level settings whose value is a word (an enum), kept when it is not a name. */
32
+ const ENUM_SETTINGS = new Set(['Pace', 'Fog', 'MoveOrder', 'RoundingMode', 'InstantSurrender', 'AutomaticTerritoryDistribution']);
33
+ /** Settings never kept: free text, mod entries (their count is kept apart), the overrides (re-written). */
34
+ const DROPPED_SETTINGS = new Set(['PersonalMessage', 'Mods', 'OverriddenBonuses']);
35
+ /** Keys inside a card's settings (`<Name>Card`) whose value is a word: `cardArmyCeiling` reads `Mode`. */
36
+ const CARD_ENUM_KEYS = new Set(['Mode']);
37
+ const NO_KEYS = new Set();
38
+ const ENUM = /^[A-Za-z][A-Za-z0-9_]{0,40}$/;
39
+ const NUMERIC = /^\s*-?\d+(\.\d+)?\s*$/;
40
+ const LITERAL = /^(true|false|none|null)$/i;
41
+ const MAX_DEPTH = 3;
42
+ /** `enumKeys`: the keys of this value (an object) whose word values are kept; deeper levels keep none. */
43
+ function cleanValue(v, depth, enumOk, names, enumKeys = NO_KEYS) {
44
+ if (v === null || typeof v === 'boolean')
45
+ return v;
46
+ if (typeof v === 'number')
47
+ return Number.isFinite(v) ? v : undefined;
48
+ if (typeof v === 'string') {
49
+ if (NUMERIC.test(v) || LITERAL.test(v))
50
+ return v;
51
+ return enumOk && ENUM.test(v) && !names.has(v.toLowerCase()) ? v : undefined;
52
+ }
53
+ if (depth > MAX_DEPTH)
54
+ return undefined;
55
+ if (Array.isArray(v))
56
+ return v.map((x) => cleanValue(x, depth + 1, false, names)).filter((x) => x !== undefined);
57
+ if (isRec(v)) {
58
+ const out = {};
59
+ for (const [k, x] of Object.entries(v)) {
60
+ if (!ENUM.test(k) && !NUMERIC.test(k))
61
+ continue;
62
+ const c = cleanValue(x, depth + 1, enumKeys.has(k), names);
63
+ if (c !== undefined)
64
+ out[k] = c;
65
+ }
66
+ return out;
67
+ }
68
+ return undefined;
69
+ }
70
+ /**
71
+ * GameFeed's raw settings without free text or names: numbers, booleans, numeric strings, the
72
+ * literals true/false/none/null, and the {@link ENUM_SETTINGS} words (and a card's
73
+ * {@link CARD_ENUM_KEYS} words) that are not one of `names` (compared without case); objects to a
74
+ * depth of {@link MAX_DEPTH}.
75
+ */
76
+ export function sanitizeSettings(raw, names) {
77
+ const lower = new Set(names.map((n) => n.toLowerCase()));
78
+ const out = {};
79
+ for (const [k, v] of Object.entries(raw)) {
80
+ if (DROPPED_SETTINGS.has(k) || (!ENUM.test(k) && !NUMERIC.test(k)))
81
+ continue;
82
+ const c = cleanValue(v, 1, ENUM_SETTINGS.has(k), lower, k.endsWith('Card') ? CARD_ENUM_KEYS : NO_KEYS);
83
+ if (c !== undefined)
84
+ out[k] = c;
85
+ }
86
+ return out;
87
+ }
88
+ function playerRecord(p) {
89
+ return {
90
+ id: p.id,
91
+ ...(p.feedId !== undefined ? { feedId: p.feedId } : {}),
92
+ isAI: p.isAI,
93
+ humanTurnedIntoAI: p.humanTurnedIntoAI,
94
+ ...(p.state !== undefined ? { state: p.state } : {}),
95
+ ...(p.team !== undefined ? { team: p.team } : {}),
96
+ };
97
+ }
98
+ /** Delete game records older than the board cache keeps, then the oldest beyond the cap. Best effort. */
99
+ async function pruneGames(dir, keep) {
100
+ const folder = gamesDir(dir);
101
+ const cutoff = Date.now() - BOARD_CACHE_MAX_AGE_MS;
102
+ const files = [];
103
+ for (const name of await readdir(folder)) {
104
+ if (!GAME_FILE.test(name) || name === `${keep}.json`)
105
+ continue;
106
+ try {
107
+ const at = (await stat(join(folder, name))).mtimeMs;
108
+ if (at < cutoff)
109
+ await unlink(join(folder, name));
110
+ else
111
+ files.push({ name, at });
112
+ }
113
+ catch {
114
+ // Gone already.
115
+ }
116
+ }
117
+ const excess = files.length + 1 - MAX_GAME_RECORDS;
118
+ if (excess <= 0)
119
+ return;
120
+ files.sort((a, b) => a.at - b.at || a.name.localeCompare(b.name));
121
+ for (const f of files.slice(0, excess))
122
+ await unlink(join(folder, f.name)).catch(() => { });
123
+ }
124
+ /**
125
+ * `game`'s raw settings without free text or names (`sanitizeSettings`, against its players' and its own
126
+ * names), the overridden bonuses re-written in their verified shape; `undefined` without settings. What the
127
+ * replay record and the end-of-game record (src/finished-store.ts) keep as the settings shape.
128
+ */
129
+ export function nameFreeSettings(game) {
130
+ const s = game.settings;
131
+ if (!s)
132
+ return undefined;
133
+ const names = [...game.players.map((p) => p.name), ...(game.name !== undefined ? [game.name] : [])];
134
+ const settings = sanitizeSettings(s.raw, names);
135
+ if (s.overriddenBonuses)
136
+ settings.OverriddenBonuses = [...s.overriddenBonuses].map(([bonusID, value]) => ({ bonusID, value }));
137
+ return settings;
138
+ }
139
+ /** Keep the settings needed to replay `game` (name-free). `false` when it has none or the write failed; never throws. */
140
+ export async function writeGameRecord(dir, game) {
141
+ const s = game.settings;
142
+ if (!s)
143
+ return false;
144
+ try {
145
+ const settings = nameFreeSettings(game);
146
+ const derived = {
147
+ ...(s.mods !== undefined ? { mods: s.mods } : {}),
148
+ ...(s.commerce !== undefined ? { commerce: s.commerce } : {}),
149
+ ...(s.overriddenBonusesUnparsed ? { overriddenBonusesUnparsed: true } : {}),
150
+ };
151
+ await writeJsonAtomic(gameRecordPath(dir, game.id), gamesDir(dir), {
152
+ version: VERSION,
153
+ gameId: game.id,
154
+ ...(s.mapId !== undefined ? { mapId: s.mapId } : {}),
155
+ state: game.state,
156
+ ...(game.numberOfTurns !== undefined ? { numberOfTurns: game.numberOfTurns } : {}),
157
+ players: game.players.map(playerRecord),
158
+ settings,
159
+ derived,
160
+ });
161
+ await pruneGames(dir, game.id).catch(() => { });
162
+ return true;
163
+ }
164
+ catch {
165
+ return false;
166
+ }
167
+ }
168
+ function playerOf(p) {
169
+ if (!isRec(p) || !isInt(p.id))
170
+ return undefined;
171
+ const out = {
172
+ id: p.id,
173
+ // Name-free by design: the id stands in for the name.
174
+ name: String(p.id),
175
+ isAI: p.isAI === true,
176
+ humanTurnedIntoAI: p.humanTurnedIntoAI === true,
177
+ hasCommittedOrders: false,
178
+ };
179
+ if (typeof p.feedId === 'string')
180
+ out.feedId = p.feedId;
181
+ if (typeof p.state === 'string')
182
+ out.state = p.state;
183
+ if (isInt(p.team))
184
+ out.team = p.team;
185
+ return out;
186
+ }
187
+ /** The game kept for `gameId` (name-free, without its map); `undefined` when absent or unusable. Never throws. */
188
+ export async function readGameRecord(dir, gameId) {
189
+ try {
190
+ const r = JSON.parse(await readFile(gameRecordPath(dir, gameId), 'utf8'));
191
+ if (!isRec(r) || r.version !== VERSION || r.gameId !== gameId || typeof r.state !== 'string' || !isRec(r.settings))
192
+ return undefined;
193
+ const settings = normalizeSettings(r.settings);
194
+ const d = isRec(r.derived) ? r.derived : {};
195
+ if (isInt(d.mods))
196
+ settings.mods = d.mods;
197
+ if (typeof d.commerce === 'boolean')
198
+ settings.commerce = d.commerce;
199
+ if (d.overriddenBonusesUnparsed === true)
200
+ settings.overriddenBonusesUnparsed = true;
201
+ const players = Array.isArray(r.players) ? r.players.map(playerOf).filter((p) => p !== undefined) : [];
202
+ const game = { id: gameId, state: r.state, players, settings, endRules: parseEndRules(r.settings) };
203
+ if (isInt(r.numberOfTurns))
204
+ game.numberOfTurns = r.numberOfTurns;
205
+ return game;
206
+ }
207
+ catch {
208
+ return undefined;
209
+ }
210
+ }
211
+ /**
212
+ * Rebuild a game's planner inputs from `dataDir` alone: its kept settings, the stored map and the
213
+ * cached boards and orders. `undefined` when the game has no settings record. Never throws.
214
+ */
215
+ export async function loadReplay(dataDir, gameId) {
216
+ const game = await readGameRecord(dataDir, gameId);
217
+ if (!game)
218
+ return undefined;
219
+ const settings = game.settings;
220
+ const map = settings.mapId !== undefined ? await readStoredMap(dataDir, settings.mapId, { maxAgeMs: Number.POSITIVE_INFINITY }) : undefined;
221
+ if (map)
222
+ game.map = map;
223
+ const playerId = await readCachedPlayer(dataDir, gameId);
224
+ const boards = playerId !== undefined ? await readBoardHistory(dataDir, gameId, playerId) : [];
225
+ const orders = playerId !== undefined ? await readCachedOrders(dataDir, gameId, playerId) : new Map();
226
+ return { game, settings, map, playerId, boards, orders };
227
+ }
@@ -0,0 +1,28 @@
1
+ // Scalar coercion for GameFeed's string-typed values.
2
+ /** An integer from a number or an integer string; `undefined` otherwise. */
3
+ export function asInt(v) {
4
+ if (typeof v === 'number')
5
+ return Number.isSafeInteger(v) ? v : undefined;
6
+ if (typeof v !== 'string' || !/^\s*-?\d+\s*$/.test(v))
7
+ return undefined;
8
+ const n = Number(v);
9
+ return Number.isSafeInteger(n) ? n : undefined;
10
+ }
11
+ /** A finite number from a number or a numeric string; `undefined` otherwise. */
12
+ export function asNum(v) {
13
+ if (typeof v === 'number')
14
+ return Number.isFinite(v) ? v : undefined;
15
+ if (typeof v !== 'string' || v.trim() === '')
16
+ return undefined;
17
+ const n = Number(v);
18
+ return Number.isFinite(n) ? n : undefined;
19
+ }
20
+ /** A boolean from a boolean or a `True`/`False` string (any case); `undefined` otherwise. */
21
+ export function asBool(v) {
22
+ if (typeof v === 'boolean')
23
+ return v;
24
+ if (typeof v !== 'string')
25
+ return undefined;
26
+ const s = v.trim().toLowerCase();
27
+ return s === 'true' ? true : s === 'false' ? false : undefined;
28
+ }