@chrischall/warapp-mcp 0.4.0 → 0.6.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 (92) hide show
  1. package/.claude-plugin/marketplace.json +3 -3
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +41 -5
  4. package/dist/analysis/card-support.js +2 -1
  5. package/dist/analysis/card-threats.js +59 -12
  6. package/dist/analysis/game-lessons.js +3 -4
  7. package/dist/analysis/hold-diff.js +3 -1
  8. package/dist/analysis/income-trend.js +38 -0
  9. package/dist/analysis/intel.js +75 -0
  10. package/dist/analysis/opens.js +64 -0
  11. package/dist/analysis/opponent-profile.js +75 -7
  12. package/dist/analysis/opponents.js +2 -2
  13. package/dist/analysis/outlook.js +39 -0
  14. package/dist/analysis/picks.js +91 -12
  15. package/dist/analysis/plan/bonus-attempts.js +105 -0
  16. package/dist/analysis/plan/capture-instead.js +116 -0
  17. package/dist/analysis/plan/captures.js +45 -4
  18. package/dist/analysis/plan/conceded-out.js +13 -2
  19. package/dist/analysis/plan/estimates.js +135 -26
  20. package/dist/analysis/plan/holds.js +31 -3
  21. package/dist/analysis/plan/jabs.js +113 -0
  22. package/dist/analysis/plan/leftover.js +249 -4
  23. package/dist/analysis/plan/orders.js +76 -4
  24. package/dist/analysis/plan/relations.js +21 -1
  25. package/dist/analysis/plan/report.js +69 -3
  26. package/dist/analysis/plan/second-sizing.js +133 -0
  27. package/dist/analysis/plan/shared.js +82 -20
  28. package/dist/analysis/plan/siege.js +303 -0
  29. package/dist/analysis/plan/stand-still.js +7 -3
  30. package/dist/analysis/plan/state.js +8 -0
  31. package/dist/analysis/plan/strike.js +10 -5
  32. package/dist/analysis/plan/targets.js +91 -60
  33. package/dist/analysis/plan/threats.js +41 -6
  34. package/dist/analysis/plan/transfers.js +46 -6
  35. package/dist/analysis/planner.js +234 -16
  36. package/dist/analysis/profile.js +13 -2
  37. package/dist/analysis/stress.js +8 -2
  38. package/dist/bonus-attempt-store.js +55 -0
  39. package/dist/bundle.js +48009 -39350
  40. package/dist/cards.js +7 -5
  41. package/dist/chat.js +46 -4
  42. package/dist/commerce.js +111 -0
  43. package/dist/index.js +9 -1
  44. package/dist/live.js +43 -0
  45. package/dist/move-order.js +64 -3
  46. package/dist/my-games.js +1 -1
  47. package/dist/normalize.js +17 -0
  48. package/dist/profile-store.js +12 -2
  49. package/dist/protocol/bundle.js +28 -10
  50. package/dist/protocol/codec.js +1 -1
  51. package/dist/protocol/dialect.js +371 -0
  52. package/dist/protocol/interp.js +143 -66
  53. package/dist/protocol/methods.js +95 -34
  54. package/dist/protocol/rpc.js +35 -3
  55. package/dist/push/socketio.js +2 -2
  56. package/dist/relations-store.js +38 -4
  57. package/dist/siege-store.js +49 -0
  58. package/dist/state-bundle.js +525 -0
  59. package/dist/state-cli.js +69 -0
  60. package/dist/surrender-pending.js +4 -4
  61. package/dist/team-cards.js +25 -0
  62. package/dist/tools/award.js +15 -1
  63. package/dist/tools/card-advice.js +16 -5
  64. package/dist/tools/card-plays.js +2 -2
  65. package/dist/tools/card-support-advice.js +2 -1
  66. package/dist/tools/chat-inbox.js +36 -3
  67. package/dist/tools/chat-read-mark.js +3 -1
  68. package/dist/tools/chat.js +65 -6
  69. package/dist/tools/check-plan.js +54 -10
  70. package/dist/tools/commerce-deploy.js +33 -0
  71. package/dist/tools/common.js +31 -0
  72. package/dist/tools/end-of-game.js +5 -3
  73. package/dist/tools/index.js +7 -0
  74. package/dist/tools/my-games.js +10 -3
  75. package/dist/tools/notifications.js +2 -2
  76. package/dist/tools/picks.js +12 -0
  77. package/dist/tools/profile-opponents.js +2 -0
  78. package/dist/tools/push.js +2 -1
  79. package/dist/tools/relations.js +137 -0
  80. package/dist/tools/state.js +227 -0
  81. package/dist/tools/stress-opponents.js +5 -2
  82. package/dist/tools/surrender-pending.js +11 -6
  83. package/dist/tools/survival.js +11 -3
  84. package/dist/tools/team-brief.js +2 -2
  85. package/dist/tools/team.js +12 -3
  86. package/dist/tools/turn.js +332 -60
  87. package/dist/version.js +1 -1
  88. package/manifest.json +10 -2
  89. package/mint.yaml +14 -4
  90. package/package.json +4 -4
  91. package/server.json +2 -2
  92. package/skills/warapp-mcp/SKILL.md +31 -9
@@ -0,0 +1,525 @@
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 — and, for games still in play only, the per-game
9
+ // files the planner reads (boards, game records, outlook, picks, move order, teams, the per-game
10
+ // profile turns, siege memory and contested-bonus attempts). Never: credentials (`.env`, `session.json`), the client bundle
11
+ // cache, the guess salt, chat cursors, the map cache and stats (all rebuilt), nor the per-game files
12
+ // of a finished game. A path outside {@link RULES} is never read on export nor written on import.
13
+ //
14
+ // Which games are active is read from the local records alone (no request, no credential): a game
15
+ // whose end-of-game record or processed mark exists, or whose game record says `Finished`, is
16
+ // finished; one whose game record says otherwise is active; one with no game record and no mark is
17
+ // unknown and left out.
18
+ //
19
+ // Import (`warapp_import_state`): every file's sha256 is checked against the manifest before
20
+ // anything is written; the bundle's account must be the signed-in one; a salt on record that differs
21
+ // from the bundle's refuses unless `replace`, and under `replace` the hashed stores written under the
22
+ // old salt (profiles, relations, finished, lessons, maps-record) are moved aside into
23
+ // `<dataDir>/state-backups/<time>/`, never deleted — entries under two salts would count a player or a
24
+ // game twice. Without `replace` an existing file that differs is kept; under it the bundle's wins and
25
+ // the displaced file goes to the same backup. The salt is written first, then every file atomically
26
+ // (0600, folders 0700), each under the path lock its store uses. Nothing here returns or prints the
27
+ // salt or a file's contents; errors name paths and counts only.
28
+ import { createHash, randomUUID } from 'node:crypto';
29
+ import { chmod, link, lstat, mkdir, readdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
30
+ import { join } from 'node:path';
31
+ import { gunzipSync, gzipSync } from 'node:zlib';
32
+ import { withPathLock } from './path-lock.js';
33
+ import { finishedGameKey } from './player-record-store.js';
34
+ export const STATE_FORMAT = 'warapp-state';
35
+ export const STATE_VERSION = 1;
36
+ /** The largest bundle accepted (compressed). */
37
+ export const MAX_BUNDLE_BYTES = 32 * 1024 * 1024;
38
+ /** The largest bundle unpacked (a gzip bomb stops here). */
39
+ export const MAX_UNPACKED_BYTES = 256 * 1024 * 1024;
40
+ /** Where `replace` moves the old stores. */
41
+ export const BACKUP_DIR = 'state-backups';
42
+ export class StateBundleError extends Error {
43
+ name = 'StateBundleError';
44
+ }
45
+ /** The stores a bundle carries, as the counts name them. */
46
+ export const STORES = [
47
+ 'salt',
48
+ 'playerRecord',
49
+ 'ledgers',
50
+ 'profiles',
51
+ 'profileGames',
52
+ 'lessons',
53
+ 'mapsRecord',
54
+ 'finished',
55
+ 'games',
56
+ 'boards',
57
+ 'outlook',
58
+ 'picks',
59
+ 'moveOrder',
60
+ 'teams',
61
+ 'siege',
62
+ 'bonusAttempts',
63
+ ];
64
+ const RULES = [
65
+ { store: 'salt', dir: 'relations', name: /^players\.salt$/ },
66
+ { store: 'playerRecord', dir: 'relations', name: /^players\.json$/ },
67
+ { store: 'ledgers', dir: 'relations', name: /^(\d{1,12})-(\d{1,20})\.json$/, game: 'game-account', allGames: true },
68
+ { store: 'profiles', dir: 'profiles', name: /^(players|population)\.json$/ },
69
+ { store: 'profileGames', dir: 'profiles/games', name: /^(\d{1,12})-(\d{1,20})\.json$/, game: 'game-account' },
70
+ { store: 'lessons', dir: '', name: /^lessons\.json$/ },
71
+ { store: 'mapsRecord', dir: 'maps-record', name: /^\d{1,12}\.json$/ },
72
+ { store: 'finished', dir: 'finished', name: /^([0-9a-f]{32}|processed)\.json$/ },
73
+ { store: 'games', dir: 'games', name: /^(\d{1,12})\.json$/, game: 'game' },
74
+ { store: 'boards', dir: 'boards', name: /^(\d{1,12})\.json$/, game: 'game' },
75
+ { store: 'outlook', dir: 'outlook', name: /^(\d{1,12})\.json$/, game: 'game' },
76
+ { store: 'picks', dir: 'picks', name: /^(\d{1,12})\.json$/, game: 'game' },
77
+ { store: 'moveOrder', dir: 'move-order', name: /^(\d{1,12})\.json$/, game: 'game' },
78
+ { store: 'teams', dir: 'teams', name: /^(\d{1,12})\.json$/, game: 'game' },
79
+ { store: 'siege', dir: 'siege', name: /^(\d{1,12})-(\d{1,20})\.json$/, game: 'game-account' },
80
+ // #410: the planner's contested-bonus attempt and drop memory (#405, src/bonus-attempt-store.ts).
81
+ { store: 'bonusAttempts', dir: 'bonus-attempts', name: /^(\d{1,12})-(\d{1,20})\.json$/, game: 'game-account' },
82
+ ];
83
+ /** Top-level entries keyed by the salt: moved aside whole under `replace` when the salt changes. */
84
+ const HASHED_ENTRIES = ['relations', 'profiles', 'finished', 'maps-record', 'lessons.json'];
85
+ const SALT_PATH = 'relations/players.salt';
86
+ const SALT = /^[0-9a-f]{32}$/;
87
+ /** The rule a relative path falls under, with its game and account; `undefined` when none. */
88
+ function ruleOf(path) {
89
+ const slash = path.lastIndexOf('/');
90
+ const dir = slash === -1 ? '' : path.slice(0, slash);
91
+ const name = path.slice(slash + 1);
92
+ for (const rule of RULES) {
93
+ if (rule.dir !== dir)
94
+ continue;
95
+ const m = rule.name.exec(name);
96
+ if (!m)
97
+ continue;
98
+ if (!rule.game)
99
+ return { rule };
100
+ return { rule, gameId: Number(m[1]), ...(rule.game === 'game-account' ? { account: Number(m[2]) } : {}) };
101
+ }
102
+ return undefined;
103
+ }
104
+ /** The in-process lock a store takes for this file (src/path-lock.ts). */
105
+ function lockKey(dir, path) {
106
+ // The two cross-game profile stores share one lock (src/profile-store.ts `storeLock`).
107
+ if (path === 'profiles/players.json' || path === 'profiles/population.json')
108
+ return join(dir, 'profiles', '.store');
109
+ return join(dir, path);
110
+ }
111
+ const sha256 = (b) => createHash('sha256').update(b).digest('hex');
112
+ const isRec = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
113
+ async function listDir(dir) {
114
+ return readdir(dir).catch(() => []);
115
+ }
116
+ async function readJson(path) {
117
+ try {
118
+ return JSON.parse(await readFile(path, 'utf8'));
119
+ }
120
+ catch {
121
+ return undefined;
122
+ }
123
+ }
124
+ /** Every candidate file of the rules under `dir` (regular files only), as relative paths. */
125
+ async function candidates(dir) {
126
+ const out = [];
127
+ for (const sub of [...new Set(RULES.map((r) => r.dir))]) {
128
+ for (const name of await listDir(join(dir, sub))) {
129
+ const rel = sub ? `${sub}/${name}` : name;
130
+ if (!ruleOf(rel))
131
+ continue;
132
+ const st = await lstat(join(dir, rel)).catch(() => undefined);
133
+ if (st?.isFile())
134
+ out.push(rel);
135
+ }
136
+ }
137
+ return out.sort();
138
+ }
139
+ /**
140
+ * Collect the export of `dir` for one account (`account`, else the one account the per-account files
141
+ * name). Throws {@link StateBundleError} when there is no valid salt or the account cannot be told.
142
+ */
143
+ export async function collectExport(dir, opts = {}) {
144
+ const saltText = await readFile(join(dir, SALT_PATH), 'utf8').catch(() => undefined);
145
+ const salt = saltText?.trim();
146
+ if (!salt || !SALT.test(salt)) {
147
+ throw new StateBundleError('No usable salt (relations/players.salt) in this data dir, so there is no hashed history to export.');
148
+ }
149
+ const paths = await candidates(dir);
150
+ const accounts = new Set();
151
+ for (const p of paths) {
152
+ const a = ruleOf(p).account;
153
+ if (a !== undefined)
154
+ accounts.add(a);
155
+ }
156
+ // The board caches name the account that planned (`playerId`): the clearest witness.
157
+ const planners = new Set();
158
+ for (const p of paths) {
159
+ if (!p.startsWith('boards/'))
160
+ continue;
161
+ const c = await readJson(join(dir, p));
162
+ if (isRec(c) && typeof c.playerId === 'number')
163
+ planners.add(c.playerId);
164
+ }
165
+ let account = opts.account;
166
+ if (account === undefined && planners.size === 1)
167
+ account = [...planners][0];
168
+ if (account === undefined) {
169
+ if (accounts.size !== 1) {
170
+ throw new StateBundleError(accounts.size === 0
171
+ ? 'No per-account file names the account; pass --account <your war.app player id>.'
172
+ : `${accounts.size} accounts have files in this data dir; pass --account <your war.app player id>.`);
173
+ }
174
+ account = [...accounts][0];
175
+ }
176
+ if (!Number.isSafeInteger(account) || account <= 0)
177
+ throw new StateBundleError('The account must be a positive integer.');
178
+ // Which games are finished: the end-of-game record or processed mark, else the game record's state.
179
+ const marks = await readJson(join(dir, 'finished', 'processed.json'));
180
+ const marked = new Set(isRec(marks) && Array.isArray(marks.keys) ? marks.keys.filter((k) => typeof k === 'string') : []);
181
+ const status = new Map();
182
+ const statusOf = async (gameId) => {
183
+ const known = status.get(gameId);
184
+ if (known)
185
+ return known;
186
+ const key = finishedGameKey(salt, account, gameId);
187
+ let s;
188
+ const hasRecord = await lstat(join(dir, 'finished', `${key}.json`)).then(() => true, () => false);
189
+ if (marked.has(key) || hasRecord)
190
+ s = 'finished';
191
+ else {
192
+ const rec = await readJson(join(dir, 'games', `${gameId}.json`));
193
+ s = isRec(rec) && typeof rec.state === 'string' ? (rec.state === 'Finished' ? 'finished' : 'active') : 'unknown';
194
+ }
195
+ status.set(gameId, s);
196
+ return s;
197
+ };
198
+ const files = [];
199
+ const finishedGames = new Set();
200
+ const unknownGames = new Set();
201
+ let otherAccountFiles = 0;
202
+ for (const p of paths) {
203
+ const { rule, gameId, account: a } = ruleOf(p);
204
+ if (a !== undefined && a !== account) {
205
+ otherAccountFiles++;
206
+ continue;
207
+ }
208
+ if (gameId !== undefined && !rule.allGames) {
209
+ const s = await statusOf(gameId);
210
+ if (s === 'finished') {
211
+ finishedGames.add(gameId);
212
+ continue;
213
+ }
214
+ if (s === 'unknown') {
215
+ unknownGames.add(gameId);
216
+ continue;
217
+ }
218
+ }
219
+ const bytes = await readFile(join(dir, p));
220
+ files.push({ path: p, bytes, store: rule.store, sha256: sha256(bytes) });
221
+ }
222
+ return {
223
+ manifest: {
224
+ format: STATE_FORMAT,
225
+ version: STATE_VERSION,
226
+ accountId: account,
227
+ createdAt: (opts.now ?? new Date()).toISOString(),
228
+ files: files.map((f) => ({ path: f.path, sha256: f.sha256, size: f.bytes.length })),
229
+ },
230
+ files,
231
+ leftOut: { finishedGames: finishedGames.size, unknownGames: unknownGames.size, otherAccountFiles },
232
+ };
233
+ }
234
+ /** The bundle's bytes: gzipped JSON `{ format, version, manifest, files: { path: base64 } }`. */
235
+ export function encodeBundle(r) {
236
+ const body = {
237
+ format: STATE_FORMAT,
238
+ version: STATE_VERSION,
239
+ manifest: r.manifest,
240
+ files: Object.fromEntries(r.files.map((f) => [f.path, f.bytes.toString('base64')])),
241
+ };
242
+ return gzipSync(JSON.stringify(body), { level: 9 });
243
+ }
244
+ /** Write a bundle to `out`, 0600 and atomically; refuses an existing file unless `force`. */
245
+ export async function writeBundleFile(out, bytes, opts = {}) {
246
+ if (!opts.force && (await lstat(out).then(() => true, () => false))) {
247
+ throw new StateBundleError(`${out} already exists; pass --force to replace it.`);
248
+ }
249
+ const tmp = `${out}.${process.pid}.${randomUUID()}.tmp`;
250
+ await writeFile(tmp, bytes, { mode: 0o600, flag: 'wx' });
251
+ try {
252
+ await chmod(tmp, 0o600);
253
+ await rename(tmp, out);
254
+ }
255
+ catch (e) {
256
+ await unlink(tmp).catch(() => undefined);
257
+ throw e;
258
+ }
259
+ }
260
+ const B64 = /^[A-Za-z0-9+/]*={0,2}$/;
261
+ /**
262
+ * Decode and verify a bundle: format and version, every path one a store owns (no traversal, no
263
+ * credential), every per-account file the bundle's account, each file's size and sha256 as the
264
+ * manifest says, every `.json` parsing, a salt present and well formed. Throws
265
+ * {@link StateBundleError} naming paths only, never contents.
266
+ */
267
+ export function decodeBundle(bytes) {
268
+ if (bytes.length > MAX_BUNDLE_BYTES)
269
+ throw new StateBundleError(`The bundle is larger than ${MAX_BUNDLE_BYTES} bytes.`);
270
+ let parsed;
271
+ try {
272
+ parsed = JSON.parse(gunzipSync(bytes, { maxOutputLength: MAX_UNPACKED_BYTES }).toString('utf8'));
273
+ }
274
+ catch {
275
+ throw new StateBundleError('This is not a warapp-mcp state bundle (not gzipped JSON, or too large unpacked).');
276
+ }
277
+ if (!isRec(parsed) || parsed.format !== STATE_FORMAT)
278
+ throw new StateBundleError('This is not a warapp-mcp state bundle (wrong format).');
279
+ if (parsed.version !== STATE_VERSION) {
280
+ throw new StateBundleError(`The bundle's format version is not supported here (this server reads version ${STATE_VERSION}).`);
281
+ }
282
+ const m = parsed.manifest;
283
+ if (!isRec(m) ||
284
+ m.format !== STATE_FORMAT ||
285
+ m.version !== STATE_VERSION ||
286
+ typeof m.accountId !== 'number' ||
287
+ !Number.isSafeInteger(m.accountId) ||
288
+ m.accountId <= 0 ||
289
+ typeof m.createdAt !== 'string' ||
290
+ !Array.isArray(m.files) ||
291
+ !isRec(parsed.files)) {
292
+ throw new StateBundleError('The bundle manifest is malformed.');
293
+ }
294
+ const accountId = m.accountId;
295
+ const contents = parsed.files;
296
+ const files = new Map();
297
+ const list = [];
298
+ for (const f of m.files) {
299
+ if (!isRec(f) || typeof f.path !== 'string' || typeof f.sha256 !== 'string' || typeof f.size !== 'number') {
300
+ throw new StateBundleError('The bundle manifest has a malformed file entry.');
301
+ }
302
+ const path = f.path;
303
+ const r = ruleOf(path);
304
+ if (!r || path.includes('..') || path.startsWith('/'))
305
+ throw new StateBundleError(`The bundle carries a path no store owns: ${JSON.stringify(path.slice(0, 80))}.`);
306
+ if (r.account !== undefined && r.account !== accountId)
307
+ throw new StateBundleError(`The bundle carries a file of another account (${path}).`);
308
+ if (files.has(path))
309
+ throw new StateBundleError(`The bundle lists ${path} twice.`);
310
+ const b64 = contents[path];
311
+ if (typeof b64 !== 'string' || !B64.test(b64))
312
+ throw new StateBundleError(`The bundle has no readable content for ${path}.`);
313
+ const body = Buffer.from(b64, 'base64');
314
+ if (body.toString('base64') !== b64)
315
+ throw new StateBundleError(`The content of ${path} is not canonical base64.`);
316
+ if (sha256(body) !== f.sha256)
317
+ throw new StateBundleError(`The sha256 of ${path} does not match the manifest, so nothing was imported.`);
318
+ if (body.length !== f.size)
319
+ throw new StateBundleError(`The size of ${path} does not match the manifest.`);
320
+ if (path.endsWith('.json')) {
321
+ try {
322
+ JSON.parse(body.toString('utf8'));
323
+ }
324
+ catch {
325
+ throw new StateBundleError(`${path} is not valid JSON.`);
326
+ }
327
+ }
328
+ files.set(path, body);
329
+ list.push({ path, sha256: f.sha256, size: f.size });
330
+ }
331
+ for (const p of Object.keys(contents))
332
+ if (!files.has(p))
333
+ throw new StateBundleError('The bundle carries content the manifest does not list.');
334
+ const salt = files.get(SALT_PATH)?.toString('utf8').trim();
335
+ if (!salt || !SALT.test(salt))
336
+ throw new StateBundleError('The bundle has no usable salt (relations/players.salt).');
337
+ return { manifest: { format: STATE_FORMAT, version: STATE_VERSION, accountId, createdAt: m.createdAt, files: list }, files };
338
+ }
339
+ async function saltState(dir, bundle) {
340
+ let text;
341
+ try {
342
+ text = await readFile(join(dir, SALT_PATH), 'utf8');
343
+ }
344
+ catch (e) {
345
+ return e.code === 'ENOENT' ? 'absent' : 'malformed';
346
+ }
347
+ const t = text.trim();
348
+ if (!SALT.test(t))
349
+ return 'malformed';
350
+ return t === bundle.files.get(SALT_PATH).toString('utf8').trim() ? 'same' : 'different';
351
+ }
352
+ async function onDisk(path) {
353
+ return readFile(path).catch(() => undefined);
354
+ }
355
+ /** What an import of `bundle` into `dir` would do, for `signedIn` (the signed-in account). Writes nothing. */
356
+ export async function planImport(dir, bundle, signedIn) {
357
+ const salt = await saltState(dir, bundle);
358
+ const stores = {};
359
+ let conflicts = 0;
360
+ let total = 0;
361
+ for (const [path, body] of bundle.files) {
362
+ const store = ruleOf(path).rule.store;
363
+ const c = (stores[store] ??= { files: 0, bytes: 0, new: 0, same: 0, differ: 0 });
364
+ c.files++;
365
+ c.bytes += body.length;
366
+ total += body.length;
367
+ const existing = await onDisk(join(dir, path));
368
+ if (!existing)
369
+ c.new++;
370
+ else if (existing.equals(body))
371
+ c.same++;
372
+ else {
373
+ c.differ++;
374
+ if (path !== SALT_PATH)
375
+ conflicts++;
376
+ }
377
+ }
378
+ return {
379
+ accountId: bundle.manifest.accountId,
380
+ signedIn,
381
+ accountMatches: signedIn === bundle.manifest.accountId,
382
+ salt,
383
+ createdAt: bundle.manifest.createdAt,
384
+ stores,
385
+ totals: { files: bundle.files.size, bytes: total },
386
+ conflicts,
387
+ };
388
+ }
389
+ /** Make `path`'s parent folders (0700) under `root`. */
390
+ async function ensureDirs(root, rel) {
391
+ const parts = rel.split('/').slice(0, -1);
392
+ let cur = root;
393
+ for (const p of parts) {
394
+ cur = join(cur, p);
395
+ await mkdir(cur, { recursive: true, mode: 0o700 });
396
+ await chmod(cur, 0o700);
397
+ }
398
+ }
399
+ async function writeAtomic(path, body) {
400
+ const tmp = `${path}.${process.pid}.${randomUUID()}.tmp`;
401
+ await writeFile(tmp, body, { mode: 0o600, flag: 'wx' });
402
+ try {
403
+ await chmod(tmp, 0o600);
404
+ await rename(tmp, path);
405
+ }
406
+ catch (e) {
407
+ await unlink(tmp).catch(() => undefined);
408
+ throw e;
409
+ }
410
+ }
411
+ /** A fresh backup folder `state-backups/<time>[-n]` (0700), as a relative path. */
412
+ async function makeBackup(dir, now) {
413
+ await mkdir(join(dir, BACKUP_DIR), { recursive: true, mode: 0o700 });
414
+ await chmod(join(dir, BACKUP_DIR), 0o700);
415
+ const stamp = now.toISOString().replace(/[:.]/g, '-');
416
+ for (let n = 0;; n++) {
417
+ const rel = `${BACKUP_DIR}/${stamp}${n ? `-${n}` : ''}`;
418
+ try {
419
+ await mkdir(join(dir, rel), { mode: 0o700 });
420
+ await chmod(join(dir, rel), 0o700);
421
+ return rel;
422
+ }
423
+ catch (e) {
424
+ if (e.code !== 'EEXIST' || n > 100)
425
+ throw e;
426
+ }
427
+ }
428
+ }
429
+ /**
430
+ * Import `bundle` into `dir` as `signedIn`. Refuses another account, and a salt on record that is not
431
+ * the bundle's unless `replace` (see the module header). Re-checks everything the plan showed, since
432
+ * the store may have changed since the preview.
433
+ */
434
+ export async function applyImport(dir, bundle, opts) {
435
+ if (opts.signedIn !== bundle.manifest.accountId) {
436
+ 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.`);
437
+ }
438
+ // One import at a time per data dir.
439
+ return withPathLock(join(dir, '.state-import'), async () => {
440
+ const salt = await saltState(dir, bundle);
441
+ if ((salt === 'different' || salt === 'malformed') && !opts.replace) {
442
+ 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.`);
443
+ }
444
+ await mkdir(dir, { recursive: true, mode: 0o700 });
445
+ let backup;
446
+ const backupDir = async () => (backup ??= await makeBackup(dir, opts.now ?? new Date()));
447
+ const movedAside = [];
448
+ if (opts.replace && salt !== 'same') {
449
+ for (const entry of HASHED_ENTRIES) {
450
+ const from = join(dir, entry);
451
+ if (!(await lstat(from).then(() => true, () => false)))
452
+ continue;
453
+ const to = join(dir, await backupDir(), entry);
454
+ await withPathLock(entry === 'lessons.json' ? from : join(dir, entry, '.state-import'), () => rename(from, to));
455
+ movedAside.push(entry);
456
+ }
457
+ }
458
+ let written = 0;
459
+ let unchanged = 0;
460
+ let kept = 0;
461
+ let displaced = 0;
462
+ // The salt first: whatever fails after it, what landed is keyed under the salt on record.
463
+ const order = [SALT_PATH, ...[...bundle.files.keys()].filter((p) => p !== SALT_PATH).sort()];
464
+ for (const rel of order) {
465
+ const body = bundle.files.get(rel);
466
+ const path = join(dir, rel);
467
+ await withPathLock(lockKey(dir, rel), async () => {
468
+ const existing = await onDisk(path);
469
+ if (existing?.equals(body)) {
470
+ unchanged++;
471
+ return;
472
+ }
473
+ if (existing && !opts.replace) {
474
+ kept++;
475
+ return;
476
+ }
477
+ await ensureDirs(dir, rel);
478
+ if (existing) {
479
+ const b = await backupDir();
480
+ await ensureDirs(join(dir, b), rel);
481
+ await rename(path, join(dir, b, rel));
482
+ displaced++;
483
+ }
484
+ if (rel === SALT_PATH) {
485
+ // Never over a salt another writer made in between (link fails when the file exists).
486
+ const tmp = `${path}.${process.pid}.${randomUUID()}.tmp`;
487
+ await writeFile(tmp, body, { mode: 0o600, flag: 'wx' });
488
+ try {
489
+ await chmod(tmp, 0o600);
490
+ await link(tmp, path);
491
+ }
492
+ catch (e) {
493
+ if (e.code === 'EEXIST') {
494
+ throw new StateBundleError('A salt was made on this server while importing, so nothing more was imported. Preview the import again.');
495
+ }
496
+ throw e;
497
+ }
498
+ finally {
499
+ await unlink(tmp).catch(() => undefined);
500
+ }
501
+ }
502
+ else {
503
+ await writeAtomic(path, body);
504
+ }
505
+ written++;
506
+ });
507
+ }
508
+ return {
509
+ written,
510
+ unchanged,
511
+ kept,
512
+ ...(backup ? { backup } : {}),
513
+ ...(movedAside.length ? { movedAside } : {}),
514
+ ...(displaced ? { displaced } : {}),
515
+ };
516
+ });
517
+ }
518
+ /** Whole bytes as a short human size ("1.6 MB"). */
519
+ export function humanSize(n) {
520
+ if (n < 1024)
521
+ return `${n} B`;
522
+ if (n < 1024 * 1024)
523
+ return `${(n / 1024).toFixed(1)} KB`;
524
+ return `${(n / 1024 / 1024).toFixed(1)} MB`;
525
+ }
@@ -0,0 +1,69 @@
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, 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 } = 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; credentials, chat, maps, stats and the bundle cache are never included.`);
62
+ io.out('It holds the salt behind your hashed history: keep it private, and delete it once imported.');
63
+ return 0;
64
+ }
65
+ catch (e) {
66
+ io.err(e instanceof StateBundleError ? e.message : `Export failed: ${e.code ?? 'error'}.`);
67
+ return 1;
68
+ }
69
+ }
@@ -2,10 +2,10 @@
2
2
  // UNVERIFIED live (docs/WEB-PROTOCOL.md, "Accepting a surrender").
3
3
  //
4
4
  // GameFeed keeps a player who asked to surrender `Playing`, and neither GetMyGames nor
5
- // LatestGameInfo says anything about it: only the game details do. GameRefresh (39) asked with
5
+ // LatestGameInfo says anything about it: only the game details do. GameRefresh (40) asked with
6
6
  // `nonChat` answers `warlight.shared.GameDetailsAndChat`, whose second field is the game
7
7
  // (`warlight.shared.GameWL`); the game's eighth field is its players, a dict of in-game id →
8
- // `warlight.shared.GamePlayer`. Of a player's 36 fields this reads the AI id, "human turned into
8
+ // `warlight.shared.GamePlayer`. Of a player's 37 fields this reads the AI id, "human turned into
9
9
  // an AI", the in-game id, who accepted its surrender, its state and the `Surrendered` flag.
10
10
  //
11
11
  // The client's player reader first sets a link back to the game being read (only when it is read
@@ -22,8 +22,8 @@ export const GAME_PLAYER = 'warlight.shared.GamePlayer';
22
22
  /** GameWL: its field count and where the players are, in read order. */
23
23
  export const GAME_WL_FIELDS = 14;
24
24
  const GW_PLAYERS = 7;
25
- /** GamePlayer: its field count and the positions read, in read order. */
26
- export const GAME_PLAYER_FIELDS = 36;
25
+ /** GamePlayer: its field count (protocol 243 added an int32 at 31) and the positions read, in read order. */
26
+ export const GAME_PLAYER_FIELDS = 37;
27
27
  const GPL = { aiId: 0, turnedAI: 14, id: 20, accepted: 21, state: 28, surrendered: 29 };
28
28
  /** Whether a details seat is still playing (GamePlayerState `Playing`, src/player-states.ts). */
29
29
  export const seatPlaying = (s) => playerStateName(s.state) === 'Playing';
@@ -1,3 +1,10 @@
1
+ // PLAN-TEAMS C3.7: the team hand and my teammates' entered card plays (#163). A team shares one hand, so a
2
+ // card my teammate has already entered a play or a discard of is theirs this turn: the plan never plays it
3
+ // too, and the card advice says who plays each card.
4
+ //
5
+ // UNVERIFIED live: whether war.app sends a teammate's orders before they commit (V5). VERIFIED (V8, #310): how a
6
+ // team's hand and its limit are keyed (teamCardLimit). Tolerant: no teammate orders read means no claim.
7
+ import { cardsToShed } from './cards.js';
1
8
  /** Every card play and discard in my teammates' entered orders (`teammates`: their player ids), in entry order. */
2
9
  export function teamCardClaims(entries, teammates) {
3
10
  const out = [];
@@ -82,3 +89,21 @@ export function unclaimedFirst(hand, claimed) {
82
89
  const ids = new Set(claimed.map((c) => c.card.id));
83
90
  return [...hand.filter((c) => !ids.has(c.id)), ...hand.filter((c) => ids.has(c.id))];
84
91
  }
92
+ /**
93
+ * The team's card limit as war.app applies it (V8, #310; the client bundle's GameValidateOrders, the hand seen
94
+ * live): the standing keeps each player's cards under that player's id, and a team's hand is every card under
95
+ * any of its players, counted against `MaxCardsHold` (the settings call it the most "a player or team" may hold).
96
+ * The cards my committed teammates' orders play or discard leave it first; then mine. Over the limit, war.app
97
+ * refuses (error 51) only the orders of the last of the team still playing to commit: while a teammate has yet
98
+ * to commit, they may still shed, and the orders are taken. `binding` holds only when every committed
99
+ * teammate's orders were read, so an unread teammate never makes a refusal.
100
+ */
101
+ export function teamCardLimit(hand, rules, mates, entries) {
102
+ const playing = mates.filter((m) => (m.state ?? 'Playing') === 'Playing');
103
+ const committed = playing.filter((m) => m.hasCommittedOrders);
104
+ const lastToCommit = playing.every((m) => m.hasCommittedOrders);
105
+ const ordersRead = committed.every((m) => entries?.some((e) => e.playerId === m.id && e.orders !== null) === true);
106
+ const { left } = teamHandLeft(hand, teamCardClaims(entries, new Set(committed.map((m) => m.id))));
107
+ const shed = cardsToShed(left, rules);
108
+ return { left, shed, lastToCommit, ordersRead, binding: lastToCommit && ordersRead };
109
+ }