@chrischall/warapp-mcp 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/.claude-plugin/marketplace.json +3 -3
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +133 -8
  4. package/dist/analysis/accept-surrender.js +20 -2
  5. package/dist/analysis/calibrate.js +1 -0
  6. package/dist/analysis/card-support.js +177 -17
  7. package/dist/analysis/card-threats.js +126 -14
  8. package/dist/analysis/chat-advice.js +182 -0
  9. package/dist/analysis/chat-blocks.js +106 -0
  10. package/dist/analysis/chat-intent.js +559 -0
  11. package/dist/analysis/chat-read.js +159 -0
  12. package/dist/analysis/decision-replay.js +279 -0
  13. package/dist/analysis/decision-truth.js +146 -0
  14. package/dist/analysis/finished-game.js +62 -3
  15. package/dist/analysis/game-lessons.js +15 -10
  16. package/dist/analysis/hold-diff.js +3 -1
  17. package/dist/analysis/income-trend.js +38 -0
  18. package/dist/analysis/intel.js +75 -0
  19. package/dist/analysis/opens.js +64 -0
  20. package/dist/analysis/opponent-profile.js +121 -10
  21. package/dist/analysis/opponents.js +246 -20
  22. package/dist/analysis/outlook.js +360 -15
  23. package/dist/analysis/picks.js +91 -12
  24. package/dist/analysis/plan/after-leftover.js +4 -1
  25. package/dist/analysis/plan/bonus-attempts.js +105 -0
  26. package/dist/analysis/plan/capture-instead.js +116 -0
  27. package/dist/analysis/plan/captures.js +49 -7
  28. package/dist/analysis/plan/conceded-out.js +13 -2
  29. package/dist/analysis/plan/estimates.js +203 -30
  30. package/dist/analysis/plan/guard-off.js +2 -1
  31. package/dist/analysis/plan/holds.js +110 -9
  32. package/dist/analysis/plan/jabs.js +113 -0
  33. package/dist/analysis/plan/leftover.js +393 -8
  34. package/dist/analysis/plan/orders.js +76 -4
  35. package/dist/analysis/plan/relations.js +135 -2
  36. package/dist/analysis/plan/report.js +69 -3
  37. package/dist/analysis/plan/second-sizing.js +133 -0
  38. package/dist/analysis/plan/shared.js +279 -27
  39. package/dist/analysis/plan/siege.js +303 -0
  40. package/dist/analysis/plan/stand-still.js +9 -5
  41. package/dist/analysis/plan/state.js +8 -0
  42. package/dist/analysis/plan/stockpile.js +104 -0
  43. package/dist/analysis/plan/strike.js +39 -7
  44. package/dist/analysis/plan/targets.js +256 -110
  45. package/dist/analysis/plan/threats.js +148 -10
  46. package/dist/analysis/plan/transfers.js +57 -6
  47. package/dist/analysis/plan/two-move.js +70 -0
  48. package/dist/analysis/plan/vacated.js +124 -2
  49. package/dist/analysis/planner.js +527 -49
  50. package/dist/analysis/profile.js +13 -2
  51. package/dist/analysis/since-last.js +18 -5
  52. package/dist/analysis/stress.js +8 -2
  53. package/dist/board.js +36 -2
  54. package/dist/bonus-attempt-store.js +55 -0
  55. package/dist/build-id.js +106 -0
  56. package/dist/bundle.js +54138 -41059
  57. package/dist/cards.js +7 -5
  58. package/dist/chat-automation.js +22 -0
  59. package/dist/chat.js +35 -1
  60. package/dist/client.js +14 -0
  61. package/dist/commerce.js +111 -0
  62. package/dist/decision-log.js +1093 -0
  63. package/dist/finished-store.js +5 -1
  64. package/dist/index.js +9 -1
  65. package/dist/lessons-store.js +322 -21
  66. package/dist/live.js +43 -0
  67. package/dist/move-order.js +64 -3
  68. package/dist/normalize.js +17 -0
  69. package/dist/open-games.js +36 -16
  70. package/dist/outlook-log.js +42 -1
  71. package/dist/profile-store.js +12 -2
  72. package/dist/protocol/methods.js +62 -5
  73. package/dist/protocol/rpc.js +8 -0
  74. package/dist/relations-store.js +38 -4
  75. package/dist/review-export.js +198 -0
  76. package/dist/siege-store.js +49 -0
  77. package/dist/state-bundle.js +584 -0
  78. package/dist/state-cli.js +71 -0
  79. package/dist/strategy/notes.js +56 -0
  80. package/dist/team-cards.js +25 -0
  81. package/dist/tools/accept-surrender.js +23 -9
  82. package/dist/tools/award.js +20 -2
  83. package/dist/tools/card-advice.js +93 -28
  84. package/dist/tools/card-plays.js +2 -2
  85. package/dist/tools/card-support-advice.js +37 -7
  86. package/dist/tools/chat-advice.js +330 -0
  87. package/dist/tools/chat-inbox.js +19 -4
  88. package/dist/tools/chat.js +106 -17
  89. package/dist/tools/check-plan.js +68 -12
  90. package/dist/tools/commerce-deploy.js +33 -0
  91. package/dist/tools/common.js +31 -0
  92. package/dist/tools/decision-capture.js +459 -0
  93. package/dist/tools/end-of-game.js +151 -21
  94. package/dist/tools/game-kind.js +92 -0
  95. package/dist/tools/how-lost.js +7 -2
  96. package/dist/tools/index.js +10 -0
  97. package/dist/tools/join-game.js +10 -4
  98. package/dist/tools/live-context.js +6 -0
  99. package/dist/tools/live.js +10 -1
  100. package/dist/tools/map-curves.js +73 -0
  101. package/dist/tools/notifications.js +4 -3
  102. package/dist/tools/opponents.js +2 -0
  103. package/dist/tools/past-games.js +74 -8
  104. package/dist/tools/picks.js +61 -10
  105. package/dist/tools/profile-hook.js +62 -3
  106. package/dist/tools/profile-opponents.js +4 -0
  107. package/dist/tools/push.js +2 -2
  108. package/dist/tools/relations.js +139 -0
  109. package/dist/tools/scout.js +16 -2
  110. package/dist/tools/state.js +232 -0
  111. package/dist/tools/strategy.js +3 -3
  112. package/dist/tools/stress-opponents.js +7 -2
  113. package/dist/tools/surrender-pending.js +10 -1
  114. package/dist/tools/surrender.js +18 -3
  115. package/dist/tools/survival.js +11 -3
  116. package/dist/tools/team-brief.js +2 -2
  117. package/dist/tools/team.js +12 -3
  118. package/dist/tools/turn.js +643 -76
  119. package/dist/tools/where.js +3 -1
  120. package/dist/version.js +1 -1
  121. package/manifest.json +32 -3
  122. package/mint.yaml +37 -4
  123. package/package.json +4 -4
  124. package/server.json +20 -2
  125. package/skills/warapp-mcp/SKILL.md +73 -17
@@ -17,6 +17,7 @@
17
17
  // write of a process.
18
18
  import { mkdir, readdir, readFile, rename, stat, unlink, writeFile } from 'node:fs/promises';
19
19
  import { join } from 'node:path';
20
+ import { armiesToTake } from './analysis/combat.js';
20
21
  /** Where a game's first mover is kept. */
21
22
  export const firstMoverPath = (dir, gameId) => join(dir, 'move-order', `${gameId}.json`);
22
23
  /** A game's file not written for this long is deleted (finished or abandoned games). */
@@ -26,12 +27,17 @@ const pruned = new Set();
26
27
  const other = (m) => (m === 'me' ? 'opponent' : 'me');
27
28
  const isTurn = (v) => typeof v === 'number' && Number.isSafeInteger(v) && v >= 1;
28
29
  const isMover = (v) => v === 'me' || v === 'opponent';
29
- const isSource = (v) => v === 'explicit' || v === 'award';
30
+ const isSource = (v) => v === 'explicit' || v === 'award' || v === 'inferred';
30
31
  /** The first mover on `turn`, from one known turn: the same every second turn, the other in between. */
31
32
  export function projectFirstMover(seen, turn) {
32
33
  return Math.abs(turn - seen.turn) % 2 === 0 ? seen.firstMover : other(seen.firstMover);
33
34
  }
34
- const RANK = { award: 0, explicit: 1 };
35
+ const RANK = { award: 0, inferred: 1, explicit: 2 };
36
+ const KEPT_LABEL = {
37
+ explicit: (t) => `the first_mover given on turn ${t}`,
38
+ inferred: (t) => `my first order's result on turn ${t}`,
39
+ award: (t) => `the award of picks (kept on turn ${t})`,
40
+ };
35
41
  const said = (m, turn) => `${m === 'me' ? 'you move' : 'the opponent moves'} first on turn ${turn}`;
36
42
  /**
37
43
  * Who moves first on `turn` and how it is known, with the record to keep (absent when nothing new
@@ -48,13 +54,23 @@ export function resolveFirstMover(input) {
48
54
  const kept = input.remembered;
49
55
  const fromKept = () => kept && {
50
56
  firstMover: projectFirstMover(kept, turn),
51
- label: kept.source === 'explicit' ? `the first_mover given on turn ${kept.turn}` : `the award of picks (kept on turn ${kept.turn})`,
57
+ label: KEPT_LABEL[kept.source](kept.turn),
52
58
  resolved: { firstMover: projectFirstMover(kept, turn), source: 'remembered', from: { turn: kept.turn, source: kept.source } },
53
59
  };
54
60
  if (explicit)
55
61
  candidates.push({ firstMover: explicit, label: 'first_mover', resolved: { firstMover: explicit, source: 'explicit' }, record: { turn, firstMover: explicit, source: 'explicit' } });
56
62
  if (kept?.source === 'explicit')
57
63
  candidates.push(fromKept());
64
+ const inf = input.inferred;
65
+ if (inf && !same(inf, kept))
66
+ candidates.push({
67
+ firstMover: projectFirstMover(inf, turn),
68
+ label: KEPT_LABEL.inferred(inf.turn),
69
+ resolved: { firstMover: projectFirstMover(inf, turn), source: 'remembered', from: { turn: inf.turn, source: 'inferred' } },
70
+ record: inf,
71
+ });
72
+ if (kept?.source === 'inferred')
73
+ candidates.push(fromKept());
58
74
  if (award)
59
75
  candidates.push({ firstMover: award, label: 'the award of picks', resolved: { firstMover: award, source: 'award' }, record: { turn, firstMover: award, source: 'award' } });
60
76
  if (kept?.source === 'award')
@@ -72,6 +88,51 @@ export function resolveFirstMover(input) {
72
88
  const record = used.record && (!kept || RANK[used.record.source] >= RANK[kept.source]) && !same(used.record, kept) ? used.record : undefined;
73
89
  return { resolved: used.resolved, ...(record ? { record } : {}), warnings };
74
90
  }
91
+ /**
92
+ * #299: who moved first on the previous turn, read from my own first order on it. Moving first, my
93
+ * first order runs before any order of the opponent's, against the target as it stood plus deploys
94
+ * only, which never shrink it: so when that order captured a territory its sender could not have
95
+ * taken from the armies the target held at the start of the turn, the opponent's order ran before
96
+ * it (the stack had left). Read only when the result is exact (0% luck, straight rounding), the
97
+ * order is the only one of mine into the target, no commander was on either side, and no card could
98
+ * explain it: none of mine touching the source or target, nor an Order Priority or Order Delay of
99
+ * mine, nor one the opponent may hold (`orderPriorityPossible`: it reorders that turn alone). Gives
100
+ * `null` when it proves nothing. The other case of #299 (an attack of mine that failed against
101
+ * armies moved in first) is not read: my losses cannot be told apart from the opponent's attacks on
102
+ * my source. Pure.
103
+ */
104
+ export function inferFirstMover(input) {
105
+ const { before, after, orders, me, opponent, rates = {} } = input;
106
+ if (input.orderPriorityPossible || !orders.cards)
107
+ return null;
108
+ if ((rates.luckModifier ?? 0) !== 0 || (rates.roundingMode !== undefined && rates.roundingMode !== 'StraightRound'))
109
+ return null;
110
+ const sent = orders.sent ?? orders.moves;
111
+ const first = sent[0];
112
+ if (!first || ('transferOnly' in first && first.transferOnly) || first.commander)
113
+ return null;
114
+ const move = orders.moves[0];
115
+ if (!move || move.from !== first.from || move.to !== first.to)
116
+ return null;
117
+ if (sent.some((m, i) => i > 0 && m.to === move.to) || orders.moves.some((m, i) => i > 0 && m.to === move.to))
118
+ return null;
119
+ if (orders.cards.some((c) => c.card === 'Order Priority' || c.card === 'Order Delay' || [c.from, c.to, c.target].some((t) => t === move.from || t === move.to)))
120
+ return null;
121
+ const at = (b, id) => b.territories.find((t) => t.territoryId === id);
122
+ const held = (t, p) => t !== undefined && t.owner.kind === 'player' && t.owner.playerId === p && typeof t.armies === 'number' && !t.specialUnits?.length;
123
+ const source = at(before, move.from);
124
+ const target = at(before, move.to);
125
+ if (!held(source, me) || !held(target, opponent))
126
+ return null;
127
+ const now = at(after, move.to);
128
+ if (now?.owner.kind !== 'player' || now.owner.playerId !== me)
129
+ return null;
130
+ const deployed = orders.deploys.filter((d) => d.territoryId === move.from).reduce((s, d) => s + d.armies, 0);
131
+ const guard = rates.oneArmyStandsGuard === false ? 0 : 1;
132
+ const sendable = Math.min(move.armies, source.armies + deployed - guard);
133
+ const need = armiesToTake(target.armies, rates);
134
+ return need !== null && need > sendable ? { turn: input.turn, firstMover: 'opponent', source: 'inferred' } : null;
135
+ }
75
136
  /**
76
137
  * #215 review: a first mover the user gave (`first_mover`, now or on a remembered turn, alternated)
77
138
  * is verified; one read from the award of picks — the wiki's rule, not verified live — is not, and
package/dist/normalize.js CHANGED
@@ -190,6 +190,23 @@ export function normalizeSettings(raw) {
190
190
  }
191
191
  if (r.Commerce !== undefined && r.Commerce !== null)
192
192
  s.commerce = isRec(r.Commerce) ? Object.keys(r.Commerce).length > 0 : true;
193
+ if (isRec(r.Commerce) && Object.keys(r.Commerce).length > 0) {
194
+ const c = r.Commerce;
195
+ const rules = {};
196
+ const pairs = [
197
+ ['armyCostMultiplier', c.ArmyCostMultiplier],
198
+ ['cityBaseCost', c.CityBaseCost],
199
+ ['territoryCityCostIncrease', c.TerritoryCityCostIncrease],
200
+ ['globalCityCostIncrease', c.GlobalCityCostIncrease],
201
+ ['cityIncome', c.CityIncome],
202
+ ];
203
+ for (const [k, v] of pairs) {
204
+ const n = asInt(v);
205
+ if (n !== undefined)
206
+ rules[k] = n;
207
+ }
208
+ s.commerceRules = rules;
209
+ }
193
210
  if (r.Mods !== undefined && r.Mods !== null) {
194
211
  const empty = r.Mods === '' || (isRec(r.Mods) && Object.keys(r.Mods).length === 0);
195
212
  s.mods = Array.isArray(r.Mods) ? r.Mods.length : empty ? 0 : -1;
@@ -474,36 +474,56 @@ const POLICY_MIN_BOOT_MINUTES = 12 * 60;
474
474
  * map size went unread breaks it too). Lobbies are not counted against the game cap. Pure.
475
475
  */
476
476
  export function joiningPolicy(game, screen) {
477
+ const breaks = policyBreaks(game, screen).map((b) => b.text);
478
+ if (breaks.length)
479
+ return { passes: false, breaks };
480
+ const unchecked = [];
481
+ if (!screen)
482
+ unchecked.push("the cheapest neutral's cost");
483
+ return unchecked.length ? { passes: null, breaks, unchecked } : { passes: true, breaks };
484
+ }
485
+ /** The joining policy's checks, by code, in policy order (#437: the decision log's join context). */
486
+ export const POLICY_CHECKS = ['commerce', 'mods', 'custom-scenario', 'neutral-cost', 'seats', 'boot-time', 'lottery'];
487
+ /** Each rule `game` breaks, its code and the policy's words, in policy order. Pure. */
488
+ function policyBreaks(game, screen) {
477
489
  const breaks = [];
478
490
  if (game.rules.some((r) => r.startsWith('Commerce')))
479
- breaks.push('Commerce — the policy joins no Commerce games');
491
+ breaks.push({ code: 'commerce', text: 'Commerce — the policy joins no Commerce games' });
480
492
  if (game.rules.includes('Mods'))
481
- breaks.push('Mods — the policy joins no mod games');
493
+ breaks.push({ code: 'mods', text: 'Mods — the policy joins no mod games' });
482
494
  if (game.rules.includes('Custom scenario'))
483
- breaks.push('Custom scenario — the policy joins no custom scenarios');
495
+ breaks.push({ code: 'custom-scenario', text: 'Custom scenario — the policy joins no custom scenarios' });
484
496
  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`);
497
+ breaks.push({
498
+ code: 'neutral-cost',
499
+ text: screen.armiesToTake === null
500
+ ? 'Costly neutrals — the cheapest cannot be taken at these kill rates; the policy is at most one turn of base income'
501
+ : `Costly neutrals — the cheapest takes ${screen.armiesToTake} armies, ${screen.turnsOfBaseIncome ?? '∞'} turns of base income; the policy is at most one turn`,
502
+ });
488
503
  }
489
504
  const seats = game.maxPlayers ?? game.seats;
490
505
  if (seats > POLICY_MAX_SEATS)
491
- breaks.push(`${seats} seats — the policy is 1v1 or at most four players`);
506
+ breaks.push({ code: 'seats', text: `${seats} seats — the policy is 1v1 or at most four players` });
492
507
  if (game.bootTimeMinutes !== undefined && game.bootTimeMinutes < POLICY_MIN_BOOT_MINUTES) {
493
- breaks.push(`Boot time ${game.bootTime} — the policy wants at least 12 hours`);
508
+ breaks.push({ code: 'boot-time', text: `Boot time ${game.bootTime} — the policy wants at least 12 hours` });
494
509
  }
495
510
  if (game.lottery === true)
496
- breaks.push(`Lottery (${game.lotteryBasis ?? 'a tiny map'}) — pure luck; the policy joins no lotteries`);
511
+ breaks.push({ code: 'lottery', text: `Lottery (${game.lotteryBasis ?? 'a tiny map'}) — pure luck; the policy joins no lotteries` });
497
512
  // A likely lottery (the lottery shape, map size unread) breaks the policy too: a caller filtering on
498
513
  // breaks must not let one through (#217 live check).
499
514
  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 };
515
+ breaks.push({ code: 'lottery', text: `Likely a lottery (${game.lotteryBasis ?? 'map size not read'}) — the policy joins no lotteries` });
516
+ return breaks;
517
+ }
518
+ /**
519
+ * {@link joiningPolicy} by code (#437): the checks broken, passed and not checked (the neutral cost without
520
+ * the lobby's screen), and the verdict. Pure.
521
+ */
522
+ export function policyChecks(game, screen) {
523
+ const broke = [...new Set(policyBreaks(game, screen).map((b) => b.code))];
524
+ const unchecked = screen ? [] : ['neutral-cost'];
525
+ const passed = POLICY_CHECKS.filter((c) => !broke.includes(c) && !unchecked.includes(c));
526
+ return { passes: broke.length ? false : unchecked.length ? null : true, broke, passed, unchecked };
507
527
  }
508
528
  /**
509
529
  * 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 } : {}),
@@ -97,6 +97,10 @@ function primitivesOf(v) {
97
97
  const lost = ids(v.lostToMe);
98
98
  if (took === undefined || !lost)
99
99
  return undefined;
100
+ // #361: absent in a record kept before it (unknown); a non-integer makes it unknown too.
101
+ const jabs = v.jabs === null ? null : isInt(v.jabs) ? v.jabs : undefined;
102
+ // #295: likewise.
103
+ const topUp = v.topUp === null || typeof v.topUp === 'boolean' ? v.topUp : undefined;
100
104
  return {
101
105
  contact: v.contact,
102
106
  attackedMe: v.attackedMe,
@@ -105,6 +109,8 @@ function primitivesOf(v) {
105
109
  stack: s === null ? null : { top: s.top, total: s.total },
106
110
  tookFromMe: took,
107
111
  lostToMe: lost,
112
+ ...(jabs !== undefined ? { jabs } : {}),
113
+ ...(topUp !== undefined ? { topUp } : {}),
108
114
  };
109
115
  }
110
116
  const seatsOf = (v) => isRec(v) && PROFILE_FORMATS.includes(v.format) && isInt(v.players) && ids(v.ai) && ids(v.turnedAI)
@@ -319,13 +325,17 @@ function habitsFrom(v) {
319
325
  const f = rateOf(v.firstStrike);
320
326
  const rt = rateOf(v.retaliate);
321
327
  const rk = rateOf(v.retake);
328
+ // #361: absent in counts kept before it: none read.
329
+ const jb = v.jab === undefined ? { e: 0, n: 0 } : rateOf(v.jab);
330
+ // #295: likewise.
331
+ const tu = v.capacityTopUp === undefined ? { e: 0, n: 0 } : rateOf(v.capacityTopUp);
322
332
  const x = v.reinforceExtra;
323
333
  const s = v.stacking;
324
- if (!r || !a || !f || !rt || !rk || !num(v.turns))
334
+ if (!r || !a || !f || !rt || !rk || !jb || !tu || !num(v.turns))
325
335
  return undefined;
326
336
  if (!isRec(x) || !num(x.n) || !num(x.sum) || !isRec(s) || !num(s.n) || !num(s.sum) || !num(s.sq))
327
337
  return undefined;
328
- return { reinforce: r, reinforceExtra: { n: x.n, sum: x.sum }, attack: a, firstStrike: f, stacking: { n: s.n, sum: s.sum, sq: s.sq }, retaliate: rt, retake: rk, turns: v.turns };
338
+ return { reinforce: r, reinforceExtra: { n: x.n, sum: x.sum }, attack: a, firstStrike: f, stacking: { n: s.n, sum: s.sum, sq: s.sq }, retaliate: rt, retake: rk, jab: jb, capacityTopUp: tu, turns: v.turns };
329
339
  }
330
340
  function totalsFrom(v) {
331
341
  const out = {};
@@ -11,6 +11,8 @@ export const Method = {
11
11
  GetLatestGameInfo: 41,
12
12
  SendChat: 43,
13
13
  RegisterChatView: 44,
14
+ RetrieveChat: 45,
15
+ RetrievePrivateMessageHistory: 46,
14
16
  GetGameSettings: 49,
15
17
  GetMyGames: 51,
16
18
  AcceptGame: 61,
@@ -304,11 +306,42 @@ export function writeRegisterChatViewParams(w, p) {
304
306
  writeMarkDict(w, p.privateMarks);
305
307
  writeMarkDict(w, p.groupMarks);
306
308
  }
309
+ /**
310
+ * The "older than" marker of a chat history read when nothing has been received on that channel yet: the
311
+ * client's 9999E14 (its initial lowest-id-received), written as text.
312
+ */
313
+ export const OLDEST_CHAT_MARKER = '999900000000000000';
314
+ const MESSAGE_ID_TEXT = /^\d{1,20}$/;
315
+ function beforeMarker(m) {
316
+ if (m === undefined)
317
+ return OLDEST_CHAT_MARKER;
318
+ if (!MESSAGE_ID_TEXT.test(m))
319
+ throw new RangeError(`not a message id: ${JSON.stringify(m)}`);
320
+ return m;
321
+ }
322
+ /**
323
+ * RetrieveChat(auth, …) — the web client's "show older messages" for the public and team channels (#363). READ
324
+ * FROM THE CLIENT BUNDLE's writer: the int32 game id, then per channel the lowest message id the client has
325
+ * received (string; 9999E14 when none). Reply: a result flag, then a list of optional `GameMessage` (as the
326
+ * SendChat reply). GameRefresh with `-1` markers leaves out messages war.app counts as seen (an own team
327
+ * message, seen live 2026-11-19); this read returns them.
328
+ */
329
+ export function writeRetrieveChatParams(w, p) {
330
+ w.int32(p.gameId).string(beforeMarker(p.publicBefore)).string(beforeMarker(p.teamBefore));
331
+ }
332
+ /**
333
+ * RetrievePrivateMessageHistory(auth, …) — the client's history button of one private conversation (#387). READ
334
+ * FROM THE CLIENT BUNDLE's writer: the int32 game id, the lowest message id received in it (string; 9999E14 when
335
+ * none), the counterpart's in-game id (int32). Reply as RetrieveChat's.
336
+ */
337
+ export function writeRetrievePrivateMessageHistoryParams(w, p) {
338
+ w.int32(p.gameId).string(beforeMarker(p.before)).int32(p.counterpart);
339
+ }
307
340
  /**
308
341
  * SendChat(auth, …) per docs/WEB-PROTOCOL.md (read from the client's
309
342
  * serializer; the owner verifies it live): game id, text, channel, optional
310
343
  * private recipient, optional game-group id (absent), two marker strings
311
- * (absent), two optional "last seen" dicts (absent). An optional int32 is a
344
+ * (`-1`: seen nothing), two optional "last seen" dicts (absent). An optional int32 is a
312
345
  * present flag then the value.
313
346
  */
314
347
  export function writeSendChatParams(w, p) {
@@ -317,9 +350,11 @@ export function writeSendChatParams(w, p) {
317
350
  w.bool(false);
318
351
  else
319
352
  w.bool(true).int32(p.recipient);
353
+ // The two chat markers are the last message seen on each channel: war.app parses them as numbers
354
+ // (ParseLongSafe), so a null one is refused (server error 1); a client that has seen nothing sends `-1`.
320
355
  w.bool(false) // game-group id
321
- .string(null)
322
- .string(null)
356
+ .string(NO_CHAT_MARKER)
357
+ .string(NO_CHAT_MARKER)
323
358
  .bool(false)
324
359
  .bool(false)
325
360
  // Protocol 243 added a last, optional list of strings (the shared images a message carries): absent.
@@ -347,6 +382,17 @@ export function writeDeployOrder(w, o) {
347
382
  .int32(o.armies);
348
383
  writeOrderBase(w, o.playerId);
349
384
  }
385
+ const ORDER_TAG_PURCHASE = 24;
386
+ /**
387
+ * Encode a Purchase order (`GameOrderPurchase`, client 6.08.0.2's writer; UNVERIFIED live): tag 24, a present bool,
388
+ * an int32 count of territory → cities entries, each two int32s, then the order base.
389
+ */
390
+ export function writePurchaseOrder(w, o) {
391
+ w.u8(ORDER_TAG_PURCHASE).bool(true).int32(o.cities.length);
392
+ for (const c of o.cities)
393
+ w.int32(c.territoryId).int32(c.count);
394
+ writeOrderBase(w, o.playerId);
395
+ }
350
396
  /** The special-unit tag of a Commander (`warlight.shared.Commander`, from the bundle; docs/WEB-PROTOCOL.md). */
351
397
  const SPECIAL_UNIT_COMMANDER = 1;
352
398
  /**
@@ -408,9 +454,13 @@ export const TARGETED_CARD_PLAYS = new Set([
408
454
  ]);
409
455
  /**
410
456
  * The card plays whose encoding is read from the bundle but not yet sent live (V9): the preview warns
411
- * and the result carries `cardPlayCheck`. Airlift left it once verified live 2026-11-16 (#296).
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),
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).
412
461
  */
413
- export const UNVERIFIED_CARD_PLAYS = new Set([...TARGETED_CARD_PLAYS].filter((kind) => kind !== 'Airlift'));
462
+ const VERIFIED_CARD_PLAYS = new Set(['Airlift', 'Diplomacy', 'Reconnaissance']);
463
+ export const UNVERIFIED_CARD_PLAYS = new Set([...TARGETED_CARD_PLAYS].filter((kind) => !VERIFIED_CARD_PLAYS.has(kind)));
414
464
  function need(v, card, what) {
415
465
  if (v === undefined)
416
466
  throw new Error(`A ${card} card play needs ${what}.`);
@@ -490,6 +540,8 @@ export function writeDiscardOrder(w, o) {
490
540
  * from the bundle's `GameOrderDiscard.Vd`).
491
541
  */
492
542
  export const TurnPhase = {
543
+ /** #332, bundle (`GameOrderPurchase`), UNVERIFIED live: a commerce game's purchase, before every other order. */
544
+ Purchases: 0,
493
545
  Discards: 10,
494
546
  OrderPriorityCards: 12,
495
547
  /** Spy, Reconnaissance and Surveillance (bundle, UNVERIFIED live). */
@@ -534,6 +586,8 @@ export function turnPhaseOf(o) {
534
586
  return TurnPhase.Attacks;
535
587
  if (o.kind === 'discard')
536
588
  return TurnPhase.Discards;
589
+ if (o.kind === 'purchase')
590
+ return TurnPhase.Purchases;
537
591
  return CARD_PHASE[o.card];
538
592
  }
539
593
  /**
@@ -609,6 +663,9 @@ export function writeSendOrdersParams(w, gameId, playerId, orders, turnNumber) {
609
663
  else if (o.kind === 'discard') {
610
664
  writeDiscardOrder(w, { playerId, cardId: o.cardId });
611
665
  }
666
+ else if (o.kind === 'purchase') {
667
+ writePurchaseOrder(w, { playerId, cities: o.cities });
668
+ }
612
669
  else if (o.kind === 'deploy') {
613
670
  writeDeployOrder(w, { playerId, territoryId: o.territoryId, armies: o.armies });
614
671
  }
@@ -45,6 +45,14 @@ export const SERVER_ERROR_MESSAGES = {
45
45
  254: 'Sorry, your slot was assigned to someone else by the game creator. Please ask the game creator to open up your slot.',
46
46
  473: "You don't have enough coins to join this game. Please deposit some coins and try again.",
47
47
  750: 'Sorry, the slot you joined is no longer available. Please try again with a different slot.',
48
+ // #332, commerce games: the client names these but shows no wording; these are ours.
49
+ 593: 'war.app worked out a different gold cost for these orders than the client did (ExpectedCostInaccurate).',
50
+ 596: 'In a commerce game every deploy must be paid for in gold (DeploymentsCannotBeFree).',
51
+ 597: 'You do not have enough gold for these orders (InsufficientGold): deploy fewer armies or buy fewer cities.',
52
+ 599: 'Only one purchase order may be sent in a turn (CannotSendDuplicatePurchaseOrders).',
53
+ 600: 'A city can only be built on a territory you hold (CannotBuildCityOnAnotherPlayersTerritory).',
54
+ 601: 'The number of cities to build cannot be negative (CannotBuildNegativeCitites).',
55
+ 602: 'This game does not allow cities (CannotBuildCities).',
48
56
  };
49
57
  /** The longest slice of an unmapped server message shown to the caller. */
50
58
  const MAX_SERVER_MESSAGE = 200;
@@ -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) {