@chrischall/warapp-mcp 0.5.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 (80) hide show
  1. package/.claude-plugin/marketplace.json +3 -3
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +37 -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 +47965 -39683
  40. package/dist/cards.js +7 -5
  41. package/dist/chat.js +35 -1
  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/normalize.js +17 -0
  47. package/dist/profile-store.js +12 -2
  48. package/dist/protocol/methods.js +60 -5
  49. package/dist/protocol/rpc.js +8 -0
  50. package/dist/relations-store.js +38 -4
  51. package/dist/siege-store.js +49 -0
  52. package/dist/state-bundle.js +525 -0
  53. package/dist/state-cli.js +69 -0
  54. package/dist/team-cards.js +25 -0
  55. package/dist/tools/award.js +15 -1
  56. package/dist/tools/card-advice.js +16 -5
  57. package/dist/tools/card-plays.js +2 -2
  58. package/dist/tools/card-support-advice.js +2 -1
  59. package/dist/tools/chat-inbox.js +4 -0
  60. package/dist/tools/chat.js +65 -6
  61. package/dist/tools/check-plan.js +54 -10
  62. package/dist/tools/commerce-deploy.js +33 -0
  63. package/dist/tools/common.js +31 -0
  64. package/dist/tools/end-of-game.js +5 -3
  65. package/dist/tools/index.js +7 -0
  66. package/dist/tools/picks.js +12 -0
  67. package/dist/tools/profile-opponents.js +2 -0
  68. package/dist/tools/relations.js +137 -0
  69. package/dist/tools/state.js +227 -0
  70. package/dist/tools/stress-opponents.js +5 -2
  71. package/dist/tools/survival.js +11 -3
  72. package/dist/tools/team-brief.js +2 -2
  73. package/dist/tools/team.js +12 -3
  74. package/dist/tools/turn.js +332 -60
  75. package/dist/version.js +1 -1
  76. package/manifest.json +10 -2
  77. package/mint.yaml +14 -4
  78. package/package.json +4 -4
  79. package/server.json +2 -2
  80. package/skills/warapp-mcp/SKILL.md +31 -9
@@ -9,6 +9,9 @@
9
9
  // `commitments` (part B4): what my chat messages promised (warapp_send_chat's declared commitments,
10
10
  // never the text), recorded once a message is sent; warapp_submit_turn warns when orders break one.
11
11
  //
12
+ // `intel` (#386): avoid targets and stated incomes from diplomacy (warapp_record_intel), applied by
13
+ // warapp_plan_turn and warapp_check_plan by default.
14
+ //
12
15
  // `usage` (part B2): per planned turn, what each honoured truce freed and what a break would have
13
16
  // cost (rule T6: the armies and the income); warapp_plan_turn calls `recordTruceUsage`.
14
17
  import { randomUUID } from 'node:crypto';
@@ -17,6 +20,7 @@ import { join } from 'node:path';
17
20
  import { withPathLock } from './path-lock.js';
18
21
  import { AGREEMENT_STATUSES, MAX_NOTICE_TURNS, } from './analysis/relations.js';
19
22
  import { COMMITMENT_KINDS } from './analysis/commitments.js';
23
+ import { AVOID_REASONS, intelIsEmpty } from './analysis/intel.js';
20
24
  const isRec = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
21
25
  const isInt = (v) => typeof v === 'number' && Number.isInteger(v);
22
26
  const ints = (v) => (Array.isArray(v) && v.every(isInt) ? [...v] : undefined);
@@ -26,6 +30,9 @@ export const MAX_AGREEMENTS = 50;
26
30
  export const MAX_USAGE_TURNS = 200;
27
31
  /** Commitments kept per game (the newest). */
28
32
  export const MAX_COMMITMENTS = 200;
33
+ /** #386: intel entries kept per game and kind (the newest). */
34
+ export const MAX_INTEL_TERRITORIES = 200;
35
+ export const MAX_INTEL_PLAYERS = 50;
29
36
  export const relationsDir = (dir) => join(dir, 'relations');
30
37
  export const relationsPath = (dir, gameId, playerId) => join(relationsDir(dir), `${gameId}-${playerId}.json`);
31
38
  const AGREEMENT_ID = /^a(\d{1,9})$/;
@@ -122,6 +129,24 @@ export function nextCommitmentId(ledger) {
122
129
  const n = (ledger.commitments ?? []).reduce((m, c) => Math.max(m, Number(COMMITMENT_ID.exec(c.id)?.[1] ?? 0)), 0);
123
130
  return `c${n + 1}`;
124
131
  }
132
+ /** #386: the intel of a ledger file, the unusable entries dropped; absent when none. */
133
+ export function intelOf(v) {
134
+ if (!isRec(v))
135
+ return {};
136
+ const list = (x) => (Array.isArray(x) ? x.filter(isRec) : []);
137
+ const intel = {
138
+ avoidTerritories: list(v.avoidTerritories)
139
+ .filter((a) => isInt(a.territory) && isInt(a.turn))
140
+ .map((a) => ({ territory: a.territory, turn: a.turn, ...(isInt(a.promisedTo) ? { promisedTo: a.promisedTo } : {}) })),
141
+ avoidPlayers: list(v.avoidPlayers)
142
+ .filter((a) => isInt(a.player) && isInt(a.turn) && typeof a.reason === 'string' && AVOID_REASONS.includes(a.reason))
143
+ .map((a) => ({ player: a.player, turn: a.turn, reason: a.reason })),
144
+ incomes: list(v.incomes)
145
+ .filter((a) => isInt(a.player) && isInt(a.income) && a.income >= 0 && isInt(a.turn))
146
+ .map((a) => ({ player: a.player, income: a.income, turn: a.turn })),
147
+ };
148
+ return intelIsEmpty(intel) ? {} : { intel };
149
+ }
125
150
  function usageOf(v) {
126
151
  if (!isRec(v))
127
152
  return {};
@@ -153,7 +178,7 @@ export async function readLedger(dir, gameId, playerId) {
153
178
  if (!isRec(c) || c.gameId !== gameId || c.playerId !== playerId || !Array.isArray(c.agreements))
154
179
  return undefined;
155
180
  const agreements = c.agreements.map(agreementOf).filter((a) => a !== undefined);
156
- return { gameId, playerId, agreements, usage: usageOf(c.usage), ...commitmentsOf(c.commitments) };
181
+ return { gameId, playerId, agreements, usage: usageOf(c.usage), ...commitmentsOf(c.commitments), ...intelOf(c.intel) };
157
182
  }
158
183
  catch {
159
184
  return undefined;
@@ -177,7 +202,7 @@ export async function readLedgerForWrite(dir, gameId, playerId) {
177
202
  if (!isRec(c) || c.gameId !== gameId || c.playerId !== playerId || !Array.isArray(c.agreements))
178
203
  return 'unreadable';
179
204
  const agreements = c.agreements.map(agreementOf).filter((a) => a !== undefined);
180
- return { gameId, playerId, agreements, usage: usageOf(c.usage), ...commitmentsOf(c.commitments) };
205
+ return { gameId, playerId, agreements, usage: usageOf(c.usage), ...commitmentsOf(c.commitments), ...intelOf(c.intel) };
181
206
  }
182
207
  catch {
183
208
  return 'unreadable';
@@ -200,8 +225,17 @@ export function boundLedger(ledger) {
200
225
  .slice(0, MAX_USAGE_TURNS)
201
226
  .sort((a, b) => a - b);
202
227
  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 };
228
+ const { commitments: _all, intel: _intel, ...rest } = ledger;
229
+ const intel = intelIsEmpty(ledger.intel)
230
+ ? {}
231
+ : {
232
+ intel: {
233
+ avoidTerritories: ledger.intel.avoidTerritories.slice(-MAX_INTEL_TERRITORIES),
234
+ avoidPlayers: ledger.intel.avoidPlayers.slice(-MAX_INTEL_PLAYERS),
235
+ incomes: ledger.intel.incomes.slice(-MAX_INTEL_PLAYERS),
236
+ },
237
+ };
238
+ return { ...rest, agreements, usage: Object.fromEntries(turns.map((t) => [String(t), ledger.usage[String(t)]])), ...commitments, ...intel };
205
239
  }
206
240
  /** Write the ledger (bounded), atomically, 0600. `true` when written; never throws. */
207
241
  export async function writeLedger(dir, ledger) {
@@ -0,0 +1,49 @@
1
+ // The siege's memory on disk (#382): per game and account, at `<dataDir>/siege/<gameId>-<playerId>.json`,
2
+ // the target and each planned siege turn (the target's income, mine, the bonuses that turn's plan broke).
3
+ // Ids and numbers only, never a name; 0600 in a 0700 directory, written atomically under the in-process
4
+ // path lock. Written by warapp_plan_turn under `goal: 'siege'` (not with `enemy_deploy`, a what-if) and
5
+ // read back as `PlanInput.siegeMemory`. Reads are loose: an unusable file is no memory, an unusable turn
6
+ // is dropped; nothing here throws.
7
+ import { randomUUID } from 'node:crypto';
8
+ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
9
+ import { join } from 'node:path';
10
+ import { withPathLock } from './path-lock.js';
11
+ const isRec = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
12
+ const isInt = (v) => typeof v === 'number' && Number.isSafeInteger(v);
13
+ const isNum = (v) => typeof v === 'number' && Number.isFinite(v);
14
+ export const siegeDir = (dir) => join(dir, 'siege');
15
+ export const siegePath = (dir, gameId, playerId) => join(siegeDir(dir), `${gameId}-${playerId}.json`);
16
+ function turnOf(v) {
17
+ if (!isRec(v) || !isInt(v.turn) || !isNum(v.opponentIncome) || !isNum(v.myIncome))
18
+ return undefined;
19
+ const breaks = Array.isArray(v.breaks) && v.breaks.every(isInt) ? [...v.breaks] : [];
20
+ return { turn: v.turn, opponentIncome: v.opponentIncome, myIncome: v.myIncome, breaks };
21
+ }
22
+ /** The siege memory kept for `gameId` as `playerId`; `undefined` when none or unusable. Never throws. */
23
+ export async function readSiegeMemory(dir, gameId, playerId) {
24
+ try {
25
+ const c = JSON.parse(await readFile(siegePath(dir, gameId, playerId), 'utf8'));
26
+ if (!isRec(c) || c.gameId !== gameId || c.playerId !== playerId || !isInt(c.target) || !Array.isArray(c.turns))
27
+ return undefined;
28
+ return { target: c.target, turns: c.turns.map(turnOf).filter((t) => t !== undefined) };
29
+ }
30
+ catch {
31
+ return undefined;
32
+ }
33
+ }
34
+ /** Write the siege memory, atomically, 0600. `true` when written; never throws. */
35
+ export async function writeSiegeMemory(dir, gameId, playerId, memory) {
36
+ const path = siegePath(dir, gameId, playerId);
37
+ return withPathLock(path, async () => {
38
+ try {
39
+ await mkdir(siegeDir(dir), { recursive: true, mode: 0o700 });
40
+ const tmp = `${path}.${process.pid}.${randomUUID()}.tmp`;
41
+ await writeFile(tmp, JSON.stringify({ gameId, playerId, target: memory.target, turns: memory.turns }), { mode: 0o600 });
42
+ await rename(tmp, path);
43
+ return true;
44
+ }
45
+ catch {
46
+ return false;
47
+ }
48
+ });
49
+ }
@@ -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
+ }