@chrischall/warapp-mcp 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/.claude-plugin/marketplace.json +3 -3
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +37 -5
  4. package/dist/analysis/card-support.js +2 -1
  5. package/dist/analysis/card-threats.js +59 -12
  6. package/dist/analysis/game-lessons.js +3 -4
  7. package/dist/analysis/hold-diff.js +3 -1
  8. package/dist/analysis/income-trend.js +38 -0
  9. package/dist/analysis/intel.js +75 -0
  10. package/dist/analysis/opens.js +64 -0
  11. package/dist/analysis/opponent-profile.js +75 -7
  12. package/dist/analysis/opponents.js +2 -2
  13. package/dist/analysis/outlook.js +39 -0
  14. package/dist/analysis/picks.js +91 -12
  15. package/dist/analysis/plan/bonus-attempts.js +105 -0
  16. package/dist/analysis/plan/capture-instead.js +116 -0
  17. package/dist/analysis/plan/captures.js +45 -4
  18. package/dist/analysis/plan/conceded-out.js +13 -2
  19. package/dist/analysis/plan/estimates.js +135 -26
  20. package/dist/analysis/plan/holds.js +31 -3
  21. package/dist/analysis/plan/jabs.js +113 -0
  22. package/dist/analysis/plan/leftover.js +249 -4
  23. package/dist/analysis/plan/orders.js +76 -4
  24. package/dist/analysis/plan/relations.js +21 -1
  25. package/dist/analysis/plan/report.js +69 -3
  26. package/dist/analysis/plan/second-sizing.js +133 -0
  27. package/dist/analysis/plan/shared.js +82 -20
  28. package/dist/analysis/plan/siege.js +303 -0
  29. package/dist/analysis/plan/stand-still.js +7 -3
  30. package/dist/analysis/plan/state.js +8 -0
  31. package/dist/analysis/plan/strike.js +10 -5
  32. package/dist/analysis/plan/targets.js +91 -60
  33. package/dist/analysis/plan/threats.js +41 -6
  34. package/dist/analysis/plan/transfers.js +46 -6
  35. package/dist/analysis/planner.js +234 -16
  36. package/dist/analysis/profile.js +13 -2
  37. package/dist/analysis/stress.js +8 -2
  38. package/dist/bonus-attempt-store.js +55 -0
  39. package/dist/bundle.js +47965 -39683
  40. package/dist/cards.js +7 -5
  41. package/dist/chat.js +35 -1
  42. package/dist/commerce.js +111 -0
  43. package/dist/index.js +9 -1
  44. package/dist/live.js +43 -0
  45. package/dist/move-order.js +64 -3
  46. package/dist/normalize.js +17 -0
  47. package/dist/profile-store.js +12 -2
  48. package/dist/protocol/methods.js +60 -5
  49. package/dist/protocol/rpc.js +8 -0
  50. package/dist/relations-store.js +38 -4
  51. package/dist/siege-store.js +49 -0
  52. package/dist/state-bundle.js +525 -0
  53. package/dist/state-cli.js +69 -0
  54. package/dist/team-cards.js +25 -0
  55. package/dist/tools/award.js +15 -1
  56. package/dist/tools/card-advice.js +16 -5
  57. package/dist/tools/card-plays.js +2 -2
  58. package/dist/tools/card-support-advice.js +2 -1
  59. package/dist/tools/chat-inbox.js +4 -0
  60. package/dist/tools/chat.js +65 -6
  61. package/dist/tools/check-plan.js +54 -10
  62. package/dist/tools/commerce-deploy.js +33 -0
  63. package/dist/tools/common.js +31 -0
  64. package/dist/tools/end-of-game.js +5 -3
  65. package/dist/tools/index.js +7 -0
  66. package/dist/tools/picks.js +12 -0
  67. package/dist/tools/profile-opponents.js +2 -0
  68. package/dist/tools/relations.js +137 -0
  69. package/dist/tools/state.js +227 -0
  70. package/dist/tools/stress-opponents.js +5 -2
  71. package/dist/tools/survival.js +11 -3
  72. package/dist/tools/team-brief.js +2 -2
  73. package/dist/tools/team.js +12 -3
  74. package/dist/tools/turn.js +332 -60
  75. package/dist/version.js +1 -1
  76. package/manifest.json +10 -2
  77. package/mint.yaml +14 -4
  78. package/package.json +4 -4
  79. package/server.json +2 -2
  80. package/skills/warapp-mcp/SKILL.md +31 -9
@@ -96,6 +96,9 @@ export function registerPickTools(server, ctx, deps = {}) {
96
96
  '`twoOrderCaptures` (neutrals its opening takes with two attacks because one cannot be paid for), ' +
97
97
  'the award (how many sets the round-by-round award order can grant from the list, and the worst of them with the ' +
98
98
  'other players\' starts it implies), ' +
99
+ '`side` (the positive bonus income on my side of the map — every member strictly nearer the primary than any start the ' +
100
+ 'award implies for the others — against the contested rest; `known: false` with a note when no start is implied; ' +
101
+ 'report only, never in the score), ' +
99
102
  'warnings (assumed settings) and the reasoning. The primary group carries its `coverage`: the share of reasonable bonuses ' +
100
103
  '(positive, with a pickable territory, no wasteland, value per army at least the median) a pick can stand next to within 2 moves, ' +
101
104
  'and the ones it cannot, by name. In a two-player game without spread it may also return an `alternative`: a coverage-first list ' +
@@ -279,6 +282,15 @@ export function registerPickTools(server, ctx, deps = {}) {
279
282
  reordered: plan.award.reordered,
280
283
  }
281
284
  : null,
285
+ // #305: the bonus income on my side of the map (nearer my primary than any start the award implies
286
+ // for the others) against the rest; report only, never scored.
287
+ side: {
288
+ known: plan.side.known,
289
+ opponentStarts: plan.side.opponentStarts.map(name),
290
+ ...(plan.side.mine ? { mine: plan.side.mine } : {}),
291
+ ...(plan.side.contested ? { contested: plan.side.contested } : {}),
292
+ ...(plan.side.note ? { note: plan.side.note } : {}),
293
+ },
282
294
  warnings: [...warnings, ...plan.warnings],
283
295
  rationale: plan.rationale,
284
296
  submitPicks: { game_id: game.id, territories: plan.picks.map((p) => p.territoryId) },
@@ -108,6 +108,8 @@ export function registerProfileOpponentsTool(server, ctx, deps = {}) {
108
108
  stacking: { n: h.stacking.n, sum: Math.round(h.stacking.sum * 1000) / 1000 },
109
109
  retaliate: h.retaliate,
110
110
  retake: h.retake,
111
+ jab: h.jab,
112
+ capacityTopUp: h.capacityTopUp,
111
113
  },
112
114
  defaults: HABIT_DEFAULTS,
113
115
  turns: turns.map((t) => ({ turn: t.turn, ...t.primitives })),
@@ -11,6 +11,7 @@ import { boardIncome, incomeRules, trackGame, trackOpponents } from '../analysis
11
11
  import { agreementChange } from '../analysis/commitments.js';
12
12
  import { playerRecord, recordDelta, recordEntryFor } from '../analysis/player-record.js';
13
13
  import { AGREEMENT_STATUSES, agreementState, breachWatch, MAX_NOTICE_TURNS, newAgreement, OPENING_STATUSES, partyRefusal, scopeRefusal, tacitTruces, TERMINAL_STATUSES, transitionAgreement, TRUCE_OUTGROW_RATIO, trust, truceEndgame, } from '../analysis/relations.js';
14
+ import { AVOID_REASONS, emptyIntel, INCOME_STALE_TURNS, intelIsEmpty } from '../analysis/intel.js';
14
15
  import { boardStateFromLive } from '../live.js';
15
16
  import { entryKey, legacyEntryKey, playerRecordEnabled, playerRecordState, readPlayerRecord, updatePlayerRecord } from '../player-record-store.js';
16
17
  import { emptyLedger, nextAgreementId, nextCommitmentId, readLedger, readLedgerForWrite, withLedgerLock, writeLedger } from '../relations-store.js';
@@ -28,6 +29,9 @@ import { boardHistory, plannerSettings } from './turn.js';
28
29
  import { resolveTeamsFor } from './team-source.js';
29
30
  const VIEWS = ['compact', 'full'];
30
31
  const MAX_SCOPE_ITEMS = 200;
32
+ /** #386: what warapp_record_intel writes, and where. */
33
+ export const INTEL_NOTE = "Written only to the server's data directory (the game's agreement ledger: ids, turns and reason codes, no name or " +
34
+ 'message); nothing was sent to war.app or to any player. warapp_plan_turn and warapp_check_plan apply it by default.';
31
35
  /** What the results say about the board-derived parts. */
32
36
  export const RELATIONS_NOTE = 'Flags come from your own board history (the boards warapp_plan_turn, warapp_track_opponents and this tool ' +
33
37
  'cached, with the orders warapp_submit_turn sent): a fog reveal is never an event, and an event the fog leaves ' +
@@ -608,4 +612,137 @@ export function registerRelationsTools(server, ctx, opts = {}) {
608
612
  written: LEDGER_NOTE,
609
613
  }));
610
614
  });
615
+ server.registerTool('warapp_record_intel', {
616
+ title: 'Record avoid targets and stated incomes for a war.app game',
617
+ _meta: mintMeta('change', ['remember not to attack', 'they said their income', 'promised them a territory', 'forget the intel']),
618
+ description: untrustedDescription("Keep what diplomacy told you for a war.app (Warzone) game in this server's agreement ledger, so every " +
619
+ 'warapp_plan_turn and warapp_check_plan call applies it without being told again (another session or the ' +
620
+ 'hosted connector included): `avoid_territories` (territories never to attack — a neutral promised to ' +
621
+ '`promised_to`, say), `avoid_players` (players never to attack outside any truce, each with a `reason` code: ' +
622
+ `${AVOID_REASONS.join(', ')}) and \`known_income\` (a player's stated income, kept with the turn it was stated: ` +
623
+ '`stated_turn`, default this turn). Recording a territory, player or income again replaces its entry; `forget` ' +
624
+ 'removes entries. The plans apply them by default and report it as `intel`; an explicit `avoid_territories`, ' +
625
+ '`avoid_players` or `known_income` argument replaces the stored list of its kind for that call (an empty list ' +
626
+ `included), and a stored income more than ${INCOME_STALE_TURNS} turns old is not applied (the estimate stands, ` +
627
+ 'with a warning). Nothing is sent to war.app or to any player (no confirmation step), and the ledger keeps ids, ' +
628
+ 'turns and reason codes only: no name, no message. Refused for yourself as a player, and outside a game being played.'),
629
+ annotations: toolAnnotations({ title: 'Record war.app intel', readOnly: false, destructive: false, idempotent: true, openWorld: true }),
630
+ inputSchema: z.object({
631
+ game_id: gameIdArg,
632
+ player: playerArg,
633
+ avoid_territories: z.array(playerRef).max(MAX_SCOPE_ITEMS).optional().describe('Territories (names or ids) never to attack.'),
634
+ promised_to: playerRef.optional().describe('The player (name or id) `avoid_territories` were promised to, when one.'),
635
+ avoid_players: z
636
+ .array(z.object({ player: playerRef.describe('The player (name or GameFeed id).'), reason: z.enum(AVOID_REASONS).describe('Why.') }))
637
+ .max(50)
638
+ .optional()
639
+ .describe('Players never to attack outside any truce, each with a reason code.'),
640
+ known_income: z
641
+ .array(z.object({
642
+ player: playerRef.describe('The player (name or GameFeed id).'),
643
+ income: z.coerce.number().int().min(0).max(10_000).describe('The income it stated, per turn, card armies aside.'),
644
+ }))
645
+ .max(50)
646
+ .optional()
647
+ .describe("Players' stated incomes."),
648
+ stated_turn: z.coerce.number().int().min(0).optional().describe('The turn the incomes were stated (default this turn; never later).'),
649
+ forget: z
650
+ .object({
651
+ territories: z.array(playerRef).max(MAX_SCOPE_ITEMS).optional().describe('Territories to stop avoiding.'),
652
+ players: z.array(playerRef).max(50).optional().describe('Players to stop avoiding.'),
653
+ incomes: z.array(playerRef).max(50).optional().describe('Players whose stated income to drop.'),
654
+ })
655
+ .optional()
656
+ .describe('Entries to remove.'),
657
+ }),
658
+ }, async (args) => {
659
+ if (!ctx.dataDir) {
660
+ throw new McpToolError('This server has no data directory, so there is no ledger to record into: nothing was recorded.', {
661
+ hint: 'Set MCP_DATA_DIR, or run with a writable home directory.',
662
+ });
663
+ }
664
+ const dir = ctx.dataDir;
665
+ const refuse = (why, hint) => {
666
+ throw new McpToolError(`${why}: nothing was recorded.`, { hint });
667
+ };
668
+ const given = args.avoid_territories?.length || args.avoid_players?.length || args.known_income?.length ||
669
+ args.forget?.territories?.length || args.forget?.players?.length || args.forget?.incomes?.length;
670
+ if (!given)
671
+ refuse('Nothing to record', 'Give `avoid_territories`, `avoid_players`, `known_income` or `forget`.');
672
+ const feed = await ctx.client.getGame(args.game_id, { settings: true });
673
+ if (feed.state !== 'Playing' && feed.state !== 'DistributingTerritories')
674
+ refuse(`Game ${feed.id} is ${feed.state}: intel is recorded only while it is being played`, 'Record it once the game has started (picks included).');
675
+ const me = await resolveMe(ctx, feed.players, args.player);
676
+ const map = mapOf(feed);
677
+ const turn = Math.max(0, currentTurn(feed) ?? 0);
678
+ const other = (ref, what) => {
679
+ const p = resolvePlayer(feed.players, ref);
680
+ if (p.id === me.id)
681
+ refuse(`${what} must be another player, not yourself`, 'Name another player in the game.');
682
+ return p.id;
683
+ };
684
+ if (args.stated_turn !== undefined && args.stated_turn > turn)
685
+ refuse(`stated_turn ${args.stated_turn} is after this turn (${turn})`, 'Give the turn the income was stated, this one or earlier.');
686
+ const statedTurn = args.stated_turn ?? turn;
687
+ const promisedTo = args.promised_to !== undefined ? other(args.promised_to, '`promised_to`') : undefined;
688
+ const addT = (args.avoid_territories ?? []).map((t) => resolveTerritory(map, t).id);
689
+ const addP = (args.avoid_players ?? []).map((a) => ({ player: other(a.player, 'A player to avoid'), reason: a.reason }));
690
+ const addI = (args.known_income ?? []).map((k) => ({ player: other(k.player, 'A player whose income'), income: k.income }));
691
+ const dropT = new Set((args.forget?.territories ?? []).map((t) => resolveTerritory(map, t).id));
692
+ const dropP = new Set((args.forget?.players ?? []).map((p) => resolvePlayer(feed.players, p).id));
693
+ const dropI = new Set((args.forget?.incomes ?? []).map((p) => resolvePlayer(feed.players, p).id));
694
+ const intel = await withLedgerLock(dir, feed.id, me.id, async () => {
695
+ const read = await readLedgerForWrite(dir, feed.id, me.id);
696
+ if (read === 'unreadable') {
697
+ throw new McpToolError(`The ledger for game ${feed.id} exists but cannot be read: nothing was recorded, and the file was left as it is.`, {
698
+ hint: "Inspect or move aside the game's file under the server's data directory (relations/), then record again.",
699
+ });
700
+ }
701
+ const ledger = read ?? emptyLedger(feed.id, me.id);
702
+ const was = ledger.intel ?? emptyIntel();
703
+ const tNew = new Set(addT);
704
+ const pNew = new Set(addP.map((a) => a.player));
705
+ const iNew = new Set(addI.map((a) => a.player));
706
+ const next = {
707
+ avoidTerritories: [
708
+ ...was.avoidTerritories.filter((a) => !tNew.has(a.territory) && !dropT.has(a.territory)),
709
+ ...[...tNew].filter((t) => !dropT.has(t)).map((territory) => ({ territory, turn, ...(promisedTo !== undefined ? { promisedTo } : {}) })),
710
+ ],
711
+ avoidPlayers: [
712
+ ...was.avoidPlayers.filter((a) => !pNew.has(a.player) && !dropP.has(a.player)),
713
+ ...addP.filter((a) => !dropP.has(a.player)).map((a) => ({ player: a.player, turn, reason: a.reason })),
714
+ ],
715
+ incomes: [
716
+ ...was.incomes.filter((a) => !iNew.has(a.player) && !dropI.has(a.player)),
717
+ ...addI.filter((a) => !dropI.has(a.player)).map((a) => ({ player: a.player, income: a.income, turn: statedTurn })),
718
+ ],
719
+ };
720
+ const { intel: _old, ...rest } = ledger;
721
+ if (!(await writeLedger(dir, { ...rest, ...(intelIsEmpty(next) ? {} : { intel: next }) }))) {
722
+ throw new McpToolError(`The ledger for game ${feed.id} could not be written: nothing was recorded.`, {
723
+ hint: "Check that the server's data directory is writable.",
724
+ });
725
+ }
726
+ return next;
727
+ });
728
+ const name = namer(map);
729
+ const playerName = (id) => {
730
+ const p = feed.players.find((x) => x.id === id);
731
+ return { id, name: p ? untrustedText(p.name) : null };
732
+ };
733
+ return respond(undefined, ['compact'], () => ({
734
+ game: { id: feed.id, turn },
735
+ intel: {
736
+ avoidTerritories: intel.avoidTerritories.map((a) => ({
737
+ territory: name(a.territory),
738
+ turn: a.turn,
739
+ ...(a.promisedTo !== undefined ? { promisedTo: playerName(a.promisedTo) } : {}),
740
+ })),
741
+ avoidPlayers: intel.avoidPlayers.map((a) => ({ player: playerName(a.player), reason: a.reason, turn: a.turn })),
742
+ incomes: intel.incomes.map((a) => ({ player: playerName(a.player), income: a.income, statedTurn: a.turn })),
743
+ },
744
+ incomeStaleAfterTurns: INCOME_STALE_TURNS,
745
+ written: INTEL_NOTE,
746
+ }));
747
+ });
611
748
  }
@@ -0,0 +1,227 @@
1
+ // Moving history into this server, and finishing the end-of-game backlog faster.
2
+ //
3
+ // warapp_upload_slots + warapp_import_state (registered only where mcp-host hands this server a blob
4
+ // store, i.e. hosted): a local install's history, written by `warapp-mcp export-state`
5
+ // (src/state-cli.ts, src/state-bundle.ts), comes in through the fleet's upload-slot pattern
6
+ // (@chrischall/mcp-utils/export: `mintUploadSlot` signs a PUT the caller curls the bundle to, and
7
+ // `resolveUploadSource` reads it back by its `blobKey`), since the bundle is far too big for one tool
8
+ // argument. The import is confirm-gated like every write here (`defineGatedWrite`): the preview shows
9
+ // the counts per store, the bundle's account against the signed-in one (another account is refused),
10
+ // and the salt on this server against the bundle's (a different one is refused unless `replace`, which
11
+ // moves this server's hashed stores aside into a backup, never deleting them). Each file's sha256 is
12
+ // checked against the manifest before anything is written. Neither the preview nor the result carries
13
+ // the salt or any file's contents. The upload is deleted once imported, and at once when it is no
14
+ // bundle (it can never import); a refusal that a retry may clear (the account, the salt) keeps it.
15
+ //
16
+ // warapp_backfill_history: the warapp_my_games sweep (src/tools/end-of-game.ts) at a bigger batch —
17
+ // up to 25 finished games not yet processed per call, each history read once, as the sweep reads it —
18
+ // with an optional wider window. Writes only this server's state; nothing goes to war.app.
19
+ import { CONFIRM_INJECTION_RULE, McpToolError, toolAnnotations } from '@chrischall/mcp-utils';
20
+ import { mintUploadSlot, resolveUploadSource } from '@chrischall/mcp-utils/export';
21
+ import { z } from 'zod';
22
+ import { MAX_FINISHED_RECORDS } from '../finished-store.js';
23
+ import { profileEnabled } from '../profile-store.js';
24
+ import { applyImport, decodeBundle, MAX_BUNDLE_BYTES, planImport, StateBundleError, } from '../state-bundle.js';
25
+ import { respond } from './common.js';
26
+ import { sweepFinished, sweepWindow } from './end-of-game.js';
27
+ import { mintMeta } from './hints.js';
28
+ import { requireApprovedAccount, writeAccount } from './live-context.js';
29
+ import { BRIDGE_NOTE } from './live.js';
30
+ import { fetchMyGames, finishedGamesOf } from './my-games.js';
31
+ import { accountUnknown, defineGatedWrite, refuse } from './write-kit.js';
32
+ const SLOT_TOOL = 'warapp_upload_slots';
33
+ /** Finished games warapp_backfill_history processes per call: the default and the most. */
34
+ export const BACKFILL_DEFAULT = 10;
35
+ export const BACKFILL_MAX = 25;
36
+ export function registerStateTools(server, ctx, deps = {}) {
37
+ const env = deps.env ?? process.env;
38
+ const store = deps.store ?? undefined;
39
+ if (store)
40
+ registerImportTools(server, ctx, store);
41
+ registerBackfillTool(server, ctx, env);
42
+ }
43
+ function registerImportTools(server, ctx, store) {
44
+ server.registerTool(SLOT_TOOL, {
45
+ title: 'Get an upload URL for a warapp-mcp state bundle',
46
+ _meta: mintMeta('other', ['upload my warapp history', 'move local warapp state']),
47
+ description: 'Get a signed upload URL for a warapp-mcp state bundle (the file `warapp-mcp export-state` writes on a ' +
48
+ 'local install), so warapp_import_state can read it on this hosted server. PUT the file to `uploadUrl` with ' +
49
+ 'exactly its Content-Type (the returned `curl` does it), then call warapp_import_state with the `blobKey`. ' +
50
+ 'Changes nothing; the URL is a short-lived credential to write that one file, so share it with no one, and ' +
51
+ 'the upload is deleted once imported.',
52
+ annotations: toolAnnotations({ title: 'Upload URL for a state bundle', readOnly: true, destructive: false, idempotent: false, openWorld: true }),
53
+ inputSchema: z.object({
54
+ filename: z
55
+ .string()
56
+ .optional()
57
+ .describe('The bundle file name (default "warapp-state.json.gz"); one plain name, no path.'),
58
+ }),
59
+ }, async ({ filename }) => {
60
+ const slot = mintUploadSlot(store, { filename: filename ?? 'warapp-state.json.gz', mimeType: 'application/octet-stream' });
61
+ return respond(undefined, ['compact'], () => ({
62
+ slot,
63
+ maxBytes: MAX_BUNDLE_BYTES,
64
+ next: "Replace the curl's `<path to …>` with the bundle's path and run it, then call warapp_import_state with " +
65
+ 'blob_key set to `blobKey`: it previews first and imports only once you confirm.',
66
+ }));
67
+ });
68
+ defineGatedWrite(server, {
69
+ title: 'Import a warapp-mcp state bundle into this server',
70
+ _meta: mintMeta('change', ['import my warapp history', 'move local warapp state to hosted']),
71
+ }, {
72
+ name: 'warapp_import_state',
73
+ description: "Import a local install's warapp-mcp history (the bundle `warapp-mcp export-state` writes, uploaded with " +
74
+ 'warapp_upload_slots) into this server: the salt behind its hashed keys, the deal record and ledgers, the ' +
75
+ 'opponent profiles, lessons, map records and end-of-game records, and the per-game files of games still in ' +
76
+ "play. The preview shows the files per store, the bundle's account against the signed-in one (another " +
77
+ "account is refused) and whether this server already has a salt: a different one is refused unless " +
78
+ "`replace: true`, which moves this server's hashed stores (profiles, relations, finished, lessons, " +
79
+ 'maps-record) into a dated backup folder (never deleted), since entries under two salts would count twice. ' +
80
+ "Each file's sha256 is checked against the bundle's manifest first; files are written atomically, 0600. " +
81
+ 'Without `replace` a file already here that differs is kept. Writes only this server\'s state, never ' +
82
+ `war.app; never shows the salt or any file's contents. ${CONFIRM_INJECTION_RULE}`,
83
+ annotations: toolAnnotations({
84
+ title: 'Import a warapp-mcp state bundle',
85
+ readOnly: false,
86
+ destructive: false,
87
+ idempotent: true,
88
+ openWorld: true,
89
+ }),
90
+ inputSchema: z.object({
91
+ blob_key: z.string().describe('The `blobKey` from warapp_upload_slots, after PUTting the bundle to its URL.'),
92
+ replace: z
93
+ .boolean()
94
+ .optional()
95
+ .describe("Take the bundle's salt over a different one here: this server's hashed stores, and every file the " +
96
+ 'bundle replaces, are moved into state-backups/<time>/ first (default false).'),
97
+ }),
98
+ async plan({ blob_key, replace }) {
99
+ const dir = ctx.dataDir;
100
+ if (!dir)
101
+ refuse('This server has no data directory, so there is nowhere to import into; nothing was imported.', 'Nothing to do here.');
102
+ const source = await resolveUploadSource({ blobKey: blob_key }, { maxBytes: MAX_BUNDLE_BYTES, store, hosted: true, names: { blobKey: 'blob_key', inline: 'blob_key', path: 'blob_key', slotTool: SLOT_TOOL } });
103
+ let bundle;
104
+ try {
105
+ bundle = decodeBundle(source.bytes);
106
+ }
107
+ catch (e) {
108
+ // It can never import: drop the upload now rather than leave it to the store's retention.
109
+ await source.release();
110
+ if (e instanceof StateBundleError)
111
+ refuse(e.message, 'Export the bundle again with `warapp-mcp export-state` and upload the new file.');
112
+ throw e;
113
+ }
114
+ const me = await ctx.myInviteToken({ fresh: true }).catch(() => undefined);
115
+ if (me === undefined)
116
+ throw accountUnknown(ctx, 'nothing was imported');
117
+ const p = await planImport(dir, bundle, me);
118
+ if (!p.accountMatches) {
119
+ refuse(`The bundle is for war.app account ${p.accountId}, but account ${me} is signed in here, so nothing was imported.`, 'Sign in to war.app as the account the bundle was exported from, or export the right account (`--account`).');
120
+ }
121
+ const conflictSalt = p.salt === 'different' || p.salt === 'malformed';
122
+ if (conflictSalt && !replace) {
123
+ refuse(`This server already has a ${p.salt} salt, so its hashed history cannot be merged with the bundle's ` +
124
+ `(${p.totals.files} files); nothing was imported.`, "Call again with replace: true to move this server's hashed stores (profiles, relations, finished, lessons, " +
125
+ "maps-record) into a dated backup folder, never deleted, and take the bundle's.");
126
+ }
127
+ return {
128
+ gate: {
129
+ action: 'warapp.import_state',
130
+ summary: `Import a state bundle of ${p.totals.files} files for war.app account ${p.accountId} into this server`,
131
+ account: writeAccount(me),
132
+ target: source.sha256,
133
+ payload: { action: 'import-state', sha256: source.sha256, replace: replace === true, salt: p.salt },
134
+ willSend: { files: p.totals.files, bytes: p.totals.bytes },
135
+ preview: {
136
+ warning: "This writes this server's own state only (nothing goes to war.app or to any player)." +
137
+ (replace && conflictSalt
138
+ ? " replace: this server's hashed stores move into state-backups/<time>/ (kept, not deleted) and the bundle's salt is taken."
139
+ : '') +
140
+ (p.conflicts && !replace ? ` ${p.conflicts} file(s) here differ from the bundle's and are kept.` : '') +
141
+ (p.conflicts && replace ? ` ${p.conflicts} file(s) here that differ are moved into the backup and replaced.` : ''),
142
+ account: `war.app account ${me}`,
143
+ bundleAccount: p.accountId,
144
+ accountMatches: p.accountMatches,
145
+ bundleCreatedAt: p.createdAt,
146
+ saltOnServer: p.salt,
147
+ stores: p.stores,
148
+ totals: p.totals,
149
+ conflicts: p.conflicts,
150
+ sha256: source.sha256,
151
+ },
152
+ },
153
+ state: { me, replace: replace === true, bundle, source },
154
+ };
155
+ },
156
+ async execute({ me, replace, bundle, source }) {
157
+ await requireApprovedAccount(ctx, writeAccount(me));
158
+ let r;
159
+ try {
160
+ r = await applyImport(ctx.dataDir, bundle, { signedIn: me, replace });
161
+ }
162
+ catch (e) {
163
+ if (e instanceof StateBundleError)
164
+ throw new McpToolError(e.message, { kind: 'unknown' });
165
+ throw new McpToolError(`The import stopped part way (${e.code ?? 'write failed'}); import the same bundle again to finish it.`, {
166
+ kind: 'unknown',
167
+ });
168
+ }
169
+ const released = await source.release();
170
+ return {
171
+ status: 'imported',
172
+ outcome: 'confirmed',
173
+ ...r,
174
+ blobDeleted: released.deleted === true,
175
+ note: 'Imported. The bundle held the salt behind your hashed history: delete the local file too. Finished ' +
176
+ 'games not yet processed here get their pass from warapp_backfill_history.',
177
+ };
178
+ },
179
+ });
180
+ }
181
+ function registerBackfillTool(server, ctx, env) {
182
+ server.registerTool('warapp_backfill_history', {
183
+ title: 'Process more finished war.app games at once',
184
+ _meta: mintMeta('change', ['backfill my war.app history', 'process finished games', 'catch up past games']),
185
+ description: 'Give the end-of-game pass to up to `limit` (default 10, at most 25) of your finished war.app games not yet ' +
186
+ 'processed, newest first: each game\'s history is read ONCE from GameFeed (never again, whatever comes of ' +
187
+ 'it) and kept name-free for the opponent profiles, map records and lessons — what warapp_my_games does two ' +
188
+ 'games per call. `window` widens how many of your newest finished games are considered (default 250, at ' +
189
+ `most ${MAX_FINISHED_RECORDS}). Reports what it processed and how many remain; safe to call again until ` +
190
+ '`remaining` is 0. Writes only this server\'s state and never writes to war.app. ' +
191
+ BRIDGE_NOTE,
192
+ annotations: toolAnnotations({ title: 'Backfill finished war.app games', readOnly: false, destructive: false, idempotent: true, openWorld: true }),
193
+ inputSchema: z.object({
194
+ limit: z.number().int().min(1).max(BACKFILL_MAX).optional().describe(`Games to process this call (default ${BACKFILL_DEFAULT}, max ${BACKFILL_MAX}).`),
195
+ window: z
196
+ .number()
197
+ .int()
198
+ .min(1)
199
+ .max(MAX_FINISHED_RECORDS)
200
+ .optional()
201
+ .describe(`How many of your newest finished games to consider (default ${sweepWindow()}, max ${MAX_FINISHED_RECORDS}).`),
202
+ }),
203
+ }, async ({ limit, window }) => {
204
+ if (!ctx.dataDir)
205
+ refuse('This server has no data directory, so no history can be kept.', 'Nothing to do here.');
206
+ if (!profileEnabled(env))
207
+ refuse('The end-of-game pass is off (WARAPP_PLAYER_PROFILE=off), so nothing was read.', 'Turn profiling on to backfill.');
208
+ const { me, games } = await fetchMyGames(ctx);
209
+ const token = await ctx.myInviteToken().catch(() => undefined);
210
+ if (token === undefined)
211
+ throw accountUnknown(ctx, 'nothing was read');
212
+ const ids = finishedGamesOf(games, me);
213
+ const size = Math.min(window ?? sweepWindow(), MAX_FINISHED_RECORDS);
214
+ const r = await sweepFinished({ client: ctx.client, dataDir: ctx.dataDir, env }, token, ids, {
215
+ limit: limit ?? BACKFILL_DEFAULT,
216
+ window: size,
217
+ });
218
+ return respond(undefined, ['compact'], () => ({
219
+ processed: r.processed,
220
+ processedCount: r.processed.length,
221
+ remaining: r.pending,
222
+ finishedGames: ids.length,
223
+ window: size,
224
+ ...(ids.length > size ? { outsideWindow: ids.length - size } : {}),
225
+ }));
226
+ });
227
+ }
@@ -6,6 +6,7 @@ import { neutralizeSeats, seatEndRules, staticSeats } from '../analysis/static-s
6
6
  import { carriesTeam } from '../teams.js';
7
7
  import { opponentReinforcement } from './card-advice.js';
8
8
  import { boardCardsInEffect } from './card-effects.js';
9
+ import { commerceDeployOf } from './commerce-deploy.js';
9
10
  export function stressOpponents(input) {
10
11
  const { graph, map, game, me, seen, turn, settings, hand, info } = input;
11
12
  // #270: a player out of the game whose seat no AI plays deploys and attacks nothing: its
@@ -18,7 +19,9 @@ export function stressOpponents(input) {
18
19
  : undefined;
19
20
  // #253: what the army cap leaves me and what I earn before the cut.
20
21
  const incomeOnBoard = incomeDetail(graph, board, me.id, game.settings);
21
- const income = incomeOnBoard.income;
22
+ // #332: in a commerce game, the armies my gold buys (as warapp_plan_turn and warapp_submit_turn have it).
23
+ const commerce = commerceDeployOf(game, me, info, incomeOnBoard.income);
24
+ const income = commerce ? commerce.armies : incomeOnBoard.income;
22
25
  const earnedIncome = incomeOnBoard.cap ? incomeOnBoard.cap.uncapped : income;
23
26
  // PLAN-TEAMS D3: the cards in effect the decoder is sure of.
24
27
  const effect = boardCardsInEffect(game, me, turn, info);
@@ -79,5 +82,5 @@ export function stressOpponents(input) {
79
82
  // (two at least; enemy_deploy is a what-if, not the game's standing).
80
83
  const rivals = opponents.filter((o) => inView.has(o.id));
81
84
  const leader = teams.size === 0 && rivals.length >= 2 && rivals.every((o) => earnedIncome > estimateOf(o.id));
82
- return { board, seats, tracks, incomeOnBoard, income, earnedIncome, effect, estimates, estimateOf, friend, opponents, teams, inView, leader };
85
+ return { board, seats, tracks, incomeOnBoard, income, earnedIncome, effect, estimates, estimateOf, friend, opponents, teams, inView, leader, commerce };
83
86
  }
@@ -144,14 +144,21 @@ export function safeHeadroom(input) {
144
144
  return [];
145
145
  }
146
146
  }
147
+ /** #306: a border whose fall costs more than the tile: a held bonus, bonus income behind it, or a breach's income. */
148
+ export const protectsSomething = (r) => r.bonuses.length > 0 || r.behindIncome > 0 || r.breach.income > 0;
147
149
  /**
148
- * The headroom table as the tools show it: names beside ids, each row with whether it is below my income.
150
+ * The headroom table as the tools show it: names beside ids, each row with whether it is below my income
151
+ * and (#306, given `estimateOf`) below its opponent's own deploy estimate (`belowOpponentEstimate`, with
152
+ * `opponentEstimate`; absent when that opponent has none) — for a leader my income flags every row. The
153
+ * compact view (#306) lists the rows that protect something first (`protectsSomething`), each part weakest
154
+ * first, so bare 1-army tiles at headroom 0 no longer crowd out the borders that decide the turn.
149
155
  * `mayBeTeammate` (the teams unknown, `resolveTeams`' `known: false`): every row says its opponent may be a teammate.
150
156
  */
151
- export function headroomView(rows, map, myIncome, full, mayBeTeammate = false) {
157
+ export function headroomView(rows, map, myIncome, full, mayBeTeammate = false, estimateOf) {
152
158
  const name = namer(map);
153
159
  const bonusName = new Map(map.bonuses.map((b) => [b.id, b.name]));
154
- return rows.slice(0, full ? rows.length : HEADROOM_COMPACT).map((r) => ({
160
+ const shown = full ? rows : [...rows.filter(protectsSomething), ...rows.filter((r) => !protectsSomething(r))].slice(0, HEADROOM_COMPACT);
161
+ return shown.map((r) => ({
155
162
  territory: name(r.territory),
156
163
  armies: r.armies,
157
164
  deploy: r.deploy,
@@ -159,6 +166,7 @@ export function headroomView(rows, map, myIncome, full, mayBeTeammate = false) {
159
166
  from: name(r.from),
160
167
  ...(r.firstMover ? { needsFirstMove: r.firstMover === 'me' ? 'you' : 'opponent' } : {}),
161
168
  belowMyIncome: r.deploy !== null && r.deploy < myIncome,
169
+ ...((est) => (est === undefined ? {} : { opponentEstimate: est, belowOpponentEstimate: r.deploy !== null && r.deploy < est }))(estimateOf?.(r.opponent)),
162
170
  bonuses: r.bonuses.map((b) => ({ id: b.id, name: bonusName.get(b.id) ?? String(b.id), value: b.value })),
163
171
  behind: r.behind.map(name),
164
172
  behindIncome: r.behindIncome,
@@ -6,8 +6,8 @@
6
6
  //
7
7
  // Read-only: it plans as warapp_plan_turn would (livePlanSetup, award not read and not written) and writes
8
8
  // nothing — no board cache, no award, no outlook. UNVERIFIED live: the teams (V1, via resolveTeams), the
9
- // teammates' entered orders (V5) and picks (V5/V6), what a move onto a teammate does (V7) and how the team hand
10
- // is keyed (V8). The pure parts are src/analysis/team-brief.ts.
9
+ // teammates' entered orders (V5) and picks (V5/V6) and what a move onto a teammate does (V7); how the team hand
10
+ // is keyed is verified (V8, #310). The pure parts are src/analysis/team-brief.ts.
11
11
  import { McpToolError } from '@chrischall/mcp-utils';
12
12
  import { z } from 'zod';
13
13
  import { readAward } from '../analysis/award.js';
@@ -4,7 +4,7 @@
4
4
  //
5
5
  // UNVERIFIED live: GameFeed's player `team` (V1; without it the team comes from GetMyGames' GameInfoPlayer,
6
6
  // read from the bundle), the teammate orders in LatestGameInfo (V5), GetTerritoryPicks with a teammate's id
7
- // (V6) and how a team's hand is keyed (#163, V8). Every read here is tolerant: what cannot be read is
7
+ // (V6). How a team's hand is keyed is VERIFIED (V8, #310). Every read here is tolerant: what cannot be read is
8
8
  // unknown (`null`), never an error — except a game that is not a team game, which is refused.
9
9
  import { McpToolError } from '@chrischall/mcp-utils';
10
10
  import { z } from 'zod';
@@ -30,7 +30,7 @@ const NOTES = [
30
30
  'means unknown — none entered, or war.app did not send them — never "nothing entered".',
31
31
  "While distributing, a teammate's picks not in the board are asked with GetTerritoryPicks and the teammate's id " +
32
32
  '(UNVERIFIED, V6); a refusal reads as unknown.',
33
- "The team's hand is every card under me and my teammates; how war.app keys a team's hand is UNVERIFIED (#163).",
33
+ "The team's hand is every card under me and my teammates: war.app keeps each player's cards under that player's id (`heldBy`), and the limit is the team's (V8, verified).",
34
34
  ];
35
35
  const DISTRIBUTING = 'DistributingTerritories';
36
36
  const BOARD_STATES = new Set(['Playing', DISTRIBUTING]);
@@ -136,6 +136,10 @@ export function registerTeamTool(server, ctx) {
136
136
  });
137
137
  }
138
138
  const owners = handOwners(game, me);
139
+ const heldBy = new Map([me, ...mates].flatMap((p) => {
140
+ const id = inGameOf(p);
141
+ return id === undefined ? [] : [[id, p.id]];
142
+ }));
139
143
  // No card in play is known from the settings, board or not; `null` is a hand that could not be read.
140
144
  const hand = game.settings && !rules.inPlay.length
141
145
  ? { inPlay: false }
@@ -143,7 +147,12 @@ export function registerTeamTool(server, ctx) {
143
147
  ? null
144
148
  : {
145
149
  readable: handReadable(info, owners),
146
- cards: readHand(info, owners).map((c) => ({ id: c.id, name: c.name, ...(c.armies !== undefined ? { armies: c.armies } : {}) })),
150
+ // V8 (#310): war.app keeps each player's cards under that player's id; the team's hand is all of
151
+ // them. `heldBy` is the GameFeed id of the player whose entry holds the card.
152
+ cards: readHand(info, owners).map((c) => {
153
+ const holder = c.owner !== undefined ? heldBy.get(c.owner) : undefined;
154
+ return { id: c.id, name: c.name, ...(c.armies !== undefined ? { armies: c.armies } : {}), ...(holder !== undefined ? { heldBy: holder } : {}) };
155
+ }),
147
156
  ...(rules.maxCardsHold !== undefined ? { limit: rules.maxCardsHold } : {}),
148
157
  };
149
158
  const chatMeOf = identity;