@chrischall/warapp-mcp 0.0.0 → 0.2.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 (194) hide show
  1. package/.claude-plugin/marketplace.json +4 -4
  2. package/.claude-plugin/plugin.json +2 -2
  3. package/README.md +211 -9
  4. package/dist/analysis/accept-surrender.js +56 -0
  5. package/dist/analysis/award.js +159 -0
  6. package/dist/analysis/bonuses.js +98 -0
  7. package/dist/analysis/breach.js +62 -0
  8. package/dist/analysis/calibrate.js +239 -0
  9. package/dist/analysis/card-support.js +329 -0
  10. package/dist/analysis/card-threats.js +234 -0
  11. package/dist/analysis/cards-in-effect.js +130 -0
  12. package/dist/analysis/chains.js +59 -0
  13. package/dist/analysis/chokepoints.js +140 -0
  14. package/dist/analysis/combat.js +231 -0
  15. package/dist/analysis/commander-safety.js +149 -0
  16. package/dist/analysis/commitments.js +338 -0
  17. package/dist/analysis/exchange.js +155 -0
  18. package/dist/analysis/finished-game.js +136 -0
  19. package/dist/analysis/game-lessons.js +217 -0
  20. package/dist/analysis/graph.js +82 -0
  21. package/dist/analysis/guard-off.js +54 -0
  22. package/dist/analysis/guess.js +351 -0
  23. package/dist/analysis/headroom.js +241 -0
  24. package/dist/analysis/hold-diff.js +64 -0
  25. package/dist/analysis/how-lost.js +130 -0
  26. package/dist/analysis/index.js +14 -0
  27. package/dist/analysis/local-deploy.js +179 -0
  28. package/dist/analysis/lookahead.js +108 -0
  29. package/dist/analysis/opponent-profile.js +552 -0
  30. package/dist/analysis/opponents.js +1253 -0
  31. package/dist/analysis/outlook.js +695 -0
  32. package/dist/analysis/overrides.js +60 -0
  33. package/dist/analysis/picks.js +1879 -0
  34. package/dist/analysis/plan/after-leftover.js +140 -0
  35. package/dist/analysis/plan/cap-spend.js +242 -0
  36. package/dist/analysis/plan/captures.js +1195 -0
  37. package/dist/analysis/plan/commander.js +236 -0
  38. package/dist/analysis/plan/completed.js +29 -0
  39. package/dist/analysis/plan/conceded-out.js +131 -0
  40. package/dist/analysis/plan/estimates.js +715 -0
  41. package/dist/analysis/plan/guard-off.js +232 -0
  42. package/dist/analysis/plan/holds.js +1631 -0
  43. package/dist/analysis/plan/leftover.js +760 -0
  44. package/dist/analysis/plan/move-order.js +319 -0
  45. package/dist/analysis/plan/orders.js +317 -0
  46. package/dist/analysis/plan/relations.js +702 -0
  47. package/dist/analysis/plan/report.js +672 -0
  48. package/dist/analysis/plan/shared.js +1405 -0
  49. package/dist/analysis/plan/stand-still.js +823 -0
  50. package/dist/analysis/plan/state.js +44 -0
  51. package/dist/analysis/plan/strike.js +1416 -0
  52. package/dist/analysis/plan/targets.js +651 -0
  53. package/dist/analysis/plan/team.js +299 -0
  54. package/dist/analysis/plan/threats.js +1001 -0
  55. package/dist/analysis/plan/transfers.js +328 -0
  56. package/dist/analysis/plan/util.js +5 -0
  57. package/dist/analysis/plan/vacated.js +285 -0
  58. package/dist/analysis/planner.js +2927 -0
  59. package/dist/analysis/player-record.js +144 -0
  60. package/dist/analysis/player.js +268 -0
  61. package/dist/analysis/profile.js +347 -0
  62. package/dist/analysis/relations.js +1030 -0
  63. package/dist/analysis/schedule.js +88 -0
  64. package/dist/analysis/since-last.js +50 -0
  65. package/dist/analysis/static-seats.js +71 -0
  66. package/dist/analysis/stress.js +584 -0
  67. package/dist/analysis/team-brief.js +151 -0
  68. package/dist/analysis/tripwire.js +644 -0
  69. package/dist/analysis/turn-sim.js +259 -0
  70. package/dist/analysis/whereabouts.js +1112 -0
  71. package/dist/board.js +105 -0
  72. package/dist/bundle.js +121082 -36148
  73. package/dist/calibration-source.js +75 -0
  74. package/dist/cards.js +435 -0
  75. package/dist/chat-cursor.js +135 -0
  76. package/dist/chat.js +265 -0
  77. package/dist/client.js +439 -0
  78. package/dist/config.js +62 -0
  79. package/dist/direct/link.js +102 -0
  80. package/dist/direct/session.js +267 -0
  81. package/dist/direct/transport.js +424 -0
  82. package/dist/finished-store.js +357 -0
  83. package/dist/guess-salt.js +65 -0
  84. package/dist/hosted.js +24 -0
  85. package/dist/index.js +33 -0
  86. package/dist/join-color.js +140 -0
  87. package/dist/lessons-store.js +356 -0
  88. package/dist/live.js +287 -0
  89. package/dist/map-details.js +127 -0
  90. package/dist/map-stats.js +160 -0
  91. package/dist/map-store.js +242 -0
  92. package/dist/move-order.js +141 -0
  93. package/dist/my-games.js +218 -0
  94. package/dist/normalize.js +443 -0
  95. package/dist/notifications.js +143 -0
  96. package/dist/open-games.js +537 -0
  97. package/dist/outlook-log.js +165 -0
  98. package/dist/path-lock.js +22 -0
  99. package/dist/pick-list.js +193 -0
  100. package/dist/player-record-store.js +231 -0
  101. package/dist/player-states.js +31 -0
  102. package/dist/profile-store.js +727 -0
  103. package/dist/protocol/bundle.js +375 -0
  104. package/dist/protocol/codec.js +556 -0
  105. package/dist/protocol/decoded.js +12 -0
  106. package/dist/protocol/interp.js +1904 -0
  107. package/dist/protocol/methods.js +615 -0
  108. package/dist/protocol/rpc.js +202 -0
  109. package/dist/push/listener.js +393 -0
  110. package/dist/push/packets.js +66 -0
  111. package/dist/push/socketio.js +333 -0
  112. package/dist/push/websocket.js +179 -0
  113. package/dist/redact.js +62 -0
  114. package/dist/relations-store.js +242 -0
  115. package/dist/replay.js +227 -0
  116. package/dist/scalars.js +28 -0
  117. package/dist/scout.js +346 -0
  118. package/dist/stats.js +291 -0
  119. package/dist/strategy/card-clock.js +185 -0
  120. package/dist/strategy/map-notes.js +128 -0
  121. package/dist/strategy/notes.js +2223 -0
  122. package/dist/surrender-pending.js +126 -0
  123. package/dist/team-cards.js +84 -0
  124. package/dist/team-orders.js +150 -0
  125. package/dist/teams.js +19 -0
  126. package/dist/tools/accept-surrender.js +311 -0
  127. package/dist/tools/award.js +206 -0
  128. package/dist/tools/begin-turn.js +162 -0
  129. package/dist/tools/board.js +77 -0
  130. package/dist/tools/card-advice.js +256 -0
  131. package/dist/tools/card-effects.js +49 -0
  132. package/dist/tools/card-plays.js +434 -0
  133. package/dist/tools/card-support-advice.js +140 -0
  134. package/dist/tools/chat-inbox.js +158 -0
  135. package/dist/tools/chat-read-mark.js +179 -0
  136. package/dist/tools/chat.js +525 -0
  137. package/dist/tools/check-plan.js +689 -0
  138. package/dist/tools/commander-check.js +103 -0
  139. package/dist/tools/commitments.js +216 -0
  140. package/dist/tools/common.js +143 -0
  141. package/dist/tools/diplomacy.js +342 -0
  142. package/dist/tools/end-of-game.js +384 -0
  143. package/dist/tools/game.js +151 -0
  144. package/dist/tools/guess-view.js +56 -0
  145. package/dist/tools/healthcheck.js +90 -0
  146. package/dist/tools/hints.js +34 -0
  147. package/dist/tools/how-lost.js +154 -0
  148. package/dist/tools/index.js +152 -0
  149. package/dist/tools/join-game.js +327 -0
  150. package/dist/tools/leave-game.js +181 -0
  151. package/dist/tools/live-context.js +339 -0
  152. package/dist/tools/live.js +404 -0
  153. package/dist/tools/map-details.js +88 -0
  154. package/dist/tools/map-stats.js +130 -0
  155. package/dist/tools/map.js +141 -0
  156. package/dist/tools/my-games.js +193 -0
  157. package/dist/tools/notifications.js +484 -0
  158. package/dist/tools/open-games.js +104 -0
  159. package/dist/tools/opponents.js +163 -0
  160. package/dist/tools/order-options.js +135 -0
  161. package/dist/tools/past-games.js +94 -0
  162. package/dist/tools/picks.js +305 -0
  163. package/dist/tools/profile-hook.js +156 -0
  164. package/dist/tools/profile-opponents.js +121 -0
  165. package/dist/tools/profile-reads.js +99 -0
  166. package/dist/tools/push.js +445 -0
  167. package/dist/tools/relations.js +611 -0
  168. package/dist/tools/resolve.js +45 -0
  169. package/dist/tools/route.js +36 -0
  170. package/dist/tools/scout.js +87 -0
  171. package/dist/tools/session.js +163 -0
  172. package/dist/tools/strategy.js +257 -0
  173. package/dist/tools/stress-opponents.js +83 -0
  174. package/dist/tools/surrender-pending.js +74 -0
  175. package/dist/tools/surrender.js +247 -0
  176. package/dist/tools/survival.js +189 -0
  177. package/dist/tools/team-brief.js +266 -0
  178. package/dist/tools/team-source.js +222 -0
  179. package/dist/tools/team.js +178 -0
  180. package/dist/tools/turn.js +2825 -0
  181. package/dist/tools/uncommit.js +160 -0
  182. package/dist/tools/where.js +300 -0
  183. package/dist/tools/write-kit.js +164 -0
  184. package/dist/transport-bridge.js +33 -0
  185. package/dist/trend.js +577 -0
  186. package/dist/version.js +4 -0
  187. package/manifest.json +194 -4
  188. package/mint.yaml +106 -14
  189. package/package.json +11 -6
  190. package/server.json +40 -3
  191. package/skills/warapp-api/SKILL.md +95 -4
  192. package/skills/warapp-api/references/scout.mjs +348 -0
  193. package/skills/warapp-api/scripts/warapp.sh +69 -8
  194. package/skills/warapp-mcp/SKILL.md +1096 -21
@@ -0,0 +1,689 @@
1
+ // The plan stress test as a tool: a list of orders (the shape warapp_plan_turn returns and
2
+ // warapp_submit_turn takes) is carried out on the live board against the single replies each
3
+ // opponent could make with its estimated deploy, and the replies that cost something are
4
+ // reported, worst first (src/analysis/stress.ts, on the turn resolver src/analysis/turn-sim.ts).
5
+ // Read-only on war.app, and it writes nothing: not the board cache either.
6
+ import { McpToolError } from '@chrischall/mcp-utils';
7
+ import { z } from 'zod';
8
+ import { stressPlan } from '../analysis/stress.js';
9
+ import { neutralizeSeats, seatTerritories, staticSeats } from '../analysis/static-seats.js';
10
+ import { handOwners } from './card-advice.js';
11
+ import { sanctionMyIncome } from './card-effects.js';
12
+ import { cardTypeByName, cardTypeName, normalizeGuid, readHand } from '../cards.js';
13
+ import { claimedCardUses, claimedCardWarning, teamCardClaims, teamHandLeft, unclaimedFirst } from '../team-cards.js';
14
+ import { boardStateFromLive } from '../live.js';
15
+ import { withTeammateOrders } from '../team-orders.js';
16
+ import { assumedWarning, awardView, loadAward, openingThreat } from './award.js';
17
+ import { gameIdArg, graphOf, namer, readAnnotations, respond, untrustedDescription, untrustedText, viewArg } from './common.js';
18
+ import { lookupMeta } from './hints.js';
19
+ import { HEADROOM_COMPACT, headroomView, readTripwires, safeHeadroom, teamsOf, tripwireWarnings, untrustedDeploy } from './survival.js';
20
+ import { loadLiveGame } from './live-context.js';
21
+ import { BRIDGE_NOTE, playerArg, resolveMe } from './live.js';
22
+ import { mapOf } from './map.js';
23
+ import { resolveTerritory } from './resolve.js';
24
+ import { BELOW_PLAN_BASIS, boardHistory, bordersBelowPlan, currentTurn, truceRelations, friendsOf, guardOffWarnings, modsWarning, plannerSettings, requirePlayingSeat, requireTurnPhase, turnOrdersArg, } from './turn.js';
25
+ import { resolveTeamsFor } from './team-source.js';
26
+ import { stressOpponents } from './stress-opponents.js';
27
+ import { COMMANDER_SIZING, commanderCheckOn } from './commander-check.js';
28
+ const VIEWS = ['compact', 'full'];
29
+ const MAX_ENEMY_DEPLOY = 10_000;
30
+ /** Replies listed beside the worst one on the compact view; the full view lists the stress test's own maximum. */
31
+ const COMPACT_OTHERS = 2;
32
+ /** The most territories or bonuses any one list names; the rest are a count. */
33
+ const LIST_MAX = 10;
34
+ const ORDER_PRIORITY = cardTypeByName('Order Priority');
35
+ /** Card plays that change the board this test does not simulate, each with what the test does instead. */
36
+ const UNSIMULATED_CARDS = new Map([
37
+ [cardTypeByName('Bomb'), (on) => `The Bomb${on} is not simulated: the test fights at its armies before the Bomb halves them.`],
38
+ [cardTypeByName('Emergency Blockade'), (on) => `The Emergency Blockade${on} is not simulated: the test keeps it yours, armies unchanged.`],
39
+ ]);
40
+ /** #274: the card plays the commander check reads (an Airlift simulated, the others named on its territory). */
41
+ const COMMANDER_CARD_KINDS = new Map([
42
+ [cardTypeByName('Airlift'), 'Airlift'],
43
+ [cardTypeByName('Blockade'), 'Blockade'],
44
+ [cardTypeByName('Emergency Blockade'), 'EmergencyBlockade'],
45
+ [cardTypeByName('Gift'), 'Gift'],
46
+ ]);
47
+ /** What the stress test does not try, said with every answer so "safe" is never read as more. */
48
+ export const CHECK_PLAN_NOT_COVERED = [
49
+ 'stacks hidden by fog, armies included (see blindBorders), and opponents with nothing in view (see unseenOpponents)',
50
+ 'an opponent that deploys more than the estimate (raise enemy_deploy to test it)',
51
+ 'a deploy split over several stacks',
52
+ 'two opponents together other than on one of your territories, and two free-for-all opponents together at all unless you lead (see leader)',
53
+ 'under Multi-Attack, any chain of attacks but the one most damaging per stack',
54
+ 'cards, apart from your own Order Priority',
55
+ ];
56
+ export function registerCheckPlanTool(server, ctx) {
57
+ server.registerTool('warapp_check_plan', {
58
+ title: 'Stress-test a planned turn in a war.app game',
59
+ description: untrustedDescription('Stress-test a list of orders for your turn in an in-progress war.app (Warzone) game before you submit it: ' +
60
+ 'the orders (the `orders` array warapp_plan_turn returns, or your own edit of it) are carried out on the ' +
61
+ 'live board, turn rules included (deploys first, then attacks and transfers interleaved in the zigzag move ' +
62
+ 'order; each order an attack or a transfer by who holds its target when it runs; kill rates, the guard ' +
63
+ 'army, each army moving once, commanders), against the replies each opponent could make with ONE deploy: ' +
64
+ 'its whole estimated deploy on one stack and an attack on a territory you hold or are about to take, its ' +
65
+ 'whole deploy on a territory you attack, or every stack attacking at once; a stack you attack moving out ' +
66
+ 'first (a dodge: into its own territory, or a neutral or one of yours it can take — `dodges` lists each ' +
67
+ 'with the armies that got away and what your strike then hit); two opponents striking one of your ' +
68
+ 'territories together (teammates always; any two in a free-for-all when you lead — `jointFalls` gives the ' +
69
+ 'armies each such territory needs to hold); and, under Multi-Attack, each stack\'s most damaging chain ' +
70
+ 'of captures. Under Local Deployment each deploy is bounded by where its bonus armies may land. Each ' +
71
+ 'reply is tried with you moving first and with the opponent moving first unless `first_mover` says ' +
72
+ 'which. A reply that keeps alive a player your orders finish off is `eliminationsFailed`. Returns `safe` (true, ' +
73
+ 'false, or null when no reply could be tried), a one-line `summary`, the `worst` reply and ' +
74
+ '`otherReplies` that cost you something (territories `lost`, captures that fail or are `retaken`, ' +
75
+ 'bonuses and income lost, your commander), everything `atRisk` to some single reply (only one of them ' +
76
+ 'happens: one deploy, one place), what your orders do unanswered (`plan`: captures, attacks that fail, ' +
77
+ 'orders that send fewer armies than ordered or none), `blindBorders`: your territories next to the ' +
78
+ 'fog, where nothing could be tested, and `exposedNextTurn`: territories no enemy stack touches today ' +
79
+ 'that one could take next turn by first taking the territory in between (yours or neutral), each with ' +
80
+ 'the armies it would need to hold, if you add nothing next turn. Decide on the fields (`safe`, ' +
81
+ '`worst`, `exposedNextTurn`), not on the wording of `summary`, which may change. With your commander on the ' +
82
+ 'board, `commander` says where it stands after the orders, the armies there and `needs`: the armies its ' +
83
+ 'territory needs to survive every reply tried, by the check warapp_submit_turn refuses on (each reply at the larger ' +
84
+ 'of the estimate and your income, enemy_deploy only raising it, both move orders, your Airlifts counted); when a ' +
85
+ 'reply kills it, the summary starts with it. Exact with no luck and ' +
86
+ 'straight rounding; otherwise battles are resolved at their expectation and `exact` is false. It does not ' +
87
+ `try: ${CHECK_PLAN_NOT_COVERED.join('; ')}. When this server kept your pick list, \`award\` says what the ` +
88
+ "award of picks showed (as in warapp_plan_turn): the opponent's proven starts stand on the board the " +
89
+ 'orders are tried on even while fogged, and `award.firstMover` is who moves first this turn under a ' +
90
+ '`Cycle` move order (not NoLuckCycle, where play speed sets it) — pass it as `first_mover` to judge by it; both orders are still tried by default. ' +
91
+ '`headroom` lists, weakest first, each border of yours with the smallest single deploy by a neighbouring opponent that ' +
92
+ 'takes it after these orders, and what falls with it (the bonuses it breaks, the territories behind it and their bonus ' +
93
+ 'income). An opponent whose estimate one observation broke (see warapp_plan_turn) is tried at the larger of what it ' +
94
+ 'implied and your own income (`enemyDeploy` source `untrusted`), said in the first warning. ' +
95
+ '`belowPlan` compares these orders with the default plan made now on the same board (warapp_plan_turn with no ' +
96
+ 'options, the award of picks read as it reads it), or with its border guess when the deploys given are the ' +
97
+ "guess's (`belowPlanAgainst`: plan or guess): each border they leave below what that plan leaves standing there, " +
98
+ 'with `planLeaves`, `left` and `short`, the largest shortfall first (empty: none). `planLeaves` carries the ' +
99
+ "plan's surplus, so a border named may still hold (see `headroom`); orders warapp_plan_turn made with options " +
100
+ 'differ from the default plan by design. ' +
101
+ 'In a free-for-all with a truce in force (the agreement ledger), its partner is still tried — `safe` is safe ' +
102
+ 'against a break too — each reply that attacks a territory a truce covers is marked `breaksTruce`, and ' +
103
+ '`safeIfTruceHolds` is the verdict over the other replies (null when every reply is a break). ' +
104
+ `Refuses outside a turn phase. ${BRIDGE_NOTE} Read-only on ` +
105
+ 'war.app; it never submits orders.'),
106
+ _meta: lookupMeta(['check my plan', 'stress test my orders', 'what can my opponent do to this turn', 'is this plan safe']),
107
+ annotations: readAnnotations('Stress-test a war.app turn'),
108
+ inputSchema: z.object({
109
+ game_id: gameIdArg,
110
+ player: playerArg,
111
+ orders: turnOrdersArg.describe('The orders to test, in the order you would submit them: deploys and moves by territory id or name (the ' +
112
+ '`orders` array warapp_plan_turn returns). An Order Priority card play makes your first order run before ' +
113
+ "everyone's; other card plays and discards are ignored by the test (a Bomb or Emergency Blockade is named " +
114
+ 'in `warnings` as not simulated; in a team game, a card your teammate has ' +
115
+ "already entered is warned of). A move's options (mode, percent, commander, " +
116
+ 'attack_teammates) are carried out as war.app would.'),
117
+ enemy_deploy: z.coerce
118
+ .number()
119
+ .int()
120
+ .min(0)
121
+ .max(MAX_ENEMY_DEPLOY)
122
+ .optional()
123
+ .describe('Armies every opponent is assumed to deploy this turn. Default, per opponent: the estimate ' +
124
+ 'warapp_plan_turn uses (base income plus the bonuses it visibly holds, or its observed or tracked ' +
125
+ 'income when larger; in a 1v1 that started even, an opponent bordering the fog at least your own income; while an ' +
126
+ 'observation has made its estimate untrusted, the larger of what it implied and your own income). ' +
127
+ 'Income in the fog is unseen, so raise it to test a stronger opponent.'),
128
+ first_mover: z
129
+ .enum(['me', 'opponent'])
130
+ .optional()
131
+ .describe('Who moves first this turn, when you know (under cyclic move order it alternates every turn). Omit to ' +
132
+ 'try both.'),
133
+ view: viewArg(VIEWS, `compact (default) gives the verdict, the worst reply and up to ${COMPACT_OTHERS} more; "full" adds every ` +
134
+ 'reply listed, each order\'s result unanswered and the rules assumed.'),
135
+ }),
136
+ }, async ({ game_id, player, orders, enemy_deploy, first_mover, view }) => {
137
+ const feed = await ctx.client.getGame(game_id, { settings: true });
138
+ requireTurnPhase(feed);
139
+ const map = mapOf(feed);
140
+ const seat = await resolveMe(ctx, feed.players, player);
141
+ requirePlayingSeat(feed, seat);
142
+ // The teams: GameFeed's, else the game list's (asked once per game, kept).
143
+ const { game, me, source: teamSource, known: teamsKnown } = await resolveTeamsFor(ctx, feed, seat);
144
+ const turn = currentTurn(game);
145
+ const [{ territories, info }, history] = await Promise.all([loadLiveGame(ctx, game), boardHistory(ctx, game, me, turn)]);
146
+ const graph = graphOf(map);
147
+ // As warapp_plan_turn does (#166): the opponent's starts the award of picks proves stand on
148
+ // the board the orders are tried on; the history and tracks stay what war.app showed.
149
+ const seen = withTeammateOrders(boardStateFromLive(territories, me, game.players), info, me, game.players);
150
+ const award = await loadAward(ctx.dataDir, game, me, seen, turn);
151
+ // #270: a player out of the game whose seat no AI plays deploys and attacks nothing: its
152
+ // territories are neutrals here (static armies), and it is tried as no opponent.
153
+ const seats = staticSeats(game.players, game.endRules, me.id);
154
+ const board = neutralizeSeats(award?.board ?? seen, seats);
155
+ const opening = openingThreat(award, game, graph, seen, turn);
156
+ const settings = plannerSettings(game.settings);
157
+ const deploys = [];
158
+ const moves = [];
159
+ /** Options the game would refuse (#165): the orders are still tried, and the warning says so. */
160
+ const refused = new Set();
161
+ const s = game.settings;
162
+ // A team shares one hand (#163): mine and my teammates' cards.
163
+ const hand = readHand(info, handOwners(game, me));
164
+ // G3: the cards my teammates' entered orders already play or discard (V5, unverified live), warned of as
165
+ // warapp_submit_turn does; a card named by its type is taken as one nobody entered when there is one.
166
+ const { claimed } = teamHandLeft(hand, teamCardClaims(seen.teammateOrders, friendsOf(game.players, me)));
167
+ const uses = [];
168
+ const useCard = (ref, kind) => {
169
+ const guid = normalizeGuid(ref.trim());
170
+ const type = guid === undefined ? cardTypeByName(ref) : undefined;
171
+ const card = unclaimedFirst(hand, claimed).find((c) => (guid !== undefined ? c.id === guid : c.type === type) && !uses.some((u) => u.card.id === c.id));
172
+ if (card)
173
+ uses.push({ card, kind });
174
+ };
175
+ let orderPriority = false;
176
+ const airlifts = [];
177
+ const cardTargets = [];
178
+ const ignored = [];
179
+ const unsimulatedCards = [];
180
+ const friends = friendsOf(game.players, me);
181
+ const mine = new Set(board.territories.flatMap((t) => (t.owner.kind === 'player' && t.owner.playerId === me.id ? [t.territoryId] : [])));
182
+ for (const o of orders) {
183
+ if (o.kind === 'deploy') {
184
+ const t = resolveTerritory(map, o.territory);
185
+ if (!mine.has(t.id)) {
186
+ throw new McpToolError(`${untrustedText(t.name)} (${t.id}) is not yours on the live board, so nothing can be deployed there.`, {
187
+ hint: 'Deploy only on territories you hold; warapp_get_live_board lists them.',
188
+ });
189
+ }
190
+ deploys.push({ territoryId: t.id, armies: o.armies });
191
+ }
192
+ else if (o.kind === 'move') {
193
+ // As warapp_submit_turn does (#165): attacking teammates needs a teammate.
194
+ if (o.attack_teammates && !friends.size) {
195
+ const [from, to] = [resolveTerritory(map, o.from), resolveTerritory(map, o.to)];
196
+ throw new McpToolError(`${untrustedText(from.name)} (${from.id}) → ${untrustedText(to.name)} (${to.id}) sets attack_teammates, but you have no teammates in this game.`, { hint: 'Leave attack_teammates out: outside a team game every territory not yours is attacked anyway.' });
197
+ }
198
+ moves.push({
199
+ from: resolveTerritory(map, o.from).id,
200
+ to: resolveTerritory(map, o.to).id,
201
+ armies: o.armies,
202
+ ...(o.mode === 'attack-only' || o.mode === 'transfer-only' ? { mode: o.mode } : {}),
203
+ ...(o.percent ? { byPercent: true } : {}),
204
+ ...(o.commander ? { withCommander: true } : {}),
205
+ ...(o.attack_teammates ? { attackTeammates: true } : {}),
206
+ });
207
+ if (o.mode === 'transfer-only' && s?.allowTransferOnly !== true)
208
+ refused.add('Transfer Only (AllowTransferOnly is off)');
209
+ if (o.mode === 'attack-only' && s?.allowAttackOnly !== true)
210
+ refused.add('Attack Only (AllowAttackOnly is off)');
211
+ if (o.percent && s?.allowPercentageAttacks !== true)
212
+ refused.add('a percentage order (AllowPercentageAttacks is off)');
213
+ if (o.commander && s?.commanders !== true)
214
+ refused.add('a commander move (this game has no commanders)');
215
+ }
216
+ else if (o.kind === 'discard') {
217
+ useCard(o.card, 'discard');
218
+ }
219
+ else if (o.kind === 'card') {
220
+ useCard(o.card, 'play');
221
+ // By GUID it is looked up in my hand; by type name the name is enough (this is a what-if).
222
+ const guid = normalizeGuid(o.card.trim());
223
+ const type = guid !== undefined ? hand.find((c) => c.id === guid)?.type : cardTypeByName(o.card);
224
+ const unsimulated = type !== undefined ? UNSIMULATED_CARDS.get(type) : undefined;
225
+ if (unsimulated) {
226
+ let on = '';
227
+ try {
228
+ if (o.target !== undefined)
229
+ on = ` on ${resolveTerritory(map, o.target).id}`;
230
+ }
231
+ catch {
232
+ // A target not on the map: warapp_submit_turn refuses it; the warning names no territory.
233
+ }
234
+ unsimulatedCards.push(unsimulated(on));
235
+ }
236
+ // #274: the commander check simulates my Airlifts, and names a Blockade or Gift of the commander's
237
+ // territory, as warapp_submit_turn does.
238
+ const kindOf = type !== undefined ? COMMANDER_CARD_KINDS.get(type) : undefined;
239
+ try {
240
+ if (kindOf === 'Airlift' && o.from !== undefined && o.to !== undefined)
241
+ airlifts.push({
242
+ from: resolveTerritory(map, o.from).id,
243
+ to: resolveTerritory(map, o.to).id,
244
+ armies: o.armies ?? 0,
245
+ ...(o.commander ? { commander: true } : {}),
246
+ });
247
+ else if (kindOf && kindOf !== 'Airlift' && o.target !== undefined)
248
+ cardTargets.push({ kind: kindOf, territory: resolveTerritory(map, o.target).id });
249
+ }
250
+ catch {
251
+ // A territory not on the map: warapp_submit_turn refuses it; the check goes without it.
252
+ }
253
+ if (type !== undefined && type === ORDER_PRIORITY)
254
+ orderPriority = true;
255
+ else if (type === undefined || cardTypeName(type) !== 'Reinforcement')
256
+ ignored.push('a card play other than Order Priority or Reinforcement');
257
+ }
258
+ }
259
+ // The same per-opponent estimates warapp_plan_turn works from (stress-opponents.ts).
260
+ const so = stressOpponents({
261
+ graph,
262
+ map,
263
+ game,
264
+ me,
265
+ board,
266
+ seen,
267
+ boards: history.boards,
268
+ ...(history.previous ? { previous: history.previous.board } : {}),
269
+ turn,
270
+ settings,
271
+ hand,
272
+ info,
273
+ ...(opening ? { opening } : {}),
274
+ ...(enemy_deploy !== undefined ? { enemyDeploy: enemy_deploy } : {}),
275
+ });
276
+ const { tracks, income, effect, friend, teams, inView, leader, estimates } = so;
277
+ // #275 (b): an opponent whose estimate an observation broke is tried at the larger of what tripped it
278
+ // and my own income (never below its estimate). Read only: warapp_plan_turn keeps the marks.
279
+ const tripTeams = teamsOf(game.players);
280
+ const trip = await readTripwires({
281
+ dataDir: ctx.dataDir,
282
+ gameId: game.id,
283
+ me: me.id,
284
+ turn,
285
+ graph,
286
+ boards: turn !== null ? [...history.boards, { turn, board: seen }] : [],
287
+ settings,
288
+ ...(tripTeams ? { teams: tripTeams } : {}),
289
+ estimates,
290
+ ...(effect.diplomacy.length ? { peace: effect.diplomacy.map((d) => d.player) } : {}),
291
+ ...(teamsKnown ? {} : { teamsKnown: false }),
292
+ gameSettings: game.settings,
293
+ map,
294
+ staticSeats: staticSeats(game.players, game.endRules, me.id),
295
+ });
296
+ const untrustedOf = new Map(trip.tripwires.map((w) => [w.player, untrustedDeploy(w, income)]));
297
+ const opponents = so.opponents.map((o) => {
298
+ const untrusted = untrustedOf.get(o.id);
299
+ return enemy_deploy !== undefined || untrusted === undefined ? o : { ...o, deploy: Math.max(untrusted, o.deploy) };
300
+ });
301
+ // B2 T6: the truces in force (the ledger, as warapp_plan_turn reads it). Their partners stay among
302
+ // the opponents tried, so `safe` still means safe against a break; `safeIfTruceHolds` leaves the
303
+ // breaks out. Only in a free-for-all, as the planner honours them: a team game is left out here,
304
+ // and a game with two players still playing (a 1v1, or an FFA down to two) ends every agreement
305
+ // in the ledger (`agreementState`: two-left), so what binds is always one the planner's 'ffa' honours.
306
+ // `income` is the board's, card armies out — the same figure warapp_plan_turn passes.
307
+ // PLAN-TEAMS D3: a Diplomacy card in effect that the decoder is sure of is a truce here in any format
308
+ // (T9: the game enforces it). Its player stays among the opponents too: the decoder is unverified.
309
+ const truces = (await truceRelations(ctx, { game, me, turn, graph, board: seen, boards: history.boards, myIncome: income, tracks, diplomacy: effect.diplomacy }))
310
+ ?.relations ?? [];
311
+ const binding = truces.filter((r) => !friend(r.player) &&
312
+ (r.enforced
313
+ ? r.enforcedUntil === undefined || turn === null || turn < r.enforcedUntil
314
+ : teams.size === 0 && (r.state === 'active' || r.state === 'notice') && (r.endsTurn === undefined || turn === null || turn < r.endsTurn)));
315
+ // D3: the deploy total is checked against my income under the Sanctions on me.
316
+ const sanction = sanctionMyIncome(income, effect, { localDeployments: settings.localDeployments === true });
317
+ const report = stressPlan({
318
+ graph,
319
+ board,
320
+ me: me.id,
321
+ deploys,
322
+ moves,
323
+ opponents,
324
+ settings,
325
+ ...(teams.size ? { teams } : {}),
326
+ ...(first_mover !== undefined ? { firstMover: first_mover } : {}),
327
+ orderPriority,
328
+ ...(settings.localDeployments ? { localDeployments: true } : {}),
329
+ ...(settings.localDeployments && (settings.bonusArmyPer ?? 0) > 0 ? { perTerritoryIncome: true } : {}),
330
+ leader,
331
+ ...(binding.length ? { truces: binding.map((r) => ({ player: r.player, covered: r.coveredMine })) } : {}),
332
+ });
333
+ // #274: my commander, by the check warapp_submit_turn refuses on (commander-check.ts): the same
334
+ // opponents, each reply at the larger of its estimate and my income (enemy_deploy only raises it,
335
+ // and so does an untrusted opponent's figure, #275),
336
+ // both move orders whatever first_mover says, my Airlifts simulated.
337
+ const checked = commanderCheckOn({
338
+ graph,
339
+ me: me.id,
340
+ settings,
341
+ so,
342
+ income,
343
+ deploys,
344
+ moves,
345
+ orderPriority,
346
+ ...(enemy_deploy !== undefined ? { floor: enemy_deploy } : {}),
347
+ // #275: an untrusted opponent at the figure its tripwire gave it, as the stress test tries it
348
+ // (enemy_deploy aside, the floor stays: never below what warapp_submit_turn tries).
349
+ ...(untrustedOf.size ? { untrusted: untrustedOf } : {}),
350
+ airlifts,
351
+ cardTargets,
352
+ });
353
+ const guard = checked?.safety;
354
+ const name = namer(map);
355
+ const playerName = new Map(game.players.map((p) => [p.id, p.name]));
356
+ const who = (id) => ({ id, name: playerName.get(id) ?? String(id) });
357
+ const bonusOf = (id) => {
358
+ const b = map.bonuses.find((x) => x.id === id);
359
+ return { id, name: b?.name ?? String(id), value: b?.value ?? 0 };
360
+ };
361
+ const needs = (r) => r.firstMover === undefined ? 'either' : r.firstMover === 'me' ? 'you' : 'opponent';
362
+ const signed = (n) => `${n >= 0 ? '+' : ''}${n}`;
363
+ /** Ids in a sentence, the first few and then a count. */
364
+ const some = (ids) => `${ids.slice(0, LIST_MAX).join(', ')}${ids.length > LIST_MAX ? ` and ${ids.length - LIST_MAX} more` : ''}`;
365
+ const capped = (ids) => ids.slice(0, LIST_MAX).map(name);
366
+ /** One reply in a sentence, by id (the names are in the fields beside it). */
367
+ const sentence = (r) => {
368
+ const act = r.kind === 'reinforce'
369
+ ? `deploys ${r.deploy} on territory ${r.deployTo} and holds`
370
+ : r.kind === 'attack'
371
+ ? `deploys ${r.deploy} on territory ${r.deployTo} and attacks territory ${r.to} with ${r.armies}`
372
+ : r.kind === 'dodge'
373
+ ? `deploys ${r.deploy} on territory ${r.deployTo} and moves it out first, ${r.armies} into territory ${r.to}`
374
+ : r.kind === 'chain'
375
+ ? `deploys ${r.deploy} on territory ${r.deployTo} and attacks on through territories ${r.path.slice(1).join(' → ')}`
376
+ : r.kind === 'joint'
377
+ ? `and player ${r.partner} strike territory ${r.to} together from territories ${r.from} and ${r.partnerDeployTo} (deploying ${r.deploy} and ${r.partnerDeploy})`
378
+ : `attacks with every stack at once (${r.attacks.length} attacks), its ${r.deploy} on territory ${r.deployTo}`;
379
+ const when = (needs(r) === 'you' ? ', and you move first' : needs(r) === 'opponent' ? `, and ${r.kind === 'joint' ? 'they move' : 'it moves'} first` : '') +
380
+ (r.firstOpponent !== undefined ? `, player ${r.firstOpponent} before the other` : '');
381
+ // With my commander gone everything is: the rest is not listed.
382
+ const cost = r.commanderLost
383
+ ? ['you lose your commander and the game']
384
+ : [
385
+ ...(r.lost.length ? [`you lose territor${r.lost.length === 1 ? 'y' : 'ies'} ${some(r.lost)}`] : []),
386
+ ...(r.bonusesLost.length
387
+ ? [`bonus${r.bonusesLost.length === 1 ? '' : 'es'} ${r.bonusesLost.slice(0, LIST_MAX).map((b) => `${b.id} (${signed(b.value)})`).join(', ')}`]
388
+ : []),
389
+ ...(r.capturesFailed.length ? [`your capture of ${some(r.capturesFailed)} fails`] : []),
390
+ ...(r.retaken.length ? [`${some(r.retaken)} is taken straight back`] : []),
391
+ ...(r.eliminationsFailed.length ? [`player ${r.eliminationsFailed.join(', player ')} stays in the game`] : []),
392
+ ];
393
+ return `If player ${r.opponent} ${act}${when}: ${cost.join('; ')}.`;
394
+ };
395
+ const replyView = (r) => ({
396
+ text: sentence(r),
397
+ opponent: who(r.opponent),
398
+ kind: r.kind,
399
+ deploy: r.deploy,
400
+ deployTo: name(r.deployTo),
401
+ ...(r.kind === 'attack' || r.kind === 'dodge' || r.kind === 'chain' ? { attack: { from: name(r.from), to: name(r.to), armies: r.armies } } : {}),
402
+ // #180: a chain's every territory, and a joint strike's second opponent.
403
+ ...(r.path ? { path: r.path.map(name) } : {}),
404
+ ...(r.partner !== undefined
405
+ ? {
406
+ partner: who(r.partner),
407
+ partnerDeploy: r.partnerDeploy,
408
+ partnerDeployTo: name(r.partnerDeployTo),
409
+ ...(r.firstOpponent !== undefined ? { firstOpponent: who(r.firstOpponent) } : {}),
410
+ }
411
+ : {}),
412
+ // Every stack attacked: only the attacks on what was lost are listed, with the count of all.
413
+ ...(r.attacks && r.kind === 'all-attack'
414
+ ? {
415
+ attacks: r.attacks
416
+ .filter((a) => r.lost.includes(a.to) || r.retaken.includes(a.to) || r.capturesFailed.includes(a.to))
417
+ .slice(0, LIST_MAX)
418
+ .map((a) => ({ from: name(a.from), to: name(a.to) })),
419
+ attacksTried: r.attacks.length,
420
+ }
421
+ : {}),
422
+ needsFirstMove: needs(r),
423
+ // B2 T6: the reply breaks a truce (a partner attacks a territory of yours it covers).
424
+ ...(r.breaksTruce ? { breaksTruce: true } : {}),
425
+ lost: capped(r.lost),
426
+ ...(r.lost.length > LIST_MAX ? { lostMore: r.lost.length - LIST_MAX } : {}),
427
+ capturesFailed: capped(r.capturesFailed),
428
+ retaken: capped(r.retaken),
429
+ bonusesLost: r.bonusesLost.slice(0, LIST_MAX).map((b) => bonusOf(b.id)),
430
+ incomeLost: r.incomeLost,
431
+ commanderLost: r.commanderLost,
432
+ eliminationsFailed: r.eliminationsFailed.map(who),
433
+ armies: { you: r.myArmies, opponent: r.theirArmies },
434
+ });
435
+ /** #180: a dodge in a sentence, by id. */
436
+ const dodgeText = (d) => {
437
+ const hit = d.strikes.length ? ` Your ${plural(d.strikes.length, 'strike', 'strikes')} on territory ${d.stack} then ${d.strikes.map((x) => x.result).join(', ')}.` : '';
438
+ return d.took
439
+ ? `Player ${d.opponent} can move its stack on territory ${d.stack} (with its ${d.deploy}) out first into territory ${d.exit} (${d.exitOwner}), ${d.escaped} getting away${d.commander ? ' with its commander' : ''}.${hit}`
440
+ : `Player ${d.opponent} moving its stack on territory ${d.stack} out first into territory ${d.exit} (${d.exitOwner}) fails.${hit}`;
441
+ };
442
+ const dodgeView = (d) => ({
443
+ text: dodgeText(d),
444
+ opponent: who(d.opponent),
445
+ stack: name(d.stack),
446
+ exit: name(d.exit),
447
+ exitOwner: d.exitOwner,
448
+ deploy: d.deploy,
449
+ sent: d.sent,
450
+ took: d.took,
451
+ escaped: d.escaped,
452
+ commander: d.commander,
453
+ strikes: d.strikes.map((x) => ({ from: name(x.from), result: x.result, sent: x.sent })),
454
+ harmful: d.harmful,
455
+ });
456
+ /** #180: a territory two opponents take together, in a sentence. */
457
+ const jointText = (j) => `Players ${j.opponents[0]} and ${j.opponents[1]} together take territory ${j.territory} (${j.armies} there) with ${j.attackers[0]} from ` +
458
+ `territory ${j.from[0]} and ${j.attackers[1]} from territory ${j.from[1]}: it needs ${j.needs} to hold${j.bonusesLost.length ? `, or bonus${j.bonusesLost.length === 1 ? '' : 'es'} ${j.bonusesLost.map((b) => `${b.id} (${signed(b.value)})`).join(', ')} goes with it` : ''}.`;
459
+ const jointView = (j) => ({
460
+ text: jointText(j),
461
+ territory: name(j.territory),
462
+ armies: j.armies,
463
+ needs: j.needs,
464
+ opponents: j.opponents.map(who),
465
+ from: j.from.map(name),
466
+ attackers: j.attackers,
467
+ bonusesLost: j.bonusesLost.map((b) => bonusOf(b.id)),
468
+ incomeLost: j.incomeLost,
469
+ });
470
+ /** One exposure in a sentence, by id. */
471
+ const exposure = (e) => `Next turn player ${e.opponent} can reach territory ${e.territory} (${e.armies} there) with ${e.attackers} from territory ${e.from} ` +
472
+ `by taking territory ${e.via} this turn: it needs ${e.needs} to hold${e.bonusesLost.length ? `, or bonus${e.bonusesLost.length === 1 ? '' : 'es'} ${e.bonusesLost.map((b) => `${b.id} (${signed(b.value)})`).join(', ')} goes with it` : ''}.`;
473
+ const exposureView = (e) => ({
474
+ text: exposure(e),
475
+ territory: name(e.territory),
476
+ armies: e.armies,
477
+ needs: e.needs,
478
+ attackers: e.attackers,
479
+ from: name(e.from),
480
+ via: name(e.via),
481
+ opponent: who(e.opponent),
482
+ bonusesLost: e.bonusesLost.map((b) => bonusOf(b.id)),
483
+ incomeLost: e.incomeLost,
484
+ });
485
+ const orderView = (e) => ({
486
+ order: e.index + 1,
487
+ from: name(e.from),
488
+ to: name(e.to),
489
+ ordered: e.ordered,
490
+ sent: e.sent,
491
+ result: e.result,
492
+ ...(e.reason ? { reason: e.reason } : {}),
493
+ });
494
+ // A percentage order's count is a percentage: short only when it sent nothing (#165).
495
+ const short = report.baseline.log.filter((e) => e.result === 'skipped' || (moves[e.index]?.byPercent ? e.sent === 0 : e.sent < e.ordered));
496
+ const plural = (n, one, many) => (n === 1 ? one : many);
497
+ const blind = report.blindBorders.length
498
+ ? ` ${report.blindBorders.length} of your territories border the fog and were not tested.`
499
+ : '';
500
+ const inexact = report.exact ? '' : ' Battles are not exact in this game (luck or weighted rounding): each was resolved at its expectation.';
501
+ const ahead = report.exposedNextTurn.length
502
+ ? ` Next turn: ${report.exposedNextTurn.length} ${plural(report.exposedNextTurn.length, 'territory is', 'territories are')} within reach of a stack two steps away if you add nothing (see exposedNextTurn). First: ${exposure(report.exposedNextTurn[0])}`
503
+ : '';
504
+ // #180: stacks you attack that can step out of the way first.
505
+ const escapes = report.dodges.filter((d) => d.took && d.escaped > 0);
506
+ const escapingStacks = new Set(escapes.map((d) => d.stack)).size;
507
+ const dodged = escapingStacks
508
+ ? ` ${escapingStacks} of the stacks you attack can move out first and get away (see dodges).`
509
+ : '';
510
+ // B2 T6: what the verdict is if every truce holds.
511
+ const truceLine = report.safeIfTruceHolds === undefined
512
+ ? ''
513
+ : report.safe === false && report.safeIfTruceHolds === true
514
+ ? ` Only a break of a truce costs you something: if every truce holds, nothing tried does (safeIfTruceHolds).`
515
+ : report.safe === false && report.safeIfTruceHolds === null
516
+ ? ' Every reply tried breaks a truce (safeIfTruceHolds is null).'
517
+ : '';
518
+ // The count and `needs` come from one run (the commander check's), so the line never pairs a count
519
+ // the full run found with armies the targeted run says hold.
520
+ const commanderLine = guard ? commanderText(guard, guard.killers) : undefined;
521
+ const summary = (guard && (guard.killers > 0 || guard.lostUnanswered) && commanderLine ? `${commanderLine} ` : '') +
522
+ (report.safe === null
523
+ ? `Nothing could be tested this turn: no opposing stack in view touches you.${blind}${ahead}`
524
+ : report.safe
525
+ ? `None of the ${report.considered} ${plural(report.considered, 'reply', 'replies')} tried costs you a territory, a capture or a bonus.${blind}${inexact}${dodged}${ahead}`
526
+ : `${report.harmful} of the ${report.considered} ${plural(report.considered, 'reply', 'replies')} tried ${plural(report.harmful, 'costs', 'cost')} you something. Worst: ${sentence(report.worst)}${truceLine}${inexact}${dodged}${ahead}`);
527
+ const deployed = deploys.reduce((n, d) => n + d.armies, 0);
528
+ // #275 (a): the smallest single deploy that takes each border of mine after these orders.
529
+ const headroom = safeHeadroom({
530
+ graph,
531
+ board,
532
+ me: me.id,
533
+ deploys,
534
+ moves,
535
+ settings,
536
+ ...(teams.size ? { teams } : {}),
537
+ ...(first_mover !== undefined ? { firstMover: first_mover } : {}),
538
+ orderPriority,
539
+ });
540
+ // #275 pattern 3: each border these orders leave below what the default plan leaves there (one plan per call).
541
+ const belowPlan = await bordersBelowPlan(ctx, { game, map, me, turn, territories, info, history, teamsKnown, given: { deploys, moves } });
542
+ const warnings = [
543
+ // #275 (b): an untrusted estimate is the first thing said (not under an explicit enemy_deploy).
544
+ ...(enemy_deploy === undefined ? tripwireWarnings(trip.tripwires, (w) => untrustedOf.get(w.player) ?? untrustedDeploy(w, income), (p) => estimates.find((x) => x.playerId === p)?.estimate) : []),
545
+ ...(award ? assumedWarning(award) : []),
546
+ // #270: the static seats whose territories the test read as neutrals.
547
+ ...[...seatTerritories(award?.board ?? seen, seats)]
548
+ .sort((a, b) => a[0] - b[0])
549
+ .map(([p, n]) => `Player ${p} is out (${seats.get(p)}) and no AI plays its seat: its ${n} territor${n === 1 ? 'y was' : 'ies were'} tried as neutrals, and it makes no reply.`),
550
+ ...modsWarning(game.settings),
551
+ // As plan/submit do (#165); a percentage order counts what it sent unanswered.
552
+ ...guardOffWarnings(graph, map, board, me.id, friends, game.settings, deploys, moves.map((m, i) => ({
553
+ from: m.from,
554
+ to: m.to,
555
+ armies: m.byPercent ? (report.baseline.log.find((e) => e.index === i)?.sent ?? 0) : m.armies,
556
+ }))),
557
+ ...(refused.size
558
+ ? [`These orders use ${[...refused].join(', ')}: war.app would refuse them in this game, and warapp_submit_turn does; the test ran them anyway.`]
559
+ : []),
560
+ ...sanction.warnings,
561
+ ...effect.unsure,
562
+ ...[claimedCardWarning(claimedCardUses(uses, claimed))].filter((w) => w !== undefined),
563
+ ...unsimulatedCards,
564
+ ...(deployed !== sanction.income
565
+ ? [
566
+ `The orders deploy ${deployed} and your income is ${sanction.income}: the test used the orders as given (a Reinforcement card adds to the income; otherwise war.app refuses a wrong total).`,
567
+ ]
568
+ : []),
569
+ ];
570
+ const atRiskList = (rows) => rows.slice(0, LIST_MAX);
571
+ return respond(view, VIEWS, (rung) => ({
572
+ game: { id: game.id, name: game.name ?? null, turn },
573
+ player: { id: me.id, name: me.name },
574
+ safe: report.safe,
575
+ // B2 T6: with a truce in force, the verdict over the replies that break none (absent with no truce).
576
+ ...(report.safeIfTruceHolds !== undefined
577
+ ? {
578
+ safeIfTruceHolds: report.safeIfTruceHolds,
579
+ truces: binding.map((r) => ({
580
+ player: who(r.player),
581
+ ...(r.agreement ? { agreement: r.agreement } : {}),
582
+ ...(r.card ? { card: r.card } : {}),
583
+ ...(r.enforced ? { enforced: true, ...(r.enforcedUntil !== undefined ? { enforcedUntil: r.enforcedUntil } : {}), verified: false } : {}),
584
+ state: r.state,
585
+ covered: r.coveredMine.length,
586
+ })),
587
+ }
588
+ : {}),
589
+ summary,
590
+ exact: report.exact,
591
+ // Where the teams came from (GameFeed, else the game list), in a team game only.
592
+ ...(teamSource !== 'none' ? { teamSource } : {}),
593
+ firstMover: first_mover ?? 'unknown',
594
+ // #166: what the award of picks showed, the move order it implies included (absent with no pick list kept).
595
+ ...(award ? { award: awardView(award, game, turn, name) } : {}),
596
+ orderPriority,
597
+ income,
598
+ deployed,
599
+ warnings,
600
+ // Only an opponent with a stack in view can be given a reply; the others are named apart.
601
+ enemyDeploy: opponents
602
+ .filter((o) => inView.has(o.id))
603
+ .map((o) => ({
604
+ player: { id: o.id, name: playerName.get(o.id) ?? String(o.id) },
605
+ deploy: o.deploy,
606
+ source: enemy_deploy !== undefined ? 'enemy_deploy' : untrustedOf.has(o.id) ? 'untrusted' : 'estimate',
607
+ })),
608
+ // #180: in a free-for-all, whether you lead (any two opponents are then tried together).
609
+ leader,
610
+ unseenOpponents: opponents.filter((o) => !inView.has(o.id)).map((o) => ({ id: o.id, name: playerName.get(o.id) ?? String(o.id) })),
611
+ plan: {
612
+ captures: report.baseline.captured.map(name),
613
+ failedAttacks: report.baseline.failed.map(name),
614
+ // Orders that sent fewer armies than ordered, or none: a typo, or armies that are not there.
615
+ shortOrders: short.map(orderView),
616
+ ...(rung === 'full' ? { orders: report.baseline.log.map(orderView), bonusesHeld: report.baseline.heldBonuses.map(bonusOf) } : {}),
617
+ },
618
+ worst: report.worst ? replyView(report.worst) : null,
619
+ // The next most damaging replies (the worst one is above, not repeated here).
620
+ otherReplies: report.replies.slice(1, rung === 'full' ? report.replies.length : 1 + COMPACT_OTHERS).map(replyView),
621
+ harmful: report.harmful,
622
+ considered: report.considered,
623
+ atRisk: {
624
+ commander: report.atRisk.commander,
625
+ territories: atRiskList(report.atRisk.territories).map((t) => ({ territory: name(t.id), replies: t.replies })),
626
+ ...(report.atRisk.territories.length > LIST_MAX ? { territoriesMore: report.atRisk.territories.length - LIST_MAX } : {}),
627
+ captures: atRiskList(report.atRisk.captures).map((t) => ({ territory: name(t.id), replies: t.replies })),
628
+ ...(report.atRisk.captures.length > LIST_MAX ? { capturesMore: report.atRisk.captures.length - LIST_MAX } : {}),
629
+ bonuses: atRiskList(report.atRisk.bonuses).map((b) => ({ ...bonusOf(b.id), replies: b.replies })),
630
+ ...(report.atRisk.bonuses.length > LIST_MAX ? { bonusesMore: report.atRisk.bonuses.length - LIST_MAX } : {}),
631
+ },
632
+ // #180: each stack you attack moving out first (compact: those that get away), and
633
+ // territories two opponents take together.
634
+ dodges: (rung === 'full' ? report.dodges : escapes).slice(0, LIST_MAX).map(dodgeView),
635
+ // #274: my commander (only when it is on the board): where it ends up, the armies there and what holds it.
636
+ ...(guard
637
+ ? {
638
+ commander: {
639
+ text: commanderLine,
640
+ territory: name(guard.territory),
641
+ armies: guard.armies,
642
+ needs: guard.needs,
643
+ replies: guard.killers,
644
+ distance: guard.distance,
645
+ // The deploy the worst reply was sized at: as warapp_submit_turn sizes it.
646
+ replyDeploy: checked.replyDeploy,
647
+ sizing: COMMANDER_SIZING,
648
+ // A Blockade or Gift of its territory, which the check does not simulate (the submit refuses it).
649
+ ...(checked.cards ? { cards: checked.cards } : {}),
650
+ },
651
+ }
652
+ : {}),
653
+ jointFalls: report.jointFalls.slice(0, LIST_MAX).map(jointView),
654
+ ...(report.jointFalls.length > LIST_MAX ? { jointFallsMore: report.jointFalls.length - LIST_MAX } : {}),
655
+ // #275 (a): each border's headroom, the weakest first (compact: the first few).
656
+ headroom: headroomView(headroom, map, income, rung === 'full', !teamsKnown),
657
+ ...(rung !== 'full' && headroom.length > HEADROOM_COMPACT ? { headroomMore: headroom.length - HEADROOM_COMPACT } : {}),
658
+ // #275 pattern 3: absent when the default plan could not be made.
659
+ ...(belowPlan
660
+ ? {
661
+ belowPlan: belowPlan.rows
662
+ .slice(0, LIST_MAX)
663
+ .map((r) => ({ territory: name(r.territory), planLeaves: r.planLeaves, left: r.left, short: r.short })),
664
+ ...(belowPlan.rows.length > LIST_MAX ? { belowPlanMore: belowPlan.rows.length - LIST_MAX } : {}),
665
+ belowPlanAgainst: belowPlan.against,
666
+ ...(rung === 'full' ? { belowPlanBasis: BELOW_PLAN_BASIS } : {}),
667
+ }
668
+ : {}),
669
+ blindBorders: report.blindBorders.map(name),
670
+ // One turn ahead (#156): what the orders leave within reach of a stack two steps away.
671
+ exposedNextTurn: report.exposedNextTurn.slice(0, LIST_MAX).map(exposureView),
672
+ ...(report.exposedNextTurn.length > LIST_MAX ? { exposedMore: report.exposedNextTurn.length - LIST_MAX } : {}),
673
+ notCovered: [...CHECK_PLAN_NOT_COVERED, ...new Set(ignored)],
674
+ ...(rung === 'full' ? { assumptions: report.assumptions } : {}),
675
+ }));
676
+ });
677
+ }
678
+ /** #274: my commander in one sentence, by id: how many replies kill it and the armies that hold. */
679
+ export function commanderText(c, replies) {
680
+ const where = `Your commander on territory ${c.territory}`;
681
+ if (c.lostUnanswered)
682
+ return `${where} is lost to your own orders, with nobody answering.`;
683
+ if (replies === 0)
684
+ return `${where} survives every reply tried (${c.armies} armies there after your orders).`;
685
+ const hold = c.needs === null
686
+ ? 'no number of armies there holds it against all of them'
687
+ : `it needs ${c.needs} armies there (${c.armies} after your orders) to survive every one`;
688
+ return `${where} falls to ${replies} of the replies tried (${COMMANDER_SIZING}, as warapp_submit_turn sizes them): ${hold}.`;
689
+ }