@chrischall/warapp-mcp 0.13.1 → 0.15.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 (58) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +9 -6
  4. package/dist/analysis/airlift-plan.js +288 -0
  5. package/dist/analysis/blockade-plan.js +178 -0
  6. package/dist/analysis/bomb-plan.js +72 -0
  7. package/dist/analysis/card-threats.js +10 -9
  8. package/dist/analysis/cards-in-effect.js +20 -0
  9. package/dist/analysis/combat.js +5 -0
  10. package/dist/analysis/coordination.js +47 -0
  11. package/dist/analysis/income-calibration.js +280 -0
  12. package/dist/analysis/intel.js +1 -1
  13. package/dist/analysis/lookahead.js +4 -0
  14. package/dist/analysis/opponents.js +52 -3
  15. package/dist/analysis/plan/deploy-estimates.js +1 -1
  16. package/dist/analysis/plan/estimates.js +40 -6
  17. package/dist/analysis/plan/relations.js +57 -8
  18. package/dist/analysis/plan/threats.js +1 -1
  19. package/dist/analysis/player-record.js +1 -0
  20. package/dist/analysis/relations.js +40 -0
  21. package/dist/analysis/stress.js +42 -2
  22. package/dist/analysis/turn-sim.js +62 -0
  23. package/dist/bundle.js +24486 -21811
  24. package/dist/card-state.js +157 -0
  25. package/dist/decision-log.js +44 -5
  26. package/dist/local-time.js +142 -0
  27. package/dist/relations-store.js +30 -5
  28. package/dist/tools/airlift-readback.js +87 -0
  29. package/dist/tools/alternative-orders.js +21 -0
  30. package/dist/tools/begin-turn.js +19 -5
  31. package/dist/tools/calibration-harness.js +102 -0
  32. package/dist/tools/calibration.js +110 -0
  33. package/dist/tools/card-advice.js +5 -4
  34. package/dist/tools/card-plays.js +32 -20
  35. package/dist/tools/card-state-view.js +26 -0
  36. package/dist/tools/card-support-advice.js +25 -8
  37. package/dist/tools/chat-inbox.js +1 -1
  38. package/dist/tools/chat.js +1 -1
  39. package/dist/tools/check-plan.js +113 -9
  40. package/dist/tools/common.js +14 -0
  41. package/dist/tools/decision-capture.js +14 -1
  42. package/dist/tools/game.js +11 -2
  43. package/dist/tools/index.js +13 -1
  44. package/dist/tools/notifications.js +1 -1
  45. package/dist/tools/opponents.js +2 -0
  46. package/dist/tools/player-card-readback.js +45 -0
  47. package/dist/tools/relations.js +146 -14
  48. package/dist/tools/sanctions-played.js +51 -0
  49. package/dist/tools/stress-opponents.js +8 -4
  50. package/dist/tools/turn-history.js +214 -0
  51. package/dist/tools/turn.js +504 -20
  52. package/dist/turn-orders.js +64 -0
  53. package/dist/version.js +1 -1
  54. package/manifest.json +17 -2
  55. package/mint.yaml +7 -0
  56. package/package.json +1 -1
  57. package/server.json +8 -2
  58. package/skills/warapp-mcp/SKILL.md +9 -1
@@ -0,0 +1,157 @@
1
+ // My card state for a person: the whole cards I hold (by type, with how many) and the pieces toward the next
2
+ // card of each type, read from the current GameStanding's `PlayerCards` (docs/WEB-PROTOCOL.md "A team's hand":
3
+ // `PlayerID`, `Pieces`, `WholeCards` by GUID, per player, keyed by the in-game id). Shown by warapp_get_game and
4
+ // warapp_begin_turn.
5
+ //
6
+ // The whole cards are `readHand`'s (VERIFIED live, #20, #310). The pieces are UNVERIFIED live: `Pieces` is a
7
+ // dict card type → count, and the decoder keeps field names minified, so it is found by shape — the one field of
8
+ // the player's PlayerCards that is a list of `[card type, count]` pairs (a type id, or a record whose one integer
9
+ // is the type id). Several ids (a team) sum the pieces, as the client's merged team hand does. Pure; never throws.
10
+ import { cardTypeByName, cardTypeName, readHand } from './cards.js';
11
+ import { sanctionsSettings } from './analysis/cards-in-effect.js';
12
+ import { currentStanding } from './live.js';
13
+ import { fields, isObj } from './protocol/decoded.js';
14
+ import { cardClock } from './strategy/card-clock.js';
15
+ const MAX_DEPTH = 32;
16
+ const isInt = (v) => typeof v === 'number' && Number.isInteger(v);
17
+ const GUID_RE = /^[0-9a-f-]{32,38}$/i;
18
+ /** The card type a dict key names: an integer, or a record whose one integer field is it. */
19
+ function typeKey(k) {
20
+ if (isInt(k))
21
+ return k;
22
+ if (isObj(k)) {
23
+ const ints = fields(k).filter(isInt);
24
+ return ints.length === 1 ? ints[0] : undefined;
25
+ }
26
+ return undefined;
27
+ }
28
+ /** A `[card type, count]` dict: every item a pair of a type key and an integer count. */
29
+ function piecesDict(v) {
30
+ if (!Array.isArray(v) || v.length === 0)
31
+ return undefined;
32
+ const out = new Map();
33
+ for (const item of v) {
34
+ if (!Array.isArray(item) || item.length !== 2)
35
+ return undefined;
36
+ const [k, n] = item;
37
+ if (typeof k === 'string' && GUID_RE.test(k))
38
+ return undefined;
39
+ const type = typeKey(k);
40
+ if (type === undefined || !isInt(n) || n < 0)
41
+ return undefined;
42
+ out.set(type, (out.get(type) ?? 0) + n);
43
+ }
44
+ return out;
45
+ }
46
+ /**
47
+ * The pieces under the given in-game ids, summed by card type: `undefined` when no PlayerCards entry of theirs
48
+ * shows a pieces dict. An entry whose lists are all empty but for its whole cards reads as no pieces.
49
+ */
50
+ export function readPieces(info, ids) {
51
+ const owners = new Set(typeof ids === 'number' ? [ids] : ids);
52
+ const total = new Map();
53
+ let found = false;
54
+ const playerCards = (v) => {
55
+ if (!isObj(v))
56
+ return;
57
+ const values = fields(v);
58
+ const dict = values.map(piecesDict).find((d) => d !== undefined);
59
+ if (dict) {
60
+ found = true;
61
+ for (const [t, n] of dict)
62
+ total.set(t, (total.get(t) ?? 0) + n);
63
+ return;
64
+ }
65
+ // Pieces empty: every list is empty, or a list of whole cards (GUID keys), and at least two lists stand.
66
+ const lists = values.filter(Array.isArray);
67
+ if (lists.length >= 2 && lists.filter((l) => l.length === 0).length >= 1)
68
+ found = true;
69
+ };
70
+ const walk = (v, depth) => {
71
+ if (depth > MAX_DEPTH)
72
+ return;
73
+ if (Array.isArray(v)) {
74
+ for (const item of v) {
75
+ if (Array.isArray(item) && item.length === 2 && isInt(item[0]) && owners.has(item[0]) && isObj(item[1]) && /PlayerCards$/.test(String(item[1].$type))) {
76
+ playerCards(item[1]);
77
+ }
78
+ else
79
+ walk(item, depth + 1);
80
+ }
81
+ return;
82
+ }
83
+ if (!isObj(v))
84
+ return;
85
+ for (const [k, f] of Object.entries(v))
86
+ if (k !== '$type')
87
+ walk(f, depth + 1);
88
+ };
89
+ const standing = currentStanding(info);
90
+ if (standing)
91
+ walk(standing, 0);
92
+ return found ? total : undefined;
93
+ }
94
+ /** Whole cards grouped by type. */
95
+ export function heldCards(hand) {
96
+ const by = new Map();
97
+ for (const c of hand) {
98
+ const h = by.get(c.type) ?? { type: c.type, name: c.name, count: 0 };
99
+ h.count += 1;
100
+ if (c.armies !== undefined)
101
+ h.armies = Math.max(h.armies ?? 0, c.armies);
102
+ by.set(c.type, h);
103
+ }
104
+ return [...by.values()].sort((a, b) => a.type - b.type);
105
+ }
106
+ /** How many whole cards of `name` (`Airlift`, …) the hand holds. */
107
+ export const countOf = (state, name) => state.held.find((h) => h.name === name)?.count ?? 0;
108
+ /**
109
+ * My card state from a decoded LatestGameInfo: the whole cards held under `ids` (a team's merged hand when
110
+ * several) and the pieces toward the next card of each type in play (`settings`), `undefined` when no card is
111
+ * in play.
112
+ */
113
+ export function cardState(info, ids, settings) {
114
+ const clock = cardClock(settings);
115
+ if (!clock)
116
+ return undefined;
117
+ const hand = readHand(info, ids);
118
+ const held = heldCards(hand);
119
+ const read = readPieces(info, ids);
120
+ const pieces = read
121
+ ? clock.cards.flatMap((c) => {
122
+ const type = cardTypeByName(c.card);
123
+ return type === undefined ? [] : [{ type, name: cardTypeName(type), pieces: read.get(type) ?? 0, of: c.pieces }];
124
+ })
125
+ : null;
126
+ const settingsOf = cardSettings(settings, clock.cards.map((c) => c.card));
127
+ return {
128
+ held,
129
+ total: hand.length,
130
+ maxCardsHold: clock.maxCardsHold,
131
+ pieces,
132
+ ...(settingsOf.length ? { settings: settingsOf } : {}),
133
+ note: 'Whole cards are read from the live board (verified). ' +
134
+ (pieces
135
+ ? 'Pieces are read from it too, by their shape: UNVERIFIED live — check one against the web client before relying on it.'
136
+ : 'Pieces could not be read from the live board (their encoding is unverified), so none are shown.'),
137
+ };
138
+ }
139
+ /** The settings of the cards in play (`names`, as the clock lists them) that carry a duration, and Sanctions always. */
140
+ function cardSettings(settings, names) {
141
+ return names
142
+ .flatMap((name) => {
143
+ const type = cardTypeByName(name);
144
+ if (type === undefined)
145
+ return [];
146
+ if (name === 'Sanctions') {
147
+ const san = sanctionsSettings(settings);
148
+ if (!san)
149
+ return [];
150
+ return [{ type, name: cardTypeName(type), ...(san.duration !== null ? { duration: san.duration } : {}), percentage: san.percentage, effect: san.effect, targets: san.targets }];
151
+ }
152
+ const raw = settings?.raw[`${name}Card`];
153
+ const d = isObj(raw) ? Number(raw.Duration) : NaN;
154
+ return Number.isInteger(d) && d >= 1 ? [{ type, name: cardTypeName(type), duration: d }] : [];
155
+ })
156
+ .sort((a, b) => a.type - b.type);
157
+ }
@@ -83,6 +83,20 @@ export function decisionLogMode(env = process.env) {
83
83
  }
84
84
  /** The keys of `PlanInput` that are not kept in {@link LoggedInput}. */
85
85
  const INPUT_DROPPED = new Set(['graph', 'board', 'vacated', 'bonusPush', 'previousBoard']);
86
+ /** #568: the stages of an estimate as the decision log keeps them. */
87
+ export function estimateStages(e) {
88
+ return {
89
+ visible: e.base + e.bonusIncome,
90
+ observed: e.observed,
91
+ tracked: e.tracked,
92
+ prior: e.stated ? e.stated.full : e.prior,
93
+ stated: e.stated ? e.stated.scaled : null,
94
+ blend: e.priorBlend ? e.priorBlend.figure : null,
95
+ thin: e.thinEvidence ? e.thinEvidence.figure : null,
96
+ known: e.known ? e.known.income : null,
97
+ card: e.card ? e.card.armies : 0,
98
+ };
99
+ }
86
100
  /** Chat messages kept per turn at most. */
87
101
  export const MAX_LOGGED_CHAT = 50;
88
102
  /** Game events kept at most per log (the newest). */
@@ -225,10 +239,19 @@ export function decodeInput(logged, board, graph) {
225
239
  };
226
240
  }
227
241
  /** The estimates as logged: ids, figures and flags only. */
228
- export function loggedEstimates(estimates) {
242
+ export function loggedEstimates(estimates, tracks) {
243
+ const methods = new Map((tracks ?? []).flatMap((t) => (t.incomeMethod ? [[t.playerId, t.incomeMethod]] : [])));
229
244
  return [...estimates]
230
245
  .sort((a, b) => a.playerId - b.playerId)
231
- .map((e) => ({ player: e.playerId, estimate: e.estimate, source: e.source, coverage: e.coverage?.share ?? null, thin: !!e.thinEvidence }));
246
+ .map((e) => ({
247
+ player: e.playerId,
248
+ estimate: e.estimate,
249
+ source: e.source,
250
+ coverage: e.coverage?.share ?? null,
251
+ thin: !!e.thinEvidence,
252
+ ...(methods.has(e.playerId) ? { method: methods.get(e.playerId) } : {}),
253
+ stages: estimateStages(e),
254
+ }));
232
255
  }
233
256
  /** My income as `input` gives it, card armies out; `undefined` when it holds none. */
234
257
  function earnedIncome(input) {
@@ -237,7 +260,7 @@ function earnedIncome(input) {
237
260
  return undefined;
238
261
  return income - (typeof cardArmies === 'number' ? cardArmies : 0);
239
262
  }
240
- function decisionOf(plan, outlook, outlookLean, estimates, income) {
263
+ function decisionOf(plan, outlook, outlookLean, estimates, income, tracks) {
241
264
  return encodeValue({
242
265
  goal: plan.goal,
243
266
  profile: plan.profile,
@@ -252,7 +275,7 @@ function decisionOf(plan, outlook, outlookLean, estimates, income) {
252
275
  warnings: plan.warnings,
253
276
  outlook: outlook ?? null,
254
277
  ...(outlookLean ? { outlookLean } : {}),
255
- ...(estimates ? { estimates: loggedEstimates(estimates) } : {}),
278
+ ...(estimates ? { estimates: loggedEstimates(estimates, tracks) } : {}),
256
279
  ...(income !== undefined ? { income } : {}),
257
280
  });
258
281
  }
@@ -402,7 +425,7 @@ export async function recordDecision(dir, gameId, playerId, rec, opts = {}) {
402
425
  kind: 'planned',
403
426
  input,
404
427
  planner: { version: VERSION, ...(build ? { build } : {}) },
405
- decision: decisionOf(rec.plan, rec.outlookState, rec.outlookLean, rec.estimates, earnedIncome(rec.input)),
428
+ decision: decisionOf(rec.plan, rec.outlookState, rec.outlookLean, rec.estimates, earnedIncome(rec.input), rec.input.tracks),
406
429
  times: encodeValue({ plannedAt: iso(rec.now), ...rec.times }),
407
430
  ...(rec.firstMover !== undefined ? { firstMover: rec.firstMover ? { ...rec.firstMover } : null } : {}),
408
431
  ...(rec.cards ? { cards: encodeValue(rec.cards) } : {}),
@@ -653,6 +676,22 @@ export async function recordCheck(dir, gameId, playerId, turn, summary, opts = {
653
676
  return false;
654
677
  }
655
678
  }
679
+ /**
680
+ * #570: keep the resolved turn's visible orders on that turn's entry (an entry is started when none exists).
681
+ * Read again, the newest read wins. `true` when written. Never throws.
682
+ */
683
+ export async function recordSeenTurn(dir, gameId, playerId, seen, opts = {}) {
684
+ try {
685
+ const kept = { orders: seen.orders, ...(seen.omitted ? { omitted: seen.omitted } : {}) };
686
+ return await updateDecisionLog(dir, gameId, playerId, (log) => {
687
+ const was = log.turns[String(seen.turn)] ?? {};
688
+ return { ...log, turns: { ...log.turns, [String(seen.turn)]: { ...was, seen: kept } } };
689
+ }, opts);
690
+ }
691
+ catch {
692
+ return false;
693
+ }
694
+ }
656
695
  // ---------------------------------------------------------------------------------------------
657
696
  // #437 task 2: per-game events and context
658
697
  /** States in which a seat's change is no event (still in, or not yet in). */
@@ -0,0 +1,142 @@
1
+ // Local-time rendering (WARAPP_TIMEZONE): every absolute timestamp a tool answers with gains a sibling in the
2
+ // owner's zone, e.g. `time` → `localTime: "Tue 24 Nov, 6:14 am EST"`. Applied once, at the output layer
3
+ // (`withLocalTimes` wraps every registered tool's handler), so no tool formats a time itself. The UTC fields are
4
+ // never changed; with the setting unset (or invalid) nothing is touched and every answer is byte-identical.
5
+ import { readEnvVar } from '@chrischall/mcp-utils';
6
+ import { parseFeedTime } from './normalize.js';
7
+ let noted = false;
8
+ /** The IANA zone WARAPP_TIMEZONE names, or undefined when unset or not a zone (noted once per process). */
9
+ export function readTimezone(env = process.env, note = (l) => console.error(l)) {
10
+ const raw = readEnvVar('WARAPP_TIMEZONE', { env })?.trim();
11
+ if (!raw)
12
+ return undefined;
13
+ try {
14
+ new Intl.DateTimeFormat('en-US', { timeZone: raw });
15
+ return raw;
16
+ }
17
+ catch {
18
+ if (!noted) {
19
+ noted = true;
20
+ note(`warapp-mcp: WARAPP_TIMEZONE "${raw}" is not an IANA time zone (e.g. America/New_York); ignored, times stay UTC only.`);
21
+ }
22
+ return undefined;
23
+ }
24
+ }
25
+ const formatters = new Map();
26
+ /** An ISO (or GameFeed US-format, UTC) timestamp as "Tue 24 Nov, 6:14 am EST" in `timeZone`; undefined if not one. */
27
+ export function formatLocalTime(value, timeZone) {
28
+ const ms = parseFeedTime(value);
29
+ if (ms === undefined)
30
+ return undefined;
31
+ let f = formatters.get(timeZone);
32
+ if (!f) {
33
+ f = new Intl.DateTimeFormat('en-US', {
34
+ timeZone,
35
+ weekday: 'short',
36
+ day: 'numeric',
37
+ month: 'short',
38
+ hour: 'numeric',
39
+ minute: '2-digit',
40
+ hour12: true,
41
+ timeZoneName: 'short',
42
+ });
43
+ formatters.set(timeZone, f);
44
+ }
45
+ const p = {};
46
+ for (const part of f.formatToParts(new Date(ms)))
47
+ p[part.type] = part.value;
48
+ return `${p.weekday} ${p.day} ${p.month}, ${p.hour}:${p.minute} ${(p.dayPeriod ?? '').toLowerCase()} ${p.timeZoneName}`;
49
+ }
50
+ /** Keys that may carry an absolute timestamp (the value must also parse as one). */
51
+ const TIME_KEY = /(?:time|at|created|since)$/i;
52
+ /** The sibling's name: `time` → `localTime`, `lastTurnTime` → `lastTurnLocalTime`, `created` → `createdLocalTime`. */
53
+ const siblingOf = (key) => key === 'time' ? 'localTime' : /Time$/.test(key) ? `${key.slice(0, -4)}LocalTime` : `${key}LocalTime`;
54
+ /** `data` with a local-time sibling beside every timestamp field (a new value when anything was added, else `data`). */
55
+ export function addLocalTimes(data, timeZone) {
56
+ if (Array.isArray(data)) {
57
+ let changed = false;
58
+ const out = data.map((v) => {
59
+ const n = addLocalTimes(v, timeZone);
60
+ if (n !== v)
61
+ changed = true;
62
+ return n;
63
+ });
64
+ return changed ? out : data;
65
+ }
66
+ if (data === null || typeof data !== 'object')
67
+ return data;
68
+ let changed = false;
69
+ const out = {};
70
+ const src = data;
71
+ for (const [key, value] of Object.entries(src)) {
72
+ const n = addLocalTimes(value, timeZone);
73
+ if (n !== value)
74
+ changed = true;
75
+ out[key] = n;
76
+ if (typeof value === 'string' && TIME_KEY.test(key) && !/local/i.test(key)) {
77
+ const sibling = siblingOf(key);
78
+ if (sibling in src)
79
+ continue;
80
+ const local = formatLocalTime(value, timeZone);
81
+ if (local !== undefined) {
82
+ out[sibling] = local;
83
+ changed = true;
84
+ }
85
+ }
86
+ }
87
+ return changed ? out : data;
88
+ }
89
+ /** A tool result with local times added to its JSON text, indentation kept; the same object when nothing changes. */
90
+ export function localizeResult(result, timeZone) {
91
+ if (!result || !Array.isArray(result.content))
92
+ return result;
93
+ let changed = false;
94
+ const content = result.content.map((c) => {
95
+ if (c.type !== 'text' || !/^\s*[[{]/.test(c.text))
96
+ return c;
97
+ let parsed;
98
+ try {
99
+ parsed = JSON.parse(c.text);
100
+ }
101
+ catch {
102
+ return c;
103
+ }
104
+ const next = addLocalTimes(parsed, timeZone);
105
+ if (next === parsed)
106
+ return c;
107
+ changed = true;
108
+ const indented = /^[[{]\n/.test(c.text);
109
+ return { ...c, text: indented ? JSON.stringify(next, null, 2) : JSON.stringify(next) };
110
+ });
111
+ return changed ? { ...result, content } : result;
112
+ }
113
+ /**
114
+ * Run `register` with every tool it registers answering with local times in `timeZone` (none: `register` runs
115
+ * untouched). The same server object is patched and restored afterwards, as `withToolConfig` does.
116
+ */
117
+ export function withLocalTimes(server, timeZone, register) {
118
+ if (!timeZone) {
119
+ register();
120
+ return;
121
+ }
122
+ const target = server;
123
+ const hadOwn = Object.hasOwn(target, 'registerTool');
124
+ const original = target.registerTool;
125
+ target.registerTool = (...args) => {
126
+ const last = args.length - 1;
127
+ const handler = args[last];
128
+ if (typeof handler === 'function') {
129
+ args[last] = async (...callArgs) => localizeResult((await handler(...callArgs)), timeZone);
130
+ }
131
+ return original.apply(server, args);
132
+ };
133
+ try {
134
+ register();
135
+ }
136
+ finally {
137
+ if (hadOwn)
138
+ target.registerTool = original;
139
+ else
140
+ delete target.registerTool;
141
+ }
142
+ }
@@ -9,10 +9,14 @@
9
9
  // An agreement's `exceptions` (partner-approved attacks that are no break: territory ids, turns, a
10
10
  // direction) may carry a short `note` — the owner's own words, never a chat message, with every player
11
11
  // name scrubbed to `Player <id>` before it is written (`scrubNames`). Files written before it have none.
12
+ // So may a territory cap in `caps` (an amendment: territory id, max, the turn it was set).
12
13
  //
13
14
  // `commitments` (part B4): what my chat messages promised (warapp_send_chat's declared commitments,
14
15
  // never the text), recorded once a message is sent; warapp_submit_turn warns when orders break one.
15
16
  //
17
+ // `coordination`: joint attacks agreed with a partner (warapp_record_agreement `coordination`; ids,
18
+ // turns and a scrubbed note), reported by warapp_get_relations and warapp_plan_turn, never an order.
19
+ //
16
20
  // `intel` (#386): avoid targets and stated incomes from diplomacy (warapp_record_intel), applied by
17
21
  // warapp_plan_turn and warapp_check_plan by default.
18
22
  //
@@ -22,8 +26,9 @@ import { randomUUID } from 'node:crypto';
22
26
  import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
23
27
  import { join } from 'node:path';
24
28
  import { withPathLock } from './path-lock.js';
25
- import { AGREEMENT_STATUSES, EXCEPTION_DIRECTIONS, MAX_EXCEPTION_NOTE, MAX_EXCEPTIONS, MAX_NOTICE_TURNS, } from './analysis/relations.js';
29
+ import { AGREEMENT_STATUSES, EXCEPTION_DIRECTIONS, MAX_CAPS, MAX_EXCEPTION_NOTE, MAX_EXCEPTIONS, MAX_NOTICE_TURNS, } from './analysis/relations.js';
26
30
  import { COMMITMENT_KINDS } from './analysis/commitments.js';
31
+ import { coordinationOf, MAX_COORDINATION } from './analysis/coordination.js';
27
32
  import { AVOID_REASONS, intelIsEmpty } from './analysis/intel.js';
28
33
  const isRec = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
29
34
  const isInt = (v) => typeof v === 'number' && Number.isInteger(v);
@@ -93,8 +98,20 @@ export function agreementOf(v) {
93
98
  const exceptions = Array.isArray(v.exceptions) ? v.exceptions.map(exceptionOf).filter((e) => e !== undefined).slice(-MAX_EXCEPTIONS) : [];
94
99
  if (exceptions.length)
95
100
  a.exceptions = exceptions;
101
+ const caps = Array.isArray(v.caps) ? v.caps.map(capOf).filter((c) => c !== undefined).slice(-MAX_CAPS) : [];
102
+ if (caps.length)
103
+ a.caps = caps;
96
104
  return a;
97
105
  }
106
+ /** A territory cap read back, or `undefined` when it is unusable (files before it have none). */
107
+ function capOf(v) {
108
+ if (!isRec(v) || !isInt(v.territory) || !isInt(v.max) || v.max < 0 || !isInt(v.addedTurn))
109
+ return undefined;
110
+ const c = { territory: v.territory, max: v.max, addedTurn: v.addedTurn };
111
+ if (typeof v.note === 'string' && v.note.length)
112
+ c.note = v.note.slice(0, MAX_EXCEPTION_NOTE);
113
+ return c;
114
+ }
98
115
  /** A partner-approved exception read back, or `undefined` when it is unusable (files before it have none). */
99
116
  function exceptionOf(v) {
100
117
  if (!isRec(v) || typeof v.id !== 'string' || !/^e\d{1,9}$/.test(v.id))
@@ -157,6 +174,13 @@ export function nextCommitmentId(ledger) {
157
174
  const n = (ledger.commitments ?? []).reduce((m, c) => Math.max(m, Number(COMMITMENT_ID.exec(c.id)?.[1] ?? 0)), 0);
158
175
  return `c${n + 1}`;
159
176
  }
177
+ /** The coordination notes of a ledger file, the unusable dropped; absent when none. */
178
+ function coordinationsOf(v) {
179
+ if (!Array.isArray(v))
180
+ return {};
181
+ const list = v.map(coordinationOf).filter((c) => c !== undefined);
182
+ return list.length ? { coordination: list.slice(-MAX_COORDINATION) } : {};
183
+ }
160
184
  /** #386: the intel of a ledger file, the unusable entries dropped; absent when none. */
161
185
  export function intelOf(v) {
162
186
  if (!isRec(v))
@@ -206,7 +230,7 @@ export async function readLedger(dir, gameId, playerId) {
206
230
  if (!isRec(c) || c.gameId !== gameId || c.playerId !== playerId || !Array.isArray(c.agreements))
207
231
  return undefined;
208
232
  const agreements = c.agreements.map(agreementOf).filter((a) => a !== undefined);
209
- return { gameId, playerId, agreements, usage: usageOf(c.usage), ...commitmentsOf(c.commitments), ...intelOf(c.intel) };
233
+ return { gameId, playerId, agreements, usage: usageOf(c.usage), ...commitmentsOf(c.commitments), ...intelOf(c.intel), ...coordinationsOf(c.coordination) };
210
234
  }
211
235
  catch {
212
236
  return undefined;
@@ -230,7 +254,7 @@ export async function readLedgerForWrite(dir, gameId, playerId) {
230
254
  if (!isRec(c) || c.gameId !== gameId || c.playerId !== playerId || !Array.isArray(c.agreements))
231
255
  return 'unreadable';
232
256
  const agreements = c.agreements.map(agreementOf).filter((a) => a !== undefined);
233
- return { gameId, playerId, agreements, usage: usageOf(c.usage), ...commitmentsOf(c.commitments), ...intelOf(c.intel) };
257
+ return { gameId, playerId, agreements, usage: usageOf(c.usage), ...commitmentsOf(c.commitments), ...intelOf(c.intel), ...coordinationsOf(c.coordination) };
234
258
  }
235
259
  catch {
236
260
  return 'unreadable';
@@ -253,7 +277,8 @@ export function boundLedger(ledger) {
253
277
  .slice(0, MAX_USAGE_TURNS)
254
278
  .sort((a, b) => a - b);
255
279
  const commitments = ledger.commitments?.length ? { commitments: ledger.commitments.slice(-MAX_COMMITMENTS) } : {};
256
- const { commitments: _all, intel: _intel, ...rest } = ledger;
280
+ const { commitments: _all, intel: _intel, coordination: _coord, ...rest } = ledger;
281
+ const coordination = ledger.coordination?.length ? { coordination: ledger.coordination.slice(-MAX_COORDINATION) } : {};
257
282
  const intel = intelIsEmpty(ledger.intel)
258
283
  ? {}
259
284
  : {
@@ -263,7 +288,7 @@ export function boundLedger(ledger) {
263
288
  incomes: ledger.intel.incomes.slice(-MAX_INTEL_PLAYERS),
264
289
  },
265
290
  };
266
- return { ...rest, agreements, usage: Object.fromEntries(turns.map((t) => [String(t), ledger.usage[String(t)]])), ...commitments, ...intel };
291
+ return { ...rest, agreements, usage: Object.fromEntries(turns.map((t) => [String(t), ledger.usage[String(t)]])), ...commitments, ...intel, ...coordination };
267
292
  }
268
293
  /** Write the ledger (bounded), atomically, 0600. `true` when written; never throws. */
269
294
  export async function writeLedger(dir, ledger) {
@@ -0,0 +1,87 @@
1
+ // Owner request 2026-11-24 (Airlift part 5): after warapp_submit_turn commits, the Airlifts it sent are read back
2
+ // from war.app's own copy of my committed orders (LatestGameInfo's active orders, src/my-orders.ts, the read
3
+ // warapp_get_my_orders makes; VERIFIED live 2026-11-22 for committed turns) and compared field by field: the
4
+ // card instance, from, to, armies and the commander. Pure; the tool throws when one is missing or altered.
5
+ import { normalizeGuid } from '../cards.js';
6
+ /** The Airlift plays among the orders sent. */
7
+ export function sentAirlifts(orders) {
8
+ return orders.flatMap((o) => o.kind === 'card' && o.card === 'Airlift' && o.from !== undefined && o.to !== undefined && o.armies !== undefined
9
+ ? [{ card: normalizeGuid(o.cardId) ?? o.cardId, from: o.from, to: o.to, armies: o.armies, commander: o.commander !== undefined }]
10
+ : []);
11
+ }
12
+ const same = (a, b) => a.from === b.from && a.to === b.to && a.armies === b.armies && a.commander === b.commander;
13
+ /** Compare the Airlifts sent with my orders read back (`null`: unknown). */
14
+ export function checkAirlifts(sent, read) {
15
+ if (!read)
16
+ return { status: 'unread', sent: [...sent], missing: [], altered: [] };
17
+ const back = read.orders.flatMap((o) => o.kind === 'card' && o.cardType === 'Airlift' && o.from !== undefined && o.to !== undefined
18
+ ? [{ card: normalizeGuid(o.card) ?? o.card, from: o.from, to: o.to, armies: o.armies ?? 0, commander: o.commander === true }]
19
+ : []);
20
+ const missing = [];
21
+ const altered = [];
22
+ const used = new Set();
23
+ for (const s of sent) {
24
+ // The same card instance, else (a card swapped for another of its type, as the validator may do) one with the same fields.
25
+ let i = back.findIndex((b, k) => !used.has(k) && b.card === s.card);
26
+ if (i < 0)
27
+ i = back.findIndex((b, k) => !used.has(k) && same(b, s));
28
+ if (i < 0) {
29
+ missing.push(s);
30
+ continue;
31
+ }
32
+ used.add(i);
33
+ if (!same(back[i], s))
34
+ altered.push({ sent: s, read: back[i] });
35
+ }
36
+ return { status: missing.length || altered.length ? 'mismatch' : 'verified', sent: [...sent], missing, altered };
37
+ }
38
+ const line = (a) => `${a.armies}${a.commander ? ' + commander' : ''} from ${a.from} to ${a.to}`;
39
+ /** The error message for a mismatch: what is missing or altered, by id (`more`: other card plays' parts). */
40
+ export function mismatchMessage(r, turn, game, more = []) {
41
+ const parts = [
42
+ ...r.missing.map((a) => `the Airlift of ${line(a)} is missing`),
43
+ ...r.altered.map((x) => `the Airlift of ${line(x.sent)} reads back as ${line(x.read)}`),
44
+ ...more,
45
+ ];
46
+ return (`Your orders for game ${game}, turn ${turn} are committed, but war.app's copy of them does not match what was sent: ` +
47
+ `${parts.join('; ')}. Nothing was resent.`);
48
+ }
49
+ /** The result fields a commit records beside its orders (#556): kept in the error when an Airlift reads back wrong. */
50
+ const RECORDED_KEYS = ['agreementsBroken', 'exceptionsRecorded', 'commanderRiskAccepted', 'chatReviewed'];
51
+ /** One line naming what the commit recorded (a truce break, exceptions, an accepted commander risk, waived chat), or none. */
52
+ export function recordedWithCommit(result) {
53
+ const parts = RECORDED_KEYS.filter((k) => result[k] !== undefined).map((k) => `${k} ${JSON.stringify(result[k])}`);
54
+ return parts.length ? `Recorded with this commit: ${parts.join('; ')}.` : undefined;
55
+ }
56
+ /** The card plays of these kinds (`TurnOrder` card names, e.g. `Bomb`) among the orders sent. */
57
+ export function sentTargeted(orders, kinds) {
58
+ return orders.flatMap((o) => o.kind === 'card' && kinds.has(o.card) && o.target !== undefined ? [{ card: normalizeGuid(o.cardId) ?? o.cardId, kind: o.card, target: o.target }] : []);
59
+ }
60
+ export function checkTargeted(sent, read) {
61
+ if (!read)
62
+ return { status: 'unread', sent: [...sent], missing: [], altered: [] };
63
+ const back = read.orders.flatMap((o) => o.kind === 'card' && o.target !== undefined && o.from === undefined ? [{ card: normalizeGuid(o.card) ?? o.card, target: o.target }] : []);
64
+ const used = new Set();
65
+ const missing = [];
66
+ const altered = [];
67
+ for (const s of sent) {
68
+ let i = back.findIndex((b, k) => !used.has(k) && b.card === s.card);
69
+ if (i < 0)
70
+ i = back.findIndex((b, k) => !used.has(k) && b.target === s.target);
71
+ if (i < 0) {
72
+ missing.push(s);
73
+ continue;
74
+ }
75
+ used.add(i);
76
+ if (back[i].target !== s.target)
77
+ altered.push({ sent: s, read: back[i] });
78
+ }
79
+ return { status: missing.length || altered.length ? 'mismatch' : 'verified', sent: [...sent], missing, altered };
80
+ }
81
+ /** The error message's parts for a targeted mismatch. */
82
+ export function targetedMismatchParts(r) {
83
+ return [
84
+ ...r.missing.map((t) => `the ${t.kind} play on ${t.target} is missing`),
85
+ ...r.altered.map((x) => `the ${x.sent.kind} play on ${x.sent.target} reads back on ${x.read.target}`),
86
+ ];
87
+ }
@@ -0,0 +1,21 @@
1
+ // The orders of an alternative plan beside the plain one (`airliftPlan`): the plain plan's card plays and discards, then
2
+ // the alternative's own card plays, deploys and moves. The advised Order Delay is left out (its `before` names a move of
3
+ // the plain plan); it is discarded instead only when the plain card choice had to shed it (it was among the discards and
4
+ // played in their place, `insteadOfDiscard`) — otherwise the player keeps it (auto-review #558). Pure.
5
+ /** Whether the orders play a card of `type` (by the hand's card ids): an advised Order Priority included. */
6
+ export function playsCardType(orders, hand, type) {
7
+ const ids = new Set(hand.filter((c) => c.type === type).map((c) => c.id));
8
+ return orders.some((o) => o.kind === 'card' && typeof o.card === 'string' && ids.has(o.card));
9
+ }
10
+ /** The cards of one type left after this plan: those the plain plan leaves (`free`), less those it spends. */
11
+ export const cardsLeftAfter = (a) => Math.max(0, Math.min(a.held, a.free) - a.spent);
12
+ export function alternativeOrders(a) {
13
+ const delayDiscard = a.playedDelay && a.delayOrder !== undefined && a.delayMustGo ? [{ kind: 'discard', card: a.playedDelay }] : [];
14
+ return [
15
+ ...a.orders.filter((o) => (o.kind === 'discard' || o.kind === 'card') && o !== a.delayOrder),
16
+ ...delayDiscard,
17
+ ...a.cardPlays,
18
+ ...a.deploys,
19
+ ...a.moves,
20
+ ];
21
+ }
@@ -9,6 +9,8 @@
9
9
  import { CONFIRM_INJECTION_RULE, toolAnnotations } from '@chrischall/mcp-utils';
10
10
  import { z } from 'zod';
11
11
  import { parseGameId } from '../client.js';
12
+ import { cardState } from '../card-state.js';
13
+ import { handOwners } from './card-advice.js';
12
14
  import { Method, writeBeginFirstTurnParams } from '../protocol/methods.js';
13
15
  import { gameIdArg, shownAccount, UNTRUSTED_PREVIEW_NOTE, untrustedText } from './common.js';
14
16
  import { mintMeta } from './hints.js';
@@ -54,7 +56,9 @@ export function registerBeginTurnTool(server, ctx) {
54
56
  'Begin is pressed, and pressing it STARTS YOUR TURN TIMER — call this only when ready to plan and ' +
55
57
  'submit at once (warapp_plan_turn, then warapp_submit_turn; in manual distribution, the picks). ' +
56
58
  'Refuses games past their first turn, games without the speed first turn, games you are not ' +
57
- 'playing, and games whose board is already visible; reads the board back to report `begun`. ' +
59
+ 'playing, and games whose board is already visible; reads the board back to report `begun` (with a card in ' +
60
+ 'play, `cards`: the hand by type with counts, the pieces toward the next card and the card settings — Sanctions\' ' +
61
+ 'percentage and whom it goes on — as warapp_get_game shows it). ' +
58
62
  `The BeginFirstTurn encoding is read from the war.app client, not yet verified live. ${CONFIRM_INJECTION_RULE}`,
59
63
  annotations: toolAnnotations({
60
64
  title: 'Begin the first turn of a war.app speed game',
@@ -96,10 +100,16 @@ export function registerBeginTurnTool(server, ctx) {
96
100
  untrusted: UNTRUSTED_PREVIEW_NOTE,
97
101
  },
98
102
  },
99
- state: { gameId, name, picking, me },
103
+ state: {
104
+ gameId,
105
+ name,
106
+ picking,
107
+ me,
108
+ ...(game.settings?.cards.length ? { hand: { owners: handOwners(game, mySeat(game, me)), settings: game.settings } } : {}),
109
+ },
100
110
  };
101
111
  },
102
- async execute({ gameId, name, picking, me }) {
112
+ async execute({ gameId, name, picking, me, hand }) {
103
113
  await requireApprovedAccount(ctx, writeAccount(me));
104
114
  const game = { id: gameId, name };
105
115
  const notReadBack = (ignored, readFailure) => ({
@@ -128,10 +138,13 @@ export function registerBeginTurnTool(server, ctx) {
128
138
  'already have gone through and your timer may be running. Check warapp_get_live_board; do not ' +
129
139
  'press Begin again blindly.',
130
140
  }),
131
- readBack: () => liveBoard(ctx, gameId),
141
+ readBack: () => readLatestBoard(ctx, gameId),
132
142
  // Nothing was read: never conclude the board is hidden from a failed read (#130).
133
143
  unreadable: (failure, ignored) => notReadBack(ignored !== undefined, failure),
134
- classify: (territories, ignored) => {
144
+ classify: ({ territories: read, info }, ignored) => {
145
+ const territories = read ?? undefined;
146
+ // My hand once the board shows (owner request 2026-11-24): whole cards by type and pieces toward the next.
147
+ const cards = territories && hand ? cardState(info, hand.owners, hand.settings) : undefined;
135
148
  if (!territories && ignored) {
136
149
  return {
137
150
  status: 'not_begun',
@@ -149,6 +162,7 @@ export function registerBeginTurnTool(server, ctx) {
149
162
  outcome: 'confirmed',
150
163
  game,
151
164
  territoriesVisible: territories.length,
165
+ ...(cards ? { cards } : {}),
152
166
  next: picking
153
167
  ? 'Your pick timer is running: choose and submit your picks now (warapp_submit_picks).'
154
168
  : 'Your turn timer is running: plan and submit now (warapp_plan_turn, then warapp_submit_turn).',