@chrischall/warapp-mcp 0.5.0 → 0.7.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 (125) hide show
  1. package/.claude-plugin/marketplace.json +3 -3
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +133 -8
  4. package/dist/analysis/accept-surrender.js +20 -2
  5. package/dist/analysis/calibrate.js +1 -0
  6. package/dist/analysis/card-support.js +177 -17
  7. package/dist/analysis/card-threats.js +126 -14
  8. package/dist/analysis/chat-advice.js +182 -0
  9. package/dist/analysis/chat-blocks.js +106 -0
  10. package/dist/analysis/chat-intent.js +559 -0
  11. package/dist/analysis/chat-read.js +159 -0
  12. package/dist/analysis/decision-replay.js +279 -0
  13. package/dist/analysis/decision-truth.js +146 -0
  14. package/dist/analysis/finished-game.js +62 -3
  15. package/dist/analysis/game-lessons.js +15 -10
  16. package/dist/analysis/hold-diff.js +3 -1
  17. package/dist/analysis/income-trend.js +38 -0
  18. package/dist/analysis/intel.js +75 -0
  19. package/dist/analysis/opens.js +64 -0
  20. package/dist/analysis/opponent-profile.js +121 -10
  21. package/dist/analysis/opponents.js +246 -20
  22. package/dist/analysis/outlook.js +360 -15
  23. package/dist/analysis/picks.js +91 -12
  24. package/dist/analysis/plan/after-leftover.js +4 -1
  25. package/dist/analysis/plan/bonus-attempts.js +105 -0
  26. package/dist/analysis/plan/capture-instead.js +116 -0
  27. package/dist/analysis/plan/captures.js +49 -7
  28. package/dist/analysis/plan/conceded-out.js +13 -2
  29. package/dist/analysis/plan/estimates.js +203 -30
  30. package/dist/analysis/plan/guard-off.js +2 -1
  31. package/dist/analysis/plan/holds.js +110 -9
  32. package/dist/analysis/plan/jabs.js +113 -0
  33. package/dist/analysis/plan/leftover.js +393 -8
  34. package/dist/analysis/plan/orders.js +76 -4
  35. package/dist/analysis/plan/relations.js +135 -2
  36. package/dist/analysis/plan/report.js +69 -3
  37. package/dist/analysis/plan/second-sizing.js +133 -0
  38. package/dist/analysis/plan/shared.js +279 -27
  39. package/dist/analysis/plan/siege.js +303 -0
  40. package/dist/analysis/plan/stand-still.js +9 -5
  41. package/dist/analysis/plan/state.js +8 -0
  42. package/dist/analysis/plan/stockpile.js +104 -0
  43. package/dist/analysis/plan/strike.js +39 -7
  44. package/dist/analysis/plan/targets.js +256 -110
  45. package/dist/analysis/plan/threats.js +148 -10
  46. package/dist/analysis/plan/transfers.js +57 -6
  47. package/dist/analysis/plan/two-move.js +70 -0
  48. package/dist/analysis/plan/vacated.js +124 -2
  49. package/dist/analysis/planner.js +527 -49
  50. package/dist/analysis/profile.js +13 -2
  51. package/dist/analysis/since-last.js +18 -5
  52. package/dist/analysis/stress.js +8 -2
  53. package/dist/board.js +36 -2
  54. package/dist/bonus-attempt-store.js +55 -0
  55. package/dist/build-id.js +106 -0
  56. package/dist/bundle.js +54138 -41059
  57. package/dist/cards.js +7 -5
  58. package/dist/chat-automation.js +22 -0
  59. package/dist/chat.js +35 -1
  60. package/dist/client.js +14 -0
  61. package/dist/commerce.js +111 -0
  62. package/dist/decision-log.js +1093 -0
  63. package/dist/finished-store.js +5 -1
  64. package/dist/index.js +9 -1
  65. package/dist/lessons-store.js +322 -21
  66. package/dist/live.js +43 -0
  67. package/dist/move-order.js +64 -3
  68. package/dist/normalize.js +17 -0
  69. package/dist/open-games.js +36 -16
  70. package/dist/outlook-log.js +42 -1
  71. package/dist/profile-store.js +12 -2
  72. package/dist/protocol/methods.js +62 -5
  73. package/dist/protocol/rpc.js +8 -0
  74. package/dist/relations-store.js +38 -4
  75. package/dist/review-export.js +198 -0
  76. package/dist/siege-store.js +49 -0
  77. package/dist/state-bundle.js +584 -0
  78. package/dist/state-cli.js +71 -0
  79. package/dist/strategy/notes.js +56 -0
  80. package/dist/team-cards.js +25 -0
  81. package/dist/tools/accept-surrender.js +23 -9
  82. package/dist/tools/award.js +20 -2
  83. package/dist/tools/card-advice.js +93 -28
  84. package/dist/tools/card-plays.js +2 -2
  85. package/dist/tools/card-support-advice.js +37 -7
  86. package/dist/tools/chat-advice.js +330 -0
  87. package/dist/tools/chat-inbox.js +19 -4
  88. package/dist/tools/chat.js +106 -17
  89. package/dist/tools/check-plan.js +68 -12
  90. package/dist/tools/commerce-deploy.js +33 -0
  91. package/dist/tools/common.js +31 -0
  92. package/dist/tools/decision-capture.js +459 -0
  93. package/dist/tools/end-of-game.js +151 -21
  94. package/dist/tools/game-kind.js +92 -0
  95. package/dist/tools/how-lost.js +7 -2
  96. package/dist/tools/index.js +10 -0
  97. package/dist/tools/join-game.js +10 -4
  98. package/dist/tools/live-context.js +6 -0
  99. package/dist/tools/live.js +10 -1
  100. package/dist/tools/map-curves.js +73 -0
  101. package/dist/tools/notifications.js +4 -3
  102. package/dist/tools/opponents.js +2 -0
  103. package/dist/tools/past-games.js +74 -8
  104. package/dist/tools/picks.js +61 -10
  105. package/dist/tools/profile-hook.js +62 -3
  106. package/dist/tools/profile-opponents.js +4 -0
  107. package/dist/tools/push.js +2 -2
  108. package/dist/tools/relations.js +139 -0
  109. package/dist/tools/scout.js +16 -2
  110. package/dist/tools/state.js +232 -0
  111. package/dist/tools/strategy.js +3 -3
  112. package/dist/tools/stress-opponents.js +7 -2
  113. package/dist/tools/surrender-pending.js +10 -1
  114. package/dist/tools/surrender.js +18 -3
  115. package/dist/tools/survival.js +11 -3
  116. package/dist/tools/team-brief.js +2 -2
  117. package/dist/tools/team.js +12 -3
  118. package/dist/tools/turn.js +643 -76
  119. package/dist/tools/where.js +3 -1
  120. package/dist/version.js +1 -1
  121. package/manifest.json +32 -3
  122. package/mint.yaml +37 -4
  123. package/package.json +4 -4
  124. package/server.json +20 -2
  125. package/skills/warapp-mcp/SKILL.md +73 -17
@@ -0,0 +1,584 @@
1
+ // Moving a data dir's history to another data dir (a local install's into a hosted child's
2
+ // `MCP_DATA_DIR`): one versioned bundle, gzipped JSON with a manifest (format, version, account id,
3
+ // created time, each file's path, sha256 and size) and the files' bytes.
4
+ //
5
+ // What travels is what war.app cannot give back: the salt behind every hashed key
6
+ // (`relations/players.salt`; the keys also carry my account id, so a bundle is one account's), the
7
+ // deal record and the per-game ledgers, the opponent profiles, the lessons, the map records and the
8
+ // end-of-game records with their processed marks, the decision logs of every game (#412: one account's
9
+ // each, the account read from the file's `playerId`; newest first up to MAX_EXPORT_DECISION_BYTES) — and, for games still in play only, the per-game
10
+ // files the planner reads (boards, game records, outlook, picks, move order, teams, the per-game
11
+ // profile turns, siege memory and contested-bonus attempts). Never: credentials (`.env`, `session.json`), the client bundle
12
+ // cache, the guess salt, chat cursors, the map cache and stats (all rebuilt), nor the per-game files
13
+ // of a finished game. A path outside {@link RULES} is never read on export nor written on import.
14
+ //
15
+ // Which games are active is read from the local records alone (no request, no credential): a game
16
+ // whose end-of-game record or processed mark exists, or whose game record says `Finished`, is
17
+ // finished; one whose game record says otherwise is active; one with no game record and no mark is
18
+ // unknown and left out.
19
+ //
20
+ // Import (`warapp_import_state`): every file's sha256 is checked against the manifest before
21
+ // anything is written; the bundle's account must be the signed-in one; a salt on record that differs
22
+ // from the bundle's refuses unless `replace`, and under `replace` the hashed stores written under the
23
+ // old salt (profiles, relations, finished, lessons, maps-record) are moved aside into
24
+ // `<dataDir>/state-backups/<time>/`, never deleted — entries under two salts would count a player or a
25
+ // game twice. Without `replace` an existing file that differs is kept; under it the bundle's wins and
26
+ // the displaced file goes to the same backup. The salt is written first, then every file atomically
27
+ // (0600, folders 0700), each under the path lock its store uses. Nothing here returns or prints the
28
+ // salt or a file's contents; errors name paths and counts only.
29
+ import { createHash, randomUUID } from 'node:crypto';
30
+ import { chmod, link, lstat, mkdir, readdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
31
+ import { join } from 'node:path';
32
+ import { gunzipSync, gzipSync } from 'node:zlib';
33
+ import { decisionLogOwner } from './decision-log.js';
34
+ import { withPathLock } from './path-lock.js';
35
+ import { finishedGameKey } from './player-record-store.js';
36
+ export const STATE_FORMAT = 'warapp-state';
37
+ export const STATE_VERSION = 1;
38
+ /** The largest bundle accepted (compressed). */
39
+ export const MAX_BUNDLE_BYTES = 32 * 1024 * 1024;
40
+ /** The largest bundle unpacked (a gzip bomb stops here). */
41
+ export const MAX_UNPACKED_BYTES = 256 * 1024 * 1024;
42
+ /**
43
+ * #412: the decision logs a bundle carries at most (raw bytes, newest first; the rest are counted as left
44
+ * out). Their store may hold far more (src/decision-log.ts MAX_DECISION_BYTES), and base64 inside the
45
+ * bundle's JSON is 4/3 of that: this keeps them, even incompressible, under {@link MAX_BUNDLE_BYTES} and a
46
+ * quarter of {@link MAX_UNPACKED_BYTES}, so they can never make a bundle the import refuses.
47
+ */
48
+ export const MAX_EXPORT_DECISION_BYTES = 16 * 1024 * 1024;
49
+ /** Where `replace` moves the old stores. */
50
+ export const BACKUP_DIR = 'state-backups';
51
+ export class StateBundleError extends Error {
52
+ name = 'StateBundleError';
53
+ }
54
+ /** The stores a bundle carries, as the counts name them. */
55
+ export const STORES = [
56
+ 'salt',
57
+ 'playerRecord',
58
+ 'ledgers',
59
+ 'profiles',
60
+ 'profileGames',
61
+ 'lessons',
62
+ 'mapsRecord',
63
+ 'finished',
64
+ 'games',
65
+ 'boards',
66
+ 'outlook',
67
+ 'picks',
68
+ 'moveOrder',
69
+ 'teams',
70
+ 'siege',
71
+ 'bonusAttempts',
72
+ 'decisions',
73
+ ];
74
+ const RULES = [
75
+ { store: 'salt', dir: 'relations', name: /^players\.salt$/ },
76
+ { store: 'playerRecord', dir: 'relations', name: /^players\.json$/ },
77
+ { store: 'ledgers', dir: 'relations', name: /^(\d{1,12})-(\d{1,20})\.json$/, game: 'game-account', allGames: true },
78
+ { store: 'profiles', dir: 'profiles', name: /^(players|population)\.json$/ },
79
+ { store: 'profileGames', dir: 'profiles/games', name: /^(\d{1,12})-(\d{1,20})\.json$/, game: 'game-account' },
80
+ { store: 'lessons', dir: '', name: /^lessons\.json$/ },
81
+ { store: 'mapsRecord', dir: 'maps-record', name: /^\d{1,12}\.json$/ },
82
+ { store: 'finished', dir: 'finished', name: /^([0-9a-f]{32}|processed)\.json$/ },
83
+ { store: 'games', dir: 'games', name: /^(\d{1,12})\.json$/, game: 'game' },
84
+ { store: 'boards', dir: 'boards', name: /^(\d{1,12})\.json$/, game: 'game' },
85
+ { store: 'outlook', dir: 'outlook', name: /^(\d{1,12})\.json$/, game: 'game' },
86
+ { store: 'picks', dir: 'picks', name: /^(\d{1,12})\.json$/, game: 'game' },
87
+ { store: 'moveOrder', dir: 'move-order', name: /^(\d{1,12})\.json$/, game: 'game' },
88
+ { store: 'teams', dir: 'teams', name: /^(\d{1,12})\.json$/, game: 'game' },
89
+ { store: 'siege', dir: 'siege', name: /^(\d{1,12})-(\d{1,20})\.json$/, game: 'game-account' },
90
+ // #410: the planner's contested-bonus attempt and drop memory (#405, src/bonus-attempt-store.ts).
91
+ { store: 'bonusAttempts', dir: 'bonus-attempts', name: /^(\d{1,12})-(\d{1,20})\.json$/, game: 'game-account' },
92
+ // #412: the decision log (src/decision-log.ts), one account's per game; kept for finished games too (its truth and accuracy).
93
+ { store: 'decisions', dir: 'decisions', name: /^(\d{1,12})\.json$/, game: 'game', allGames: true, accountInside: true },
94
+ ];
95
+ /** Top-level entries keyed by the salt: moved aside whole under `replace` when the salt changes. */
96
+ const HASHED_ENTRIES = ['relations', 'profiles', 'finished', 'maps-record', 'lessons.json'];
97
+ const SALT_PATH = 'relations/players.salt';
98
+ const SALT = /^[0-9a-f]{32}$/;
99
+ /** The rule a relative path falls under, with its game and account; `undefined` when none. */
100
+ function ruleOf(path) {
101
+ const slash = path.lastIndexOf('/');
102
+ const dir = slash === -1 ? '' : path.slice(0, slash);
103
+ const name = path.slice(slash + 1);
104
+ for (const rule of RULES) {
105
+ if (rule.dir !== dir)
106
+ continue;
107
+ const m = rule.name.exec(name);
108
+ if (!m)
109
+ continue;
110
+ if (!rule.game)
111
+ return { rule };
112
+ return { rule, gameId: Number(m[1]), ...(rule.game === 'game-account' ? { account: Number(m[2]) } : {}) };
113
+ }
114
+ return undefined;
115
+ }
116
+ /** The in-process lock a store takes for this file (src/path-lock.ts). */
117
+ function lockKey(dir, path) {
118
+ // The two cross-game profile stores share one lock (src/profile-store.ts `storeLock`).
119
+ if (path === 'profiles/players.json' || path === 'profiles/population.json')
120
+ return join(dir, 'profiles', '.store');
121
+ return join(dir, path);
122
+ }
123
+ const sha256 = (b) => createHash('sha256').update(b).digest('hex');
124
+ const isRec = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
125
+ async function listDir(dir) {
126
+ return readdir(dir).catch(() => []);
127
+ }
128
+ async function readJson(path) {
129
+ try {
130
+ return JSON.parse(await readFile(path, 'utf8'));
131
+ }
132
+ catch {
133
+ return undefined;
134
+ }
135
+ }
136
+ /** Every candidate file of the rules under `dir` (regular files only), as relative paths. */
137
+ async function candidates(dir) {
138
+ const out = [];
139
+ for (const sub of [...new Set(RULES.map((r) => r.dir))]) {
140
+ for (const name of await listDir(join(dir, sub))) {
141
+ const rel = sub ? `${sub}/${name}` : name;
142
+ if (!ruleOf(rel))
143
+ continue;
144
+ const st = await lstat(join(dir, rel)).catch(() => undefined);
145
+ if (st?.isFile())
146
+ out.push(rel);
147
+ }
148
+ }
149
+ return out.sort();
150
+ }
151
+ /**
152
+ * Collect the export of `dir` for one account (`account`, else the one account the per-account files
153
+ * name). Throws {@link StateBundleError} when there is no valid salt or the account cannot be told.
154
+ */
155
+ export async function collectExport(dir, opts = {}) {
156
+ const saltText = await readFile(join(dir, SALT_PATH), 'utf8').catch(() => undefined);
157
+ const salt = saltText?.trim();
158
+ if (!salt || !SALT.test(salt)) {
159
+ throw new StateBundleError('No usable salt (relations/players.salt) in this data dir, so there is no hashed history to export.');
160
+ }
161
+ const paths = await candidates(dir);
162
+ const accounts = new Set();
163
+ for (const p of paths) {
164
+ const a = ruleOf(p).account;
165
+ if (a !== undefined)
166
+ accounts.add(a);
167
+ }
168
+ // The board caches name the account that planned (`playerId`): the clearest witness.
169
+ const planners = new Set();
170
+ for (const p of paths) {
171
+ if (!p.startsWith('boards/'))
172
+ continue;
173
+ const c = await readJson(join(dir, p));
174
+ if (isRec(c) && typeof c.playerId === 'number')
175
+ planners.add(c.playerId);
176
+ }
177
+ let account = opts.account;
178
+ if (account === undefined && planners.size === 1)
179
+ account = [...planners][0];
180
+ if (account === undefined) {
181
+ if (accounts.size !== 1) {
182
+ throw new StateBundleError(accounts.size === 0
183
+ ? 'No per-account file names the account; pass --account <your war.app player id>.'
184
+ : `${accounts.size} accounts have files in this data dir; pass --account <your war.app player id>.`);
185
+ }
186
+ account = [...accounts][0];
187
+ }
188
+ if (!Number.isSafeInteger(account) || account <= 0)
189
+ throw new StateBundleError('The account must be a positive integer.');
190
+ // Which games are finished: the end-of-game record or processed mark, else the game record's state.
191
+ const marks = await readJson(join(dir, 'finished', 'processed.json'));
192
+ const marked = new Set(isRec(marks) && Array.isArray(marks.keys) ? marks.keys.filter((k) => typeof k === 'string') : []);
193
+ const status = new Map();
194
+ const statusOf = async (gameId) => {
195
+ const known = status.get(gameId);
196
+ if (known)
197
+ return known;
198
+ const key = finishedGameKey(salt, account, gameId);
199
+ let s;
200
+ const hasRecord = await lstat(join(dir, 'finished', `${key}.json`)).then(() => true, () => false);
201
+ if (marked.has(key) || hasRecord)
202
+ s = 'finished';
203
+ else {
204
+ const rec = await readJson(join(dir, 'games', `${gameId}.json`));
205
+ s = isRec(rec) && typeof rec.state === 'string' ? (rec.state === 'Finished' ? 'finished' : 'active') : 'unknown';
206
+ }
207
+ status.set(gameId, s);
208
+ return s;
209
+ };
210
+ const files = [];
211
+ const finishedGames = new Set();
212
+ const unknownGames = new Set();
213
+ let otherAccountFiles = 0;
214
+ // #412: the decision logs, weighed after the walk: newest first, up to their share.
215
+ const decisions = [];
216
+ for (const p of paths) {
217
+ const { rule, gameId, account: a } = ruleOf(p);
218
+ if (a !== undefined && a !== account) {
219
+ otherAccountFiles++;
220
+ continue;
221
+ }
222
+ if (rule.accountInside) {
223
+ // A decision log names its account in its head: only the logs exported are read whole (below).
224
+ const owner = rule.store === 'decisions' ? await decisionLogOwner(join(dir, p), gameId) : (await readJson(join(dir, p)).then((c) => (isRec(c) ? c.playerId : undefined)));
225
+ if (owner !== account) {
226
+ otherAccountFiles++;
227
+ continue;
228
+ }
229
+ }
230
+ if (gameId !== undefined && !rule.allGames) {
231
+ const s = await statusOf(gameId);
232
+ if (s === 'finished') {
233
+ finishedGames.add(gameId);
234
+ continue;
235
+ }
236
+ if (s === 'unknown') {
237
+ unknownGames.add(gameId);
238
+ continue;
239
+ }
240
+ }
241
+ if (rule.store === 'decisions') {
242
+ const st = await lstat(join(dir, p)).catch(() => undefined);
243
+ if (st)
244
+ decisions.push({ path: p, size: st.size, mtimeMs: st.mtimeMs });
245
+ continue;
246
+ }
247
+ const bytes = await readFile(join(dir, p));
248
+ files.push({ path: p, bytes, store: rule.store, sha256: sha256(bytes) });
249
+ }
250
+ const budget = opts.decisionBytes ?? MAX_EXPORT_DECISION_BYTES;
251
+ let used = 0;
252
+ let decisionLogs = 0;
253
+ decisions.sort((a, b) => b.mtimeMs - a.mtimeMs || a.path.localeCompare(b.path));
254
+ for (const [i, d] of decisions.entries()) {
255
+ const bytes = used + d.size <= budget ? await readFile(join(dir, d.path)) : undefined;
256
+ // Past the share (or grown past it since): this one and every older one stay home.
257
+ if (!bytes || used + bytes.length > budget) {
258
+ decisionLogs = decisions.length - i;
259
+ break;
260
+ }
261
+ // Its head named the account; the whole file must too (one that no longer parses, or names another, stays home).
262
+ let whole;
263
+ try {
264
+ whole = JSON.parse(bytes.toString('utf8'));
265
+ }
266
+ catch {
267
+ whole = undefined;
268
+ }
269
+ if (!isRec(whole) || whole.playerId !== account) {
270
+ otherAccountFiles++;
271
+ continue;
272
+ }
273
+ used += bytes.length;
274
+ files.push({ path: d.path, bytes, store: 'decisions', sha256: sha256(bytes) });
275
+ }
276
+ files.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
277
+ return {
278
+ manifest: {
279
+ format: STATE_FORMAT,
280
+ version: STATE_VERSION,
281
+ accountId: account,
282
+ createdAt: (opts.now ?? new Date()).toISOString(),
283
+ files: files.map((f) => ({ path: f.path, sha256: f.sha256, size: f.bytes.length })),
284
+ },
285
+ files,
286
+ leftOut: { finishedGames: finishedGames.size, unknownGames: unknownGames.size, otherAccountFiles, decisionLogs },
287
+ };
288
+ }
289
+ /** The bundle's bytes: gzipped JSON `{ format, version, manifest, files: { path: base64 } }`. */
290
+ export function encodeBundle(r) {
291
+ const body = {
292
+ format: STATE_FORMAT,
293
+ version: STATE_VERSION,
294
+ manifest: r.manifest,
295
+ files: Object.fromEntries(r.files.map((f) => [f.path, f.bytes.toString('base64')])),
296
+ };
297
+ return gzipSync(JSON.stringify(body), { level: 9 });
298
+ }
299
+ /** Write a bundle to `out`, 0600 and atomically; refuses an existing file unless `force`. */
300
+ export async function writeBundleFile(out, bytes, opts = {}) {
301
+ if (!opts.force && (await lstat(out).then(() => true, () => false))) {
302
+ throw new StateBundleError(`${out} already exists; pass --force to replace it.`);
303
+ }
304
+ const tmp = `${out}.${process.pid}.${randomUUID()}.tmp`;
305
+ await writeFile(tmp, bytes, { mode: 0o600, flag: 'wx' });
306
+ try {
307
+ await chmod(tmp, 0o600);
308
+ await rename(tmp, out);
309
+ }
310
+ catch (e) {
311
+ await unlink(tmp).catch(() => undefined);
312
+ throw e;
313
+ }
314
+ }
315
+ const B64 = /^[A-Za-z0-9+/]*={0,2}$/;
316
+ /**
317
+ * Decode and verify a bundle: format and version, every path one a store owns (no traversal, no
318
+ * credential), every per-account file the bundle's account, each file's size and sha256 as the
319
+ * manifest says, every `.json` parsing, a salt present and well formed. Throws
320
+ * {@link StateBundleError} naming paths only, never contents.
321
+ */
322
+ export function decodeBundle(bytes) {
323
+ if (bytes.length > MAX_BUNDLE_BYTES)
324
+ throw new StateBundleError(`The bundle is larger than ${MAX_BUNDLE_BYTES} bytes.`);
325
+ let parsed;
326
+ try {
327
+ parsed = JSON.parse(gunzipSync(bytes, { maxOutputLength: MAX_UNPACKED_BYTES }).toString('utf8'));
328
+ }
329
+ catch {
330
+ throw new StateBundleError('This is not a warapp-mcp state bundle (not gzipped JSON, or too large unpacked).');
331
+ }
332
+ if (!isRec(parsed) || parsed.format !== STATE_FORMAT)
333
+ throw new StateBundleError('This is not a warapp-mcp state bundle (wrong format).');
334
+ if (parsed.version !== STATE_VERSION) {
335
+ throw new StateBundleError(`The bundle's format version is not supported here (this server reads version ${STATE_VERSION}).`);
336
+ }
337
+ const m = parsed.manifest;
338
+ if (!isRec(m) ||
339
+ m.format !== STATE_FORMAT ||
340
+ m.version !== STATE_VERSION ||
341
+ typeof m.accountId !== 'number' ||
342
+ !Number.isSafeInteger(m.accountId) ||
343
+ m.accountId <= 0 ||
344
+ typeof m.createdAt !== 'string' ||
345
+ !Array.isArray(m.files) ||
346
+ !isRec(parsed.files)) {
347
+ throw new StateBundleError('The bundle manifest is malformed.');
348
+ }
349
+ const accountId = m.accountId;
350
+ const contents = parsed.files;
351
+ const files = new Map();
352
+ const list = [];
353
+ for (const f of m.files) {
354
+ if (!isRec(f) || typeof f.path !== 'string' || typeof f.sha256 !== 'string' || typeof f.size !== 'number') {
355
+ throw new StateBundleError('The bundle manifest has a malformed file entry.');
356
+ }
357
+ const path = f.path;
358
+ const r = ruleOf(path);
359
+ if (!r || path.includes('..') || path.startsWith('/'))
360
+ throw new StateBundleError(`The bundle carries a path no store owns: ${JSON.stringify(path.slice(0, 80))}.`);
361
+ if (r.account !== undefined && r.account !== accountId)
362
+ throw new StateBundleError(`The bundle carries a file of another account (${path}).`);
363
+ if (files.has(path))
364
+ throw new StateBundleError(`The bundle lists ${path} twice.`);
365
+ const b64 = contents[path];
366
+ if (typeof b64 !== 'string' || !B64.test(b64))
367
+ throw new StateBundleError(`The bundle has no readable content for ${path}.`);
368
+ const body = Buffer.from(b64, 'base64');
369
+ if (body.toString('base64') !== b64)
370
+ throw new StateBundleError(`The content of ${path} is not canonical base64.`);
371
+ if (sha256(body) !== f.sha256)
372
+ throw new StateBundleError(`The sha256 of ${path} does not match the manifest, so nothing was imported.`);
373
+ if (body.length !== f.size)
374
+ throw new StateBundleError(`The size of ${path} does not match the manifest.`);
375
+ if (path.endsWith('.json')) {
376
+ let parsedFile;
377
+ try {
378
+ parsedFile = JSON.parse(body.toString('utf8'));
379
+ }
380
+ catch {
381
+ throw new StateBundleError(`${path} is not valid JSON.`);
382
+ }
383
+ if (r.rule.accountInside && (!isRec(parsedFile) || parsedFile.playerId !== accountId)) {
384
+ throw new StateBundleError(`The bundle carries a file of another account (${path}).`);
385
+ }
386
+ }
387
+ files.set(path, body);
388
+ list.push({ path, sha256: f.sha256, size: f.size });
389
+ }
390
+ for (const p of Object.keys(contents))
391
+ if (!files.has(p))
392
+ throw new StateBundleError('The bundle carries content the manifest does not list.');
393
+ const salt = files.get(SALT_PATH)?.toString('utf8').trim();
394
+ if (!salt || !SALT.test(salt))
395
+ throw new StateBundleError('The bundle has no usable salt (relations/players.salt).');
396
+ return { manifest: { format: STATE_FORMAT, version: STATE_VERSION, accountId, createdAt: m.createdAt, files: list }, files };
397
+ }
398
+ async function saltState(dir, bundle) {
399
+ let text;
400
+ try {
401
+ text = await readFile(join(dir, SALT_PATH), 'utf8');
402
+ }
403
+ catch (e) {
404
+ return e.code === 'ENOENT' ? 'absent' : 'malformed';
405
+ }
406
+ const t = text.trim();
407
+ if (!SALT.test(t))
408
+ return 'malformed';
409
+ return t === bundle.files.get(SALT_PATH).toString('utf8').trim() ? 'same' : 'different';
410
+ }
411
+ async function onDisk(path) {
412
+ return readFile(path).catch(() => undefined);
413
+ }
414
+ /** What an import of `bundle` into `dir` would do, for `signedIn` (the signed-in account). Writes nothing. */
415
+ export async function planImport(dir, bundle, signedIn) {
416
+ const salt = await saltState(dir, bundle);
417
+ const stores = {};
418
+ let conflicts = 0;
419
+ let total = 0;
420
+ for (const [path, body] of bundle.files) {
421
+ const store = ruleOf(path).rule.store;
422
+ const c = (stores[store] ??= { files: 0, bytes: 0, new: 0, same: 0, differ: 0 });
423
+ c.files++;
424
+ c.bytes += body.length;
425
+ total += body.length;
426
+ const existing = await onDisk(join(dir, path));
427
+ if (!existing)
428
+ c.new++;
429
+ else if (existing.equals(body))
430
+ c.same++;
431
+ else {
432
+ c.differ++;
433
+ if (path !== SALT_PATH)
434
+ conflicts++;
435
+ }
436
+ }
437
+ return {
438
+ accountId: bundle.manifest.accountId,
439
+ signedIn,
440
+ accountMatches: signedIn === bundle.manifest.accountId,
441
+ salt,
442
+ createdAt: bundle.manifest.createdAt,
443
+ stores,
444
+ totals: { files: bundle.files.size, bytes: total },
445
+ conflicts,
446
+ };
447
+ }
448
+ /** Make `path`'s parent folders (0700) under `root`. */
449
+ async function ensureDirs(root, rel) {
450
+ const parts = rel.split('/').slice(0, -1);
451
+ let cur = root;
452
+ for (const p of parts) {
453
+ cur = join(cur, p);
454
+ await mkdir(cur, { recursive: true, mode: 0o700 });
455
+ await chmod(cur, 0o700);
456
+ }
457
+ }
458
+ async function writeAtomic(path, body) {
459
+ const tmp = `${path}.${process.pid}.${randomUUID()}.tmp`;
460
+ await writeFile(tmp, body, { mode: 0o600, flag: 'wx' });
461
+ try {
462
+ await chmod(tmp, 0o600);
463
+ await rename(tmp, path);
464
+ }
465
+ catch (e) {
466
+ await unlink(tmp).catch(() => undefined);
467
+ throw e;
468
+ }
469
+ }
470
+ /** A fresh backup folder `state-backups/<time>[-n]` (0700), as a relative path. */
471
+ async function makeBackup(dir, now) {
472
+ await mkdir(join(dir, BACKUP_DIR), { recursive: true, mode: 0o700 });
473
+ await chmod(join(dir, BACKUP_DIR), 0o700);
474
+ const stamp = now.toISOString().replace(/[:.]/g, '-');
475
+ for (let n = 0;; n++) {
476
+ const rel = `${BACKUP_DIR}/${stamp}${n ? `-${n}` : ''}`;
477
+ try {
478
+ await mkdir(join(dir, rel), { mode: 0o700 });
479
+ await chmod(join(dir, rel), 0o700);
480
+ return rel;
481
+ }
482
+ catch (e) {
483
+ if (e.code !== 'EEXIST' || n > 100)
484
+ throw e;
485
+ }
486
+ }
487
+ }
488
+ /**
489
+ * Import `bundle` into `dir` as `signedIn`. Refuses another account, and a salt on record that is not
490
+ * the bundle's unless `replace` (see the module header). Re-checks everything the plan showed, since
491
+ * the store may have changed since the preview.
492
+ */
493
+ export async function applyImport(dir, bundle, opts) {
494
+ if (opts.signedIn !== bundle.manifest.accountId) {
495
+ throw new StateBundleError(`The bundle is for war.app account ${bundle.manifest.accountId}, but ${opts.signedIn === undefined ? 'the signed-in account could not be read' : `account ${opts.signedIn} is signed in`}, so nothing was imported.`);
496
+ }
497
+ // One import at a time per data dir.
498
+ return withPathLock(join(dir, '.state-import'), async () => {
499
+ const salt = await saltState(dir, bundle);
500
+ if ((salt === 'different' || salt === 'malformed') && !opts.replace) {
501
+ throw new StateBundleError(`This server already has a ${salt === 'malformed' ? 'malformed' : 'different'} salt, so its hashed history cannot be merged with the bundle's; nothing was imported. Pass replace: true to move this server's hashed stores aside (backed up, not deleted) and take the bundle's.`);
502
+ }
503
+ await mkdir(dir, { recursive: true, mode: 0o700 });
504
+ let backup;
505
+ const backupDir = async () => (backup ??= await makeBackup(dir, opts.now ?? new Date()));
506
+ const movedAside = [];
507
+ if (opts.replace && salt !== 'same') {
508
+ for (const entry of HASHED_ENTRIES) {
509
+ const from = join(dir, entry);
510
+ if (!(await lstat(from).then(() => true, () => false)))
511
+ continue;
512
+ const to = join(dir, await backupDir(), entry);
513
+ await withPathLock(entry === 'lessons.json' ? from : join(dir, entry, '.state-import'), () => rename(from, to));
514
+ movedAside.push(entry);
515
+ }
516
+ }
517
+ let written = 0;
518
+ let unchanged = 0;
519
+ let kept = 0;
520
+ let displaced = 0;
521
+ // The salt first: whatever fails after it, what landed is keyed under the salt on record.
522
+ const order = [SALT_PATH, ...[...bundle.files.keys()].filter((p) => p !== SALT_PATH).sort()];
523
+ for (const rel of order) {
524
+ const body = bundle.files.get(rel);
525
+ const path = join(dir, rel);
526
+ await withPathLock(lockKey(dir, rel), async () => {
527
+ const existing = await onDisk(path);
528
+ if (existing?.equals(body)) {
529
+ unchanged++;
530
+ return;
531
+ }
532
+ if (existing && !opts.replace) {
533
+ kept++;
534
+ return;
535
+ }
536
+ await ensureDirs(dir, rel);
537
+ if (existing) {
538
+ const b = await backupDir();
539
+ await ensureDirs(join(dir, b), rel);
540
+ await rename(path, join(dir, b, rel));
541
+ displaced++;
542
+ }
543
+ if (rel === SALT_PATH) {
544
+ // Never over a salt another writer made in between (link fails when the file exists).
545
+ const tmp = `${path}.${process.pid}.${randomUUID()}.tmp`;
546
+ await writeFile(tmp, body, { mode: 0o600, flag: 'wx' });
547
+ try {
548
+ await chmod(tmp, 0o600);
549
+ await link(tmp, path);
550
+ }
551
+ catch (e) {
552
+ if (e.code === 'EEXIST') {
553
+ throw new StateBundleError('A salt was made on this server while importing, so nothing more was imported. Preview the import again.');
554
+ }
555
+ throw e;
556
+ }
557
+ finally {
558
+ await unlink(tmp).catch(() => undefined);
559
+ }
560
+ }
561
+ else {
562
+ await writeAtomic(path, body);
563
+ }
564
+ written++;
565
+ });
566
+ }
567
+ return {
568
+ written,
569
+ unchanged,
570
+ kept,
571
+ ...(backup ? { backup } : {}),
572
+ ...(movedAside.length ? { movedAside } : {}),
573
+ ...(displaced ? { displaced } : {}),
574
+ };
575
+ });
576
+ }
577
+ /** Whole bytes as a short human size ("1.6 MB"). */
578
+ export function humanSize(n) {
579
+ if (n < 1024)
580
+ return `${n} B`;
581
+ if (n < 1024 * 1024)
582
+ return `${(n / 1024).toFixed(1)} KB`;
583
+ return `${(n / 1024 / 1024).toFixed(1)} MB`;
584
+ }
@@ -0,0 +1,71 @@
1
+ // `warapp-mcp export-state --out <file>`: write this install's history as a state bundle
2
+ // (src/state-bundle.ts) for `warapp_import_state` on another server, the hosted one included.
3
+ // Local only: it reads the data dir (`--data-dir`, else `MCP_DATA_DIR`, else ~/.config/warapp-mcp)
4
+ // and nothing else — never the env file or a credential, never a request. It prints counts and sizes
5
+ // only: never the salt, a file's contents, or an id.
6
+ import { dataDir } from './config.js';
7
+ import { collectExport, encodeBundle, humanSize, MAX_EXPORT_DECISION_BYTES, StateBundleError, STORES, writeBundleFile } from './state-bundle.js';
8
+ const USAGE = 'Usage: warapp-mcp export-state --out <file> [--data-dir <dir>] [--account <war.app player id>] [--force]\n' +
9
+ 'Writes this install\'s warapp-mcp history (file mode 0600) for warapp_import_state. The file holds the\n' +
10
+ 'salt behind your hashed history: keep it private and delete it once imported.';
11
+ const defaultIo = { out: (s) => process.stdout.write(`${s}\n`), err: (s) => process.stderr.write(`${s}\n`) };
12
+ /** Run the CLI; resolves to the exit code (0 ok, 1 refused, 2 usage). */
13
+ export async function runExportCli(argv, io = defaultIo) {
14
+ let out;
15
+ let dir;
16
+ let account;
17
+ let force = false;
18
+ for (let i = 0; i < argv.length; i++) {
19
+ const a = argv[i];
20
+ const value = () => argv[++i];
21
+ if (a === '--out')
22
+ out = value();
23
+ else if (a === '--data-dir')
24
+ dir = value();
25
+ else if (a === '--account') {
26
+ const v = Number(value());
27
+ if (!Number.isSafeInteger(v) || v <= 0) {
28
+ io.err('--account must be a positive integer.');
29
+ return 2;
30
+ }
31
+ account = v;
32
+ }
33
+ else if (a === '--force')
34
+ force = true;
35
+ else if (a === '--help' || a === '-h') {
36
+ io.out(USAGE);
37
+ return 0;
38
+ }
39
+ else {
40
+ io.err(`Unknown argument.\n${USAGE}`);
41
+ return 2;
42
+ }
43
+ }
44
+ if (!out) {
45
+ io.err(`--out is required.\n${USAGE}`);
46
+ return 2;
47
+ }
48
+ try {
49
+ const r = await collectExport(dir ?? dataDir(), account !== undefined ? { account } : {});
50
+ const bytes = encodeBundle(r);
51
+ await writeBundleFile(out, bytes, { force });
52
+ const raw = r.files.reduce((n, f) => n + f.bytes.length, 0);
53
+ io.out(`Wrote ${out}: ${r.files.length} files, ${humanSize(raw)} (${humanSize(bytes.length)} compressed), file mode 0600.`);
54
+ for (const store of STORES) {
55
+ const fs = r.files.filter((f) => f.store === store);
56
+ if (fs.length)
57
+ io.out(` ${store}: ${fs.length} file${fs.length === 1 ? '' : 's'}, ${humanSize(fs.reduce((n, f) => n + f.bytes.length, 0))}`);
58
+ }
59
+ const { finishedGames, unknownGames, otherAccountFiles, decisionLogs } = r.leftOut;
60
+ io.out(`Left out: per-game files of ${finishedGames} finished game(s) and ${unknownGames} game(s) of unknown state, ` +
61
+ `${otherAccountFiles} file(s) of another account` +
62
+ (decisionLogs ? `, ${decisionLogs} older decision log(s) past the bundle's ${humanSize(MAX_EXPORT_DECISION_BYTES)} share` : '') +
63
+ '; credentials, chat, maps, stats and the bundle cache are never included.');
64
+ io.out('It holds the salt behind your hashed history: keep it private, and delete it once imported.');
65
+ return 0;
66
+ }
67
+ catch (e) {
68
+ io.err(e instanceof StateBundleError ? e.message : `Export failed: ${e.code ?? 'error'}.`);
69
+ return 1;
70
+ }
71
+ }