@chrischall/warapp-mcp 0.6.0 → 0.8.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 (111) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +100 -7
  4. package/dist/analysis/accept-surrender.js +20 -2
  5. package/dist/analysis/calibrate.js +1 -0
  6. package/dist/analysis/card-support.js +187 -20
  7. package/dist/analysis/card-threats.js +68 -3
  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/coalition.js +55 -0
  13. package/dist/analysis/decision-replay.js +279 -0
  14. package/dist/analysis/decision-truth.js +146 -0
  15. package/dist/analysis/finished-game.js +62 -3
  16. package/dist/analysis/game-lessons.js +12 -6
  17. package/dist/analysis/local-deploy.js +14 -0
  18. package/dist/analysis/opponent-profile.js +46 -3
  19. package/dist/analysis/opponents.js +246 -19
  20. package/dist/analysis/outlook.js +323 -17
  21. package/dist/analysis/picks.js +270 -37
  22. package/dist/analysis/plan/after-leftover.js +28 -3
  23. package/dist/analysis/plan/captures.js +80 -16
  24. package/dist/analysis/plan/completed.js +8 -1
  25. package/dist/analysis/plan/conceded-out.js +16 -11
  26. package/dist/analysis/plan/deploy-estimates.js +513 -0
  27. package/dist/analysis/plan/doomed-out.js +135 -0
  28. package/dist/analysis/plan/estimates.js +73 -7
  29. package/dist/analysis/plan/free-capture.js +34 -0
  30. package/dist/analysis/plan/guard-off.js +2 -1
  31. package/dist/analysis/plan/holds.js +85 -313
  32. package/dist/analysis/plan/horizon.js +42 -0
  33. package/dist/analysis/plan/leftover.js +188 -10
  34. package/dist/analysis/plan/observe.js +896 -0
  35. package/dist/analysis/plan/orders.js +35 -1
  36. package/dist/analysis/plan/relations.js +115 -2
  37. package/dist/analysis/plan/report.js +10 -4
  38. package/dist/analysis/plan/shared.js +7 -1189
  39. package/dist/analysis/plan/stand-still.js +7 -5
  40. package/dist/analysis/plan/state.js +12 -0
  41. package/dist/analysis/plan/stockpile.js +104 -0
  42. package/dist/analysis/plan/strike-stack.js +467 -0
  43. package/dist/analysis/plan/strike.js +8 -441
  44. package/dist/analysis/plan/targets.js +374 -72
  45. package/dist/analysis/plan/threats.js +120 -9
  46. package/dist/analysis/plan/transfers.js +35 -1
  47. package/dist/analysis/plan/two-move.js +70 -0
  48. package/dist/analysis/plan/vacated.js +124 -2
  49. package/dist/analysis/plan/withdraw.js +316 -0
  50. package/dist/analysis/planner.js +356 -53
  51. package/dist/analysis/player.js +4 -0
  52. package/dist/analysis/relations.js +8 -2
  53. package/dist/analysis/since-last.js +18 -5
  54. package/dist/analysis/stress.js +1 -1
  55. package/dist/board.js +36 -2
  56. package/dist/build-id.js +106 -0
  57. package/dist/bundle.js +15863 -10242
  58. package/dist/chat-automation.js +22 -0
  59. package/dist/client.js +14 -0
  60. package/dist/decision-log.js +1093 -0
  61. package/dist/finished-store.js +5 -1
  62. package/dist/lessons-store.js +322 -21
  63. package/dist/my-games.js +2 -0
  64. package/dist/open-games.js +122 -18
  65. package/dist/outlook-log.js +42 -1
  66. package/dist/protocol/methods.js +4 -2
  67. package/dist/review-export.js +198 -0
  68. package/dist/state-bundle.js +62 -3
  69. package/dist/state-cli.js +5 -3
  70. package/dist/strategy/notes.js +56 -0
  71. package/dist/tools/accept-surrender.js +23 -9
  72. package/dist/tools/award.js +5 -1
  73. package/dist/tools/card-advice.js +102 -33
  74. package/dist/tools/card-support-advice.js +53 -8
  75. package/dist/tools/chat-advice.js +330 -0
  76. package/dist/tools/chat-inbox.js +15 -4
  77. package/dist/tools/chat.js +41 -11
  78. package/dist/tools/check-plan.js +16 -3
  79. package/dist/tools/commander-check.js +2 -1
  80. package/dist/tools/decision-capture.js +461 -0
  81. package/dist/tools/end-of-game.js +146 -18
  82. package/dist/tools/game-kind.js +92 -0
  83. package/dist/tools/how-lost.js +7 -2
  84. package/dist/tools/index.js +3 -0
  85. package/dist/tools/join-game.js +51 -9
  86. package/dist/tools/live-context.js +6 -0
  87. package/dist/tools/live.js +43 -6
  88. package/dist/tools/map-curves.js +73 -0
  89. package/dist/tools/notifications.js +4 -3
  90. package/dist/tools/open-games.js +2 -2
  91. package/dist/tools/opponents.js +2 -0
  92. package/dist/tools/past-games.js +74 -8
  93. package/dist/tools/picks.js +169 -57
  94. package/dist/tools/profile-hook.js +62 -3
  95. package/dist/tools/profile-opponents.js +2 -0
  96. package/dist/tools/push.js +2 -2
  97. package/dist/tools/relations.js +2 -0
  98. package/dist/tools/scout.js +16 -2
  99. package/dist/tools/state.js +6 -1
  100. package/dist/tools/strategy.js +3 -3
  101. package/dist/tools/stress-opponents.js +2 -0
  102. package/dist/tools/surrender-pending.js +10 -1
  103. package/dist/tools/surrender.js +18 -3
  104. package/dist/tools/turn.js +353 -19
  105. package/dist/tools/where.js +3 -1
  106. package/dist/version.js +1 -1
  107. package/manifest.json +23 -2
  108. package/mint.yaml +23 -0
  109. package/package.json +1 -1
  110. package/server.json +20 -2
  111. package/skills/warapp-mcp/SKILL.md +42 -8
@@ -47,7 +47,15 @@ const GI = {
47
47
  players: 16,
48
48
  realTime: 19,
49
49
  settings: 21,
50
+ tournament: 25,
50
51
  };
52
+ /**
53
+ * GameInfoTournament (#423): the coin structure, a number, and the tournament's id (verified live 2026-11-22: the id of
54
+ * both of my tournament games was in war.app's `/API/GameIDFeed?TournamentID=` list; 54 other games held no record).
55
+ */
56
+ const GAME_INFO_TOURNAMENT = 'warlight.shared.GameInfoTournament';
57
+ const GAME_INFO_TOURNAMENT_FIELDS = 3;
58
+ const GT = { tournamentId: 2 };
51
59
  /** GameInfoPlayer: the colour (an optional GameColor), the in-game id, the state (GamePlayerState) and the team. */
52
60
  // `ai` is the client's IsAI (GameInfoPlayer is built from GamePlayer's get_IsAI in that place; read from the bundle).
53
61
  const GP = { color: 0, ai: 4, id: 6, state: 7, team: 8 };
@@ -325,12 +333,25 @@ function readOpenGame(record) {
325
333
  game.openSeatTeams = openSeatTeams;
326
334
  if (settings?.cards)
327
335
  game.cards = settings.cards;
336
+ const tournamentId = tournamentOf(f[GI.tournament]);
337
+ if (tournamentId !== undefined)
338
+ game.tournamentId = tournamentId;
328
339
  const colorsTaken = [...new Set(all.map((p) => p.color).filter((c) => c !== null))];
329
340
  return {
330
341
  game: orderKeys(game),
331
342
  lobby: { seatedPlayerIds: seated.map((p) => p.id), colorsTaken, seated: seated.map((p) => ({ id: p.id, team: p.team, ai: p.ai })) },
332
343
  };
333
344
  }
345
+ /** The tournament id a GameInfoTournament carries (#423); undefined for none or a shape this server does not know. */
346
+ function tournamentOf(v) {
347
+ if (!isObj(v) || v.$type !== GAME_INFO_TOURNAMENT)
348
+ return undefined;
349
+ const f = fields(v);
350
+ if (f.length !== GAME_INFO_TOURNAMENT_FIELDS)
351
+ return undefined;
352
+ const id = f[GT.tournamentId];
353
+ return isInt(id) && id > 0 ? id : undefined;
354
+ }
334
355
  /** `games` with `joined: true` on each lobby where the in-game id `me` holds a seat. */
335
356
  export function markJoined(games, lobbies, me) {
336
357
  return games.map((g) => (lobbies.get(g.id)?.seatedPlayerIds.includes(me) ? orderKeys({ ...g, joined: true }) : g));
@@ -341,7 +362,7 @@ export function withLottery(game, verdict) {
341
362
  }
342
363
  const KEY_ORDER = [
343
364
  'id', 'name', 'url', 'pace', 'bootTime', 'bootTimeMinutes', 'players', 'openSeats', 'seats', 'maxPlayers',
344
- 'teamGame', 'joined', 'lottery', 'lotteryBasis', 'randomTeamsOf', 'openSeatTeams', 'mapId', 'entryFeeCoins', 'prizeCoins', 'cards', 'rules', 'plannerGaps',
365
+ 'teamGame', 'joined', 'tournamentId', 'lottery', 'lotteryBasis', 'randomTeamsOf', 'openSeatTeams', 'mapId', 'entryFeeCoins', 'prizeCoins', 'cards', 'rules', 'plannerGaps',
345
366
  ];
346
367
  function orderKeys(g) {
347
368
  const out = {};
@@ -473,37 +494,120 @@ const POLICY_MIN_BOOT_MINUTES = 12 * 60;
473
494
  * boot time — war.app's "never" — keeps it); no lotteries (#217: `game.lottery`; a likely one whose
474
495
  * map size went unread breaks it too). Lobbies are not counted against the game cap. Pure.
475
496
  */
476
- export function joiningPolicy(game, screen) {
497
+ export function joiningPolicy(game, screen, account) {
498
+ const breaks = policyBreaks(game, screen, account).map((b) => b.text);
499
+ const warnings = policyWarnings(game);
500
+ const warned = warnings.length ? { warnings } : {};
501
+ if (breaks.length)
502
+ return { passes: false, breaks, ...warned };
503
+ const unchecked = [];
504
+ if (!screen)
505
+ unchecked.push("the cheapest neutral's cost");
506
+ if (account && account.attendedGames === undefined)
507
+ unchecked.push('how many games I am playing');
508
+ if (account && account.negativeBonus === undefined)
509
+ unchecked.push("whether the map has a negative bonus");
510
+ return unchecked.length ? { passes: null, breaks, unchecked, ...warned } : { passes: true, breaks, ...warned };
511
+ }
512
+ /**
513
+ * What the joining policy warns about but never refuses (#423; owner 2026-11-22: a tournament game warns, it never
514
+ * refuses; a game from a template already running is allowed with no preference, so it is not here). Pure.
515
+ */
516
+ export function policyWarnings(game) {
517
+ const out = [];
518
+ if (game.tournamentId !== undefined) {
519
+ out.push(`A tournament game (tournament ${game.tournamentId}): it counts in the tournament, a surrender or boot is a loss there, ` +
520
+ 'and a vote to end is not allowed — join only meaning to play it out');
521
+ }
522
+ return out;
523
+ }
524
+ /**
525
+ * The owner's cap on games played at once (2026-11-22: 15): a game being played or picked, my seat playing; lobbies
526
+ * are not counted. Joining at the cap breaks the policy.
527
+ */
528
+ export const ATTENDED_GAMES_LIMIT = 15;
529
+ /** The joining policy's checks, by code, in policy order (#437: the decision log's join context). */
530
+ export const POLICY_CHECKS = [
531
+ 'commerce',
532
+ 'mods',
533
+ 'custom-scenario',
534
+ 'neutral-cost',
535
+ 'seats',
536
+ 'boot-time',
537
+ 'lottery',
538
+ 'local-deployment',
539
+ 'commanders',
540
+ 'no-split',
541
+ 'army-cap',
542
+ 'multi-attack',
543
+ 'kill-rates',
544
+ 'attended-games',
545
+ 'negative-bonus',
546
+ ];
547
+ /** Each rule `game` breaks, its code and the policy's words, in policy order. Pure. */
548
+ function policyBreaks(game, screen, account) {
477
549
  const breaks = [];
478
550
  if (game.rules.some((r) => r.startsWith('Commerce')))
479
- breaks.push('Commerce — the policy joins no Commerce games');
551
+ breaks.push({ code: 'commerce', text: 'Commerce — the policy joins no Commerce games' });
480
552
  if (game.rules.includes('Mods'))
481
- breaks.push('Mods — the policy joins no mod games');
553
+ breaks.push({ code: 'mods', text: 'Mods — the policy joins no mod games' });
482
554
  if (game.rules.includes('Custom scenario'))
483
- breaks.push('Custom scenario — the policy joins no custom scenarios');
555
+ breaks.push({ code: 'custom-scenario', text: 'Custom scenario — the policy joins no custom scenarios' });
484
556
  if (screen && !screen.passes) {
485
- breaks.push(screen.armiesToTake === null
486
- ? 'Costly neutrals — the cheapest cannot be taken at these kill rates; the policy is at most one turn of base income'
487
- : `Costly neutrals — the cheapest takes ${screen.armiesToTake} armies, ${screen.turnsOfBaseIncome ?? '∞'} turns of base income; the policy is at most one turn`);
557
+ breaks.push({
558
+ code: 'neutral-cost',
559
+ text: screen.armiesToTake === null
560
+ ? 'Costly neutrals — the cheapest cannot be taken at these kill rates; the policy is at most one turn of base income'
561
+ : `Costly neutrals — the cheapest takes ${screen.armiesToTake} armies, ${screen.turnsOfBaseIncome ?? '∞'} turns of base income; the policy is at most one turn`,
562
+ });
488
563
  }
564
+ // #423: handicap rules (12 of 26 games played under them): each one is a break, so a join needs an explicit override.
565
+ if (game.rules.includes('Local deployments'))
566
+ breaks.push({ code: 'local-deployment', text: 'Local Deployment — the policy joins no Local Deployment games' });
567
+ if (game.rules.includes('Commanders'))
568
+ breaks.push({ code: 'commanders', text: 'Commanders — the policy joins no Commanders games' });
569
+ if (game.rules.includes('No-split mode'))
570
+ breaks.push({ code: 'no-split', text: 'No-Split — the policy joins no No-Split games' });
571
+ if (game.rules.some((r) => r.startsWith('Army cap')))
572
+ breaks.push({ code: 'army-cap', text: 'An army cap — the policy joins no capped games' });
573
+ if (game.rules.includes('Multi-attack'))
574
+ breaks.push({ code: 'multi-attack', text: 'Multi-Attack — the policy joins no Multi-Attack games' });
575
+ if (game.rules.some((r) => r.startsWith('Kill rates')))
576
+ breaks.push({ code: 'kill-rates', text: 'Kill rates other than 60/70 — the policy joins only the default rates' });
489
577
  const seats = game.maxPlayers ?? game.seats;
490
578
  if (seats > POLICY_MAX_SEATS)
491
- breaks.push(`${seats} seats — the policy is 1v1 or at most four players`);
579
+ breaks.push({ code: 'seats', text: `${seats} seats — the policy is 1v1 or at most four players` });
492
580
  if (game.bootTimeMinutes !== undefined && game.bootTimeMinutes < POLICY_MIN_BOOT_MINUTES) {
493
- breaks.push(`Boot time ${game.bootTime} — the policy wants at least 12 hours`);
581
+ breaks.push({ code: 'boot-time', text: `Boot time ${game.bootTime} — the policy wants at least 12 hours` });
494
582
  }
495
583
  if (game.lottery === true)
496
- breaks.push(`Lottery (${game.lotteryBasis ?? 'a tiny map'}) — pure luck; the policy joins no lotteries`);
584
+ breaks.push({ code: 'lottery', text: `Lottery (${game.lotteryBasis ?? 'a tiny map'}) — pure luck; the policy joins no lotteries` });
497
585
  // A likely lottery (the lottery shape, map size unread) breaks the policy too: a caller filtering on
498
586
  // breaks must not let one through (#217 live check).
499
587
  if (game.lottery === null)
500
- breaks.push(`Likely a lottery (${game.lotteryBasis ?? 'map size not read'}) — the policy joins no lotteries`);
501
- if (breaks.length)
502
- return { passes: false, breaks };
503
- const unchecked = [];
504
- if (!screen)
505
- unchecked.push("the cheapest neutral's cost");
506
- return unchecked.length ? { passes: null, breaks, unchecked } : { passes: true, breaks };
588
+ breaks.push({ code: 'lottery', text: `Likely a lottery (${game.lotteryBasis ?? 'map size not read'}) — the policy joins no lotteries` });
589
+ if (account?.attendedGames !== undefined && account.attendedGames >= ATTENDED_GAMES_LIMIT) {
590
+ breaks.push({ code: 'attended-games', text: `${account.attendedGames} games already being played — the policy is at most ${ATTENDED_GAMES_LIMIT} at once` });
591
+ }
592
+ if (account?.negativeBonus === true)
593
+ breaks.push({ code: 'negative-bonus', text: 'The map has a negative bonus — the policy joins no negative-bonus maps' });
594
+ return breaks;
595
+ }
596
+ /**
597
+ * {@link joiningPolicy} by code (#437): the checks broken, passed and not checked (the neutral cost without
598
+ * the lobby's screen), and the verdict. Pure.
599
+ */
600
+ export function policyChecks(game, screen, account) {
601
+ const broke = [...new Set(policyBreaks(game, screen, account).map((b) => b.code))];
602
+ const unchecked = screen ? [] : ['neutral-cost'];
603
+ // The two account checks run only when the caller gave an account (the list tool has none: not evaluated, not unchecked).
604
+ if (account && account.attendedGames === undefined)
605
+ unchecked.push('attended-games');
606
+ if (account && account.negativeBonus === undefined)
607
+ unchecked.push('negative-bonus');
608
+ const notEvaluated = account ? [] : ['attended-games', 'negative-bonus'];
609
+ const passed = POLICY_CHECKS.filter((c) => !broke.includes(c) && !unchecked.includes(c) && !notEvaluated.includes(c));
610
+ return { passes: broke.length ? false : unchecked.length ? null : true, broke, passed, unchecked };
507
611
  }
508
612
  /**
509
613
  * A map of at most this many territories makes a lottery (#217): every player starts on (or next
@@ -7,6 +7,7 @@
7
7
  import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
8
8
  import { randomUUID } from 'node:crypto';
9
9
  import { join } from 'node:path';
10
+ import { splitReading } from './analysis/outlook.js';
10
11
  const isRec = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
11
12
  /** Turns kept per game (a long game is still a small file). */
12
13
  const OUTLOOK_LOG_TURNS = 500;
@@ -22,12 +23,28 @@ export async function readOutlookLog(dir, gameId, playerId) {
22
23
  const c = JSON.parse(await readFile(outlookLogPath(dir, gameId), 'utf8'));
23
24
  if (!isRec(c) || c.gameId !== gameId || c.playerId !== playerId || !isRec(c.turns))
24
25
  return undefined;
25
- return c;
26
+ return contractStates(c);
26
27
  }
27
28
  catch {
28
29
  return undefined;
29
30
  }
30
31
  }
32
+ /**
33
+ * #454: a log written while #453 put the income lean in the state (`ahead`, `behind`, `unknown`) reads as
34
+ * `even` with that lean, per turn and on the latest; every other entry is left as it is.
35
+ */
36
+ function contractStates(log) {
37
+ const fix = (e) => {
38
+ const { state, lean } = splitReading(e.state);
39
+ return lean && e.lean === undefined ? { ...e, state, lean } : e;
40
+ };
41
+ for (const [k, t] of Object.entries(log.turns))
42
+ if (isRec(t))
43
+ log.turns[k] = fix(t);
44
+ if (isRec(log.latest))
45
+ log.latest = fix(log.latest);
46
+ return log;
47
+ }
31
48
  async function write(dir, log) {
32
49
  const path = outlookLogPath(dir, log.gameId);
33
50
  await mkdir(join(dir, 'outlook'), { recursive: true, mode: 0o700 });
@@ -47,6 +64,7 @@ export async function recordOutlook(dir, gameId, playerId, outlook) {
47
64
  high: t.strongest?.high ?? null,
48
65
  ratio: t.ratio,
49
66
  state: t.state,
67
+ ...(t.lean ? { lean: t.lean } : {}),
50
68
  ...(t.estimated ? { estimated: true } : {}),
51
69
  ...(t.figures
52
70
  ? {
@@ -63,6 +81,18 @@ export async function recordOutlook(dir, gameId, playerId, outlook) {
63
81
  }
64
82
  : {}),
65
83
  ...(t.evidence ? { evidence: logged(t.evidence) } : {}),
84
+ ...(t.income
85
+ ? {
86
+ income: {
87
+ mine: t.income.mine,
88
+ low: t.income.theirs.low,
89
+ high: t.income.theirs.high,
90
+ estimate: t.income.theirs.estimate,
91
+ lean: t.income.lean,
92
+ calibrated: t.income.calibrated,
93
+ },
94
+ }
95
+ : {}),
66
96
  };
67
97
  const keep = Object.keys(log.turns)
68
98
  .map(Number)
@@ -74,9 +104,14 @@ export async function recordOutlook(dir, gameId, playerId, outlook) {
74
104
  log.latest = {
75
105
  turn: last.turn,
76
106
  state: outlook.state,
107
+ ...(outlook.lean ? { lean: outlook.lean } : {}),
77
108
  heldTurns: outlook.heldTurns,
78
109
  basis: outlook.basis,
79
110
  ...(outlook.evidence ? { evidence: logged(outlook.evidence) } : {}),
111
+ // #436: the surrender line as it stood (advice only), figures only.
112
+ ...(outlook.surrenderLine
113
+ ? { surrenderLine: { crossed: outlook.surrenderLine.crossed, turnsBelow: outlook.surrenderLine.turnsBelow, line: outlook.surrenderLine.line } }
114
+ : {}),
80
115
  };
81
116
  await write(dir, log);
82
117
  }
@@ -84,6 +119,11 @@ export async function recordOutlook(dir, gameId, playerId, outlook) {
84
119
  // The log is optional.
85
120
  }
86
121
  }
122
+ /** #454: a final outlook read back from a finished record: one written with the lean as the state reads as `even` with that lean. */
123
+ export function contractFinalOutlook(o) {
124
+ const { state, lean } = splitReading(o.state);
125
+ return lean && o.lean === undefined ? { ...o, state, lean } : o;
126
+ }
87
127
  export function finalOutlookOf(log) {
88
128
  const l = log.latest;
89
129
  if (!l || typeof l.turn !== 'number')
@@ -92,6 +132,7 @@ export function finalOutlookOf(log) {
92
132
  return {
93
133
  turn: l.turn,
94
134
  state: l.state ?? null,
135
+ ...(l.lean ? { lean: l.lean } : {}),
95
136
  heldTurns: typeof l.heldTurns === 'number' ? l.heldTurns : 0,
96
137
  ...(t?.ratio ? { ratio: { low: t.ratio.low, high: t.ratio.high } } : {}),
97
138
  ...(t?.estimated ? { estimated: true } : {}),
@@ -455,9 +455,11 @@ export const TARGETED_CARD_PLAYS = new Set([
455
455
  /**
456
456
  * The card plays whose encoding is read from the bundle but not yet sent live (V9): the preview warns
457
457
  * and the result carries `cardPlayCheck`. Airlift left it once verified live 2026-11-16 (#296), Diplomacy
458
- * once verified live 2026-11-18 (#369: played through warapp_submit_turn, read in force on later boards).
458
+ * once verified live 2026-11-18 (#369: played through warapp_submit_turn, read in force on later boards),
459
+ * Reconnaissance once war.app accepted it live 2026-11-20 (#443: a turn with the play committed, no error;
460
+ * withdrawn before it resolved, so the reveal itself is not yet seen).
459
461
  */
460
- const VERIFIED_CARD_PLAYS = new Set(['Airlift', 'Diplomacy']);
462
+ const VERIFIED_CARD_PLAYS = new Set(['Airlift', 'Diplomacy', 'Reconnaissance']);
461
463
  export const UNVERIFIED_CARD_PLAYS = new Set([...TARGETED_CARD_PLAYS].filter((kind) => !VERIFIED_CARD_PLAYS.has(kind)));
462
464
  function need(v, card, what) {
463
465
  if (v === undefined)
@@ -0,0 +1,198 @@
1
+ // The review export (#437 task 5, `scripts/review-export.mjs`, a LOCAL dev script: never a tool, never in
2
+ // CI). A strategy review reads one file per game instead of reconstructing it from six stores: this joins,
3
+ // for each game, what this server kept of it — the decision log (#412, with #437's per-turn additions, its
4
+ // events, seats, join context, opponents and picks phase), the end-of-game record (src/finished-store.ts:
5
+ // outcome, kinds, the history's truth), the game's entry in its map's record and in the lessons
6
+ // (src/lessons-store.ts, by `finishedGameKey`), the settings record (src/replay.ts: state, turns, seats by
7
+ // id) and the stored map's name and size — plus an `index.json` of every game with which sources exist.
8
+ //
9
+ // Name-free: every store it reads is (player ids, the map's own names, HMAC keys); the settings record's
10
+ // player names are never read back (`readGameRecord` puts the id in their place) and only ids are written.
11
+ // The decision log's encoded boards and the planner's replay `input` are left out (`hasInput` says whether
12
+ // a turn kept one: `scripts/replay-decisions.mjs` replays those); `boards: true` adds each logged turn's
13
+ // board rebuilt whole (`boardAt`). It makes no request and writes nothing to the data dir. The export is
14
+ // 0600 files in a 0700 folder; an existing folder others can read is refused, never chmod-ed.
15
+ import { existsSync } from 'node:fs';
16
+ import { chmod, mkdir, readdir, rename, stat, unlink, writeFile } from 'node:fs/promises';
17
+ import { join } from 'node:path';
18
+ import { randomBytes } from 'node:crypto';
19
+ import { profileFormatOf } from './analysis/opponent-profile.js';
20
+ import { boardAt, decisionLogPath, decisionsDir, readDecisionLog, } from './decision-log.js';
21
+ import { finishedPath, readFinishedRecord } from './finished-store.js';
22
+ import { lessonsPath, mapRecordPath, readLessons, readMapRecord, } from './lessons-store.js';
23
+ import { readStoredMap } from './map-store.js';
24
+ import { finishedGameKey, playerRecordSalt } from './player-record-store.js';
25
+ import { gameRecordPath, gamesDir, readGameRecord } from './replay.js';
26
+ import { readCachedPlayer } from './trend.js';
27
+ const idsIn = async (folder) => (await readdir(folder).catch(() => [])).filter((n) => /^\d{1,12}\.json$/.test(n)).map((n) => Number(n.slice(0, -5)));
28
+ /** Every game with a decision log (readable or not) or a settings record, ascending. Never throws. */
29
+ export async function reviewGameIds(dir) {
30
+ const ids = new Set([...(await idsIn(decisionsDir(dir))), ...(await idsIn(gamesDir(dir)))]);
31
+ return [...ids].sort((a, b) => a - b);
32
+ }
33
+ function reviewTurns(log, boards) {
34
+ const out = {};
35
+ for (const [k, e] of Object.entries(log.turns)) {
36
+ const { board, input, ...rest } = e;
37
+ const t = { ...rest, hasInput: input !== undefined };
38
+ if (boards && board)
39
+ t.board = boardAt(log, Number(k)) ?? null;
40
+ out[k] = t;
41
+ }
42
+ return out;
43
+ }
44
+ const gameOf = (g) => ({
45
+ state: g.state,
46
+ ...(g.numberOfTurns !== undefined ? { numberOfTurns: g.numberOfTurns } : {}),
47
+ players: g.players.map((p) => ({
48
+ id: p.id,
49
+ ...(p.team !== undefined ? { team: p.team } : {}),
50
+ ...(p.state !== undefined ? { state: p.state } : {}),
51
+ ...(p.isAI ? { ai: true } : {}),
52
+ })),
53
+ });
54
+ const newestTurn = (log) => {
55
+ const ks = Object.keys(log.turns).filter((k) => /^\d+$/.test(k)).map(Number);
56
+ return ks.length ? Math.max(...ks) : null;
57
+ };
58
+ /**
59
+ * The finished record for `gameId`: tried as `me` when known, else as each seat of the settings record
60
+ * (a legacy game keeps no log or board cache naming my account; the record's name is an HMAC, so only a
61
+ * seat id can match it). Never throws.
62
+ */
63
+ async function findFinished(dir, salt, gameId, me, game) {
64
+ if (!salt)
65
+ return { record: 'missing' };
66
+ const candidates = me !== undefined ? [me] : (game?.players.map((p) => p.id) ?? []);
67
+ for (const id of candidates) {
68
+ const r = await readFinishedRecord(finishedPath(dir, salt, id, gameId));
69
+ if (r !== 'missing')
70
+ return { me: id, record: r };
71
+ }
72
+ return { record: 'missing' };
73
+ }
74
+ /** What a store keyed by `finishedGameKey` holds for the game: its entry, or that it was counted apart. */
75
+ function keyedEntry(path, store, key) {
76
+ if (store === 'unreadable')
77
+ return { state: 'unreadable', value: null };
78
+ if (!key || !existsSync(path))
79
+ return { state: 'missing', value: null };
80
+ const entry = store.entries.find((e) => e.key === key);
81
+ if (entry)
82
+ return { state: 'present', value: { entry } };
83
+ const apart = store.excluded?.keys.find((k) => k.key === key);
84
+ if (apart)
85
+ return { state: 'excluded', value: { entry: null, excluded: apart.kind } };
86
+ return { state: 'missing', value: null };
87
+ }
88
+ /** One game joined from the data dir; `undefined` when it has neither a decision log nor a settings record. Never throws. */
89
+ export async function reviewGame(dir, gameId, opts = {}) {
90
+ const logExists = existsSync(decisionLogPath(dir, gameId));
91
+ const log = logExists ? await readDecisionLog(dir, gameId) : undefined;
92
+ const game = await readGameRecord(dir, gameId);
93
+ if (!logExists && !game && !existsSync(gameRecordPath(dir, gameId)))
94
+ return undefined;
95
+ const salt = await playerRecordSalt(dir).catch(() => undefined);
96
+ const cached = log?.playerId ?? (await readCachedPlayer(dir, gameId));
97
+ const found = await findFinished(dir, salt, gameId, cached, game);
98
+ const me = cached ?? found.me;
99
+ const finished = typeof found.record === 'object' ? found.record : null;
100
+ const mapId = finished?.mapId ?? game?.settings?.mapId;
101
+ const stored = mapId !== undefined ? await readStoredMap(dir, mapId, { maxAgeMs: Number.POSITIVE_INFINITY }) : undefined;
102
+ const key = salt && me !== undefined ? finishedGameKey(salt, me, gameId) : undefined;
103
+ const mapRecord = mapId !== undefined ? keyedEntry(mapRecordPath(dir, mapId), await readMapRecord(dir, mapId), key) : { state: 'missing', value: null };
104
+ const lessons = keyedEntry(lessonsPath(dir), await readLessons(dir), key);
105
+ const format = finished?.format ?? log?.join?.flags.format ?? (game?.players.length ? profileFormatOf(game.players) : null);
106
+ return {
107
+ version: 1,
108
+ gameId,
109
+ playerId: me ?? null,
110
+ kinds: finished?.kinds ?? null,
111
+ format,
112
+ map: mapId !== undefined ? { id: mapId, ...(stored ? { name: stored.name, territories: stored.territories.length } : {}) } : null,
113
+ outcome: finished?.outcome ?? null,
114
+ turns: finished?.outcome?.turn ?? game?.numberOfTurns ?? (log ? newestTurn(log) : null),
115
+ game: game ? gameOf(game) : null,
116
+ decisionLog: log
117
+ ? {
118
+ status: log.status,
119
+ turns: reviewTurns(log, opts.boards === true),
120
+ ...(log.accuracySummary ? { accuracySummary: log.accuracySummary } : {}),
121
+ ...(log.truthMissing ? { truthMissing: log.truthMissing } : {}),
122
+ }
123
+ : null,
124
+ events: log?.events ?? null,
125
+ ...(log?.eventsDropped ? { eventsDropped: log.eventsDropped } : {}),
126
+ seats: log?.seats ?? null,
127
+ join: log?.join ?? null,
128
+ opponents: log?.opponents ?? null,
129
+ picks: log?.picks ?? null,
130
+ finished,
131
+ mapRecord: mapRecord.value,
132
+ lessons: lessons.value,
133
+ sources: {
134
+ decisionLog: log ? 'present' : logExists ? 'unreadable' : 'missing',
135
+ finished: found.record === 'unreadable' ? 'unreadable' : finished ? 'present' : 'missing',
136
+ settingsRecord: game ? 'present' : 'missing',
137
+ map: stored ? 'present' : 'missing',
138
+ mapRecord: mapRecord.state,
139
+ lessons: lessons.state,
140
+ },
141
+ };
142
+ }
143
+ const indexEntry = (g) => ({
144
+ gameId: g.gameId,
145
+ kinds: g.kinds,
146
+ format: g.format,
147
+ mapId: g.map?.id ?? null,
148
+ mapName: g.map?.name ?? null,
149
+ outcome: g.outcome?.result ?? null,
150
+ turns: g.turns,
151
+ sources: g.sources,
152
+ });
153
+ /** The export folder: made 0700, or an existing one only when no one else can read it. Throws otherwise. */
154
+ async function privateFolder(out) {
155
+ const s = await stat(out).catch(() => undefined);
156
+ if (!s) {
157
+ await mkdir(out, { recursive: true, mode: 0o700 });
158
+ // `mode` is masked by the umask: set it outright on the folder made here.
159
+ await chmod(out, 0o700);
160
+ return;
161
+ }
162
+ if (!s.isDirectory())
163
+ throw new Error(`${out} is not a directory`);
164
+ if (s.mode & 0o077)
165
+ throw new Error(`${out} is readable by others: use a new folder or chmod 700 it`);
166
+ }
167
+ async function writePrivate(path, body) {
168
+ const tmp = `${path}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
169
+ try {
170
+ await writeFile(tmp, `${JSON.stringify(body, null, 2)}\n`, { mode: 0o600 });
171
+ await chmod(tmp, 0o600);
172
+ await rename(tmp, path);
173
+ }
174
+ catch (e) {
175
+ await unlink(tmp).catch(() => { });
176
+ throw e;
177
+ }
178
+ }
179
+ /**
180
+ * Write `game-<id>.json` per game (every game `reviewGameIds` lists, or `game` alone) and `index.json`
181
+ * into `out`. Throws when the folder is not private or `game` has no data.
182
+ */
183
+ export async function exportReview(dir, out, opts = {}) {
184
+ const ids = opts.game !== undefined ? [opts.game] : await reviewGameIds(dir);
185
+ const games = [];
186
+ for (const id of ids) {
187
+ const g = await reviewGame(dir, id, opts);
188
+ if (g)
189
+ games.push(g);
190
+ }
191
+ if (opts.game !== undefined && !games.length)
192
+ throw new Error(`game ${opts.game}: no data (no decision log or settings record)`);
193
+ await privateFolder(out);
194
+ for (const g of games)
195
+ await writePrivate(join(out, `game-${g.gameId}.json`), g);
196
+ await writePrivate(join(out, 'index.json'), { version: 1, games: games.map(indexEntry) });
197
+ return { games: games.length, out };
198
+ }
@@ -5,7 +5,8 @@
5
5
  // What travels is what war.app cannot give back: the salt behind every hashed key
6
6
  // (`relations/players.salt`; the keys also carry my account id, so a bundle is one account's), the
7
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
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
9
10
  // files the planner reads (boards, game records, outlook, picks, move order, teams, the per-game
10
11
  // profile turns, siege memory and contested-bonus attempts). Never: credentials (`.env`, `session.json`), the client bundle
11
12
  // cache, the guess salt, chat cursors, the map cache and stats (all rebuilt), nor the per-game files
@@ -29,6 +30,7 @@ import { createHash, randomUUID } from 'node:crypto';
29
30
  import { chmod, link, lstat, mkdir, readdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
30
31
  import { join } from 'node:path';
31
32
  import { gunzipSync, gzipSync } from 'node:zlib';
33
+ import { decisionLogOwner } from './decision-log.js';
32
34
  import { withPathLock } from './path-lock.js';
33
35
  import { finishedGameKey } from './player-record-store.js';
34
36
  export const STATE_FORMAT = 'warapp-state';
@@ -37,6 +39,13 @@ export const STATE_VERSION = 1;
37
39
  export const MAX_BUNDLE_BYTES = 32 * 1024 * 1024;
38
40
  /** The largest bundle unpacked (a gzip bomb stops here). */
39
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;
40
49
  /** Where `replace` moves the old stores. */
41
50
  export const BACKUP_DIR = 'state-backups';
42
51
  export class StateBundleError extends Error {
@@ -60,6 +69,7 @@ export const STORES = [
60
69
  'teams',
61
70
  'siege',
62
71
  'bonusAttempts',
72
+ 'decisions',
63
73
  ];
64
74
  const RULES = [
65
75
  { store: 'salt', dir: 'relations', name: /^players\.salt$/ },
@@ -79,6 +89,8 @@ const RULES = [
79
89
  { store: 'siege', dir: 'siege', name: /^(\d{1,12})-(\d{1,20})\.json$/, game: 'game-account' },
80
90
  // #410: the planner's contested-bonus attempt and drop memory (#405, src/bonus-attempt-store.ts).
81
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 },
82
94
  ];
83
95
  /** Top-level entries keyed by the salt: moved aside whole under `replace` when the salt changes. */
84
96
  const HASHED_ENTRIES = ['relations', 'profiles', 'finished', 'maps-record', 'lessons.json'];
@@ -199,12 +211,22 @@ export async function collectExport(dir, opts = {}) {
199
211
  const finishedGames = new Set();
200
212
  const unknownGames = new Set();
201
213
  let otherAccountFiles = 0;
214
+ // #412: the decision logs, weighed after the walk: newest first, up to their share.
215
+ const decisions = [];
202
216
  for (const p of paths) {
203
217
  const { rule, gameId, account: a } = ruleOf(p);
204
218
  if (a !== undefined && a !== account) {
205
219
  otherAccountFiles++;
206
220
  continue;
207
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
+ }
208
230
  if (gameId !== undefined && !rule.allGames) {
209
231
  const s = await statusOf(gameId);
210
232
  if (s === 'finished') {
@@ -216,9 +238,42 @@ export async function collectExport(dir, opts = {}) {
216
238
  continue;
217
239
  }
218
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
+ }
219
247
  const bytes = await readFile(join(dir, p));
220
248
  files.push({ path: p, bytes, store: rule.store, sha256: sha256(bytes) });
221
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));
222
277
  return {
223
278
  manifest: {
224
279
  format: STATE_FORMAT,
@@ -228,7 +283,7 @@ export async function collectExport(dir, opts = {}) {
228
283
  files: files.map((f) => ({ path: f.path, sha256: f.sha256, size: f.bytes.length })),
229
284
  },
230
285
  files,
231
- leftOut: { finishedGames: finishedGames.size, unknownGames: unknownGames.size, otherAccountFiles },
286
+ leftOut: { finishedGames: finishedGames.size, unknownGames: unknownGames.size, otherAccountFiles, decisionLogs },
232
287
  };
233
288
  }
234
289
  /** The bundle's bytes: gzipped JSON `{ format, version, manifest, files: { path: base64 } }`. */
@@ -318,12 +373,16 @@ export function decodeBundle(bytes) {
318
373
  if (body.length !== f.size)
319
374
  throw new StateBundleError(`The size of ${path} does not match the manifest.`);
320
375
  if (path.endsWith('.json')) {
376
+ let parsedFile;
321
377
  try {
322
- JSON.parse(body.toString('utf8'));
378
+ parsedFile = JSON.parse(body.toString('utf8'));
323
379
  }
324
380
  catch {
325
381
  throw new StateBundleError(`${path} is not valid JSON.`);
326
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
+ }
327
386
  }
328
387
  files.set(path, body);
329
388
  list.push({ path, sha256: f.sha256, size: f.size });