@chrischall/warapp-mcp 0.6.0 → 0.8.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 (111) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +100 -7
  4. package/dist/analysis/accept-surrender.js +20 -2
  5. package/dist/analysis/calibrate.js +1 -0
  6. package/dist/analysis/card-support.js +187 -20
  7. package/dist/analysis/card-threats.js +68 -3
  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/coalition.js +55 -0
  13. package/dist/analysis/decision-replay.js +279 -0
  14. package/dist/analysis/decision-truth.js +146 -0
  15. package/dist/analysis/finished-game.js +62 -3
  16. package/dist/analysis/game-lessons.js +12 -6
  17. package/dist/analysis/local-deploy.js +14 -0
  18. package/dist/analysis/opponent-profile.js +46 -3
  19. package/dist/analysis/opponents.js +246 -19
  20. package/dist/analysis/outlook.js +323 -17
  21. package/dist/analysis/picks.js +270 -37
  22. package/dist/analysis/plan/after-leftover.js +28 -3
  23. package/dist/analysis/plan/captures.js +80 -16
  24. package/dist/analysis/plan/completed.js +8 -1
  25. package/dist/analysis/plan/conceded-out.js +16 -11
  26. package/dist/analysis/plan/deploy-estimates.js +513 -0
  27. package/dist/analysis/plan/doomed-out.js +135 -0
  28. package/dist/analysis/plan/estimates.js +73 -7
  29. package/dist/analysis/plan/free-capture.js +34 -0
  30. package/dist/analysis/plan/guard-off.js +2 -1
  31. package/dist/analysis/plan/holds.js +85 -313
  32. package/dist/analysis/plan/horizon.js +42 -0
  33. package/dist/analysis/plan/leftover.js +188 -10
  34. package/dist/analysis/plan/observe.js +896 -0
  35. package/dist/analysis/plan/orders.js +35 -1
  36. package/dist/analysis/plan/relations.js +115 -2
  37. package/dist/analysis/plan/report.js +10 -4
  38. package/dist/analysis/plan/shared.js +7 -1189
  39. package/dist/analysis/plan/stand-still.js +7 -5
  40. package/dist/analysis/plan/state.js +12 -0
  41. package/dist/analysis/plan/stockpile.js +104 -0
  42. package/dist/analysis/plan/strike-stack.js +467 -0
  43. package/dist/analysis/plan/strike.js +8 -441
  44. package/dist/analysis/plan/targets.js +374 -72
  45. package/dist/analysis/plan/threats.js +120 -9
  46. package/dist/analysis/plan/transfers.js +35 -1
  47. package/dist/analysis/plan/two-move.js +70 -0
  48. package/dist/analysis/plan/vacated.js +124 -2
  49. package/dist/analysis/plan/withdraw.js +316 -0
  50. package/dist/analysis/planner.js +356 -53
  51. package/dist/analysis/player.js +4 -0
  52. package/dist/analysis/relations.js +8 -2
  53. package/dist/analysis/since-last.js +18 -5
  54. package/dist/analysis/stress.js +1 -1
  55. package/dist/board.js +36 -2
  56. package/dist/build-id.js +106 -0
  57. package/dist/bundle.js +15863 -10242
  58. package/dist/chat-automation.js +22 -0
  59. package/dist/client.js +14 -0
  60. package/dist/decision-log.js +1093 -0
  61. package/dist/finished-store.js +5 -1
  62. package/dist/lessons-store.js +322 -21
  63. package/dist/my-games.js +2 -0
  64. package/dist/open-games.js +122 -18
  65. package/dist/outlook-log.js +42 -1
  66. package/dist/protocol/methods.js +4 -2
  67. package/dist/review-export.js +198 -0
  68. package/dist/state-bundle.js +62 -3
  69. package/dist/state-cli.js +5 -3
  70. package/dist/strategy/notes.js +56 -0
  71. package/dist/tools/accept-surrender.js +23 -9
  72. package/dist/tools/award.js +5 -1
  73. package/dist/tools/card-advice.js +102 -33
  74. package/dist/tools/card-support-advice.js +53 -8
  75. package/dist/tools/chat-advice.js +330 -0
  76. package/dist/tools/chat-inbox.js +15 -4
  77. package/dist/tools/chat.js +41 -11
  78. package/dist/tools/check-plan.js +16 -3
  79. package/dist/tools/commander-check.js +2 -1
  80. package/dist/tools/decision-capture.js +461 -0
  81. package/dist/tools/end-of-game.js +146 -18
  82. package/dist/tools/game-kind.js +92 -0
  83. package/dist/tools/how-lost.js +7 -2
  84. package/dist/tools/index.js +3 -0
  85. package/dist/tools/join-game.js +51 -9
  86. package/dist/tools/live-context.js +6 -0
  87. package/dist/tools/live.js +43 -6
  88. package/dist/tools/map-curves.js +73 -0
  89. package/dist/tools/notifications.js +4 -3
  90. package/dist/tools/open-games.js +2 -2
  91. package/dist/tools/opponents.js +2 -0
  92. package/dist/tools/past-games.js +74 -8
  93. package/dist/tools/picks.js +169 -57
  94. package/dist/tools/profile-hook.js +62 -3
  95. package/dist/tools/profile-opponents.js +2 -0
  96. package/dist/tools/push.js +2 -2
  97. package/dist/tools/relations.js +2 -0
  98. package/dist/tools/scout.js +16 -2
  99. package/dist/tools/state.js +6 -1
  100. package/dist/tools/strategy.js +3 -3
  101. package/dist/tools/stress-opponents.js +2 -0
  102. package/dist/tools/surrender-pending.js +10 -1
  103. package/dist/tools/surrender.js +18 -3
  104. package/dist/tools/turn.js +353 -19
  105. package/dist/tools/where.js +3 -1
  106. package/dist/version.js +1 -1
  107. package/manifest.json +23 -2
  108. package/mint.yaml +23 -0
  109. package/package.json +1 -1
  110. package/server.json +20 -2
  111. package/skills/warapp-mcp/SKILL.md +42 -8
@@ -7,6 +7,7 @@ import { straightKills } from '../combat.js';
7
7
  import { neighborsOf } from '../graph.js';
8
8
  import { lateArrivals } from './holds.js';
9
9
  import { byNum } from './util.js';
10
+ import { isDoomedOut } from './doomed-out.js';
10
11
  /**
11
12
  * The helpers rule 4e works with, over the plan as it stands when each is called: what reaches a
12
13
  * step, trying one (and undoing it), what a capture loses and leaves exposed, and why a step was
@@ -85,7 +86,8 @@ export function standStillKit(pc, ps, book, threats, hd, tgt, caps) {
85
86
  const rLine = r >= 0 ? rationale.splice(r, 1)[0] : undefined;
86
87
  const w = warnings.findIndex((l) => l.startsWith(`The withdrawal from ${label(x)} only executes`));
87
88
  const wLine = w >= 0 ? warnings.splice(w, 1)[0] : undefined;
88
- if (!moves.some((o) => o.kind === 'transfer' && o.reason === WITHDRAWS))
89
+ // #431's orders out of a doomed stack keep the advice too.
90
+ if (!moves.some((o) => (o.kind === 'transfer' && o.reason === WITHDRAWS) || isDoomedOut(o)))
89
91
  ps.cardAdvice = null;
90
92
  return () => {
91
93
  moves.splice(i, 0, m);
@@ -431,7 +433,7 @@ export function neverStandStill(pc, ps, book, threats, hd, tgt, caps) {
431
433
  ]
432
434
  : []),
433
435
  ].join('; ');
434
- const reasonOf = ({ id, f }) => `cheapest expansion toward bonus ${bonusName(id)} (+${f.value}, ${toFinish(f.cost, f.fogged, f.fogEach)}, ${f.cost === fewest ? 'the fewest of any bonus in reach' : 'the fewest of any bonus with a capture affordable this turn'})`;
436
+ const reasonOf = ({ id, f }) => `cheapest expansion toward bonus ${bonusName(id)} (+${f.value}, ${toFinish(f.cost, f)}, ${f.cost === fewest ? 'the fewest of any bonus in reach' : 'the fewest of any bonus with a capture affordable this turn'})`;
435
437
  // ---- #107, in contact: enemy captures ----
436
438
  /** Rule 0p.2's setting: an FFA with two or more opponents left. Applied here with or without adapt. */
437
439
  const ffaFronts = profile.format === 'ffa' && profile.opponents >= 2 && !leadLever;
@@ -503,7 +505,7 @@ export function neverStandStill(pc, ps, book, threats, hd, tgt, caps) {
503
505
  if (e.bonus.breaks)
504
506
  return `cheapest capture: breaks bonus ${bonusName(e.bonus.id)} (+${v}) of player ${e.player}`;
505
507
  const f = finishCost.get(e.bonus.id);
506
- return `cheapest capture: advances bonus ${bonusName(e.bonus.id)} (+${v}, ${toFinish(f.cost, f.fogged, f.fogEach)}) from player ${e.player}`;
508
+ return `cheapest capture: advances bonus ${bonusName(e.bonus.id)} (+${v}, ${toFinish(f.cost, f)}) from player ${e.player}`;
507
509
  };
508
510
  // #240 review: what fits is judged on a repulsed territory's sure size.
509
511
  const shortOf = (x) => Math.max(0, sizeOf(x.t, x.cost) - x.reach);
@@ -544,7 +546,7 @@ export function neverStandStill(pc, ps, book, threats, hd, tgt, caps) {
544
546
  // does not is ranked like any other capture.
545
547
  const repays = (p) => {
546
548
  const id = completedBy(p);
547
- return id !== undefined && costOfPick(p.st.t) <= pc.paybackTurns * g.bonusById.get(id).value;
549
+ return id !== undefined && costOfPick(p.st.t) <= pc.capturePaybackTurns * g.bonusById.get(id).value;
548
550
  };
549
551
  const teamFocused = (p) => p.kind === 'enemy' && pc.teamFocus.has(p.st.player);
550
552
  const keyOf = (p) => [
@@ -806,7 +808,7 @@ export function neverStandStill(pc, ps, book, threats, hd, tgt, caps) {
806
808
  // #240: a completion that repays its cost goes first among the affordable candidates.
807
809
  if (repays(taken) && !repays(p))
808
810
  return [
809
- `${label(t)} ${after}: taking ${label(taken.st.t)} completes bonus ${bonusName(completedBy(taken))} this turn, which repays its cost of ${costOfPick(taken.st.t)} within ${pc.paybackTurns} turns`,
811
+ `${label(t)} ${after}: taking ${label(taken.st.t)} completes bonus ${bonusName(completedBy(taken))} this turn, which repays its cost of ${costOfPick(taken.st.t)} within ${pc.capturePaybackTurns} turns`,
810
812
  ];
811
813
  // PLAN-TEAMS C3.4: equal but for the team focus.
812
814
  if (teamFocused(taken) && !teamFocused(p) && keyOf(p).slice(0, FOCUS_KEY).every((k, i) => k === keyOf(taken)[i]))
@@ -35,8 +35,11 @@ export function newPlanState() {
35
35
  moves: [],
36
36
  incoming: new Map(),
37
37
  survivorsAt: new Map(),
38
+ paybackFalls: new Map(),
39
+ paybackBonuses: new Map(),
38
40
  captureOrder: [],
39
41
  captureUndo: new Map(),
42
+ doomedOut: new Set(),
40
43
  staged: new Map(),
41
44
  anchor: undefined,
42
45
  assumeGone: () => false,
@@ -50,3 +53,12 @@ export function newPlanState() {
50
53
  capRefused: new Map(),
51
54
  };
52
55
  }
56
+ /**
57
+ * #422: whether `id` is in a payback map (`ps.paybackBonuses` or `ps.paybackFalls`) for a completion this
58
+ * plan still makes. Every rollback of a capture rewinds the rationale with it (whichever path undoes it), so
59
+ * the completion stands exactly while the line that states it does.
60
+ */
61
+ export function paybackLive(ps, m, id) {
62
+ const line = m.get(id);
63
+ return line !== undefined && ps.rationale.includes(line);
64
+ }
@@ -0,0 +1,104 @@
1
+ import { bonusTerritories } from '../bonuses.js';
2
+ import { neighborsOf } from '../graph.js';
3
+ /** #421: armies of mine in view, in turns of my income, that make a stockpile on a flat income. */
4
+ export const STOCKPILE_TURNS = 4;
5
+ /** #421: the visible-army lead over one opponent beside me that turns a stockpile into a strike stack facing it. */
6
+ export const STOCKPILE_LEAD = 2;
7
+ /** #421 (owner decision, 2026-11-20): the share of a flat income held out of captures for the strike stack. */
8
+ export const STRIKE_SHARE = 0.25;
9
+ /** My armies in view and each other player's (special units counted), visible territories only. */
10
+ export function armiesInView(a) {
11
+ const by = new Map();
12
+ let my = 0;
13
+ for (const [id, st] of a.territories) {
14
+ if (st.owner.kind !== 'player' || st.armies === null)
15
+ continue;
16
+ if (a.mineSet.has(id))
17
+ my += st.armies + a.unitsAt(id);
18
+ else
19
+ by.set(st.owner.playerId, (by.get(st.owner.playerId) ?? 0) + st.armies + a.unitsAt(id));
20
+ }
21
+ return { my, by };
22
+ }
23
+ /**
24
+ * #421: the pile — adapting (not `defend`, not No-Split), my income flat and my armies in view at least
25
+ * {@link STOCKPILE_TURNS} turns of it. `undefined` otherwise.
26
+ */
27
+ export function pileOf(a) {
28
+ if (!a.auto || a.goal === 'defend' || a.noSplit || !a.incomeTrend?.flat || a.income <= 0)
29
+ return undefined;
30
+ const { my, by } = armiesInView(a);
31
+ if (my < STOCKPILE_TURNS * a.income)
32
+ return undefined;
33
+ return { my, by, turns: Math.round((my / a.income) * 10) / 10 };
34
+ }
35
+ /**
36
+ * #421 (#450): outside a 1v1 and a siege, the pile builds the strike stack facing the opponent in
37
+ * `facing` whose armies in view mine outnumber {@link STOCKPILE_LEAD}× or more (the fewest first, then
38
+ * id). Visible armies only, never an income estimate.
39
+ */
40
+ export function stockpileOf(a) {
41
+ if (a.siege || a.format === '1v1')
42
+ return undefined;
43
+ const pile = pileOf(a);
44
+ if (!pile)
45
+ return undefined;
46
+ const { my, by, turns } = pile;
47
+ const p = [...a.facing]
48
+ .filter((q) => a.foe(q) && my >= STOCKPILE_LEAD * (by.get(q) ?? 0))
49
+ .sort((x, y) => (by.get(x) ?? 0) - (by.get(y) ?? 0) || x - y)[0];
50
+ if (p === undefined)
51
+ return undefined;
52
+ const ratio = by.get(p) ? `${(Math.round((my / by.get(p)) * 10) / 10).toFixed(1)}×` : 'unbounded';
53
+ return {
54
+ p,
55
+ why: `the opponent whose armies in view mine outnumber ${ratio} (#421)`,
56
+ line: `${my} armies of mine stand on the board, ${turns} turns of my flat ${a.income} income, ${ratio} player ${p}'s in view`,
57
+ };
58
+ }
59
+ /**
60
+ * #421 (owner decision, 2026-11-20): in contact on a flat income — where rule 0p.3c builds a strike stack
61
+ * (a 1v1 adapting, a siege, or the stockpile above) — {@link STRIKE_SHARE} of my income, rounded down, is
62
+ * held out of captures for the stack. Holds still take their exact need first; the leftover deploy then
63
+ * gives the stack what the captures left, ahead of comfort margins. 0 otherwise.
64
+ */
65
+ export function strikeShareOf(a) {
66
+ if (!a.incomeTrend?.flat || a.income <= 0)
67
+ return 0;
68
+ const stack = (a.siege !== undefined && a.contact.has(a.siege)) ||
69
+ (a.auto && a.format === '1v1' && a.goal !== 'defend' && a.contact.size > 0) ||
70
+ stockpileOf({ ...a, siege: a.siege !== undefined, facing: a.contact }) !== undefined;
71
+ return stack ? Math.floor(STRIKE_SHARE * a.income) : 0;
72
+ }
73
+ /**
74
+ * #421 (owner decision, 2026-11-20): the contested bonuses an all-in completion could take on the pile — a
75
+ * positive bonus I hold a member of, whose every missing member is in view (armies shown) beside a territory of
76
+ * mine, at least one of them an opponent's, none a teammate's. By id.
77
+ */
78
+ export function contestedBonuses(g, territories, mineSet, foe) {
79
+ return g.map.bonuses
80
+ .filter((b) => {
81
+ const ts = bonusTerritories(g, b.id);
82
+ if (b.value <= 0 || !ts.some((t) => mineSet.has(t)))
83
+ return false;
84
+ const missing = ts.filter((t) => !mineSet.has(t));
85
+ if (!missing.length)
86
+ return false;
87
+ let opponent = false;
88
+ for (const t of missing) {
89
+ const st = territories.get(t);
90
+ if (!st || st.armies === null || st.owner.kind === 'unknown' || st.owner.kind === 'available')
91
+ return false;
92
+ if (!neighborsOf(g, t).some((n) => mineSet.has(n)))
93
+ return false;
94
+ if (st.owner.kind === 'player') {
95
+ if (!foe(st.owner.playerId))
96
+ return false;
97
+ opponent = true;
98
+ }
99
+ }
100
+ return opponent;
101
+ })
102
+ .map((b) => b.id)
103
+ .sort((a, b) => a - b);
104
+ }
@@ -0,0 +1,467 @@
1
+ // The 1v1 strike stack (rule 0p.3c, #72): which border to build it on (chooseStrikeStack) and its attacks after the leftover (spendStrikeStack) (split from strike.ts, which re-exports it).
2
+ import { forecastBorder } from '../exchange.js';
3
+ import { straightKills } from '../combat.js';
4
+ import { neighborsOf } from '../graph.js';
5
+ import { MIN_ENEMY_DEPLOY, visibleState, } from './shared.js';
6
+ import { byNum, pct } from './util.js';
7
+ import { stackFacing } from './strike.js';
8
+ import { STRIKE_SHARE, stockpileOf } from './stockpile.js';
9
+ /** Rule 0p.3c (#72, #120, #201, #421): the strike stack's border (a 1v1, a siege or a stockpile), chosen before the leftover deploy. */
10
+ export function chooseStrikeStack(pc, ps, book, threats, open, stays) {
11
+ const { g, income, profile, auto, goal, estimates, deployOf, incomeOfPlayer, paybackTurns, territories: state, label, mine, armiesOf, unitsAt, defenceAt, completedBy, inFocus, guard, rates, costAt, noSplit, } = pc;
12
+ const { rationale, captured, combined, staged } = ps;
13
+ const { guardAt, heldNow, gainWith, orderOf, roomAt } = book;
14
+ const { reinforcementAt, holdArmies, threatAt, facing } = threats;
15
+ // Concentrate (#72, adapting in a 1v1 facing the opponent): the spare deploys go to one strike stack
16
+ // on the border facing the strongest opponent (the highest income estimate, tracked when its
17
+ // track is trusted), the stack that keeps the most there, rather than to comfort margins.
18
+ // A 1v1 rule: in an FFA or a team game the comfort margins keep the leftover (several fronts), unless a stockpile (#421, below).
19
+ // Chosen even when holds and captures leave no leftover (#102): the stack is still spent.
20
+ let stack;
21
+ /**
22
+ * No-Split (#124): `x`'s one order when it is a small expansion a strike may take over — a single
23
+ * attack on a neutral that completes no bonus this turn, stages none and is not focused.
24
+ */
25
+ const smallExpansion = (x) => {
26
+ const m = orderOf(x);
27
+ if (!m || m.kind !== 'attack' || !captured.has(m.to) || combined.has(m.to))
28
+ return undefined;
29
+ if (state.get(m.to)?.owner.kind !== 'neutral' || staged.has(m.to) || inFocus(m.to))
30
+ return undefined;
31
+ const now = heldNow();
32
+ const before = completedBy(new Set([...now].filter((y) => y !== m.to)));
33
+ return completedBy(now).some((id) => !before.includes(id)) ? undefined : m;
34
+ };
35
+ /** The stack on `x` a strike could send: what stays, plus a small expansion's armies (No-Split). */
36
+ const stackAt = (x) => stays(x) + (smallExpansion(x)?.armies ?? 0);
37
+ // #382: a siege builds the stack facing its target in any format (its attacks held until the trigger:
38
+ // the target's other territories are no targets then, so the stack only grows or breaks).
39
+ const siege = pc.siege && facing.has(pc.siege.target) ? pc.siege : undefined;
40
+ // #421: outside a 1v1, a stockpile on a flat income — my armies in view at least STOCKPILE_TURNS
41
+ // turns of income while it has not grown — builds the stack facing the opponent beside me whose
42
+ // armies in view mine outnumber STOCKPILE_LEAD× or more (the fewest first, then id). Visible armies
43
+ // only, never an income estimate: the pile is spent where it dominates. Not under No-Split (an order
44
+ // carries the whole stack), and never on my commander's territory.
45
+ const stockpile = stockpileOf({
46
+ territories: state, mineSet: pc.mineSet, unitsAt, foe: pc.foe, income, ...(pc.incomeTrend ? { incomeTrend: pc.incomeTrend } : {}),
47
+ auto, goal, noSplit, format: profile.format, siege: siege !== undefined, facing,
48
+ });
49
+ if ((auto && profile.format === '1v1' && goal !== 'defend' && facing.size) || siege || stockpile) {
50
+ const player = siege
51
+ ? { p: siege.target, e: estimates.get(siege.target) }
52
+ : stockpile
53
+ ? { p: stockpile.p, e: estimates.get(stockpile.p) }
54
+ : [...facing]
55
+ .map((p) => ({ p, e: estimates.get(p) }))
56
+ .sort((a, b) => (b.e?.estimate ?? 0) - (a.e?.estimate ?? 0) || a.p - b.p)[0];
57
+ /** The opponent's territories next to `x` a strike could aim at. */
58
+ const aims = (x) => neighborsOf(g, x).filter((n) => {
59
+ const st = state.get(n);
60
+ return !captured.has(n) && st?.owner.kind === 'player' && st.owner.playerId === player.p && st.armies !== null;
61
+ });
62
+ const fronts = mine
63
+ .filter((x) => open(x) &&
64
+ // No-Split: a territory whose one order is not a small expansion has nothing left to strike with.
65
+ (!orderOf(x) || smallExpansion(x) !== undefined) &&
66
+ // #421: a stockpile's stack never stands on my commander's territory.
67
+ !(stockpile && pc.myCommanders.has(x)) &&
68
+ aims(x).length > 0)
69
+ .sort((a, b) => stackAt(b) - stackAt(a) || a - b);
70
+ /**
71
+ * #120: the best strike `x` could make this turn with every leftover army on it — an adjacent
72
+ * target sized for its defenders plus what its owner may deploy there first (rule 3) — and the
73
+ * armies it would have to spare, after what holds `x` once that target falls. `null` when none
74
+ * fits.
75
+ */
76
+ const bestStrike = (x) => {
77
+ const room = Math.max(0, Math.min(ps.budget, roomAt(x)));
78
+ let best = null;
79
+ for (const n of aims(x)) {
80
+ const extra = reinforcementAt(n);
81
+ const cost = costAt(n, defenceAt(n) + extra);
82
+ if (cost === null || gainWith([n]) < 0)
83
+ continue;
84
+ const threat = Math.max(threatAt(x, (y) => captured.has(y) || y === n)?.threat ?? 0, deployOf(player.p));
85
+ const hold = Math.max(0, holdArmies(threat) - unitsAt(x));
86
+ const can = stackAt(x) + room - guardAt(x);
87
+ const spare = Math.min(can - cost, stackAt(x) + room - cost - hold);
88
+ if (spare < 0)
89
+ continue;
90
+ if (!best || spare > best.spare || (spare === best.spare && n < best.n))
91
+ best = { n, cost, extra, spare, can };
92
+ }
93
+ return best;
94
+ };
95
+ // Rule 0p.3c (#120): the stack goes where it can strike — the border with the most to spare
96
+ // after its best strike — and only with no border able to strike, to the one holding the most
97
+ // armies (live, 180 armies fed the front facing the opponent's biggest stack while a strike on
98
+ // a 1-army territory elsewhere was affordable every turn).
99
+ const able = noSplit ? [] : fronts.flatMap((x) => {
100
+ const b = bestStrike(x);
101
+ return b ? [{ x, ...b }] : [];
102
+ });
103
+ able.sort((a, b) => b.spare - a.spare || stackAt(b.x) - stackAt(a.x) || a.x - b.x);
104
+ const pick = able[0];
105
+ // #201: with no border able to strike this turn, the multi-turn forecast (`forecastBorder`):
106
+ // the border whose stack, with the leftover and then the income every turn, breaks the
107
+ // opponent's biggest stack beside it soonest (its owner deploying there every turn too); ties,
108
+ // and none breaking within the horizon, keep the border holding the most armies.
109
+ const forecastPick = (() => {
110
+ if (pick || noSplit || fronts.length < 2)
111
+ return undefined;
112
+ const rows = fronts.flatMap((x) => {
113
+ const at = aims(x).sort((a, b) => armiesOf(b) + unitsAt(b) - (armiesOf(a) + unitsAt(a)) || a - b)[0];
114
+ const theirs = armiesOf(at) + unitsAt(at);
115
+ const f = forecastBorder({
116
+ mine: stackAt(x) + Math.max(0, Math.min(ps.budget, roomAt(x))),
117
+ theirs,
118
+ myIncome: income,
119
+ theirIncome: incomeOfPlayer(player.p),
120
+ turns: paybackTurns,
121
+ settings: { offensiveKillRate: rates.offensiveKillRate, defensiveKillRate: rates.defensiveKillRate, oneArmyStandsGuard: guard === 1 },
122
+ });
123
+ return f.outcome === 'breaks' && f.turn !== null ? [{ x, at, theirs, turn: f.turn }] : [];
124
+ });
125
+ rows.sort((a, b) => a.turn - b.turn || stackAt(b.x) - stackAt(a.x) || a.x - b.x);
126
+ const best = rows[0];
127
+ if (!best)
128
+ return undefined;
129
+ const most = fronts[0];
130
+ const other = rows.find((r) => r.x === most);
131
+ if (best.x === most || (other && other.turn === best.turn))
132
+ return undefined;
133
+ rationale.push(`Strike stack on ${label(best.x)} (#201): no border can strike this turn; pressing every turn with the income, ${label(best.x)} breaks player ${player.p}'s ${best.theirs} on ${label(best.at)} on turn ${best.turn} (the multi-turn forecast), sooner than ${label(most)}, which holds more armies but ${other ? `breaks its front only on turn ${other.turn}` : `breaks nothing within ${paybackTurns} turns`}.`);
134
+ return best.x;
135
+ })();
136
+ const id = pick?.x ?? forecastPick ?? fronts[0];
137
+ if (pick) {
138
+ const most = fronts[0];
139
+ rationale.push(`Strike stack on ${label(pick.x)}: ${label(pick.x)} can take ${label(pick.n)} this turn (${pick.cost} of the ${pick.can} it could send with the leftover, sized for its ${defenceAt(pick.n)} defenders plus the ~${pick.extra} player ${player.p} may deploy there first; ${pick.spare} to spare once it holds)${most !== pick.x
140
+ ? `, rather than ${label(most)}, which holds more armies but ${able.some((a) => a.x === most) ? `has less to spare after its best strike` : 'can take nothing next to it so sized'}`
141
+ : ''}.`);
142
+ }
143
+ if (id !== undefined && stockpile)
144
+ rationale.push(`Stockpile (#421): ${stockpile.line}, so the spare deploys build one strike stack on ${label(id)} facing it, spent on what it can take every turn, rather than comfort margins.`);
145
+ if (id !== undefined)
146
+ stack = {
147
+ id,
148
+ player: player.p,
149
+ income: player.e?.estimate ?? MIN_ENEMY_DEPLOY,
150
+ source: player.e?.source === 'tracked' ? 'tracked' : player.e?.source === 'observed' ? 'observed' : 'estimated',
151
+ ...(stockpile ? { facing: stockpile.why } : {}),
152
+ };
153
+ }
154
+ // #421 (owner decision, 2026-11-20): the share the estimates phase held out of captures.
155
+ if (pc.strikeShare > 0)
156
+ rationale.push(stack
157
+ ? `Strike share (#421): ${pc.strikeShare} of my flat ${income} income (${STRIKE_SHARE * 100}%) was held out of captures for the strike stack on ${label(stack.id)}, ahead of comfort margins; holds took their exact need first.`
158
+ : `Strike share (#421): ${pc.strikeShare} of my flat ${income} income (${STRIKE_SHARE * 100}%) was held out of captures for a strike stack, but no border could carry one this turn: it goes to the leftover as usual.`);
159
+ return { stack, smallExpansion };
160
+ }
161
+ /** #102: spend the strike stack on the enemy territories next to it, once the leftover deploy is in. */
162
+ export function spendStrikeStack(pc, ps, input, book, threats, tgt, cap, strikeStack, poolDeployed, holdLocked, smallExpansion) {
163
+ const { g, me, foe, deployOf, territories: state, label, bonusName, mineSet, unitsAt, uncounted, defenceAt, bonusTs, completedBy, rates, chanceOf, costAt, noSplit, myCommanders, } = pc;
164
+ const { warnings, rationale, avail, locked, captured, combined, moves, incoming, survivorsAt, captureOrder, captureUndo, } = ps;
165
+ const { guardAt, coverOf, heldNow, gainWith, orderOf, valueOf } = book;
166
+ const { reinforcementAt, holdArmies, threatAt } = threats;
167
+ const { breakable, offence, skipOffence } = tgt;
168
+ const { mustHold, strikes, worstCase } = cap;
169
+ // ---- spend the strike stack (#102) ----
170
+ // Once rule 0p.3c builds a strike stack, it attacks every adjacent enemy territory it can take
171
+ // at the plan's win chance (the ordinary capture sizing; rule 4c re-checked as its captures
172
+ // accumulate), breaking or retaking a bonus first (re-ranked after each capture: a bonus breaks
173
+ // once), then by bonus value, then cheapest, then id — while what stays on it holds against the threat
174
+ // left after those attacks (rule 1's arithmetic: the captured territories no longer threaten
175
+ // it). It grows (deploy, no attack) only when nothing in reach is worth taking.
176
+ if (strikeStack) {
177
+ const S = strikeStack.id;
178
+ if (strikeStack.deployed === 0)
179
+ rationale.push(`No leftover reaches the strike stack ${label(S)} this turn (holds, captures or Local Deployment pools took the income): it is spent with the armies already on it.`);
180
+ const prev = new Map((input.previousBoard?.territories ?? []).map((t) => [t.territoryId, t]));
181
+ /** Bonuses I held in full on the previous board and no longer do: lost, and retakable. */
182
+ const lost = new Set(g.map.bonuses
183
+ .filter((b) => {
184
+ const ts = bonusTs.get(b.id) ?? [];
185
+ if (b.value <= 0 || !ts.length || ts.every((t) => mineSet.has(t)))
186
+ return false;
187
+ return ts.every((t) => {
188
+ const was = visibleState(prev.get(t));
189
+ return was?.owner.kind === 'player' && was.owner.playerId === me;
190
+ });
191
+ })
192
+ .map((b) => b.id));
193
+ const candidates = [];
194
+ for (const n of neighborsOf(g, S)) {
195
+ const st = state.get(n);
196
+ if (captured.has(n) || st?.owner.kind !== 'player' || !foe(st.owner.playerId) || st.armies === null || uncounted(n))
197
+ continue;
198
+ // B2 (T1): never a truce's covered territory.
199
+ if (pc.truce.noTarget(n))
200
+ continue;
201
+ // #240: a territory my attacks failed on repeatedly is sized for its owner's deploy (#240
202
+ // review: and ranked on its plain cost, like any other).
203
+ const cost = costAt(n);
204
+ const size = tgt.costFor(n);
205
+ // Never a capture that lowers income (rule 4c): it completes a negative bonus. Re-checked
206
+ // below against the strike's own captures, which can complete one only together.
207
+ if (cost === null || size === null || gainWith([n]) < 0)
208
+ continue;
209
+ const owner = st.owner.playerId;
210
+ candidates.push({
211
+ id: n,
212
+ cost,
213
+ size,
214
+ chance: chanceOf(size, defenceAt(n)),
215
+ breaks: breakable.filter((b) => b.player === owner && bonusTs.get(b.bonusId).includes(n)),
216
+ retakes: [...lost].filter((id) => bonusTs.get(id).includes(n)).sort(byNum),
217
+ });
218
+ }
219
+ /** Captures planned from the stack so far, in order. */
220
+ const plannedHere = new Set();
221
+ /** The opponent bonuses `c` breaks: only the first member of each to fall this turn breaks it. */
222
+ const breaksOf = (c) => c.breaks.filter((b) => !bonusTs.get(b.bonusId).some((t) => t !== c.id && captured.has(t)));
223
+ const strikeValue = (c) => Math.max(0, ...breaksOf(c).map((b) => b.value), ...c.retakes.map((id) => g.bonusById.get(id).value));
224
+ /** What taking `c` does, against the captures planned so far (a retake completes only with every member held). */
225
+ const effectOf = (c) => {
226
+ const held = heldNow();
227
+ held.add(c.id);
228
+ const effects = [
229
+ ...breaksOf(c).map((b) => `breaks ${b.probable ? 'probable ' : ''}enemy bonus ${bonusName(b.bonusId)} (+${b.value} from player ${b.player})`),
230
+ ...c.retakes.map((id) => `${bonusTs.get(id).every((t) => held.has(t)) ? 'retakes' : 'toward retaking'} bonus ${bonusName(id)} (+${g.bonusById.get(id).value}), which I held last turn`),
231
+ ];
232
+ return effects.length ? effects.join('; ') : null;
233
+ };
234
+ const rank = () => [...candidates].sort((a, b) => Number(breaksOf(b).length + b.retakes.length > 0) - Number(breaksOf(a).length + a.retakes.length > 0) ||
235
+ strikeValue(b) - strikeValue(a) ||
236
+ a.cost - b.cost ||
237
+ a.id - b.id);
238
+ /** What may never leave the stack this turn: a Local Deployment pool's deploys (#103). */
239
+ const pinned = poolDeployed.get(S) ?? 0;
240
+ /**
241
+ * The threat on the stack once `gone` (and this turn's other captures) fall, and the armies that
242
+ * hold it. Never below the opponent's deploy alone: orders interleave, so it may land its deploy
243
+ * on a target before my attack resolves, and that territory then still borders the stack.
244
+ */
245
+ const holdAfter = (gone) => {
246
+ const th = threatAt(S, (x) => captured.has(x) || gone.has(x));
247
+ const threat = Math.max(th?.threat ?? 0, deployOf(strikeStack.player));
248
+ return { threat, need: Math.max(0, holdArmies(threat) - unitsAt(S)) };
249
+ };
250
+ const taken = [];
251
+ const refused = new Map();
252
+ let sent = 0;
253
+ /**
254
+ * No-Split (#124): the stack's one order goes to the strike on `t`, not to the small expansion
255
+ * `m` it already made: that capture is taken back, and its armies rejoin the stack.
256
+ */
257
+ const dropExpansion = (m, t) => {
258
+ const undo = captureUndo.get(m.to);
259
+ if (undo)
260
+ undo();
261
+ else
262
+ avail.set(S, avail.get(S) + m.armies);
263
+ captured.delete(m.to);
264
+ survivorsAt.delete(m.to);
265
+ moves.splice(moves.indexOf(m), 1);
266
+ const head = `Attack ${label(m.to)} from ${label(S)} with `;
267
+ for (let i = rationale.length - 1; i >= 0; i--)
268
+ if (rationale[i].startsWith(head))
269
+ rationale.splice(i, 1);
270
+ rationale.push(`No-Split: ${label(S)}'s one order goes to the strike on ${label(t)}, not the expansion into ${label(m.to)} (it completes no bonus): the whole stack strikes.`);
271
+ skipOffence(m.to, `No-Split: ${label(S)}'s one order goes to the strike on ${label(t)}`);
272
+ };
273
+ for (let again = true; again;) {
274
+ again = false;
275
+ for (const c of rank()) {
276
+ if (plannedHere.has(c.id))
277
+ continue;
278
+ if (gainWith([c.id]) < 0) {
279
+ const held = heldNow();
280
+ held.add(c.id);
281
+ const negs = completedBy(held)
282
+ .filter((id) => g.bonusById.get(id).value < 0 && bonusTs.get(id).includes(c.id))
283
+ .map((id) => `negative bonus ${bonusName(id)} (${g.bonusById.get(id).value})`);
284
+ refused.set(c.id, `with this turn's other captures it lowers next income: it completes ${negs.join(', ')} (rule 4c)`);
285
+ continue;
286
+ }
287
+ const expansion = noSplit && !taken.length ? smallExpansion(S) : undefined;
288
+ if (noSplit && ((orderOf(S) && !expansion) || taken.length)) {
289
+ refused.set(c.id, `No-Split: ${label(S)} issues one order this turn`);
290
+ continue;
291
+ }
292
+ if (noSplit) {
293
+ // The whole stack goes (#124): nothing stays to hold S but the guard, so it strikes only
294
+ // when it need not hold (it protects nothing, or the strike leaves no visible threat to it).
295
+ const whole = avail.get(S) + (expansion?.armies ?? 0);
296
+ if (pinned > 0) {
297
+ refused.set(c.id, `No-Split: the ${pinned} Local Deployment armies defending ${label(S)} would leave with the whole stack`);
298
+ continue;
299
+ }
300
+ if (c.size > whole) {
301
+ refused.set(c.id, `it needs ${c.size}, more than the ${Math.max(0, whole)} the stack can send`);
302
+ continue;
303
+ }
304
+ const h = mustHold(S, c.id, whole);
305
+ if (h) {
306
+ refused.set(c.id, `No-Split: the whole stack would go, leaving ${h.stays} against the ~${h.threat} threat, and ${label(S)} must hold (${h.value > 0 ? `protects +${h.value}` : 'my commander stands there'})`);
307
+ continue;
308
+ }
309
+ if (expansion)
310
+ dropExpansion(expansion, c.id);
311
+ const armies = avail.get(S);
312
+ plannedHere.add(c.id);
313
+ refused.delete(c.id);
314
+ taken.push({ c, effect: effectOf(c), value: strikeValue(c), armies, chance: chanceOf(armies, defenceAt(c.id)) });
315
+ avail.set(S, 0);
316
+ sent += armies;
317
+ captured.add(c.id);
318
+ survivorsAt.set(c.id, armies - straightKills(defenceAt(c.id), rates.defensiveKillRate));
319
+ captureOrder.push(c.id);
320
+ again = true;
321
+ break;
322
+ }
323
+ const gone = new Set([...plannedHere, c.id]);
324
+ const { threat, need } = holdAfter(gone);
325
+ // #179: what covers a finished-off player's exit stays too.
326
+ const movable = avail.get(S) - Math.max(pinned, coverOf(S));
327
+ const stay = avail.get(S) + guardAt(S) + (incoming.get(S) ?? 0) - c.size;
328
+ if (c.size > movable) {
329
+ refused.set(c.id, `it needs ${c.size}, more than the ${Math.max(0, movable)} the stack can send`);
330
+ continue;
331
+ }
332
+ if (stay < need) {
333
+ refused.set(c.id, `it would leave the stack ${stay}, below the ${need} that hold it against the ~${threat} threat after the attacks`);
334
+ continue;
335
+ }
336
+ const effect = effectOf(c);
337
+ const value = strikeValue(c);
338
+ plannedHere.add(c.id);
339
+ refused.delete(c.id);
340
+ taken.push({ c, effect, value, armies: c.size, chance: c.chance });
341
+ avail.set(S, avail.get(S) - c.size);
342
+ sent += c.size;
343
+ captured.add(c.id);
344
+ survivorsAt.set(c.id, c.size - straightKills(defenceAt(c.id), rates.defensiveKillRate));
345
+ captureOrder.push(c.id);
346
+ again = true;
347
+ break;
348
+ }
349
+ }
350
+ // #120: each attack is then sized for its defenders plus what their owner may deploy there
351
+ // first, in the order taken, while the stack still covers it and keeps its hold after every
352
+ // attack. One the stack cannot cover keeps its size (its warning gives the reinforced odds).
353
+ const reinforced = new Map();
354
+ // #240 review: a repulsed territory was costed at that size when the stack took it (and No-Split
355
+ // sends at least as much): it is sized for its owner's deploy already, and says so.
356
+ for (const x of taken) {
357
+ const rep = tgt.repulsed.get(x.c.id);
358
+ // #272 review: one sized below its owner's deploy estimate is no worst case (#120 below may still size it up).
359
+ if (!rep?.sure || x.armies < rep.cost)
360
+ continue;
361
+ worstCase.set(x.c.id, rep.defenders + rep.extra);
362
+ reinforced.set(x.c.id, rep.extra);
363
+ }
364
+ if (!noSplit) {
365
+ const { need } = holdAfter(new Set());
366
+ const room = () => Math.min(avail.get(S) - Math.max(pinned, coverOf(S)), avail.get(S) + guardAt(S) + (incoming.get(S) ?? 0) - need);
367
+ // The stack's earlier attacks on a player (a break or counter-attack from it) first.
368
+ for (const m of moves) {
369
+ if (m.from !== S || m.kind !== 'attack' || combined.has(m.to) || worstCase.has(m.to) || strikes.has(m.to))
370
+ continue;
371
+ const extra = reinforcementAt(m.to);
372
+ const full = extra > 0 ? costAt(m.to, defenceAt(m.to) + extra) : null;
373
+ if (full === null || full <= m.armies || full - m.armies > room())
374
+ continue;
375
+ const add = full - m.armies;
376
+ const before = m.armies;
377
+ avail.set(S, avail.get(S) - add);
378
+ m.armies = full;
379
+ m.winChance = chanceOf(full, defenceAt(m.to));
380
+ if (survivorsAt.has(m.to))
381
+ survivorsAt.set(m.to, survivorsAt.get(m.to) + add);
382
+ worstCase.set(m.to, defenceAt(m.to) + extra);
383
+ const w = warnings.indexOf(`Attack on enemy ${label(m.to)} assumes its owner does not reinforce it first.`);
384
+ if (w >= 0)
385
+ warnings.splice(w, 1);
386
+ rationale.push(`Size the attack on ${label(m.to)} from the strike stack ${label(S)} up from ${before} to ${full}: ${full} take it even if player ${strikeStack.player} deploys its ~${extra} there first, and the stack still holds.`);
387
+ }
388
+ for (const x of taken) {
389
+ const extra = reinforcementAt(x.c.id);
390
+ const full = extra > 0 ? costAt(x.c.id, defenceAt(x.c.id) + extra) : null;
391
+ if (full === null || full <= x.armies)
392
+ continue;
393
+ const add = full - x.armies;
394
+ if (add > room())
395
+ continue;
396
+ avail.set(S, avail.get(S) - add);
397
+ sent += add;
398
+ x.armies = full;
399
+ x.chance = chanceOf(full, defenceAt(x.c.id));
400
+ survivorsAt.set(x.c.id, survivorsAt.get(x.c.id) + add);
401
+ worstCase.set(x.c.id, defenceAt(x.c.id) + extra);
402
+ reinforced.set(x.c.id, extra);
403
+ }
404
+ }
405
+ // What stays on the stack is its hold: an efficient-size top-up (S2) never draws on it, and
406
+ // the transfer step never moves it (its captures can leave it interior; it may have got no deploys).
407
+ if (taken.length) {
408
+ holdLocked.add(S);
409
+ locked.add(S);
410
+ }
411
+ const { threat: finalThreat, need: finalNeed } = holdAfter(new Set());
412
+ const stays = avail.get(S) + guardAt(S) + (incoming.get(S) ?? 0);
413
+ for (const { c, effect, value, armies, chance } of taken) {
414
+ const reason = `the strike stack ${effect ?? 'takes an adjacent enemy territory'}`;
415
+ moves.push({ from: S, to: c.id, armies, kind: 'attack', reason, winChance: chance });
416
+ const extra = reinforced.get(c.id);
417
+ if (extra === undefined)
418
+ warnings.push(`Attack on enemy ${label(c.id)} assumes its owner does not reinforce it first.`);
419
+ const keeps = noSplit
420
+ ? `No-Split sends the whole stack (${c.size} would take it), and ${label(S)} need not hold: ${valueOf(S) > 0 || myCommanders.has(S) ? 'no visible threat to it is left' : 'it protects nothing'}`
421
+ : `the stack keeps ${stays}, enough to hold against the ~${finalThreat} threat after the attacks (needs ${finalNeed})`;
422
+ const sized = extra === undefined
423
+ ? ''
424
+ : ` — sized for its ${defenceAt(c.id)} defenders plus the ~${extra} player ${strikeStack.player} may deploy there first (${c.cost} would take it as it stands)`;
425
+ rationale.push(`Attack ${label(c.id)} from the strike stack ${label(S)} with ${armies} (win chance ${pct(chance)}${sized}): ${effect ?? 'it can take this adjacent enemy territory'}; ${keeps}.`);
426
+ offence.set(`strike:${c.id}`, {
427
+ target: c.id,
428
+ kind: 'strike-attack',
429
+ cost: armies,
430
+ value,
431
+ taken: true,
432
+ why: `from the strike stack ${label(S)} with ${armies} (win chance ${pct(chance)}): ${effect ?? 'takes an adjacent enemy territory'}`,
433
+ });
434
+ }
435
+ for (const c of rank()) {
436
+ if (plannedHere.has(c.id))
437
+ continue;
438
+ const effect = effectOf(c);
439
+ offence.set(`strike:${c.id}`, {
440
+ target: c.id,
441
+ kind: 'strike-attack',
442
+ cost: c.size,
443
+ value: strikeValue(c),
444
+ taken: false,
445
+ why: `not made from the strike stack ${label(S)} — ${refused.get(c.id) ?? 'not worth it'}${effect ? `: ${effect}` : ''}`,
446
+ });
447
+ }
448
+ const builds = `the spare deploys build one strike stack facing player ${strikeStack.player}, ${stackFacing(pc, strikeStack)} (~${strikeStack.income} income, ${strikeStack.source})`;
449
+ if (!taken.length) {
450
+ const held = candidates.length
451
+ ? candidates.map((c) => `${label(c.id)}: ${refused.get(c.id) ?? 'not worth it'}`).join('; ')
452
+ : 'no visible enemy territory next to it can be taken';
453
+ rationale.push(`Grow the strike stack ${label(S)}: nothing next to it is worth taking this turn (${held}).`);
454
+ }
455
+ if (strikeStack.deployed > 0 || taken.length)
456
+ offence.set(`strike:${S}`, {
457
+ target: S,
458
+ kind: 'strike',
459
+ cost: strikeStack.deployed,
460
+ value: strikeStack.income,
461
+ taken: taken.length > 0,
462
+ why: taken.length
463
+ ? `${builds}; it attacks ${taken.map(({ c }) => label(c.id)).join(', ')} this turn (${sent} armies sent)`
464
+ : `${builds}; it grows: nothing next to it is worth taking this turn`,
465
+ });
466
+ }
467
+ }