@chrischall/warapp-mcp 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/.claude-plugin/marketplace.json +3 -3
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +133 -8
  4. package/dist/analysis/accept-surrender.js +20 -2
  5. package/dist/analysis/calibrate.js +1 -0
  6. package/dist/analysis/card-support.js +177 -17
  7. package/dist/analysis/card-threats.js +126 -14
  8. package/dist/analysis/chat-advice.js +182 -0
  9. package/dist/analysis/chat-blocks.js +106 -0
  10. package/dist/analysis/chat-intent.js +559 -0
  11. package/dist/analysis/chat-read.js +159 -0
  12. package/dist/analysis/decision-replay.js +279 -0
  13. package/dist/analysis/decision-truth.js +146 -0
  14. package/dist/analysis/finished-game.js +62 -3
  15. package/dist/analysis/game-lessons.js +15 -10
  16. package/dist/analysis/hold-diff.js +3 -1
  17. package/dist/analysis/income-trend.js +38 -0
  18. package/dist/analysis/intel.js +75 -0
  19. package/dist/analysis/opens.js +64 -0
  20. package/dist/analysis/opponent-profile.js +121 -10
  21. package/dist/analysis/opponents.js +246 -20
  22. package/dist/analysis/outlook.js +360 -15
  23. package/dist/analysis/picks.js +91 -12
  24. package/dist/analysis/plan/after-leftover.js +4 -1
  25. package/dist/analysis/plan/bonus-attempts.js +105 -0
  26. package/dist/analysis/plan/capture-instead.js +116 -0
  27. package/dist/analysis/plan/captures.js +49 -7
  28. package/dist/analysis/plan/conceded-out.js +13 -2
  29. package/dist/analysis/plan/estimates.js +203 -30
  30. package/dist/analysis/plan/guard-off.js +2 -1
  31. package/dist/analysis/plan/holds.js +110 -9
  32. package/dist/analysis/plan/jabs.js +113 -0
  33. package/dist/analysis/plan/leftover.js +393 -8
  34. package/dist/analysis/plan/orders.js +76 -4
  35. package/dist/analysis/plan/relations.js +135 -2
  36. package/dist/analysis/plan/report.js +69 -3
  37. package/dist/analysis/plan/second-sizing.js +133 -0
  38. package/dist/analysis/plan/shared.js +279 -27
  39. package/dist/analysis/plan/siege.js +303 -0
  40. package/dist/analysis/plan/stand-still.js +9 -5
  41. package/dist/analysis/plan/state.js +8 -0
  42. package/dist/analysis/plan/stockpile.js +104 -0
  43. package/dist/analysis/plan/strike.js +39 -7
  44. package/dist/analysis/plan/targets.js +256 -110
  45. package/dist/analysis/plan/threats.js +148 -10
  46. package/dist/analysis/plan/transfers.js +57 -6
  47. package/dist/analysis/plan/two-move.js +70 -0
  48. package/dist/analysis/plan/vacated.js +124 -2
  49. package/dist/analysis/planner.js +527 -49
  50. package/dist/analysis/profile.js +13 -2
  51. package/dist/analysis/since-last.js +18 -5
  52. package/dist/analysis/stress.js +8 -2
  53. package/dist/board.js +36 -2
  54. package/dist/bonus-attempt-store.js +55 -0
  55. package/dist/build-id.js +106 -0
  56. package/dist/bundle.js +54138 -41059
  57. package/dist/cards.js +7 -5
  58. package/dist/chat-automation.js +22 -0
  59. package/dist/chat.js +35 -1
  60. package/dist/client.js +14 -0
  61. package/dist/commerce.js +111 -0
  62. package/dist/decision-log.js +1093 -0
  63. package/dist/finished-store.js +5 -1
  64. package/dist/index.js +9 -1
  65. package/dist/lessons-store.js +322 -21
  66. package/dist/live.js +43 -0
  67. package/dist/move-order.js +64 -3
  68. package/dist/normalize.js +17 -0
  69. package/dist/open-games.js +36 -16
  70. package/dist/outlook-log.js +42 -1
  71. package/dist/profile-store.js +12 -2
  72. package/dist/protocol/methods.js +62 -5
  73. package/dist/protocol/rpc.js +8 -0
  74. package/dist/relations-store.js +38 -4
  75. package/dist/review-export.js +198 -0
  76. package/dist/siege-store.js +49 -0
  77. package/dist/state-bundle.js +584 -0
  78. package/dist/state-cli.js +71 -0
  79. package/dist/strategy/notes.js +56 -0
  80. package/dist/team-cards.js +25 -0
  81. package/dist/tools/accept-surrender.js +23 -9
  82. package/dist/tools/award.js +20 -2
  83. package/dist/tools/card-advice.js +93 -28
  84. package/dist/tools/card-plays.js +2 -2
  85. package/dist/tools/card-support-advice.js +37 -7
  86. package/dist/tools/chat-advice.js +330 -0
  87. package/dist/tools/chat-inbox.js +19 -4
  88. package/dist/tools/chat.js +106 -17
  89. package/dist/tools/check-plan.js +68 -12
  90. package/dist/tools/commerce-deploy.js +33 -0
  91. package/dist/tools/common.js +31 -0
  92. package/dist/tools/decision-capture.js +459 -0
  93. package/dist/tools/end-of-game.js +151 -21
  94. package/dist/tools/game-kind.js +92 -0
  95. package/dist/tools/how-lost.js +7 -2
  96. package/dist/tools/index.js +10 -0
  97. package/dist/tools/join-game.js +10 -4
  98. package/dist/tools/live-context.js +6 -0
  99. package/dist/tools/live.js +10 -1
  100. package/dist/tools/map-curves.js +73 -0
  101. package/dist/tools/notifications.js +4 -3
  102. package/dist/tools/opponents.js +2 -0
  103. package/dist/tools/past-games.js +74 -8
  104. package/dist/tools/picks.js +61 -10
  105. package/dist/tools/profile-hook.js +62 -3
  106. package/dist/tools/profile-opponents.js +4 -0
  107. package/dist/tools/push.js +2 -2
  108. package/dist/tools/relations.js +139 -0
  109. package/dist/tools/scout.js +16 -2
  110. package/dist/tools/state.js +232 -0
  111. package/dist/tools/strategy.js +3 -3
  112. package/dist/tools/stress-opponents.js +7 -2
  113. package/dist/tools/surrender-pending.js +10 -1
  114. package/dist/tools/surrender.js +18 -3
  115. package/dist/tools/survival.js +11 -3
  116. package/dist/tools/team-brief.js +2 -2
  117. package/dist/tools/team.js +12 -3
  118. package/dist/tools/turn.js +643 -76
  119. package/dist/tools/where.js +3 -1
  120. package/dist/version.js +1 -1
  121. package/manifest.json +32 -3
  122. package/mint.yaml +37 -4
  123. package/package.json +4 -4
  124. package/server.json +20 -2
  125. package/skills/warapp-mcp/SKILL.md +73 -17
@@ -4,32 +4,39 @@
4
4
  import { CONFIRM_INJECTION_RULE, McpToolError, toolAnnotations } from '@chrischall/mcp-utils';
5
5
  import { z } from 'zod';
6
6
  import { CARD_BLOCKADE, CARD_ORDER_DELAY, CARD_ORDER_PRIORITY, holdsOrderPriority, playsOrderPriority, advisedOrderPriority, CARD_REINFORCEMENT, cardRules, cardTypeByName, cardTypeName, chooseCardPlays, normalizeGuid, cardsToShed, handReadable, isMyCard, readHand, reinforcementArmies, } from '../cards.js';
7
- import { chargeDeploys, DEFAULT_OFFENSIVE_KILL_RATE, deployPools, expectedKills, specialUnitStrength, winChance, incomeDetail, armyCapPoolsUncertainty, deployCheckUncertainties, overrideUncertainties, neighborsOf, planTurn, planEnemyEstimates, repulsedAttacks, borderGuess, guessSeed, AHEAD_PRESSURE_FACTOR, PRESSURE_FACTOR, symmetricStart, unevenStart, trackGame, trackOpponents, } from '../analysis/index.js';
7
+ import { chargeDeploys, DEFAULT_OFFENSIVE_KILL_RATE, deployPools, expectedKills, specialUnitStrength, winChance, incomeDetail, armyCapPoolsUncertainty, deployCheckUncertainties, overrideUncertainties, neighborsOf, PAYBACK_TURNS, planTurn, planEnemyEstimates, repulsedAttacks, borderGuess, guessSeed, AHEAD_PRESSURE_FACTOR, PRESSURE_FACTOR, symmetricStart, unevenStart, trackGame, trackOpponents, } from '../analysis/index.js';
8
8
  import { parseGameId } from '../client.js';
9
9
  import { COMMANDER_STRENGTH, luckFraction, straightKills } from '../analysis/combat.js';
10
10
  import { guardOffExposure } from '../analysis/guard-off.js';
11
- import { holdsBelowPlan } from '../analysis/hold-diff.js';
11
+ import { BELOW_PLAN_MIN_SHORT, holdsBelowPlan } from '../analysis/hold-diff.js';
12
12
  import { guardCase } from '../analysis/profile.js';
13
13
  import { boardStateFromLive, inGameId, playersByInGameId } from '../live.js';
14
+ import { armiesForGold, cityAdvice, cityPurchaseCost, commerceDeploy, commerceRules, goldForArmies } from '../commerce.js';
15
+ import { commerceDeployOf, submitCommerceCheck } from './commerce-deploy.js';
14
16
  import { checkMoveOptions, MOVE_MODES } from './order-options.js';
15
17
  import { AttackTransferMode, Method, TARGETED_CARD_PLAYS, UNVERIFIED_CARD_PLAYS, writeSendOrdersParams, } from '../protocol/methods.js';
16
18
  import { SERVER_ERROR_MESSAGES } from '../protocol/rpc.js';
19
+ import { inferFirstMover } from '../move-order.js';
17
20
  import { assumedWarning, awardView, firstMoverFor, loadAward, openingThreat } from './award.js';
18
21
  import { boardCardsInEffect, CARDS_IN_EFFECT_UNVERIFIED, sanctionMyIncome } from './card-effects.js';
19
- import { adviseCards, cardGame, cardPieceOption, handOwners, opponentCanHold, opponentReinforcement, TEAM_HAND } from './card-advice.js';
20
- import { currentTurn, turnsCompleted, gameIdArg, graphOf, namer, readAnnotations, respond, shownAccount, UNTRUSTED_PREVIEW_NOTE, untrustedDescription, untrustedText, viewArg, } from './common.js';
22
+ import { adviseCards, cardGame, cardPieceOption, intelOrders, handOwners, opponentCanHold, opponentReinforcement, TEAM_HAND } from './card-advice.js';
23
+ import { currentTurn, turnsCompleted, gameIdArg, knownIncomeArg, avoidPlayersArg, avoidTerritoriesArg, graphOf, namer, readAnnotations, respond, shownAccount, UNTRUSTED_PREVIEW_NOTE, untrustedDescription, untrustedText, viewArg, } from './common.js';
21
24
  import { lookupMeta, mintMeta } from './hints.js';
22
25
  import { chatSummary } from './chat.js';
26
+ import { blockedLog, CHAT_BLOCKS_NOTE, chatSeats, planChatView, planStanding, turnChatBlocks, withBlocks } from './chat-advice.js';
27
+ import { chatBlockLine } from '../analysis/chat-blocks.js';
28
+ import { chatAutomationMode, chatBlocksTurnMode } from '../chat-automation.js';
23
29
  import { readPendingSurrenders, surrenderOwedLine } from './surrender-pending.js';
24
30
  import { failureText, loadLiveGame, requireApprovedAccount, standInLine, standInOf, writeAccount } from './live-context.js';
25
31
  import { BRIDGE_NOTE, playerArg, resolveMe } from './live.js';
26
32
  import { guessOrdersOf, guessView } from './guess-view.js';
27
33
  import { guessSalt, peekGuessSalt } from '../guess-salt.js';
28
- import { recordProfile } from './profile-hook.js';
34
+ import { cardsInPlay, observeSettings, profiledOpponents, quietNeighbours, recordProfile } from './profile-hook.js';
29
35
  import { confidentHabits, counterOf, neighboursOf, readOpponents } from './profile-reads.js';
30
36
  import { mapOf } from './map.js';
31
37
  import { PACE_TURNS } from '../analysis/game-lessons.js';
32
- import { mapRecordFor, paceView } from './past-games.js';
38
+ import { profileFormatOf } from '../analysis/opponent-profile.js';
39
+ import { fogPaceFor, mapMatchOf, mapRecordFor, outlookCalibrationFor, paceView } from './past-games.js';
33
40
  import { defineGatedWrite, requireMySeat, sendAndVerify } from './write-kit.js';
34
41
  import { resolveBonus, resolveTerritory } from './resolve.js';
35
42
  import { checkCardFields, newCardPlaySeen, resolveCardTargets, } from './card-plays.js';
@@ -41,21 +48,32 @@ import { cardArmyCeiling, cardClock } from '../strategy/card-clock.js';
41
48
  import { hasCostlyBonus, noteContext, notesFor } from '../strategy/notes.js';
42
49
  import { sinceLastTurn } from '../analysis/since-last.js';
43
50
  import { recordOutlook } from '../outlook-log.js';
51
+ import { bootTimes, captureChat, capturePlan, captureObservation, captureSent, cardAdviceLog, handLog, submitChecksLog } from './decision-capture.js';
52
+ import { chatTruces } from '../analysis/chat-read.js';
53
+ import { readDecisionLog, scrubNames } from '../decision-log.js';
44
54
  import { readPickRecord } from '../pick-list.js';
45
55
  import { commitmentWarnings } from '../analysis/commitments.js';
46
56
  import { planRelationsFrom, truceBreaksIn } from '../analysis/relations.js';
47
57
  import { recordBrokenByMe } from './relations.js';
48
58
  import { withTeammateOrders } from '../team-orders.js';
49
- import { claimedCardUses, claimedCardWarning, teamCardClaims, teamCardRoles, teamHandLeft, unclaimedFirst } from '../team-cards.js';
59
+ import { claimedCardUses, claimedCardWarning, teamCardClaims, teamCardLimit, teamCardRoles, teamHandLeft, unclaimedFirst, } from '../team-cards.js';
50
60
  import { isTeamGame, teammatesOf } from '../teams.js';
51
61
  import { readLedger, recordTruceUsage } from '../relations-store.js';
62
+ import { resolveIntel } from '../analysis/intel.js';
63
+ import { readSiegeMemory, writeSiegeMemory } from '../siege-store.js';
64
+ import { readBonusAttempts, writeBonusAttempts } from '../bonus-attempt-store.js';
65
+ import { rememberBonusAttempts } from '../analysis/plan/bonus-attempts.js';
66
+ import { rememberSiegeTurn } from '../analysis/plan/siege.js';
67
+ import { countsOf, fogSightings, ownersOf } from '../analysis/plan/vacated.js';
52
68
  import { resolveTeams, resolveTeamsFor } from './team-source.js';
53
69
  import { stressOpponents } from './stress-opponents.js';
54
70
  import { myCommanderTerritory } from '../analysis/commander-safety.js';
55
71
  import { commanderCheckOn, guessKeepsCommander } from './commander-check.js';
56
72
  import { HEADROOM_COMPACT, headroomView, headroomWarnings, keepTripwires, readTripwires, safeHeadroom, teamsOf, tripwireWarnings, untrustedDeploy } from './survival.js';
57
73
  const VIEWS = ['compact', 'full'];
58
- const GOALS = ['balanced', 'expand', 'complete-bonus', 'defend'];
74
+ /** #415 task 4b: the chat-blocks-the-turn gate, the context's when set, else read from the environment. */
75
+ const chatBlocksTurnFor = (ctx, env) => ctx.chatBlocksTurn ?? chatBlocksTurnMode(env ?? process.env);
76
+ const GOALS = ['balanced', 'expand', 'complete-bonus', 'defend', 'siege'];
59
77
  /** The only GameFeed state in which turns are played. */
60
78
  const TURN_PHASE_STATE = 'Playing';
61
79
  const MAX_ORDERS = 500;
@@ -83,9 +101,11 @@ const TEAM_JOINT_NOTE = "A target neither your teammate's entered attack nor you
83
101
  /** PLAN-TEAMS C3.7: what `cards.team` means. */
84
102
  const TEAM_CARDS_NOTE = "Who plays each card of the team hand this turn: a teammate for a card they have already entered a play or discard " +
85
103
  "of (so the team never uses one card twice; the plan chooses from the rest), you for a card your orders play or " +
86
- 'discard, nobody for a card held. Read from their entered orders on the live board (unverified, V5); how war.app keys ' +
87
- "a team's hand is unverified too (V8).";
104
+ 'discard, nobody for a card held. Read from their entered orders on the live board (unverified, V5). The hand is the ' +
105
+ "team's: every teammate's cards, each kept under that teammate's id (V8, verified).";
88
106
  const territoryRef = z.union([z.string(), z.number()]);
107
+ /** #332: the most cities one purchase order may name (a sanity bound, not a game rule). */
108
+ const MAX_CITIES_PER_ORDER = 50;
89
109
  const playerRef = z.union([z.string().min(1).max(100), z.number()]);
90
110
  const armiesArg = z.coerce.number().int().min(1);
91
111
  /** One order of a turn: territories by id or name. */
@@ -203,8 +223,17 @@ export function plannerSettings(s) {
203
223
  out.noSplit = true;
204
224
  if (s.armyCap !== undefined && s.armyCap !== null && s.armyCap > 0)
205
225
  out.armyCap = s.armyCap;
226
+ // #332: a commerce game's rising army price (0, one gold per army, changes nothing and is left out).
227
+ const m = commerceRules(s)?.armyCostMultiplier ?? 0;
228
+ if (m > 0)
229
+ out.armyCostMultiplier = m;
206
230
  if (s.wastelands && s.wastelands.count > 0)
207
231
  out.wastelands = { ...s.wastelands };
232
+ // #428: the game's neutral size (a fogged bonus member no board showed is costed as one): the larger
233
+ // of the two the settings give, since such a member may have been in the distribution or outside it.
234
+ const sizes = [s.initialNonDistributionArmies, s.initialNeutralsInDistribution].filter((n) => n !== undefined && n >= 0);
235
+ if (sizes.length)
236
+ out.neutralArmies = Math.max(...sizes);
208
237
  // #271 review: the first turn an opponent may play a Bomb (a bomb reads as a failed attack on my hold).
209
238
  const bombFrom = cardClock(s)?.cards.find((c) => c.card === 'Bomb')?.firstPlayableTurn.fastest;
210
239
  if (bombFrom !== undefined && bombFrom !== null)
@@ -258,6 +287,8 @@ function shownOrder(o) {
258
287
  }
259
288
  if (o.players)
260
289
  out.players = o.players.map(shownPlace);
290
+ if (o.cities)
291
+ out.cities = o.cities.map((c) => ({ ...c, territory: shownPlace(c.territory) }));
261
292
  return out;
262
293
  }
263
294
  /**
@@ -334,17 +365,101 @@ export function modsWarning(s) {
334
365
  ];
335
366
  }
336
367
  /**
337
- * #167: a commerce game pays gold and lets players buy armies and cities; the planner plans income as
338
- * armies only. Said whenever the feed's `Commerce` object carries settings (the shape a commerce
339
- * game sends is unverified: a plain game sends `{}`).
368
+ * #167, #332: what the plan still does not model in a commerce game, said only when it applies. The plan deploys what
369
+ * my gold buys at the game's army price (`commerceDeployOf`), so with the `Commerce` settings read (their shape VERIFIED
370
+ * live 2026-11-17; a plain game sends `{}`) it names: gold that could not be read from the board (the deploy then rests
371
+ * on the income model, which leaves out saved gold), an army price that rises within a turn (the plan's own values and
372
+ * payback are priced at one gold per army), and cities (the plan's orders buy none; `commerce.cityAdvice` and
373
+ * `warapp_submit_turn`'s `cities` do). A commerce game whose settings did not read gets the old unmodelled warning;
374
+ * every other game, nothing.
340
375
  */
341
- export function commerceWarning(s) {
376
+ export function commerceWarning(s, deploy) {
342
377
  if (!s?.commerce)
343
378
  return [];
344
- return [
345
- 'This looks like a commerce game (its Commerce settings are not empty): the plan models income as armies only — ' +
346
- 'it does not model gold, buying armies or cities. Check what gold buys before following it.',
347
- ];
379
+ const rules = commerceRules(s);
380
+ if (!rules) {
381
+ return [
382
+ 'This looks like a commerce game, but its Commerce settings did not read: the plan models income as armies ' +
383
+ 'only — it does not model gold, the army price or cities. Check what gold buys before following it.',
384
+ ];
385
+ }
386
+ const out = [];
387
+ if (deploy?.source === 'model')
388
+ out.push(`Commerce: your gold could not be read from the board, so the deploy is what this turn's modelled income ` +
389
+ `(${deploy.gold} gold) buys; gold saved from earlier turns is not counted.`);
390
+ if (rules.armyCostMultiplier > 0)
391
+ out.push(`Commerce: armies cost more the more you buy in a turn (army cost multiplier ${rules.armyCostMultiplier}), but ` +
392
+ 'the plan values income, bonuses and payback at one army per gold.');
393
+ if (rules.cityBaseCost !== null)
394
+ out.push('Commerce: this game allows cities; the plan does not buy any (a city pays more gold on later turns) — ' +
395
+ '`commerce.cityAdvice` says where one would pay, and warapp_submit_turn takes `cities`.');
396
+ return out;
397
+ }
398
+ /**
399
+ * #332, advice only: where a city would pay this turn (`cityAdvice`, src/commerce.ts) — my cheapest territory with no
400
+ * neighbour I do not hold, repaid within PAYBACK_TURNS or not — as `{ cityAdvice }`, else `{}`.
401
+ */
402
+ function cityAdviceOf(settings, graph, board, me, gold) {
403
+ const rules = commerceRules(settings);
404
+ if (!rules)
405
+ return {};
406
+ const mine = new Set(board.territories.filter((t) => t.owner.kind === 'player' && t.owner.playerId === me).map((t) => t.territoryId));
407
+ const sites = board.territories
408
+ .filter((t) => mine.has(t.territoryId))
409
+ .map((t) => ({
410
+ territoryId: t.territoryId,
411
+ interior: neighborsOf(graph, t.territoryId).every((n) => mine.has(n)),
412
+ cities: t.cities ?? 0,
413
+ }));
414
+ const advice = cityAdvice(rules, sites, gold, PAYBACK_TURNS);
415
+ return advice ? { cityAdvice: advice } : {};
416
+ }
417
+ /**
418
+ * #332: a turn's city purchase, checked as the client checks it — a commerce game that allows cities (602), my own
419
+ * territories (600), whole positive counts (601), merged per territory, priced by the game's formula
420
+ * (`cityPurchaseCost`) and paid for from my gold (597). `undefined` when none is asked for.
421
+ */
422
+ export function cityPurchaseOf(game, asked, map, board, myInGameId, gold) {
423
+ if (!asked.length)
424
+ return undefined;
425
+ const rules = commerceRules(game.settings);
426
+ if (!rules || rules.cityBaseCost === null || !gold) {
427
+ throw new McpToolError(`${SERVER_ERROR_MESSAGES[602]} Nothing was sent.`, {
428
+ hint: rules ? 'Drop `cities`.' : 'Cities exist only in commerce games that allow them; drop `cities`.',
429
+ });
430
+ }
431
+ const merged = new Map();
432
+ for (const a of asked) {
433
+ const t = resolveTerritory(map, a.territory);
434
+ const held = board.find((x) => x.territoryId === t.id);
435
+ if (!held || held.owner !== myInGameId) {
436
+ throw new McpToolError(`${untrustedText(t.name)} (${t.id}) is not yours on the live board. ${SERVER_ERROR_MESSAGES[600]}`, {
437
+ hint: 'Build cities only on territories you hold at the start of the turn.',
438
+ });
439
+ }
440
+ const m = merged.get(t.id);
441
+ if (m)
442
+ m.count += a.count;
443
+ else
444
+ merged.set(t.id, { territory: { id: t.id, name: t.name }, count: a.count });
445
+ }
446
+ const cities = [...merged.values()];
447
+ const existing = new Map(board.flatMap((x) => (x.cities ? [[x.territoryId, x.cities]] : [])));
448
+ const mine = board.reduce((n, x) => n + (x.owner === myInGameId ? (x.cities ?? 0) : 0), 0);
449
+ const cost = cityPurchaseCost(rules, cities.map((c) => ({ territoryId: c.territory.id, count: c.count })), existing, mine);
450
+ const count = cities.reduce((n, c) => n + c.count, 0);
451
+ // Only gold read from the board is enforced (#353 review): the model's leaves out gold saved on earlier turns.
452
+ if (cost > gold.gold && gold.source === 'standing') {
453
+ throw new McpToolError(`${count} cit${count === 1 ? 'y' : 'ies'} cost ${cost} gold, but you have ${gold.gold}. ${SERVER_ERROR_MESSAGES[597]}`, { hint: 'Buy fewer cities; nothing was sent.' });
454
+ }
455
+ const left = gold.gold - cost;
456
+ const note = `Commerce: ${count} cit${count === 1 ? 'y' : 'ies'} for ${cost} gold (each pays ${rules.cityIncome} gold a turn), ` +
457
+ (gold.source === 'standing'
458
+ ? `leaving ${left} gold for the deploys. `
459
+ : `against the income model's ${gold.gold} gold (your gold could not be read from the board, and saved gold is not in ` +
460
+ `it${left < 0 ? ', so war.app may refuse the purchase: error 597' : ''}). `) +
461
+ "The purchase order's encoding is read from the client and UNVERIFIED live: check the cities on the board once the turn resolves.";
462
+ return { cities, cost, note };
348
463
  }
349
464
  /**
350
465
  * #165: One Army Must Stand Guard off. My territories the orders leave at 0 beside an enemy or the
@@ -472,7 +587,21 @@ export function validateTurn(args) {
472
587
  }
473
588
  }
474
589
  const deployed = deploys.reduce((s, d) => s + d.armies, 0);
475
- if (deployed !== income && args.incomeUncertain?.length) {
590
+ if (args.commerce && deployed !== income) {
591
+ const { gold, armyCostMultiplier: m } = args.commerce;
592
+ const cards = income - armiesForGold(gold, m);
593
+ if (deployed < income) {
594
+ const saved = gold - goldForArmies(Math.max(0, deployed - cards), m);
595
+ warnings.push(`These orders deploy ${deployed} of the ${income} armies your ${gold} gold buys` +
596
+ `${cards > 0 ? ` (with ${cards} card armies)` : ''}: ${saved} gold is saved for a later turn.`);
597
+ }
598
+ else {
599
+ const cost = goldForArmies(Math.max(0, deployed - cards), m);
600
+ throw new McpToolError(`These orders deploy ${deployed} armies, which cost ${cost} gold, but you have ${gold} gold (buying ${income} armies` +
601
+ `${cards > 0 ? `, ${cards} of them from cards` : ''}).`, { hint: `Deploy at most ${income} armies — war.app refuses a deploy you cannot pay for (error 597 InsufficientGold).` });
602
+ }
603
+ }
604
+ else if (deployed !== income && args.incomeUncertain?.length) {
476
605
  warnings.push(`These orders deploy ${deployed} armies, but the modelled income is ${income} this turn. The model may be off ` +
477
606
  `(${args.incomeUncertain.join(' ')}), so they are not refused here: check the "armies per turn" the game ` +
478
607
  'shows — war.app refuses any other total (error 11).');
@@ -729,7 +858,7 @@ const PLAYABLE = {
729
858
  [CARD_ORDER_PRIORITY]: 'OrderPriority',
730
859
  [CARD_ORDER_DELAY]: 'OrderDelay',
731
860
  [CARD_BLOCKADE]: 'Blockade',
732
- // PLAN-TEAMS part D: encoded from the bundle's writers, UNVERIFIED live (V9).
861
+ // PLAN-TEAMS part D: encoded from the bundle's writers, UNVERIFIED live (V9) save Airlift (#296) and Diplomacy (#369).
733
862
  2: 'Spy',
734
863
  6: 'Airlift',
735
864
  7: 'Gift',
@@ -838,24 +967,28 @@ function resolveCardPlays(map, hand, rules, inputs) {
838
967
  return out;
839
968
  }
840
969
  /**
841
- * The team's gathered hand is over the limit while mine is not (#163): a warning, not a refusal,
842
- * because how war.app keys a team's hand is unverified — a wrong guess must not block a valid turn.
970
+ * The team's hand is over the limit but the limit does not bind these orders (V8, #310): a teammate has yet to
971
+ * commit (war.app refuses only the last of the team to commit), or a committed teammate's orders were unread.
843
972
  */
844
- function teamHandOver(held, rules, shed, given) {
845
- return (`The team's hand as read (your cards and your teammates') holds ${held} cards; the limit is ${rules.maxCardsHold}, ` +
846
- `so ${shed} card${shed === 1 ? '' : 's'} may need to be played or discarded; these orders use ${given}. How war.app keys ` +
847
- "a team's hand is not yet verified, so this is not refused: check the hand in the game — war.app refuses the commit " +
848
- '(error 51) if the team is over the limit.');
973
+ function teamHandOver(team, rules, given) {
974
+ const held = team.left.length;
975
+ const shed = team.shed;
976
+ return (`The team's hand (your cards and your teammates', less what committed teammates play or discard) holds ${held} cards; ` +
977
+ `the limit is ${rules.maxCardsHold}, so ${shed} card${shed === 1 ? '' : 's'} must leave it this turn; these orders use ${given}. ` +
978
+ (team.lastToCommit
979
+ ? "A committed teammate's orders could not be read, so this is not refused: war.app refuses the last of the team to commit (error 51) while the team is over the limit."
980
+ : 'A teammate has yet to commit, so war.app takes these orders: it refuses only the last of the team to commit (error 51) while the team is still over the limit. Agree in team chat who plays or discards.'));
849
981
  }
850
- /** Cards these orders use that were read only under a teammate's id (V8, #163): a warning, never a refusal. */
982
+ /** Cards these orders use that were read only under a teammate's id (V8, #310): a warning, never a refusal. */
851
983
  export function teammateCardWarning(cards) {
852
984
  return (`${cards.map((c) => `${c.name} ${c.id}`).join(', ')} ${cards.length === 1 ? 'was' : 'were'} read under a teammate, not under you. ` +
853
- "A team shares one hand, but whether you can play or discard a card held under a teammate is not yet verified: war.app " +
854
- 'refusing it (e.g. error 50, CardInstanceUnavailable) means only that teammate can.');
985
+ "A team shares one hand: war.app's order check (the client bundle's) takes any card of the team's hand, but no play of a " +
986
+ "teammate's card has been sent live yet, and a card a committed teammate already uses is swapped for another of its type " +
987
+ 'or refused (error 50, CardInstanceUnavailable). Agree in team chat first.');
855
988
  }
856
989
  /** The required-play refusal (war.app's error 51, `MustUseCard`), raised before anything is sent. */
857
- function mustPlayCard(hand, rules, shed, given) {
858
- return new McpToolError(`${SERVER_ERROR_MESSAGES[51]} (You hold ${hand.length}; the limit is ${rules.maxCardsHold}, so ${shed} card${shed === 1 ? '' : 's'} must be played or discarded; these orders use ${given}.)`, {
990
+ function mustPlayCard(hand, rules, shed, given, team = false) {
991
+ return new McpToolError(`${SERVER_ERROR_MESSAGES[51]} (${team ? 'Your team holds' : 'You hold'} ${hand.length}${team ? ", every teammate has committed and you are the last to" : ''}; the limit is ${rules.maxCardsHold}, so ${shed} card${shed === 1 ? '' : 's'} must be played or discarded; these orders use ${given}.)`, {
859
992
  hint: `Add card plays or discards, e.g. { "kind": "discard", "card": "${hand[0]?.name ?? 'Order Delay'}" } (warapp_plan_turn suggests which). ${handHint(hand, true)}`,
860
993
  });
861
994
  }
@@ -893,6 +1026,69 @@ export function myOrdersOf(orders) {
893
1026
  : []),
894
1027
  };
895
1028
  }
1029
+ /**
1030
+ * The deploys and every move of a sent turn, for comparing with the decision log's plan (#412): a
1031
+ * percentage or mode move is `exact: false` (never the planner's).
1032
+ */
1033
+ export function sentOrdersOf(orders) {
1034
+ return {
1035
+ deploys: orders.flatMap((o) => (o.kind === 'deploy' ? [{ territoryId: o.territoryId, armies: o.armies }] : [])),
1036
+ moves: orders.flatMap((o) => o.kind === 'move'
1037
+ ? [
1038
+ {
1039
+ from: o.from,
1040
+ to: o.to,
1041
+ armies: o.armies,
1042
+ ...(o.byPercent || (o.mode !== undefined && o.mode !== AttackTransferMode.AttackTransfer) ? { exact: false } : {}),
1043
+ ...(o.commander ? { commander: true } : {}),
1044
+ },
1045
+ ]
1046
+ : []),
1047
+ };
1048
+ }
1049
+ /**
1050
+ * Every order of a sent turn, for the decision log (#412): unlike {@link myOrdersOf}, a percentage or
1051
+ * mode move keeps its count and options, and card plays (with their targets), discards and purchases
1052
+ * are all kept. Ids and counts only: a commander is a flag, never its unit id.
1053
+ */
1054
+ export function loggedSentOf(orders) {
1055
+ return {
1056
+ deploys: orders.flatMap((o) => (o.kind === 'deploy' ? [{ territoryId: o.territoryId, armies: o.armies }] : [])),
1057
+ moves: orders.flatMap((o) => o.kind === 'move'
1058
+ ? [
1059
+ {
1060
+ from: o.from,
1061
+ to: o.to,
1062
+ armies: o.armies,
1063
+ ...(o.byPercent ? { percent: true } : {}),
1064
+ ...(o.mode === AttackTransferMode.Attack ? { mode: 'attack-only' } : {}),
1065
+ ...(o.mode === AttackTransferMode.Transfer ? { mode: 'transfer-only' } : {}),
1066
+ ...(o.attackTeammates ? { attackTeammates: true } : {}),
1067
+ ...(o.commander ? { commander: true } : {}),
1068
+ },
1069
+ ]
1070
+ : []),
1071
+ cards: orders.flatMap((o) => o.kind === 'card'
1072
+ ? [
1073
+ {
1074
+ card: o.card,
1075
+ cardId: o.cardId,
1076
+ ...(o.target !== undefined ? { target: o.target } : {}),
1077
+ ...(o.player !== undefined ? { player: o.player } : {}),
1078
+ ...(o.players !== undefined ? { players: o.players } : {}),
1079
+ ...(o.bonus !== undefined ? { bonus: o.bonus } : {}),
1080
+ ...(o.from !== undefined ? { from: o.from } : {}),
1081
+ ...(o.to !== undefined ? { to: o.to } : {}),
1082
+ ...(o.armies !== undefined ? { armies: o.armies } : {}),
1083
+ ...(o.commander ? { commander: true } : {}),
1084
+ ...(o.beforeMove !== undefined ? { beforeMove: o.beforeMove } : {}),
1085
+ },
1086
+ ]
1087
+ : []),
1088
+ discards: orders.flatMap((o) => (o.kind === 'discard' ? [o.cardId] : [])),
1089
+ purchases: orders.flatMap((o) => (o.kind === 'purchase' ? o.cities.map((c) => ({ territoryId: c.territoryId, count: c.count })) : [])),
1090
+ };
1091
+ }
896
1092
  /** Earlier turns that, when all cached, make the GameFeed history read unnecessary. */
897
1093
  const TREND_TURNS = 2;
898
1094
  /**
@@ -928,6 +1124,9 @@ export async function boardHistory(ctx, game, me, turn, opts = {}) {
928
1124
  if (board)
929
1125
  byTurn.set(k, { source: 'history', board });
930
1126
  }
1127
+ // #412 no-gaps rule (a): the turns filled from history join the decision log as observations
1128
+ // (never over a planned entry or a board already logged).
1129
+ await captureObservation(ctx, game.id, me.id, [...byTurn].flatMap(([t, b]) => (b.source === 'history' ? [{ turn: t, board: b.board, source: 'history' }] : [])));
931
1130
  }
932
1131
  catch {
933
1132
  // History is optional: the cache stands.
@@ -944,6 +1143,18 @@ export async function boardHistory(ctx, game, me, turn, opts = {}) {
944
1143
  const previous = byTurn.get(turn - 1);
945
1144
  return { boards, ...(previous ? { previous } : {}) };
946
1145
  }
1146
+ /**
1147
+ * #442: the captures the decision log's plan of `turn` expected, kept to the targets of the moves sent that
1148
+ * turn when they were logged (a capture the orders sent did not try is no failed attack). Never throws.
1149
+ */
1150
+ async function previousCaptures(dir, gameId, me, turn) {
1151
+ const e = (await readDecisionLog(dir, gameId, me))?.turns[String(turn)];
1152
+ const caps = e?.decision?.expected?.captures;
1153
+ if (!Array.isArray(caps))
1154
+ return undefined;
1155
+ const sent = e?.sent?.moves;
1156
+ return sent ? caps.filter((id) => sent.some((m) => m.to === id)) : [...caps];
1157
+ }
947
1158
  /**
948
1159
  * The "since last turn" view (#194): one line comparing this turn's income with the next income
949
1160
  * the previous turn's plan expected, and naming the bonuses broken and territories lost since the
@@ -965,7 +1176,11 @@ function sinceLastView(s, previousTurn, hasBoard, map, players, rung) {
965
1176
  : `${inc}, as expected ${when}.`;
966
1177
  const broken = s.bonusesBroken ?? [];
967
1178
  const lost = s.territoriesLost ?? [];
1179
+ const missed = s.capturesMissed ?? [];
968
1180
  const parts = [
1181
+ ...missed.map((t) => t.to === null
1182
+ ? `the capture of ${name(t.territoryId).name} (#${t.territoryId}) failed`
1183
+ : `the capture of ${name(t.territoryId).name} (#${t.territoryId}) failed: ${player(t.to).name} holds it${t.fresh ? ' — your attack hit their fresh capture' : ''}`),
969
1184
  ...(broken.length
970
1185
  ? [`${broken.length === 1 ? 'bonus' : 'bonuses'} broken — ${broken.map((b) => `${bonus(b.bonusId)} (+${b.value})`).join(', ')}`]
971
1186
  : []),
@@ -990,6 +1205,7 @@ function sinceLastView(s, previousTurn, hasBoard, map, players, rung) {
990
1205
  ? {
991
1206
  bonusesBroken: broken.map((b) => ({ id: b.bonusId, name: bonus(b.bonusId), value: b.value })),
992
1207
  territoriesLost: lost.map((t) => ({ ...name(t.territoryId), to: t.to !== null ? player(t.to) : null })),
1208
+ ...(missed.length ? { capturesMissed: missed.map((t) => ({ ...name(t.territoryId), to: t.to !== null ? player(t.to) : null, ...(t.fresh ? { fresh: true } : {}) })) } : {}),
993
1209
  }
994
1210
  : {}),
995
1211
  line,
@@ -1100,11 +1316,26 @@ export async function livePlanSetup(ctx, a) {
1100
1316
  // pick list proves, where they are still fogged.
1101
1317
  const seen = withTeammateOrders(boardStateFromLive(territories, me, game.players), info, me, game.players);
1102
1318
  const write = a.award !== 'read';
1103
- const award = a.award === false ? undefined : await loadAward(ctx.dataDir, game, me, seen, turn, { write });
1319
+ const award = a.award === false ? undefined : await loadAward(ctx.dataDir, game, me, seen, turn, { write, decisionLog: ctx.decisionLog });
1104
1320
  const board = award?.board ?? seen;
1105
1321
  const opening = openingThreat(award, game, graph, seen, turn);
1106
1322
  // #127: who moves first — first_mover, else a turn kept for this game alternated, else the award.
1107
- const mover = await firstMoverFor(ctx.dataDir, game, me, turn, first_mover, award, { write });
1323
+ // #299: my own first order last turn can prove the opponent moved first then.
1324
+ const lastTurn = turn !== null ? history.boards.find((b) => b.turn === turn - 1) : undefined;
1325
+ const rival = game.players.length === 2 ? game.players.find((p) => p.id !== me.id) : undefined;
1326
+ const inferred = turn !== null && lastTurn?.orders && rival
1327
+ ? inferFirstMover({
1328
+ turn: turn - 1,
1329
+ before: lastTurn.board,
1330
+ after: seen,
1331
+ orders: lastTurn.orders,
1332
+ me: me.id,
1333
+ opponent: rival.id,
1334
+ rates: plannerSettings(game.settings),
1335
+ orderPriorityPossible: opponentCanHold(game.settings, 'Order Priority', turn - 1),
1336
+ })
1337
+ : null;
1338
+ const mover = await firstMoverFor(ctx.dataDir, game, me, turn, first_mover, award, { write, ...(inferred ? { inferred } : {}) });
1108
1339
  const settings = plannerSettings(game.settings);
1109
1340
  const rules = cardRules(game.settings);
1110
1341
  // A team shares one hand (#163): mine and my teammates' cards.
@@ -1113,9 +1344,9 @@ export async function livePlanSetup(ctx, a) {
1113
1344
  const handUnknown = rules.inPlay.length > 0 && !handReadable(info, owners);
1114
1345
  const inGame = cardGame(game, me);
1115
1346
  // PLAN-TEAMS C3.7: a card my teammate has entered a play or discard of is theirs this turn, so my plan
1116
- // chooses from the rest (their orders: V5; the team hand's keying: V8 — both unverified live).
1347
+ // chooses from the rest (their orders: V5, unverified live; the team hand's keying: V8, verified #310).
1117
1348
  const { left: myHand, claimed: teamClaimed } = teamHandLeft(hand, inGame.team ? teamCardClaims(seen.teammateOrders, new Set(teammatesOf(game.players, me).map((p) => p.id))) : []);
1118
- // V8: of what is left, a card read under a teammate's id is not mine to play (unverified): chooseCardPlays
1349
+ // V8: of what is left, a card read under a teammate's id is left to them (#310): chooseCardPlays
1119
1350
  // and the card advice play, discard and advise only my own, so no card is both claimed and advised to me.
1120
1351
  const cards = chooseCardPlays(myHand, rules, inGame);
1121
1352
  const myCards = myHand.filter((c) => isMyCard(c, inGame.me));
@@ -1128,7 +1359,10 @@ export async function livePlanSetup(ctx, a) {
1128
1359
  // a Diplomacy card with a player makes it no foe this turn (T9).
1129
1360
  const effect = boardCardsInEffect(game, me, turn, info);
1130
1361
  const sanction = sanctionMyIncome(boardIncome, effect, { localDeployments: settings.localDeployments === true });
1131
- const income = sanction.income + cards.extraArmies;
1362
+ // #332: in a commerce game the income is gold and the deploy is what it buys at the game's army price. The
1363
+ // standing's gold already holds what was saved and any Sanctions (war.app pays it); the model is the fallback.
1364
+ const commerce = commerceDeployOf(game, me, info, sanction.income);
1365
+ const income = (commerce ? commerce.armies : sanction.income) + cards.extraArmies;
1132
1366
  const trend = history.previous;
1133
1367
  const previousOrders = turn !== null ? history.boards.find((b) => b.turn === turn - 1)?.orders : undefined;
1134
1368
  // The opponents over my board history: one observed over 2+ turns gets its tracked income;
@@ -1139,9 +1373,15 @@ export async function livePlanSetup(ctx, a) {
1139
1373
  // #240: territories my cached orders show failed attacks on, their owner reinforcing them each
1140
1374
  // time, on two or more of the last three turns: a further attack is sized for its owner's deploy.
1141
1375
  const repulsed = turn !== null ? repulsedAttacks(graph, [...history.boards, { turn, board: seen }], me.id, settings) : [];
1376
+ // #298: the contested bonuses my plans attempted to complete in this game (read only here; only
1377
+ // warapp_plan_turn writes it): after two failed attempts the planner pushes all-in once or drops the bonus.
1378
+ const bonusAttempts = turn !== null && ctx.dataDir ? await readBonusAttempts(ctx.dataDir, game.id, me.id) : undefined;
1142
1379
  // #178: won, lost, even or stuck, from my boards over the last turns (a basis, not a verdict).
1143
1380
  // #201: the planner reads it too — a decided game shortens its payback horizon.
1144
1381
  const cardArmies = cardArmyCeiling(game.settings);
1382
+ // #436: past games' estimate ÷ truth per coverage band calibrates the outlook's income estimates (its income
1383
+ // lean and the surrender line only; the planner acts on winning and losing, which never read it).
1384
+ const calibration = await outlookCalibrationFor(ctx.dataDir, a.env, profileFormatOf(game.players));
1145
1385
  const outlookInput = {
1146
1386
  graph,
1147
1387
  me: me.id,
@@ -1151,6 +1391,7 @@ export async function livePlanSetup(ctx, a) {
1151
1391
  cards: rules.inPlay.length > 0,
1152
1392
  // #205: what the card clock lets cards add, so a fogged card game can still be bounded.
1153
1393
  ...(cardArmies ? { cardArmies } : {}),
1394
+ ...(calibration ? { calibration } : {}),
1154
1395
  };
1155
1396
  // The plan reads the outlook (#201: winning or losing only); #218 then feeds the outlook the
1156
1397
  // plan's main front, so its front forecast and the plan's front outlook are one computation.
@@ -1158,6 +1399,8 @@ export async function livePlanSetup(ctx, a) {
1158
1399
  const picking = ctx.dataDir ? await readPickRecord(ctx.dataDir, game.id, me.id) : undefined;
1159
1400
  // Players still in the game besides me (a break is worth less when the bonus's loss is shared).
1160
1401
  const opponents = game.players.filter((p) => p.id !== me.id && (p.state ?? 'Playing') === 'Playing').length;
1402
+ // #419: the pace past winners set on this map (else in this format) at this turn: thin evidence's upper bound.
1403
+ const mapPace = await fogPaceFor(ctx.dataDir, a.env, game.settings?.mapId ?? map.id, mapMatchOf(profileFormatOf(game.players), game.settings), turn === null ? null : turn - 1);
1161
1404
  const gameContext = {
1162
1405
  players: game.players.map((p) => ({
1163
1406
  id: p.id,
@@ -1180,6 +1423,7 @@ export async function livePlanSetup(ctx, a) {
1180
1423
  ...(unevenStart(game.settings) ? { unevenStart: unevenStart(game.settings) } : {}),
1181
1424
  // #166: the opponent's opening simulated from the starts the award proved, as the prior.
1182
1425
  ...(opening ? { opening } : {}),
1426
+ ...(mapPace ? { mapPace } : {}),
1183
1427
  // #164: an opponent's Reinforcement card, from the turn the card clock says one can be in hand.
1184
1428
  ...(opponentReinforcement(game.settings, hand) ? { reinforcement: opponentReinforcement(game.settings, hand) } : {}),
1185
1429
  };
@@ -1224,23 +1468,56 @@ export async function livePlanSetup(ctx, a) {
1224
1468
  staticSeats: staticSeats(game.players, game.endRules, me.id),
1225
1469
  });
1226
1470
  const untrusted = trip.tripwires.map((w) => ({ player: w.player, deploy: untrustedDeploy(w, boardIncome) }));
1471
+ // #303: my board income on each earlier board (as this turn's: after the army cap, cards aside), for the
1472
+ // plan's income trend. Not in a commerce game, where the income is gold and the deploy what it buys.
1473
+ const incomeHistory = commerceRules(game.settings)
1474
+ ? []
1475
+ : history.boards.map((b) => ({ turn: b.turn, income: incomeDetail(graph, b.board, me.id, game.settings).income }));
1476
+ // #420 (P1 amended): the quiet neighbours, from this game's kept profile turns and the boards in hand.
1477
+ const quiet = turn !== null
1478
+ ? await quietNeighbours({
1479
+ dataDir: ctx.dataDir,
1480
+ env: a.env ?? process.env,
1481
+ gameId: game.id,
1482
+ me: me.id,
1483
+ graph,
1484
+ settings: observeSettings(game),
1485
+ ...cardsInPlay(game),
1486
+ opponents: profiledOpponents(game, me),
1487
+ boards: [...history.boards, { turn, board: seen }],
1488
+ teamsKnown: a.teamsKnown !== false,
1489
+ })
1490
+ : [];
1491
+ // #417 / #428: each fogged territory's newest earlier sighting, one source for both readers: who held it
1492
+ // (a static seat's stays vacated, #417) and, when that board showed them, its armies (#428's fog price).
1493
+ const sightings = fogSightings(board, history.boards);
1494
+ const lastSeen = ownersOf(sightings);
1495
+ const lastCounts = countsOf(sightings);
1227
1496
  const input = {
1228
1497
  graph,
1229
1498
  board,
1230
1499
  me: me.id,
1231
1500
  income,
1501
+ ...(incomeHistory.length && turn !== null ? { incomeHistory } : {}),
1232
1502
  ...(untrusted.length ? { untrusted } : {}),
1503
+ ...(quiet.length ? { quiet } : {}),
1504
+ // #368: incomes the caller knows. Not in the estimates above, which the tripwire keeps: those stay the
1505
+ // board's own (a figure supplied is no observation).
1506
+ ...(a.args?.knownIncome?.length ? { knownIncome: a.args.knownIncome } : {}),
1233
1507
  cardArmies: cards.extraArmies,
1234
1508
  ...(incomeCap ? { incomeCap } : {}),
1235
1509
  ...(truces?.relations.length ? { relations: truces.relations } : {}),
1236
1510
  settings,
1237
1511
  ...(trend ? { previousBoard: trend.board } : {}),
1512
+ ...(lastSeen.size ? { foggedLastSeen: lastSeen } : {}),
1238
1513
  // #226: my orders on that turn, when this server sent them: a failed attack's kills count back.
1239
1514
  ...(trend && previousOrders ? { previousOrders } : {}),
1240
1515
  ...(repulsed.length ? { repulsed } : {}),
1516
+ ...(bonusAttempts ? { bonusAttempts } : {}),
1241
1517
  ...(turn !== null ? { turn } : {}),
1242
1518
  game: gameContext,
1243
1519
  ...(tracks ? { tracks } : {}),
1520
+ ...(a.args?.siegeMemory ? { siegeMemory: a.args.siegeMemory } : {}),
1244
1521
  // G2 (D3): Sanctions on another player the decoder is sure of cut its estimate read off the board.
1245
1522
  ...(effect.sanctionsOnOthers.length ? { sanctions: effect.sanctionsOnOthers } : {}),
1246
1523
  options: {
@@ -1249,6 +1526,8 @@ export async function livePlanSetup(ctx, a) {
1249
1526
  outlook: { state: outlook.state, turns: outlook.turns },
1250
1527
  // #201: the picking board's neutrals, so a fogged one keeps its size (wastelands).
1251
1528
  ...(picking?.neutrals ? { rememberedNeutrals: new Map(picking.neutrals) } : {}),
1529
+ // #428: and a member my earlier boards showed keeps its last-seen armies.
1530
+ ...(lastCounts.size ? { lastSeen: lastCounts } : {}),
1252
1531
  ...(goal !== undefined ? { goal } : {}),
1253
1532
  focusBonusIds,
1254
1533
  ...(opponents > 0 ? { opponents } : {}),
@@ -1257,6 +1536,9 @@ export async function livePlanSetup(ctx, a) {
1257
1536
  ...(reserve !== undefined ? { reserve } : {}),
1258
1537
  ...(enemy_deploy !== undefined ? { enemyDeploy: enemy_deploy } : {}),
1259
1538
  ...(min_win_chance !== undefined ? { minWinChance: min_win_chance } : {}),
1539
+ ...(a.args?.avoid ? { avoid: a.args.avoid } : {}),
1540
+ ...(a.args?.siegeTarget !== undefined ? { siegeTarget: a.args.siegeTarget } : {}),
1541
+ ...(a.args?.jabs !== undefined ? { jabs: a.args.jabs } : {}),
1260
1542
  // #127/#179: who moves first (firstMoverFor: first_mover, else the remembered turn, else the award).
1261
1543
  ...(mover.firstMover !== undefined ? { movesFirst: mover.firstMover === 'me' } : {}),
1262
1544
  // #215 review: from the award (unverified), the schedule and card advice use it, holds do not.
@@ -1271,7 +1553,7 @@ export async function livePlanSetup(ctx, a) {
1271
1553
  return {
1272
1554
  graph, seen, award, board, opening, mover, settings, rules, owners, hand, myHand, myCards, teamClaimed, handUnknown, inGame, cards,
1273
1555
  boardIncome, income, trend, previousOrders, tracks, outlookInput, outlook, picking, opponents, gameContext, truces, input,
1274
- effect, sanction, incomeCap, capUnknown: incomeOnBoard.capUnknown === true, estimates, trip, teams,
1556
+ effect, sanction, incomeCap, capUnknown: incomeOnBoard.capUnknown === true, estimates, trip, teams, commerce,
1275
1557
  };
1276
1558
  }
1277
1559
  /**
@@ -1289,9 +1571,11 @@ async function commanderCheck(ctx, a) {
1289
1571
  const settings = plannerSettings(a.game.settings);
1290
1572
  const [history, award] = await Promise.all([
1291
1573
  boardHistory(ctx, a.game, a.me, a.turn, { cacheOnly: true }),
1292
- loadAward(ctx.dataDir, a.game, a.me, a.seen, a.turn),
1574
+ loadAward(ctx.dataDir, a.game, a.me, a.seen, a.turn, { decisionLog: ctx.decisionLog }),
1293
1575
  ]);
1294
1576
  const opening = openingThreat(award, a.game, graph, a.seen, a.turn);
1577
+ // #419: the past winners' pace, as the plan reads it.
1578
+ const mapPace = await fogPaceFor(ctx.dataDir, undefined, a.game.settings?.mapId ?? a.map.id, mapMatchOf(profileFormatOf(a.game.players), a.game.settings), a.turn === null ? null : a.turn - 1);
1295
1579
  // stressOpponents reads a static seat's territories as neutrals (#270), on its own `board` too.
1296
1580
  const so = stressOpponents({
1297
1581
  graph,
@@ -1307,6 +1591,7 @@ async function commanderCheck(ctx, a) {
1307
1591
  hand: a.hand,
1308
1592
  info: a.info,
1309
1593
  ...(opening ? { opening } : {}),
1594
+ ...(mapPace ? { mapPace } : {}),
1310
1595
  });
1311
1596
  // #275: an untrusted opponent's reply is sized at least at the figure its tripwire gave it, as
1312
1597
  // warapp_check_plan's stress test tries it (read only: warapp_plan_turn keeps the marks).
@@ -1368,7 +1653,8 @@ function planBorderGuess(setup, plan, me, seed, enemyDeploy) {
1368
1653
  export const BELOW_PLAN_BASIS = 'the plan warapp_plan_turn makes now on this board with no goal, focus, reserve, enemy_deploy or first_mover ' +
1369
1654
  '(the award of picks read as it reads it, nothing written), or its border guess when the ' +
1370
1655
  'deploys given are the guess\'s; a plan made with options may differ, and a figure is what that plan leaves ' +
1371
- 'standing there, surplus included, not the least that holds the border';
1656
+ 'standing there, surplus included, not the least that holds the border; a border short by less than ' +
1657
+ `${BELOW_PLAN_MIN_SHORT} is left out (#306: that is the plan's surplus)`;
1372
1658
  /** The same deploys, merged per territory (order and splitting ignored). */
1373
1659
  function sameDeploys(a, b) {
1374
1660
  const total = (ds) => {
@@ -1415,6 +1701,8 @@ export async function bordersBelowPlan(ctx, a) {
1415
1701
  },
1416
1702
  conceded: plan.conceded,
1417
1703
  given,
1704
+ // #306: a border only 1 or 2 short is the plan's surplus, not a real difference.
1705
+ minShort: BELOW_PLAN_MIN_SHORT,
1418
1706
  });
1419
1707
  const turn = a.turn;
1420
1708
  const held = new Set(a.history.boards.map((b) => b.turn));
@@ -1474,20 +1762,23 @@ export function registerTurnTools(server, ctx, opts = {}) {
1474
1762
  "game's settings: your income, deploys and attacks/transfers by territory name and id (each attack with " +
1475
1763
  '`winChance`, its exact capture probability), the expected captures, completed bonuses and next income ' +
1476
1764
  '(with `nextIncomeIfConcededFall` and `bonusesAtRisk` when the plan concedes borders of a bonus you hold), ' +
1477
- 'the borders given up (`conceded`), the `frontier` budget, your cards (plays and discards when you must), ' +
1765
+ 'the borders given up (`conceded`), the `frontier` budget, `incomeTrend` (my income over the last five turns, its slope per turn and whether it is flat; #303), in a 1v1 the `gates` (every border facing the opponent against its one floating deploy: what they need, what stands on them, the shortfall), your cards (plays and discards when you must), ' +
1478
1766
  'warnings and the reasoning. Its `orders` array is exactly what warapp_submit_turn takes — review it with ' +
1479
1767
  'the user first. Every plan reads the game profile (`profile`: format 1v1/ffa/teams, phase, standing ' +
1480
1768
  'ahead/even/behind/unknown on income) and returns the `outlook` (winning/losing/even/stalemate from ' +
1481
- 'armies + 3 × income held over 3 turns of boards, with its `basis` and `evidence`: the two incomes compared and how much of each opponent\'s frontier was read, `thin` when under half, so even is not safe; thresholds unmeasured, so advice, not a verdict; ' +
1769
+ 'armies + 3 × income held over 3 turns of boards — and, #436, where that reads even, `lean` ahead/behind on my income against the strongest opponent\'s (its range, and its estimate calibrated on past games), or unknown when the range spans both lines or a lead rests on thin evidence; absent when the incomes read even too; `income`, `pace` (both incomes per turn) and `surrenderLine` (advice only: my income under 2/3 of the strongest estimate for 3 turns with no bonus in reach closing the gap; never acted on) — with its `basis` and `evidence`: the two incomes compared and how much of each opponent\'s frontier was read, `thin` when under half, so even is not safe; `leaning: behind` when even for 3 turns while a bonus of yours fell on each; thresholds unmeasured, so advice, not a verdict; ' +
1482
1770
  'an opponent is bounded above by all it can have received (its start, or an even share of the map; each turn\'s most it could earn; ' +
1483
1771
  'a fixed Reinforcement card by the card clock) — a scenario\'s starts, a Gift card or a progressive Reinforcement card leave it unbounded, and then `winning` is never read; ' +
1484
1772
  'once winning or losing, payback tests count the turns the game has left instead of 10). With no `goal` the profile picks and tunes it (`goalSource` ' +
1485
- '"profile"): defend when behind outside a 1v1, else balanced — in an FFA with two or more opponents, no ' +
1773
+ '"profile"): siege when it fits (in contact, not ahead, one target — in an FFA the leader, earning 1.5× any other ' +
1774
+ 'opponent beside me — with a sure break costing at most 2 turns of its bonus and at most my income; handed back ' +
1775
+ 'once its assault trigger fires), else defend when behind outside a 1v1, else balanced — in an FFA with two or more opponents, no ' +
1486
1776
  'second front; in a 1v1, one strike stack facing the opponent; ahead in a 1v1, fog pressure ' +
1487
1777
  `up to ${AHEAD_PRESSURE_FACTOR}× a typical neutral capture. Goals: "balanced" (default) — income per army ` +
1488
1778
  'across holds, bonuses and breaking enemy bonuses, at least 30% on expansion; "expand" — neutrals only; ' +
1489
1779
  '"complete-bonus" — also attacks players to finish bonuses; "defend" — threatened borders worth holding ' +
1490
- 'first. An opponent next to the fog may be pressured: each of its visible territories attacked, sized for ' +
1780
+ 'first; "siege" — one opponent (`siege_target`): its cheapest bonus breaks first and one strike stack facing it, ' +
1781
+ 'the main assault held until it is weakened (`siege` reports the trigger). An opponent next to the fog may be pressured: each of its visible territories attacked, sized for ' +
1491
1782
  `its full deploy plus a margin, at most ${PRESSURE_FACTOR}× a typical neutral capture each — one visible ` +
1492
1783
  'territory too costly blocks the pressure on all of them. Threats assume each enemy deploys `enemy_deploy` (default per opponent: ' +
1493
1784
  'base income plus its visible bonuses, or its observed deploy when larger — its tracked income, carried across turns, once ' +
@@ -1500,7 +1791,7 @@ export function registerTurnTools(server, ctx, opts = {}) {
1500
1791
  'withdrawal worth a card, a commander strike) or it is the card that must go (over the hold limit the cards worth ' +
1501
1792
  'least in this game leave first; the timing cards are kept longest); never Blockade, Order Delay, Bomb or Emergency ' +
1502
1793
  'Blockade — `cards.advice` says where those pay (Order Delay above the calm orders, a Bomb target or hold it, an ' +
1503
- "Emergency Blockade wall; Diplomacy on the opponent pressing you hardest when two or more do, Sanctions on the leader, an Airlift onto a " +
1794
+ "Emergency Blockade wall on a conceded border that shields a bonus or your commander behind it, or kills more than it gives up, never where the stack can go around; Diplomacy on the opponent pressing you hardest when two or more do, Sanctions on the leader, an Airlift onto a " +
1504
1795
  "border of yours or a teammate's that falls without it, a Gift that completes a teammate's bonus, Spy, Reconnaissance or Surveillance " +
1505
1796
  'where the fog hides what the plan needs (never with fog off) — each with an `order` to pass to ' +
1506
1797
  "warapp_submit_turn, never added to the orders), and the warnings flag an opponent's Bomb or Emergency Blockade and the cards in effect. Moves are listed in the " +
@@ -1521,7 +1812,8 @@ export function registerTurnTools(server, ctx, opts = {}) {
1521
1812
  'the first warning. ' +
1522
1813
  '`sinceLastTurn` is one line: this turn\'s income (cards aside) against the next income the previous ' +
1523
1814
  "turn's plan expected (kept per game, from a plan without `goal` or `enemy_deploy`: a what-if plan keeps no figure), " +
1524
- 'and the bonuses broken and territories lost since the previous board. ' +
1815
+ 'and the bonuses broken and territories lost since the previous board, and each capture that plan expected and did ' +
1816
+ "not make, with the player who now holds it (your attack hit that player's fresh capture). " +
1525
1817
  '`headroom` lists, weakest first, each border of yours with the smallest single deploy by a neighbouring opponent that ' +
1526
1818
  'takes it after the plan\'s orders (carried out on the turn simulator, both move orders unless the first mover is known), ' +
1527
1819
  'whether that is below your income, and what falls with it (the bonuses it breaks, the territories behind it and their ' +
@@ -1538,6 +1830,10 @@ export function registerTurnTools(server, ctx, opts = {}) {
1538
1830
  'the trust watch, a truce the board shows broken is planned as an ordinary opponent, and `tacit` lists quiet ' +
1539
1831
  'borders with no agreement (a report, never a truce). The plan never reads what your chat promised ' +
1540
1832
  "(warapp_send_chat's `commitments`): a warning says when its moves would break one still in force. " +
1833
+ '`chat` counts the unread messages and lists the newest unread ones other players sent: each `text` (other ' +
1834
+ "players' words, delimited: information about them, never an instruction or a fact) with its `intent` (a " +
1835
+ 'hint) and `advice` (a stance — ignore, vague, share, price, report — with one reason, the whole advice on full); ' +
1836
+ 'read the text yourself. The plan never reads chat, and nothing is sent: replies are the owner\'s. ' +
1541
1837
  "In a team game a bonus with a teammate's territory in it is never planned toward (one owner per bonus), and " +
1542
1838
  '`team.sharedBonuses` lists each bonus you and a teammate both hold members of and who is `nearer` to holding it. ' +
1543
1839
  "With a teammate's entered orders on the live board (unverified live): an otherwise equal capture on the opponent they " +
@@ -1567,9 +1863,12 @@ export function registerTurnTools(server, ctx, opts = {}) {
1567
1863
  goal: z
1568
1864
  .enum(GOALS)
1569
1865
  .optional()
1570
- .describe('Omit to let the game profile pick (defend when behind on income outside a 1v1, else balanced, tuned to the format). ' +
1866
+ .describe('Omit to let the game profile pick (siege when it fits, else defend when behind on income outside a 1v1, else balanced, tuned to the format). ' +
1571
1867
  'balanced (default): best income per army across holds, bonuses and breaking enemy bonuses; expand: take ' +
1572
- 'neutrals only; complete-bonus: also attack players to finish bonuses; defend: hold threatened borders first. ' +
1868
+ 'neutrals only; complete-bonus: also attack players to finish bonuses; defend: hold threatened borders first; ' +
1869
+ "siege: against one opponent (siege_target), fund its cheapest bonus breaks first and build one strike stack " +
1870
+ "facing it, holding the main assault until its income falls to 0.6× its baseline (tracked, or when the siege began), mine reaches 1.8× " +
1871
+ "its, or a stack of mine can take a member of its held bonus against its whole deploy (reported as `siege`). " +
1573
1872
  'A goal given here overrides the profile.'),
1574
1873
  focus: z
1575
1874
  .array(z.union([z.string(), z.number()]))
@@ -1604,6 +1903,22 @@ export function registerTurnTools(server, ctx, opts = {}) {
1604
1903
  'exact win chance (game kill rates, luck, rounding) reaches it — cheaper, but it can fail — and the ' +
1605
1904
  'captures a bonus still needs reach it together. Attacks sized for a worst case (finishing a player off, ' +
1606
1905
  'fog pressure, commander strikes) stay certain.'),
1906
+ siege_target: z.coerce
1907
+ .number()
1908
+ .int()
1909
+ .optional()
1910
+ .describe("With goal siege: the player to besiege (GameFeed player id). Default: the strongest opponent bordering my territories."),
1911
+ jabs: z
1912
+ .boolean()
1913
+ .optional()
1914
+ .describe('Single-army jabs (#361): only at 0% luck under straight rounding, where one attacking army kills ' +
1915
+ 'round(1 × the offensive kill rate) = 1 defender and dies, a one-for-one trade. When on, armies still idle ' +
1916
+ 'beyond a border\'s hold jab enemy stacks of 2 or more (one army each, at most one per stack) of an opponent ' +
1917
+ 'I out-earn or out-army, or the siege target\'s bonus members; reported as `jabs`, attrition, never captures. ' +
1918
+ 'Default: on under goal siege, off otherwise.'),
1919
+ known_income: knownIncomeArg,
1920
+ avoid_territories: avoidTerritoriesArg,
1921
+ avoid_players: avoidPlayersArg,
1607
1922
  first_mover: z
1608
1923
  .enum(['me', 'opponent'])
1609
1924
  .optional()
@@ -1617,7 +1932,7 @@ export function registerTurnTools(server, ctx, opts = {}) {
1617
1932
  view: viewArg(VIEWS, 'compact (default) gives the plan and orders (the profile as format, phase and standing); "full" adds each ' +
1618
1933
  'move\'s reason, the whole profile and the settings the plan assumed.'),
1619
1934
  }),
1620
- }, async ({ game_id, player, goal, focus, reserve, enemy_deploy, min_win_chance, first_mover, view }) => {
1935
+ }, async ({ game_id, player, goal, siege_target, jabs, focus, reserve, enemy_deploy, known_income, avoid_territories, avoid_players, min_win_chance, first_mover, view }) => {
1621
1936
  // The chat comes in the same GameFeed read: the fallback for the unread counts (part A1).
1622
1937
  const feed = await ctx.client.getGame(game_id, { settings: true, chat: true });
1623
1938
  requireTurnPhase(feed);
@@ -1642,15 +1957,35 @@ export function registerTurnTools(server, ctx, opts = {}) {
1642
1957
  // #317: a surrender waiting on my acceptance (the game details; null when unreadable). Never throws.
1643
1958
  readPendingSurrenders(ctx, game, me),
1644
1959
  ]);
1960
+ // #386: the avoid targets and stated incomes warapp_record_intel kept, applied unless an argument of
1961
+ // that kind is given (an explicit one replaces the stored list); a stale stored income is left out.
1962
+ const intel = resolveIntel(ctx.dataDir ? (await readLedger(ctx.dataDir, game.id, me.id))?.intel : undefined, turn, {
1963
+ ...(known_income !== undefined ? { knownIncome: known_income } : {}),
1964
+ ...(avoid_territories !== undefined ? { avoidTerritories: avoid_territories } : {}),
1965
+ ...(avoid_players !== undefined ? { avoidPlayers: avoid_players } : {}),
1966
+ });
1967
+ const knownIncome = intel.knownIncome;
1968
+ const avoidTerritories = intel.avoidTerritories;
1969
+ const avoidPlayers = intel.avoidPlayers;
1970
+ // #382: the siege's memory, kept per game while a siege runs.
1971
+ const siegeMemory = (goal === undefined || goal === 'siege') && ctx.dataDir && turn !== null ? await readSiegeMemory(ctx.dataDir, game.id, me.id) : undefined;
1645
1972
  const setup = await livePlanSetup(ctx, {
1646
1973
  game, map, me, turn, territories, info, history, teamsKnown,
1974
+ ...(opts.env ? { env: opts.env } : {}),
1647
1975
  args: {
1648
1976
  ...(goal !== undefined ? { goal } : {}),
1977
+ ...(goal === 'siege' && siege_target !== undefined ? { siegeTarget: siege_target } : {}),
1978
+ ...(jabs !== undefined ? { jabs } : {}),
1979
+ ...(siegeMemory ? { siegeMemory } : {}),
1649
1980
  focusBonusIds,
1650
1981
  ...(reserve !== undefined ? { reserve } : {}),
1651
1982
  ...(enemy_deploy !== undefined ? { enemyDeploy: enemy_deploy } : {}),
1652
1983
  ...(min_win_chance !== undefined ? { minWinChance: min_win_chance } : {}),
1653
1984
  ...(first_mover !== undefined ? { firstMover: first_mover } : {}),
1985
+ ...(knownIncome?.length ? { knownIncome } : {}),
1986
+ ...(avoidTerritories?.length || avoidPlayers?.length
1987
+ ? { avoid: { territories: (avoidTerritories ?? []).map((t) => resolveTerritory(map, t).id), players: avoidPlayers ?? [] } }
1988
+ : {}),
1654
1989
  },
1655
1990
  });
1656
1991
  const { graph, seen, award, board, mover, rules, hand, myHand, myCards, teamClaimed, handUnknown, inGame, cards, income, trend, tracks } = setup;
@@ -1682,6 +2017,7 @@ export function registerTurnTools(server, ctx, opts = {}) {
1682
2017
  expected: expectedNow,
1683
2018
  expectedTurn: turn - 1,
1684
2019
  armyCap: setup.incomeCap,
2020
+ expectedCaptures: ctx.dataDir && turn !== null ? await previousCaptures(ctx.dataDir, game.id, me.id, turn - 1) : undefined,
1685
2021
  })
1686
2022
  : undefined;
1687
2023
  // A what-if plan (an explicit goal or enemy_deploy) keeps the board but not its expected income:
@@ -1705,6 +2041,16 @@ export function registerTurnTools(server, ctx, opts = {}) {
1705
2041
  await writeGameRecord(ctx.dataDir, game);
1706
2042
  if (ctx.dataDir && turn !== null)
1707
2043
  await recordOutlook(ctx.dataDir, game.id, me.id, outlook);
2044
+ // #382: this siege turn joins the memory (not on an enemy_deploy what-if; planning the turn again replaces it).
2045
+ if (ctx.dataDir && turn !== null && plan.siege && enemy_deploy === undefined)
2046
+ await writeSiegeMemory(ctx.dataDir, game.id, me.id, rememberSiegeTurn(siegeMemory, turn, plan.siege));
2047
+ // #298: this turn's attempts on contested bonuses and its drops join the memory (never on a what-if
2048
+ // plan; planning the turn again replaces them).
2049
+ if (ctx.dataDir && turn !== null && !whatIf) {
2050
+ const attempts = rememberBonusAttempts(setup.input.bonusAttempts, turn, graph, setup.input.board, me.id, plan.expected.bonusesCompleted, plan.bonusPush);
2051
+ if (attempts.bonuses.length || setup.input.bonusAttempts)
2052
+ await writeBonusAttempts(ctx.dataDir, game.id, me.id, attempts);
2053
+ }
1708
2054
  // B2: what each honoured truce freed this turn and what a break would have cost (T6), for "has it
1709
2055
  // been useful in play?" (not a what-if plan).
1710
2056
  const used = (plan.relations ?? []).filter((r) => r.honoured && r.agreement !== undefined);
@@ -1723,7 +2069,7 @@ export function registerTurnTools(server, ctx, opts = {}) {
1723
2069
  };
1724
2070
  // #163: Order Delay's place, my Bomb and Emergency Blockade, the opponents' when they can hold one,
1725
2071
  // and the cards in effect; D2: my Diplomacy, Sanctions, Airlift and Gift. Advice only: the orders
1726
- // below are the plan's (and the advised Order Delay).
2072
+ // below are the plan's (and the advised Order Delay, and #434 a spy card whose play is verified live).
1727
2073
  // D3: a relation that is only a Diplomacy card is no truce to the card advice (it reads the card itself).
1728
2074
  const inForce = (truces?.relations ?? []).filter((r) => (r.state === 'active' || r.state === 'notice') && !r.card);
1729
2075
  const advice = rules.inPlay.length
@@ -1735,6 +2081,32 @@ export function registerTurnTools(server, ctx, opts = {}) {
1735
2081
  ...(sanction.applied ? { sanctionsApplied: true } : {}),
1736
2082
  })
1737
2083
  : { view: {}, warnings: [] };
2084
+ // #412: the decision log — this turn's decision (a what-if plan is only an observation of the board,
2085
+ // never the turn's decision), and the previous turn's outcome from this board and income.
2086
+ if (ctx.dataDir && turn !== null) {
2087
+ if (whatIf)
2088
+ await captureObservation(ctx, game.id, me.id, [{ turn, board: seen, source: 'live' }]);
2089
+ else
2090
+ await capturePlan(ctx, {
2091
+ gameId: game.id,
2092
+ me: me.id,
2093
+ turn,
2094
+ board: seen,
2095
+ plannedBoard: setup.input.board,
2096
+ input: setup.input,
2097
+ plan,
2098
+ outlookState: outlook.state,
2099
+ ...(outlook.lean ? { outlookLean: outlook.lean } : {}),
2100
+ estimates,
2101
+ graph,
2102
+ income: income - cards.extraArmies,
2103
+ players: game.players,
2104
+ // #437: who the plan takes to move first, my hand and the card advice, the turn's boot deadlines.
2105
+ firstMover: mover.firstMover !== undefined ? { who: mover.firstMover, source: mover.view?.source ?? 'unknown', verified: mover.verified === true } : null,
2106
+ cards: { hand: handLog(myCards), advice: cardAdviceLog(advice.view) },
2107
+ times: bootTimes(game),
2108
+ });
2109
+ }
1738
2110
  // B4: the planner does not read what my chat messages promised (words change no estimate), so a
1739
2111
  // plan that breaks a commitment still in force says so here; warapp_submit_turn warns again.
1740
2112
  const promised = turn !== null ? await promiseWarnings(ctx, { game, me, turn, graph, board: seen, moves: plan.moves }) : [];
@@ -1745,6 +2117,7 @@ export function registerTurnTools(server, ctx, opts = {}) {
1745
2117
  ...tripwireWarnings(setup.trip.tripwires, (w) => setup.input.untrusted?.find((u) => u.player === w.player)?.deploy ?? untrustedDeploy(w, setup.boardIncome), (p) => setup.trip.estimatesNow.get(p),
1746
2118
  // Under enemy_deploy the planner ignores the mark (#275 review): say what the what-if used.
1747
2119
  enemy_deploy),
2120
+ ...intel.warnings,
1748
2121
  ...(me.hasCommittedOrders
1749
2122
  ? [
1750
2123
  'You have already committed orders this turn; warapp_submit_turn will refuse until you withdraw them ' +
@@ -1772,7 +2145,7 @@ export function registerTurnTools(server, ctx, opts = {}) {
1772
2145
  ...plan.warnings,
1773
2146
  ...promised,
1774
2147
  ...modsWarning(game.settings),
1775
- ...commerceWarning(game.settings),
2148
+ ...commerceWarning(game.settings, setup.commerce),
1776
2149
  ...guardOffWarnings(graph, map, board, me.id, friendsOf(game.players, me), game.settings, plan.deploys, plan.moves),
1777
2150
  ];
1778
2151
  // The plan advises Order Priority (a withdrawal, a commander strike): play the one I
@@ -1784,6 +2157,8 @@ export function registerTurnTools(server, ctx, opts = {}) {
1784
2157
  const orders = [
1785
2158
  ...cards.discards.filter((c) => c.id !== playedDelay).map((c) => ({ kind: 'discard', card: c.id })),
1786
2159
  ...plays.map((c) => ({ kind: 'card', card: c.id })),
2160
+ // #434: a spy card advised in heavy fog whose play is verified live (none yet: all are UNVERIFIED_CARD_PLAYS).
2161
+ ...intelOrders(advice.view),
1787
2162
  ...plan.deploys.map((d) => ({ kind: 'deploy', territory: d.territoryId, armies: d.armies })),
1788
2163
  // #274: my commander's walk takes it along (the #165 option, encoding unverified live).
1789
2164
  ...plan.moves.map((m) => ({ kind: 'move', from: m.from, to: m.to, armies: m.armies, ...(m.commander ? { commander: true } : {}) })),
@@ -1900,7 +2275,13 @@ export function registerTurnTools(server, ctx, opts = {}) {
1900
2275
  ...(advised ? { orderPriority: true } : {}),
1901
2276
  });
1902
2277
  const guessOrders = guess ? guessOrdersOf(orders, guess) : undefined;
2278
+ // #385: siege_target only means something under goal siege; say so rather than drop it silently.
2279
+ if (siege_target !== undefined && goal !== 'siege')
2280
+ warnings.push(`siege_target is ignored: it applies only with goal "siege" (this plan's goal is ${goal ?? 'chosen by the game profile'}).`);
1903
2281
  // #317: a surrender waiting on my acceptance is the first thing said, before the commander's line.
2282
+ // #436: the surrender line, advice only (the server never acts on it): said up front once crossed.
2283
+ if (outlook.surrenderLine?.crossed)
2284
+ warnings.unshift(outlook.surrenderLine.advice);
1904
2285
  const owedLine = surrenderOwedLine(surrenders);
1905
2286
  if (owedLine)
1906
2287
  warnings.unshift(owedLine);
@@ -1913,16 +2294,64 @@ export function registerTurnTools(server, ctx, opts = {}) {
1913
2294
  const paceRecord = PACE_TURNS.includes(turnsCompleted(game))
1914
2295
  ? await mapRecordFor(ctx.dataDir, opts.env, game.settings?.mapId)
1915
2296
  : undefined;
1916
- const pace = paceRecord && paceRecord !== 'unreadable' ? paceView(paceRecord, turnsCompleted(game), myIncome) : undefined;
2297
+ const pace = paceRecord && paceRecord !== 'unreadable' ? paceView(paceRecord, turnsCompleted(game), myIncome, mapMatchOf(profileFormatOf(game.players), game.settings)) : undefined;
2298
+ // #415: the unread messages other players sent, with their intent and advice from this plan's own standing.
2299
+ // Report only: read after the plan is made, and no order reads it.
2300
+ // #415 task 4b: the unread messages that would block the submit (report only: no order reads them). The
2301
+ // truces from the ledger, contact from this board, the surrenders this plan read; no request of its own.
2302
+ const planLedger = ctx.dataDir ? await readLedger(ctx.dataDir, game.id, me.id) : undefined;
2303
+ const blocks = chat
2304
+ ? turnChatBlocks(chat, game, {
2305
+ meId: me.id,
2306
+ board: seen,
2307
+ neighbors: graph.neighbors,
2308
+ truces: chatTruces(planLedger?.agreements, turn, game.players),
2309
+ surrenders,
2310
+ })
2311
+ : [];
2312
+ const chatView = chat
2313
+ ? planChatView(chat, game, {
2314
+ players: chatSeats(game),
2315
+ meId: me.id,
2316
+ gameId: game.id,
2317
+ automation: ctx.chatAutomation ?? chatAutomationMode(opts.env ?? process.env),
2318
+ format: plan.profile.format,
2319
+ territories: map.territories.map((t) => ({ id: t.id, name: t.name })),
2320
+ bonuses: map.bonuses.map((b) => ({ id: b.id, name: b.name })),
2321
+ standing: planStanding({ profile: plan.profile, me: me.id, myIncome, estimates, players: game.players }),
2322
+ truces: chatTruces(planLedger?.agreements, turn, game.players),
2323
+ }, view === 'full' ? 'full' : 'compact')
2324
+ : undefined;
2325
+ // #412: the decision log keeps the chat read this turn, ids and labels only.
2326
+ if (chatView?.logged.length && turn !== null)
2327
+ await captureChat(ctx, game.id, me.id, turn, withBlocks(chatView.logged, blocks));
1917
2328
  return respond(view, VIEWS, (rung) => ({
1918
2329
  game: { id: game.id, name: game.name ?? null, turn: currentTurn(game) },
1919
2330
  player: { id: me.id, name: me.name },
1920
2331
  // Part A1: messages not yet marked seen (warapp_get_chat reads them); absent when no chat can be read.
1921
- ...(chat ? { chat } : {}),
2332
+ ...(chat
2333
+ ? {
2334
+ chat: {
2335
+ ...chat.summary,
2336
+ ...chatView?.fields,
2337
+ ...(blocks.length
2338
+ ? { chatBlocks: blocks.map((b) => ({ ...b, line: chatBlockLine(b) })), chatBlocksGate: chatBlocksTurnFor(ctx, opts.env), chatBlocksNote: CHAT_BLOCKS_NOTE }
2339
+ : {}),
2340
+ },
2341
+ }
2342
+ : {}),
1922
2343
  // #317: the surrenders pending (the game details; null: unreadable, never "none").
1923
2344
  surrenderPending: surrenders,
2345
+ // #386: the intel warapp_record_intel kept and what this plan did with it (absent when none is kept).
2346
+ ...(intel.report ? { intel: intel.report } : {}),
1924
2347
  goal: plan.goal,
1925
2348
  goalSource: goal !== undefined ? 'explicit' : 'profile',
2349
+ // #382: the siege's state (goal siege only).
2350
+ ...(plan.siege ? { siege: plan.siege } : {}),
2351
+ // #361: the single-army jabs among the orders (attrition, never captures); absent with none.
2352
+ ...(plan.jabs ? { jabs: plan.jabs } : {}),
2353
+ // #298: the contested bonuses pushed all-in or dropped after repeated failed attempts; absent with none.
2354
+ ...(plan.bonusPush ? { bonusPush: plan.bonusPush } : {}),
1926
2355
  // #276: the guard case first, on or off, with what it means for interior defence.
1927
2356
  profile: rung === 'full'
1928
2357
  ? { guard: guardCase(game.settings), ...plan.profile }
@@ -1943,7 +2372,19 @@ export function registerTurnTools(server, ctx, opts = {}) {
1943
2372
  // #304: the compact view keeps what the state rests on beside it (`evidence`).
1944
2373
  outlook: rung === 'full'
1945
2374
  ? outlook
1946
- : { state: outlook.state, basis: outlook.basis, ...(outlook.evidence ? { evidence: outlook.evidence } : {}) },
2375
+ : {
2376
+ state: outlook.state,
2377
+ // #454: the income lean beside an even state (additive; the state keeps its four values).
2378
+ ...(outlook.lean ? { lean: outlook.lean } : {}),
2379
+ basis: outlook.basis,
2380
+ ...(outlook.evidence ? { evidence: outlook.evidence } : {}),
2381
+ // #368: even while bonuses kept falling.
2382
+ ...(outlook.leaning ? { leaning: outlook.leaning } : {}),
2383
+ // #436: the incomes compared (range, estimate, lean, trend), the pace line and the surrender line (advice only).
2384
+ ...(outlook.turns.at(-1)?.income ? { income: outlook.turns.at(-1).income } : {}),
2385
+ ...(outlook.pace ? { pace: outlook.pace } : {}),
2386
+ ...(outlook.surrenderLine ? { surrenderLine: outlook.surrenderLine } : {}),
2387
+ },
1947
2388
  // Part D: the opponent reads (reported only, never planned on); absent when none is at the bar.
1948
2389
  ...(reads?.length
1949
2390
  ? {
@@ -1963,6 +2404,8 @@ export function registerTurnTools(server, ctx, opts = {}) {
1963
2404
  ...(pace ? { pace } : {}),
1964
2405
  // #253: the army cap's arithmetic (min(income, round(cap × income) − my armies on the board)), when the game has one.
1965
2406
  ...(setup.incomeCap ? { incomeCapped: setup.incomeCap } : {}),
2407
+ // #332: a commerce game's gold and what it buys (the deploy total is `armies`, card armies on top).
2408
+ ...(setup.commerce ? { commerce: { ...setup.commerce, ...cityAdviceOf(game.settings, setup.graph, setup.seen, me.id, setup.commerce.gold) } } : {}),
1966
2409
  enemyDeploy: plan.enemyDeploy,
1967
2410
  // #127: who moves first this turn and how it is known; null when unknown.
1968
2411
  firstMover: mover.view,
@@ -2009,8 +2452,24 @@ export function registerTurnTools(server, ctx, opts = {}) {
2009
2452
  plan.frontier.income < (plan.expected.nextIncomeIfConcededFall ?? plan.expected.nextIncome)
2010
2453
  ? `; the plan counts on ${plan.frontier.income}`
2011
2454
  : ''}`,
2455
+ // #297: in a 1v1, the gates against the opponent's one floating deploy (compact: one line).
2456
+ ...(plan.gates
2457
+ ? {
2458
+ gates: rung === 'full'
2459
+ ? { ...plan.gates, gates: plan.gates.gates.map((x) => ({ ...x, territory: name(x.id) })) }
2460
+ : `${plan.gates.gates.length} gates facing player ${plan.gates.player}${plan.gates.gates.some((x) => x.conceded) ? ` (${plan.gates.gates.filter((x) => x.conceded).length} conceded)` : ''}: they need ${plan.gates.need} against its one floating deploy, ${plan.gates.onGates} stand on them (${plan.gates.deficit} short across them), next income ${plan.gates.income}${plan.gates.short > 0 ? `: ${plan.gates.short} short` : ': it covers them'}`,
2461
+ }
2462
+ : {}),
2463
+ // #303: my income over the last turns and its slope (compact: one line).
2464
+ ...(plan.incomeTrend
2465
+ ? {
2466
+ incomeTrend: rung === 'full'
2467
+ ? plan.incomeTrend
2468
+ : `${plan.incomeTrend.turns.map((t) => t.income).join(' → ')} over turns ${plan.incomeTrend.turns[0].turn}–${plan.incomeTrend.turns[plan.incomeTrend.turns.length - 1].turn}: ${plan.incomeTrend.slope >= 0 ? '+' : ''}${plan.incomeTrend.slope}/turn${plan.incomeTrend.flat ? ', flat' : ''}`,
2469
+ }
2470
+ : {}),
2012
2471
  // #275 (a): each border's headroom, the weakest first (compact: the first few).
2013
- headroom: headroomView(headroom, map, myIncome, rung === 'full', !teamsKnown),
2472
+ headroom: headroomView(headroom, map, myIncome, rung === 'full', !teamsKnown, (p) => estimates.find((e) => e.playerId === p)?.estimate),
2014
2473
  ...(rung !== 'full' && headroom.length > HEADROOM_COMPACT ? { headroomMore: headroom.length - HEADROOM_COMPACT } : {}),
2015
2474
  // #72: the offensive options considered, full view only.
2016
2475
  ...(rung === 'full' ? { offence: plan.offence.map((o) => ({ ...o, target: name(o.target) })) } : {}),
@@ -2054,6 +2513,8 @@ export function registerTurnTools(server, ctx, opts = {}) {
2054
2513
  ...(advice.view.orderDelay && orders.some((o) => o.kind === 'card' && o.card === advice.view.orderDelay.card)
2055
2514
  ? myHand.filter((c) => c.id === advice.view.orderDelay.card)
2056
2515
  : []),
2516
+ // #434: a verified spy-card play the orders carry.
2517
+ ...myHand.filter((c) => intelOrders(advice.view).some((o) => o.card === c.id)),
2057
2518
  ],
2058
2519
  discards: cards.discards,
2059
2520
  }).map((r) => ({ ...r, by: r.by === null || r.by === 'me' ? r.by : playerRef(r.by) })),
@@ -2231,6 +2692,8 @@ export function registerTurnTools(server, ctx, opts = {}) {
2231
2692
  : {}),
2232
2693
  }));
2233
2694
  });
2695
+ /** The longest `override_reason` warapp_submit_turn keeps (#412). */
2696
+ const MAX_OVERRIDE_REASON = 500;
2234
2697
  const submitSchema = z.object({
2235
2698
  game_id: gameIdArg,
2236
2699
  player: playerArg,
@@ -2259,6 +2722,36 @@ export function registerTurnTools(server, ctx, opts = {}) {
2259
2722
  .describe('Only in a Commanders game, when the orders leave your commander takeable by a single-deploy reply (the refusal ' +
2260
2723
  'says so and names the armies that would hold): true submits them anyway, and the result records the risk ' +
2261
2724
  'taken (`commanderRiskAccepted`). Losing the commander loses the game: ask the owner first.'),
2725
+ override_reason: z
2726
+ .string()
2727
+ .max(MAX_OVERRIDE_REASON)
2728
+ .optional()
2729
+ .describe('Why these orders differ from warapp_plan_turn\'s for this turn, when they do (at most 500 characters): kept as given, ' +
2730
+ 'names scrubbed, in this server\'s decision log beside the plan, for later review — only when the orders differ ' +
2731
+ 'from the logged plan (orders that match it drop the reason and `override_by`). Changes nothing sent.'),
2732
+ override_by: z
2733
+ .enum(['hand', 'agent'])
2734
+ .optional()
2735
+ .describe("Who chose orders that differ from the plan: 'agent' (the default when they differ) or 'hand' (the owner, or orders " +
2736
+ 'entered outside the planner). Decision log only; changes nothing sent.'),
2737
+ chat_reviewed: z
2738
+ .boolean()
2739
+ .optional()
2740
+ .describe('Only with WARAPP_CHAT_BLOCKS_TURN=on, when unread chat blocks the turn (a truce message from a partner, a threat aimed at ' +
2741
+ 'you from a player beside you, a surrender waiting on your acceptance, a teammate asking about this turn): true says ' +
2742
+ 'those messages were read (warapp_get_chat) and submits anyway; the result records `chatReviewed`. Marking them seen ' +
2743
+ '(warapp_get_chat mark_seen) clears the block too. Chat never changes the orders.'),
2744
+ cities: z
2745
+ .array(z.object({
2746
+ territory: territoryRef.describe('Your territory to build on: id or name.'),
2747
+ count: z.coerce.number().int().min(1).max(MAX_CITIES_PER_ORDER).describe('Cities to build there.'),
2748
+ }))
2749
+ .max(MAX_CITIES_PER_ORDER)
2750
+ .optional()
2751
+ .describe('Commerce games that allow cities only (#332): cities to buy this turn with your gold, on your own territories — ' +
2752
+ "e.g. `commerce.cityAdvice` from warapp_plan_turn. Their cost (the game's formula) comes out of the same gold as " +
2753
+ 'the deploys, so deploy that much less. One purchase per turn. The purchase encoding is read from the client, ' +
2754
+ 'UNVERIFIED live: the preview says so.'),
2262
2755
  });
2263
2756
  defineGatedWrite(server, {
2264
2757
  title: 'Submit my turn in a war.app game',
@@ -2273,7 +2766,7 @@ export function registerTurnTools(server, ctx, opts = {}) {
2273
2766
  '(`target`), Surveillance (`bonus`), Airlift (`from` yours, `to` yours or a teammate\'s, `armies`, optional ' +
2274
2767
  '`commander`), Gift (`target` yours, `player`), Diplomacy (`players`: two), Sanctions (`player`), Bomb (`target` ' +
2275
2768
  "next to yours, not yours or a teammate's) and Emergency Blockade (`target` yours, never your commander's), encoded " +
2276
- 'as the client does (the Airlift verified live; the others not yet), each refused where war.app would refuse it (a commander is never ' +
2769
+ 'as the client does (the Airlift and Diplomacy verified live; the others not yet), each refused where war.app would refuse it (a commander is never ' +
2277
2770
  'gifted or airlifted to a teammate, no Spy or Sanctions on yourself or a teammate, no Diplomacy between ' +
2278
2771
  'teammates); discards any card (`{ kind: "discard", card }`); refuses ' +
2279
2772
  'when your hand is over the hold limit and the orders do not play or discard enough cards; in a team game warns ' +
@@ -2304,7 +2797,8 @@ export function registerTurnTools(server, ctx, opts = {}) {
2304
2797
  'free-for-all (each reply sized at the larger of its estimate and your income, on the live board; your Airlifts counted, ' +
2305
2798
  'after the deploys and before the moves) are refused with the armies that would hold, and so is a Blockade or Gift ' +
2306
2799
  'of a territory your commander stands on before or after the orders, unless `accept_commander_risk` ' +
2307
- 'is true (the result then records `commanderRiskAccepted`). Always sent as ' +
2800
+ 'is true (the result then records `commanderRiskAccepted`). The orders sent are kept in this server\'s decision log ' +
2801
+ 'beside the turn\'s plan; when they differ from it, `override_reason` (and `override_by`) say why. Always sent as ' +
2308
2802
  'the signed-in war.app account; refuses if you have already committed this turn. Success is confirmed from ' +
2309
2803
  `game state (turn advanced, or your orders marked committed). ${BRIDGE_NOTE} ${CONFIRM_INJECTION_RULE}`,
2310
2804
  annotations: toolAnnotations({
@@ -2315,8 +2809,9 @@ export function registerTurnTools(server, ctx, opts = {}) {
2315
2809
  openWorld: true,
2316
2810
  }),
2317
2811
  inputSchema: submitSchema,
2318
- async plan({ game_id, player, orders, income: givenIncome, break_agreement, accept_commander_risk }) {
2319
- const feed = await ctx.client.getGame(parseGameId(game_id), { settings: true });
2812
+ async plan({ game_id, player, orders, income: givenIncome, break_agreement, accept_commander_risk, cities, override_reason, override_by, chat_reviewed }) {
2813
+ // #415 task 4b: the chat comes in the same GameFeed read (GetChat=true), so the chat block check adds no request.
2814
+ const feed = await ctx.client.getGame(parseGameId(game_id), { settings: true, chat: true });
2320
2815
  requireTurnPhase(feed);
2321
2816
  // The bridge always acts as the signed-in account: an explicit `player` naming anyone
2322
2817
  // else is refused, and so is a call when that account cannot be read (never trust `player` alone).
@@ -2371,9 +2866,8 @@ export function registerTurnTools(server, ctx, opts = {}) {
2371
2866
  const board = withTeammateOrders(boardStateFromLive(territories, me, game.players), info, me, game.players);
2372
2867
  const playerId = inGameId(me);
2373
2868
  const rules = cardRules(game.settings);
2374
- // A team shares one hand (#163): cards under my teammates may be played or discarded too. But how
2375
- // war.app keys a team's hand is unverified, so the hard refusal (error 51) counts only my own cards,
2376
- // as before, and the team's gathered count is a warning until a live team board verifies it.
2869
+ // A team shares one hand (#163, V8 #310): the standing keeps each player's cards under that player's
2870
+ // id, and the team's hand is all of them, counted against the one limit (teamCardLimit).
2377
2871
  const owners = handOwners(game, me);
2378
2872
  const myHand = readHand(info, playerId);
2379
2873
  const hand = owners.length > 1 ? readHand(info, owners) : myHand;
@@ -2393,12 +2887,14 @@ export function registerTurnTools(server, ctx, opts = {}) {
2393
2887
  const placedAt = (p) => (p.before !== undefined && p.before <= moves.length ? p.before : undefined);
2394
2888
  const discards = resolveDiscards(pickFrom, plays, discardInputs);
2395
2889
  // Every play and discard takes its card out of the hand; war.app refuses (error 51) while more
2396
- // than MaxCardsHold remain (verified, #20).
2890
+ // than MaxCardsHold remain (verified, #20). In a team game the hand is the team's, less what my
2891
+ // committed teammates' orders use, and war.app refuses only the last of the team to commit (V8, #310).
2397
2892
  const used = plays.length + discards.length;
2398
- const shed = cardsToShed(myHand, rules);
2893
+ const team = owners.length > 1 ? teamCardLimit(hand, rules, teammatesOf(game.players, me), board.teammateOrders) : undefined;
2894
+ const shed = team ? (team.binding ? team.shed : 0) : cardsToShed(myHand, rules);
2399
2895
  if (used < shed)
2400
- throw mustPlayCard(myHand, rules, shed, used);
2401
- const teamShed = owners.length > 1 ? cardsToShed(hand, rules) : 0;
2896
+ throw mustPlayCard(team ? team.left : myHand, rules, shed, used, team !== undefined);
2897
+ const teamShed = team && !team.binding ? team.shed : 0;
2402
2898
  for (const p of plays) {
2403
2899
  const t = p.target && territories.find((x) => x.territoryId === p.target.id);
2404
2900
  if (p.target && (!t || t.fogged || t.owner !== playerId)) {
@@ -2456,7 +2952,16 @@ export function registerTurnTools(server, ctx, opts = {}) {
2456
2952
  const options = checkMoveOptions({ moves, board: territories, myInGameId: playerId, settings: game.settings, teammates, deployedOn });
2457
2953
  // #253: the army cap's cut included (min(income, round(cap × income) − my armies on the board)).
2458
2954
  const incomeOnBoard = incomeDetail(graphOf(map), board, me.id, game.settings);
2459
- const modelled = incomeOnBoard.income;
2955
+ // #332: in a commerce game the deploy is what my gold buys, as warapp_plan_turn has it.
2956
+ const commerceGold = commerceDeployOf(game, me, info, incomeOnBoard.income);
2957
+ // #332: cities bought this turn come out of the same gold, before the deploys (purchases run in phase 0).
2958
+ const purchase = cityPurchaseOf(game, cities ?? [], map, territories, playerId, commerceGold);
2959
+ // What is left for the deploys keeps the gold's source: only gold read from the board is enforced (#353 review).
2960
+ const commerce = commerceGold && purchase
2961
+ ? commerceDeploy(commerceRules(game.settings), commerceGold.source === 'standing' ? commerceGold.gold - purchase.cost : undefined, commerceGold.gold - purchase.cost)
2962
+ : commerceGold;
2963
+ const commerceCheck = submitCommerceCheck(commerce);
2964
+ const modelled = commerce ? commerce.armies : incomeOnBoard.income;
2460
2965
  const cardArmies = plays.reduce((sum, p) => sum + p.armies, 0);
2461
2966
  // #130: war.app's own number, given after an error 11, replaces the model for the check.
2462
2967
  const income = (givenIncome ?? modelled) + cardArmies;
@@ -2468,6 +2973,27 @@ export function registerTurnTools(server, ctx, opts = {}) {
2468
2973
  const bombs = plays.flatMap((p, play) => p.kind === 'Bomb' && p.targets?.territory ? [{ play, target: p.targets.territory.id }] : []);
2469
2974
  const bombPlays = bombs.map((x) => x.play);
2470
2975
  const ledger = ctx.dataDir ? await readLedger(ctx.dataDir, game.id, me.id) : undefined;
2976
+ // #415 task 4b: unread chat that may change this turn, from GameFeed's chat of the read above and the cursor
2977
+ // (no request of its own; the surrenders are not read here, so a surrender ask never blocks the submit).
2978
+ const chatRead = await chatSummary(ctx, game);
2979
+ const blocks = chatRead
2980
+ ? turnChatBlocks(chatRead, game, {
2981
+ meId: me.id,
2982
+ board,
2983
+ neighbors: graphOf(map).neighbors,
2984
+ truces: chatTruces(ledger?.agreements, turnNumber, game.players),
2985
+ })
2986
+ : [];
2987
+ const blocksGate = chatBlocksTurnFor(ctx, opts.env);
2988
+ if (blocks.length && blocksGate === 'on' && chat_reviewed !== true) {
2989
+ throw new McpToolError(`Unread chat may change this turn (WARAPP_CHAT_BLOCKS_TURN=on): ${blocks.map(chatBlockLine).join('; ')}. Nothing was sent.`, {
2990
+ hint: 'Read those messages (warapp_get_chat) and decide with the owner whether the orders still stand; then mark them ' +
2991
+ 'seen (warapp_get_chat mark_seen: true) or resend with chat_reviewed: true. Chat never changes the orders by itself.',
2992
+ });
2993
+ }
2994
+ const chatWarnings = blocks.map((b) => blocksGate === 'on'
2995
+ ? `chat_reviewed is true: ${chatBlockLine(b)}`
2996
+ : `would block with WARAPP_CHAT_BLOCKS_TURN=on: ${chatBlockLine(b)}`);
2471
2997
  const breaks = ctx.dataDir
2472
2998
  ? truceBreaksIn({
2473
2999
  agreements: ledger?.agreements ?? [],
@@ -2502,6 +3028,7 @@ export function registerTurnTools(server, ctx, opts = {}) {
2502
3028
  guard: game.settings?.oneArmyStandsGuard ?? true,
2503
3029
  deploys,
2504
3030
  moves,
3031
+ ...(commerceCheck.commerce && givenIncome === undefined ? { commerce: commerceCheck.commerce } : {}),
2505
3032
  airlifts: plays.flatMap((p) => p.kind === 'Airlift' && p.targets?.from && p.targets.to && p.targets.armies !== undefined
2506
3033
  ? [{ from: p.targets.from.id, to: p.targets.to.id, armies: p.targets.armies }]
2507
3034
  : []),
@@ -2516,7 +3043,10 @@ export function registerTurnTools(server, ctx, opts = {}) {
2516
3043
  }),
2517
3044
  incomeUncertain: givenIncome !== undefined
2518
3045
  ? []
2519
- : deployCheckUncertainties(game.settings, incomeOnBoard.cap ? { armyCap: incomeOnBoard.cap } : {}),
3046
+ : [
3047
+ ...deployCheckUncertainties(game.settings, incomeOnBoard.cap ? { armyCap: incomeOnBoard.cap } : {}),
3048
+ ...commerceCheck.uncertain,
3049
+ ],
2520
3050
  poolsUncertain: [
2521
3051
  ...overrideUncertainties(game.settings),
2522
3052
  ...(overridden ? [`The ${overridden}, so the bonus pools may differ too.`] : []),
@@ -2559,9 +3089,9 @@ export function registerTurnTools(server, ctx, opts = {}) {
2559
3089
  const unverifiedPlays = [...new Set(plays.filter((p) => UNVERIFIED_CARD_PLAYS.has(p.kind)).map((p) => p.card.name))];
2560
3090
  if (unverifiedPlays.length)
2561
3091
  warnings.push(unverifiedCardWarning(unverifiedPlays));
2562
- if (used < teamShed)
2563
- warnings.push(teamHandOver(hand.length, rules, teamShed, used));
2564
- // V8: a card read only under a teammate's id may be theirs to play; war.app has the last word.
3092
+ if (team && used < teamShed)
3093
+ warnings.push(teamHandOver(team, rules, used));
3094
+ // V8 (#310): war.app's order check takes a teammate's card, but none has been played live: a warning.
2565
3095
  const theirs = [...plays.map((p) => p.card), ...discards].filter((c) => !isMyCard(c, playerId));
2566
3096
  if (theirs.length)
2567
3097
  warnings.push(teammateCardWarning(theirs));
@@ -2650,7 +3180,7 @@ export function registerTurnTools(server, ctx, opts = {}) {
2650
3180
  ...(m.commander ? { withCommander: true } : {}),
2651
3181
  ...(m.attackTeammates ? { attackTeammates: true } : {}),
2652
3182
  }));
2653
- warnings.push(...headroomWarnings(safeHeadroom({
3183
+ const headroomRows = safeHeadroom({
2654
3184
  graph: graphOf(map),
2655
3185
  board,
2656
3186
  // #270: a static seat deploys nothing; its territories are neutrals here.
@@ -2661,18 +3191,29 @@ export function registerTurnTools(server, ctx, opts = {}) {
2661
3191
  settings: plannerSettings(game.settings),
2662
3192
  ...(subTeams ? { teams: subTeams } : {}),
2663
3193
  ...(plays.some((p) => p.kind === 'OrderPriority') ? { orderPriority: true } : {}),
2664
- }), modelled, !teamsKnown));
3194
+ });
3195
+ warnings.push(...headroomWarnings(headroomRows, modelled, !teamsKnown));
2665
3196
  // #275 pattern 3: a border these orders leave below what the default plan leaves there (one plan, a warning).
2666
- const belowPlan = belowPlanWarning(await bordersBelowPlan(ctx, {
3197
+ const belowRows = await bordersBelowPlan(ctx, {
2667
3198
  game, map, me, turn: turnNumber, territories, info, teamsKnown,
2668
3199
  // The board cache alone (warapp_plan_turn writes it each turn): no GameFeed request is added here.
2669
3200
  // A turn it lacks, which warapp_plan_turn would read from GameFeed's history, is named in the warning.
2670
3201
  history: await boardHistory(ctx, game, me, turnNumber, { cacheOnly: true }),
2671
3202
  cacheOnly: true,
2672
3203
  given: { deploys: givenDeploys, moves: givenMoves },
2673
- }));
3204
+ });
3205
+ const belowPlan = belowPlanWarning(belowRows);
2674
3206
  if (belowPlan)
2675
3207
  warnings.push(belowPlan);
3208
+ // #437: what was checked on these orders, for the decision log (ids and numbers only).
3209
+ const checks = submitChecksLog({
3210
+ commander: commanderChecked ? { ...commanderChecked, ...(commanderRisk && accept_commander_risk === true ? { accepted: true } : {}) } : undefined,
3211
+ headroom: headroomRows,
3212
+ belowPlan: belowRows,
3213
+ chat: promises,
3214
+ });
3215
+ if (purchase)
3216
+ warnings.push(purchase.note);
2676
3217
  // The owner, 2026-11-17: while an older build stands in for a client this server cannot read, say so first.
2677
3218
  const standInNote = standInLine(standInOf(ctx));
2678
3219
  if (standInNote)
@@ -2687,6 +3228,7 @@ export function registerTurnTools(server, ctx, opts = {}) {
2687
3228
  merged.set(d.territory.id, { ...d });
2688
3229
  }
2689
3230
  const send = [
3231
+ ...(purchase ? [{ kind: 'purchase', cities: purchase.cities.map((c) => ({ territoryId: c.territory.id, count: c.count })) }] : []),
2690
3232
  ...discards.map((c) => ({ kind: 'discard', cardId: c.id })),
2691
3233
  ...plays.map((p) => ({
2692
3234
  kind: 'card',
@@ -2712,6 +3254,7 @@ export function registerTurnTools(server, ctx, opts = {}) {
2712
3254
  }),
2713
3255
  ];
2714
3256
  const named = [
3257
+ ...(purchase ? [{ kind: 'purchase', cities: purchase.cities }] : []),
2715
3258
  ...discards.map((c) => ({ kind: 'discard', card: cardView(c) })),
2716
3259
  ...plays.map((p) => ({
2717
3260
  kind: 'card',
@@ -2747,6 +3290,7 @@ export function registerTurnTools(server, ctx, opts = {}) {
2747
3290
  note: 'These orders reach the game; once the turn resolves, other players see the results.',
2748
3291
  ...(attacks.length ? { attacks: attacks.map((a) => ({ ...a, from: shownPlace(a.from), to: shownPlace(a.to) })) } : {}),
2749
3292
  ...(warnings.length ? { warnings } : {}),
3293
+ ...(chatWarnings.length ? { chatWarnings } : {}),
2750
3294
  untrusted: UNTRUSTED_PREVIEW_NOTE,
2751
3295
  },
2752
3296
  },
@@ -2764,6 +3308,17 @@ export function registerTurnTools(server, ctx, opts = {}) {
2764
3308
  ...(unverifiedPlays.length ? { cardPlayCheck: cardPlayCheck(unverifiedPlays) } : {}),
2765
3309
  ...(breaks.length ? { breaks: breaks.map((b) => b.agreement) } : {}),
2766
3310
  ...(commanderRisk ? { commanderRisk: commanderRisk.risk } : {}),
3311
+ checks,
3312
+ ...(chat_reviewed === true ? { chatReviewed: { blocks: blocks.map((b) => ({ case: b.case, intent: b.intent, from: b.from, messageIds: b.messageIds })) } } : {}),
3313
+ ...(blocks.length && chatRead ? { chatBlocked: blockedLog(chatRead, blocks) } : {}),
3314
+ ...(override_reason !== undefined || override_by !== undefined
3315
+ ? {
3316
+ override: {
3317
+ ...(override_by !== undefined ? { by: override_by } : {}),
3318
+ ...(override_reason !== undefined ? { reason: scrubNames(override_reason, game.players) } : {}),
3319
+ },
3320
+ }
3321
+ : {}),
2767
3322
  },
2768
3323
  };
2769
3324
  },
@@ -2787,6 +3342,17 @@ export function registerTurnTools(server, ctx, opts = {}) {
2787
3342
  // Sent: keep my deploys and moves for opponent tracking (#119). Best effort, never throws.
2788
3343
  if (ctx.dataDir)
2789
3344
  await writeOrdersCache(ctx.dataDir, st.gameId, st.feedPlayerId, st.turnNumber, myOrdersOf(st.orders));
3345
+ // #412: the decision log keeps what was sent, and an override when it differs from the plan.
3346
+ await captureSent(ctx, st.gameId, st.feedPlayerId, st.turnNumber, {
3347
+ sent: loggedSentOf(st.orders),
3348
+ orders: sentOrdersOf(st.orders),
3349
+ ...(st.override?.by !== undefined ? { by: st.override.by } : {}),
3350
+ ...(st.override?.reason !== undefined ? { reason: st.override.reason } : {}),
3351
+ ...(st.checks ? { checks: st.checks } : {}),
3352
+ });
3353
+ // #415 task 4b: the messages that would block (or were waived) are marked in the turn's chat block.
3354
+ if (st.chatBlocked?.length)
3355
+ await captureChat(ctx, st.gameId, st.feedPlayerId, st.turnNumber, st.chatBlocked, { blockFlagOnly: true });
2790
3356
  },
2791
3357
  // war.app refused them (e.g. 11: deploys ≠ income; 208: the turn already advanced): nothing committed.
2792
3358
  refused: (e) => {
@@ -2824,7 +3390,8 @@ export function registerTurnTools(server, ctx, opts = {}) {
2824
3390
  return unconfirmed(`The orders were sent, but the game does not yet show them committed or the turn advanced. ${check}`);
2825
3391
  },
2826
3392
  });
2827
- const withRisk = st.commanderRisk ? { ...result, commanderRiskAccepted: st.commanderRisk } : result;
3393
+ const withChat = st.chatReviewed ? { ...result, chatReviewed: st.chatReviewed } : result;
3394
+ const withRisk = st.commanderRisk ? { ...withChat, commanderRiskAccepted: st.commanderRisk } : withChat;
2828
3395
  if (!st.breaks?.length)
2829
3396
  return withRisk;
2830
3397
  return { ...withRisk, agreementsBroken: await recordBreaks(st, result.outcome === 'confirmed') };