@chrischall/warapp-mcp 0.0.0 → 0.1.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 (177) hide show
  1. package/.claude-plugin/marketplace.json +4 -4
  2. package/.claude-plugin/plugin.json +2 -2
  3. package/README.md +199 -8
  4. package/dist/analysis/award.js +159 -0
  5. package/dist/analysis/bonuses.js +98 -0
  6. package/dist/analysis/breach.js +62 -0
  7. package/dist/analysis/card-support.js +329 -0
  8. package/dist/analysis/card-threats.js +234 -0
  9. package/dist/analysis/cards-in-effect.js +130 -0
  10. package/dist/analysis/chains.js +59 -0
  11. package/dist/analysis/chokepoints.js +140 -0
  12. package/dist/analysis/combat.js +231 -0
  13. package/dist/analysis/commander-safety.js +149 -0
  14. package/dist/analysis/commitments.js +338 -0
  15. package/dist/analysis/exchange.js +155 -0
  16. package/dist/analysis/graph.js +82 -0
  17. package/dist/analysis/guard-off.js +54 -0
  18. package/dist/analysis/guess.js +351 -0
  19. package/dist/analysis/headroom.js +241 -0
  20. package/dist/analysis/hold-diff.js +64 -0
  21. package/dist/analysis/how-lost.js +130 -0
  22. package/dist/analysis/index.js +14 -0
  23. package/dist/analysis/local-deploy.js +159 -0
  24. package/dist/analysis/lookahead.js +108 -0
  25. package/dist/analysis/opponent-profile.js +551 -0
  26. package/dist/analysis/opponents.js +1245 -0
  27. package/dist/analysis/outlook.js +633 -0
  28. package/dist/analysis/overrides.js +60 -0
  29. package/dist/analysis/picks.js +1879 -0
  30. package/dist/analysis/plan/after-leftover.js +140 -0
  31. package/dist/analysis/plan/cap-spend.js +242 -0
  32. package/dist/analysis/plan/captures.js +1195 -0
  33. package/dist/analysis/plan/commander.js +236 -0
  34. package/dist/analysis/plan/completed.js +29 -0
  35. package/dist/analysis/plan/conceded-out.js +131 -0
  36. package/dist/analysis/plan/estimates.js +715 -0
  37. package/dist/analysis/plan/guard-off.js +232 -0
  38. package/dist/analysis/plan/holds.js +1631 -0
  39. package/dist/analysis/plan/leftover.js +760 -0
  40. package/dist/analysis/plan/move-order.js +319 -0
  41. package/dist/analysis/plan/orders.js +317 -0
  42. package/dist/analysis/plan/relations.js +702 -0
  43. package/dist/analysis/plan/report.js +672 -0
  44. package/dist/analysis/plan/shared.js +1218 -0
  45. package/dist/analysis/plan/stand-still.js +823 -0
  46. package/dist/analysis/plan/state.js +44 -0
  47. package/dist/analysis/plan/strike.js +1416 -0
  48. package/dist/analysis/plan/targets.js +651 -0
  49. package/dist/analysis/plan/team.js +299 -0
  50. package/dist/analysis/plan/threats.js +927 -0
  51. package/dist/analysis/plan/transfers.js +328 -0
  52. package/dist/analysis/plan/util.js +5 -0
  53. package/dist/analysis/plan/vacated.js +285 -0
  54. package/dist/analysis/planner.js +2922 -0
  55. package/dist/analysis/player-record.js +144 -0
  56. package/dist/analysis/player.js +268 -0
  57. package/dist/analysis/profile.js +347 -0
  58. package/dist/analysis/relations.js +1030 -0
  59. package/dist/analysis/schedule.js +88 -0
  60. package/dist/analysis/since-last.js +50 -0
  61. package/dist/analysis/static-seats.js +71 -0
  62. package/dist/analysis/stress.js +577 -0
  63. package/dist/analysis/team-brief.js +151 -0
  64. package/dist/analysis/tripwire.js +644 -0
  65. package/dist/analysis/turn-sim.js +259 -0
  66. package/dist/analysis/whereabouts.js +1109 -0
  67. package/dist/board.js +105 -0
  68. package/dist/bundle.js +117959 -36172
  69. package/dist/cards.js +435 -0
  70. package/dist/chat-cursor.js +135 -0
  71. package/dist/chat.js +192 -0
  72. package/dist/client.js +361 -0
  73. package/dist/config.js +62 -0
  74. package/dist/direct/link.js +102 -0
  75. package/dist/direct/session.js +267 -0
  76. package/dist/direct/transport.js +424 -0
  77. package/dist/guess-salt.js +65 -0
  78. package/dist/hosted.js +24 -0
  79. package/dist/index.js +33 -0
  80. package/dist/join-color.js +140 -0
  81. package/dist/live.js +278 -0
  82. package/dist/map-stats.js +152 -0
  83. package/dist/map-store.js +204 -0
  84. package/dist/move-order.js +141 -0
  85. package/dist/my-games.js +180 -0
  86. package/dist/normalize.js +411 -0
  87. package/dist/open-games.js +537 -0
  88. package/dist/outlook-log.js +138 -0
  89. package/dist/path-lock.js +22 -0
  90. package/dist/pick-list.js +193 -0
  91. package/dist/player-record-store.js +229 -0
  92. package/dist/player-states.js +31 -0
  93. package/dist/profile-store.js +677 -0
  94. package/dist/protocol/bundle.js +375 -0
  95. package/dist/protocol/codec.js +556 -0
  96. package/dist/protocol/decoded.js +12 -0
  97. package/dist/protocol/interp.js +1904 -0
  98. package/dist/protocol/methods.js +531 -0
  99. package/dist/protocol/rpc.js +202 -0
  100. package/dist/push/listener.js +393 -0
  101. package/dist/push/packets.js +66 -0
  102. package/dist/push/socketio.js +333 -0
  103. package/dist/push/websocket.js +179 -0
  104. package/dist/redact.js +62 -0
  105. package/dist/relations-store.js +242 -0
  106. package/dist/replay.js +215 -0
  107. package/dist/scalars.js +28 -0
  108. package/dist/scout.js +346 -0
  109. package/dist/stats.js +269 -0
  110. package/dist/strategy/card-clock.js +185 -0
  111. package/dist/strategy/map-notes.js +128 -0
  112. package/dist/strategy/notes.js +2168 -0
  113. package/dist/team-cards.js +84 -0
  114. package/dist/team-orders.js +150 -0
  115. package/dist/teams.js +19 -0
  116. package/dist/tools/award.js +206 -0
  117. package/dist/tools/begin-turn.js +162 -0
  118. package/dist/tools/board.js +77 -0
  119. package/dist/tools/card-advice.js +256 -0
  120. package/dist/tools/card-effects.js +49 -0
  121. package/dist/tools/card-plays.js +434 -0
  122. package/dist/tools/card-support-advice.js +140 -0
  123. package/dist/tools/chat-inbox.js +146 -0
  124. package/dist/tools/chat.js +483 -0
  125. package/dist/tools/check-plan.js +688 -0
  126. package/dist/tools/commander-check.js +102 -0
  127. package/dist/tools/commitments.js +216 -0
  128. package/dist/tools/common.js +143 -0
  129. package/dist/tools/diplomacy.js +342 -0
  130. package/dist/tools/game.js +126 -0
  131. package/dist/tools/guess-view.js +56 -0
  132. package/dist/tools/healthcheck.js +90 -0
  133. package/dist/tools/hints.js +34 -0
  134. package/dist/tools/how-lost.js +154 -0
  135. package/dist/tools/index.js +142 -0
  136. package/dist/tools/join-game.js +327 -0
  137. package/dist/tools/leave-game.js +181 -0
  138. package/dist/tools/live-context.js +339 -0
  139. package/dist/tools/live.js +404 -0
  140. package/dist/tools/map-stats.js +117 -0
  141. package/dist/tools/map.js +133 -0
  142. package/dist/tools/my-games.js +123 -0
  143. package/dist/tools/open-games.js +104 -0
  144. package/dist/tools/opponents.js +151 -0
  145. package/dist/tools/order-options.js +135 -0
  146. package/dist/tools/picks.js +292 -0
  147. package/dist/tools/profile-hook.js +156 -0
  148. package/dist/tools/profile-opponents.js +121 -0
  149. package/dist/tools/profile-reads.js +99 -0
  150. package/dist/tools/push.js +385 -0
  151. package/dist/tools/relations.js +611 -0
  152. package/dist/tools/resolve.js +45 -0
  153. package/dist/tools/route.js +36 -0
  154. package/dist/tools/scout.js +87 -0
  155. package/dist/tools/session.js +163 -0
  156. package/dist/tools/strategy.js +200 -0
  157. package/dist/tools/stress-opponents.js +83 -0
  158. package/dist/tools/surrender.js +240 -0
  159. package/dist/tools/survival.js +189 -0
  160. package/dist/tools/team-brief.js +266 -0
  161. package/dist/tools/team-source.js +222 -0
  162. package/dist/tools/team.js +182 -0
  163. package/dist/tools/turn.js +2761 -0
  164. package/dist/tools/uncommit.js +160 -0
  165. package/dist/tools/where.js +275 -0
  166. package/dist/tools/write-kit.js +158 -0
  167. package/dist/transport-bridge.js +33 -0
  168. package/dist/trend.js +452 -0
  169. package/dist/version.js +4 -0
  170. package/manifest.json +174 -4
  171. package/mint.yaml +101 -14
  172. package/package.json +11 -6
  173. package/server.json +40 -3
  174. package/skills/warapp-api/SKILL.md +95 -4
  175. package/skills/warapp-api/references/scout.mjs +348 -0
  176. package/skills/warapp-api/scripts/warapp.sh +69 -8
  177. package/skills/warapp-mcp/SKILL.md +969 -21
@@ -0,0 +1,1416 @@
1
+ // The strikes of a planning pass (#133): finishing off or pressuring an opponent (rule 1e, #45),
2
+ // striking an enemy commander (rule 1s, #61) and the borders those relieve, a guard-off break
3
+ // (#165), the 1v1 strike stack (rule 0p.3c, #72, #102, #120) and the FFA lead strikes (#167).
4
+ // planPass runs them where they ran before: the commander strikes and finishing off right after
5
+ // the capture passes are defined, the strike stack's choice before the leftover deploy and its
6
+ // attacks after it, the lead strikes after No-Split's whole-stack orders.
7
+ import { forecastBorder } from '../exchange.js';
8
+ import { COMMANDER_STRENGTH, straightKills } from '../combat.js';
9
+ import { neighborsOf } from '../graph.js';
10
+ import { guardOffExposure } from '../guard-off.js';
11
+ import { captureCost, CONCEDE_FACTOR, guaranteedFallsReaching, MIN_ENEMY_DEPLOY, SECOND_FRONT_LEAD, visibleState, } from './shared.js';
12
+ import { commanderStaysLine, commanderTransit } from './commander.js';
13
+ import { byNum, pct } from './util.js';
14
+ /**
15
+ * The strikes that run before triage, in the order planPass ran them: rule 1e's finishing off is
16
+ * defined, the commander strikes (rule 1s) are made, then finishing off and pressure (rule 1e),
17
+ * the strikes not made are warned about, the relieved borders re-judged and triaged, and the
18
+ * guard-off breaks (#165) made.
19
+ */
20
+ export function strikesPhase(pc, ps, book, threats, hd, tgt, cap) {
21
+ const { finishOff } = finishOffHelper(pc, ps, book, threats, hd, tgt, cap);
22
+ const { struck, unstruck } = commanderStrikes(pc, ps, book, threats, hd, tgt, cap);
23
+ finishOffPass(pc, ps, book, threats, tgt, cap, finishOff, struck);
24
+ relieveCaptured(pc, ps, threats, hd, unstruck, book);
25
+ guardOffBreaks(pc, ps, book, hd, tgt);
26
+ return { struck };
27
+ }
28
+ /** Rule 1e (#45): finishing off an opponent, defined before the commander strikes; run by finishOffPass. */
29
+ export function finishOffHelper(pc, ps, book, threats, hd, tgt, cap) {
30
+ const { g, s, opts, income, foe, profile, marginFor, deployOf, paybackTurns, label, mine, mineSet, incomeGain, armiesOf, unitsAt, defenceAt, guard, bombOn, rates, noSplit, myCommanders, } = pc;
31
+ const { warnings, rationale, deployed, avail, coverKeep, spared, captured, combined, moves, incoming, survivorsAt, captureOrder, staged, } = ps;
32
+ const { guardAt, deploy, roomAt, valueOf, stakeAt } = book;
33
+ const { ownedBy, ownerOf, fogAnywhere, deployReaching, holdArmies, bombSized, borderAt } = threats;
34
+ const { stayAt } = hd;
35
+ const { targets, frontierDelta, repulsed } = tgt;
36
+ const { notCompleted, worstCase, finishedOff, tryCapture } = cap;
37
+ // ---- 1e. finish off an opponent (#45) ----
38
+ // Before any border is conceded: for each visible opponent whose every territory is
39
+ // visible (none borders the fog) and borders mine — any such opponent, however strong,
40
+ // fewest territories first — search the attack sizes on its territories against its best
41
+ // response (its deploy estimate is one budget, spread to save as many as it can; see
42
+ // `guaranteedFalls`). Kept when every territory falls (elimination), or when the falls it
43
+ // cannot prevent leave it one territory or take at least half, no attacking border faces
44
+ // a territory left unattacked, and every hold worth paying for against those is funded.
45
+ // The opponents in view (ownedBy, fogEdge, inReach, the weak ones) are read with the threats
46
+ // (plan/threats.ts, visibleOpponents): the holds ask who took a border from a weak opponent.
47
+ /** The most defenders `armies` attackers take for certain (`captureCost` at chance 1). */
48
+ const takesUpTo = (armies) => {
49
+ let y = 0;
50
+ while ((captureCost(y + 1, s) ?? Infinity) <= armies)
51
+ y++;
52
+ return y;
53
+ };
54
+ /** Everything a finish-off attempt may change, to restore it. */
55
+ const checkpoint = (ts) => ({
56
+ budget: ps.budget,
57
+ deployed: new Map(deployed),
58
+ avail: new Map(avail),
59
+ incoming: new Map(incoming),
60
+ captured: new Set(captured),
61
+ combined: new Set(combined),
62
+ survivorsAt: new Map(survivorsAt),
63
+ worstCase: new Map(worstCase),
64
+ targets: new Map(ts.map((t) => [t, targets.get(t)])),
65
+ notCompleted: new Map(notCompleted),
66
+ staged: new Map(staged),
67
+ captureOrder: captureOrder.length,
68
+ moves: moves.length,
69
+ rationale: rationale.length,
70
+ warnings: warnings.length,
71
+ });
72
+ const restore = (c) => {
73
+ ps.budget = c.budget;
74
+ deployed.clear();
75
+ for (const [k, v] of c.deployed)
76
+ deployed.set(k, v);
77
+ for (const [k, v] of c.avail)
78
+ avail.set(k, v);
79
+ incoming.clear();
80
+ for (const [k, v] of c.incoming)
81
+ incoming.set(k, v);
82
+ captured.clear();
83
+ for (const t of c.captured)
84
+ captured.add(t);
85
+ combined.clear();
86
+ for (const t of c.combined)
87
+ combined.add(t);
88
+ survivorsAt.clear();
89
+ for (const [k, v] of c.survivorsAt)
90
+ survivorsAt.set(k, v);
91
+ worstCase.clear();
92
+ for (const [k, v] of c.worstCase)
93
+ worstCase.set(k, v);
94
+ for (const [t, tg] of c.targets) {
95
+ if (tg)
96
+ targets.set(t, tg);
97
+ else
98
+ targets.delete(t);
99
+ }
100
+ notCompleted.clear();
101
+ for (const [k, v] of c.notCompleted)
102
+ notCompleted.set(k, v);
103
+ staged.clear();
104
+ for (const [k, v] of c.staged)
105
+ staged.set(k, v);
106
+ captureOrder.length = c.captureOrder;
107
+ moves.length = c.moves;
108
+ rationale.length = c.rationale;
109
+ warnings.length = c.warnings;
110
+ };
111
+ /** One sizing of the attacks: per target, the share of the deploy it is sized for, or SKIP. */
112
+ const SKIP = -1;
113
+ /**
114
+ * Positive when `a` beats `b`: an elimination, then more sure falls, then fewer attacking
115
+ * armies, then a dearer cheapest save (the opponent must commit more to save any one), then
116
+ * fewer deploys. A tie keeps the first found (shares are tried from the full deploy down,
117
+ * lowest territory id first), so the plan is deterministic.
118
+ */
119
+ const better = (a, b) => Number(a.all) - Number(b.all) ||
120
+ a.falls - b.falls ||
121
+ b.armies - a.armies ||
122
+ Math.min(...a.saveCost) - Math.min(...b.saveCost) ||
123
+ b.deploys - a.deploys;
124
+ /**
125
+ * Plan the captures of player `p`'s territories against its best response. Committed
126
+ * (true) when it eliminates `p`, or cuts it to one territory or takes at least half of it
127
+ * with no attacking border facing what is left unattacked and every hold worth paying for
128
+ * against that funded; otherwise rolled back. `probe`: always rolled back, true when an
129
+ * elimination is affordable.
130
+ */
131
+ const finishOff = (p, probe, fogged = []) => {
132
+ const ts = ownedBy.get(p);
133
+ /** Next to the fog (#60): only taking every visible territory for sure counts, as pressure. */
134
+ const pressure = fogged.length > 0;
135
+ /** Its estimated deploy; under pressure, sized for with a margin over it (#60). */
136
+ const estimateP = deployOf(p);
137
+ const marginP = pressure ? marginFor(estimateP) : 0;
138
+ const deployP = estimateP + marginP;
139
+ const deployText = marginP ? `~${estimateP} deploy plus a margin of ${marginP}` : `~${deployP} deploy`;
140
+ /**
141
+ * #179: what it may deploy on `t` — under Local Deployment its bonus pools pay only into their
142
+ * own territories (`deployReaching`), so a territory outside them faces less; else all of it.
143
+ */
144
+ const reachOn = new Map(ts.map((t) => [t, Math.min(deployP, deployReaching(p, [t]) + marginP)]));
145
+ const reachText = (t) => reachOn.get(t) < deployP ? `the ~${reachOn.get(t)} of its deploy that can reach it (Local Deployment)` : `its full ${deployText}`;
146
+ const start = checkpoint(ts);
147
+ if (ts.some((t) => captureCost(defenceAt(t), s) === null))
148
+ return false;
149
+ /**
150
+ * Reserve the holds for an attempt that leaves `stay` unattacked. Holds against other
151
+ * players (and against `stay`) worth paying for (rule 1a's CONCEDE_FACTOR test) come
152
+ * first. A source keeps what holds it there. On a border that attacks nothing, each such
153
+ * hold — best worth per army first, and only if it fits what is left — is deployed there
154
+ * while the captures are sized, so neither the captures nor a Local Deployment pool can
155
+ * spend that room; one that does not fit is left to triage.
156
+ */
157
+ const reserve = (stay, cover = false) => {
158
+ const tried = ts.filter((t) => !stay.has(t));
159
+ const sources = new Set(tried.flatMap((t) => neighborsOf(g, t).filter((n) => mineSet.has(n))));
160
+ const keepAt = new Map();
161
+ const elsewhere = [];
162
+ /** A hold's cost on my `x` against the threats left once `gone` fall, or null when not worth paying. */
163
+ const holdCostAt = (x, gone) => {
164
+ const rest = borderAt(x, gone);
165
+ if (!rest)
166
+ return null;
167
+ // Armies that must stay: the hold less what my special units there fight as.
168
+ const need = Math.max(0, holdArmies(rest.threat) - unitsAt(x));
169
+ const cost = Math.max(0, need - armiesOf(x));
170
+ const worth = valueOf(x) + (armiesOf(x) + stakeAt(x)) / paybackTurns;
171
+ // My commander's border is always worth holding (rule 1k).
172
+ return cost > CONCEDE_FACTOR * worth && !myCommanders.has(x) ? null : { need, cost, worth };
173
+ };
174
+ for (const x of mine) {
175
+ const h = holdCostAt(x, (n) => ownerOf(n) === p && !stay.has(n));
176
+ if (!h)
177
+ continue;
178
+ const { need, cost, worth } = h;
179
+ if (sources.has(x)) {
180
+ // No-Split (#124): nothing is kept back, the whole stack moves; a source that must hold
181
+ // against what is left issues no order instead (tryCapture asks `mustHold`).
182
+ if (noSplit)
183
+ continue;
184
+ const keep = Math.max(0, need - guardAt(x));
185
+ keepAt.set(x, keep);
186
+ avail.set(x, avail.get(x) - keep);
187
+ }
188
+ else if (cost > 0)
189
+ elsewhere.push({ x, cost, worth });
190
+ }
191
+ /** The holds reserved, by border. */
192
+ const funded = new Map();
193
+ elsewhere.sort((a, b) => b.worth / b.cost - a.worth / a.cost || a.cost - b.cost || a.x - b.x);
194
+ for (const h of elsewhere) {
195
+ if (h.cost > roomAt(h.x))
196
+ continue;
197
+ deploy(h.x, h.cost);
198
+ funded.set(h.x, h.cost);
199
+ }
200
+ // #179: cover its exits onto my land. Unless I move first, its stacks may attack before my
201
+ // attacks land, so each of my territories next to it holds against its stacks there plus the
202
+ // deploy that can reach them: a source keeps that (and what the attack would lose defending,
203
+ // so the attack still goes out whole), a border that attacks nothing is deployed to. These
204
+ // stay after the commit (the territory is locked), unlike the holds above.
205
+ const covers = new Set();
206
+ /** What each covered territory keeps, in `avail` terms. */
207
+ const coverAt = new Map();
208
+ let uncoverable = false;
209
+ if (cover)
210
+ for (const x of mine) {
211
+ const adj = ts.filter((t) => neighborsOf(g, x).includes(t));
212
+ if (!adj.length)
213
+ continue;
214
+ const threat = deployReaching(p, adj) + adj.reduce((n, t) => n + Math.max(0, armiesOf(t) - guard) + unitsAt(t), 0);
215
+ // #163: held as if a Bomb halved it first, as every other hold is.
216
+ const need = Math.max(0, holdArmies(bombSized(x, threat)) - unitsAt(x));
217
+ covers.add(x);
218
+ coverAt.set(x, Math.max(0, need - guardAt(x)));
219
+ if (sources.has(x)) {
220
+ if (noSplit) {
221
+ uncoverable = true;
222
+ break;
223
+ }
224
+ const keep = Math.max(need - guardAt(x), straightKills(threat, rates.offensiveKillRate));
225
+ // It keeps the loss buffer too through the later passes, not only the hold.
226
+ coverAt.set(x, keep);
227
+ const extra = keep - (keepAt.get(x) ?? 0);
228
+ if (extra > 0) {
229
+ keepAt.set(x, keep);
230
+ avail.set(x, avail.get(x) - extra);
231
+ }
232
+ }
233
+ else {
234
+ const cost = Math.max(0, need - armiesOf(x)) - (funded.get(x) ?? 0);
235
+ if (cost > roomAt(x)) {
236
+ uncoverable = true;
237
+ break;
238
+ }
239
+ if (cost > 0) {
240
+ deploy(x, cost);
241
+ funded.set(x, (funded.get(x) ?? 0) + cost);
242
+ }
243
+ }
244
+ }
245
+ const reserved = checkpoint(ts);
246
+ const fullReason = (t) => `takes player ${p}'s territory, sized for ${reachText(t)} landing there`;
247
+ /**
248
+ * #240 review: a territory my attacks failed on repeatedly, its owner reinforcing it, is
249
+ * attacked only at its sure size (its defenders plus `repulsed`'s deploy, when that is more
250
+ * than this pass's own reach), never pressed with a share of the deploy.
251
+ */
252
+ const sureShare = (t) => Math.max(reachOn.get(t), repulsed.get(t)?.extra ?? 0);
253
+ const reasonFor = (t, e) => e > reachOn.get(t)
254
+ ? `takes player ${p}'s territory, sized for its ~${e} deploy there (my attacks on it failed before, its owner reinforcing it: #240)`
255
+ : e >= reachOn.get(t)
256
+ ? fullReason(t)
257
+ : `presses player ${p}: sized for ${e} of its ~${reachOn.get(t)} deploy landing there`;
258
+ /** Size and plan the attacks for `sizes` (from `reserved`), and judge the result. */
259
+ const attempt = (sizes) => {
260
+ tried.forEach((t, i) => {
261
+ const e = sizes[i];
262
+ if (e === SKIP)
263
+ return;
264
+ worstCase.set(t, defenceAt(t) + e);
265
+ targets.set(t, {
266
+ id: t,
267
+ cost: captureCost(defenceAt(t) + e, s),
268
+ enemy: true,
269
+ sources: neighborsOf(g, t).filter((n) => mineSet.has(n)),
270
+ });
271
+ });
272
+ const order = tried
273
+ .map((t, i) => ({ t, e: sizes[i] }))
274
+ .filter((x) => x.e !== SKIP)
275
+ .sort((a, b) => targets.get(a.t).cost - targets.get(b.t).cost || a.t - b.t);
276
+ // No-Split (#124): a source must hold only against what stays; each target sized for the
277
+ // full deploy is taken for sure, so it threatens nothing once attacked.
278
+ const sure = new Set(order.filter((x) => x.e >= reachOn.get(x.t)).map((x) => x.t));
279
+ ps.assumeGone = (n) => sure.has(n);
280
+ const attacked = order
281
+ .filter(({ t, e }) => tryCapture(t, reasonFor(t, e)))
282
+ .map((x) => x.t)
283
+ .sort(byNum);
284
+ ps.assumeGone = () => false;
285
+ const ours = moves.slice(reserved.moves).filter((m) => m.kind === 'attack');
286
+ // #179: a covered territory that attacks nothing gets the deploys its kept hold still lacks.
287
+ let uncovered = false;
288
+ for (const x of [...covers].sort(byNum)) {
289
+ const short = -avail.get(x);
290
+ if (short <= 0 || ours.some((m) => m.from === x))
291
+ continue;
292
+ if (short > roomAt(x))
293
+ uncovered = true;
294
+ else
295
+ deploy(x, short);
296
+ }
297
+ const saveCost = attacked.map((t) => {
298
+ const at = ours.filter((m) => m.to === t);
299
+ const finisher = at[at.length - 1];
300
+ const kills = at
301
+ .slice(0, -1)
302
+ .reduce((n, m) => n + straightKills(m.armies, rates.offensiveKillRate), 0);
303
+ return Math.max(0, kills + takesUpTo(finisher.armies) - defenceAt(t) + 1);
304
+ });
305
+ const falls = guaranteedFallsReaching(saveCost, attacked.map((t) => reachOn.get(t)), deployP);
306
+ const all = falls === ts.length;
307
+ const left = ts.filter((t) => !attacked.includes(t));
308
+ const attackers = new Set(ours.map((m) => m.from));
309
+ const freed = [...attackers].every((x) => !neighborsOf(g, x).some((n) => left.includes(n)));
310
+ // What stays unattacked: a border that attacks nothing but faces it must still have its
311
+ // hold funded, or the captures cost a border worth holding.
312
+ const unfunded = ours.length
313
+ ? mine.some((x) => {
314
+ if (attackers.has(x) || !neighborsOf(g, x).some((n) => left.includes(n)))
315
+ return false;
316
+ const h = holdCostAt(x, (n) => captured.has(n));
317
+ return h !== null && h.cost > (funded.get(x) ?? 0);
318
+ })
319
+ : false;
320
+ return {
321
+ sizes,
322
+ attacked,
323
+ saveCost,
324
+ falls,
325
+ all,
326
+ armies: ours.reduce((n, m) => n + m.armies, 0),
327
+ deploys: reserved.budget - ps.budget,
328
+ enough: falls > 0 && !uncovered && (all || ts.length - falls <= 1 || falls * 2 >= ts.length),
329
+ freed,
330
+ unfunded,
331
+ left,
332
+ };
333
+ };
334
+ // Every sizing, each target sized for 0..its full deploy share (or not attacked): exact
335
+ // while there are few; otherwise evenly spaced shares, always including the full one.
336
+ const LIMIT = 1024;
337
+ let levels = deployP + 2;
338
+ while (levels > 1 && levels ** tried.length > LIMIT)
339
+ levels--;
340
+ /** Each target's sizings: its reachable deploy (#179) evenly spaced down to 0, or not attacked. */
341
+ const sharesOf = tried.map((t) => {
342
+ // B2 T1: a territory a truce covers is never attacked, so it is never sized either.
343
+ if (pc.truce.noTarget(t))
344
+ return [SKIP];
345
+ const r = reachOn.get(t);
346
+ // #240 review: a repulsed territory at its sure size, or (as any target may be) not attacked.
347
+ if (repulsed.has(t))
348
+ return levels >= 2 ? [sureShare(t), SKIP] : [sureShare(t)];
349
+ const spaced = Array.from({ length: Math.max(1, levels - 1) }, (_, i) => Math.round(r - (i * r) / Math.max(1, levels - 2)));
350
+ return levels >= 2 ? [...new Set(spaced), SKIP] : [r];
351
+ });
352
+ /** Every sizing tried; the state is left as reserved. */
353
+ const search = () => {
354
+ let best = null;
355
+ let bestUnfunded = null;
356
+ let canEliminate = false;
357
+ if (uncoverable)
358
+ return { best, bestUnfunded, canEliminate };
359
+ const sizes = tried.map(() => 0);
360
+ const visit = (i) => {
361
+ if (i === tried.length) {
362
+ const a = attempt([...sizes]);
363
+ restore(reserved);
364
+ if (a.all)
365
+ canEliminate = true;
366
+ if (!a.enough || !a.freed || (pressure && !a.all))
367
+ return;
368
+ if (a.unfunded) {
369
+ if (!bestUnfunded || better(a, bestUnfunded) > 0)
370
+ bestUnfunded = a;
371
+ }
372
+ else if (!best || better(a, best) > 0)
373
+ best = a;
374
+ return;
375
+ }
376
+ for (const e of sharesOf[i]) {
377
+ sizes[i] = e;
378
+ visit(i + 1);
379
+ }
380
+ };
381
+ if (tried.length)
382
+ visit(0);
383
+ return { best: best, bestUnfunded: bestUnfunded, canEliminate };
384
+ };
385
+ /** Plan `chosen`, then release the reservations: the triage (or the greedy step) deploys the holds. */
386
+ const commit = (chosen) => {
387
+ attempt(chosen.sizes);
388
+ // #179: a covered exit keeps its hold: every later keep honours it.
389
+ for (const [x, k] of coverAt)
390
+ coverKeep.set(x, Math.max(coverKeep.get(x) ?? 0, k));
391
+ for (const [x, k] of keepAt)
392
+ avail.set(x, avail.get(x) + k);
393
+ for (const [x, k] of funded) {
394
+ if (covers.has(x))
395
+ continue;
396
+ const d = deployed.get(x) - k;
397
+ if (d)
398
+ deployed.set(x, d);
399
+ else
400
+ deployed.delete(x);
401
+ avail.set(x, avail.get(x) - k);
402
+ ps.budget += k;
403
+ }
404
+ };
405
+ return { search, commit, covers };
406
+ };
407
+ const found = reserve(new Set()).search();
408
+ restore(start);
409
+ if (probe)
410
+ return found.canEliminate;
411
+ let chosen = found.best;
412
+ let stay = new Set();
413
+ /** #179: the elimination covers its exits onto my land (not known to move first). */
414
+ let cover = false;
415
+ if (chosen?.all && !pressure && opts.movesFirst !== true) {
416
+ const c = reserve(new Set(), true).search();
417
+ restore(start);
418
+ if (c.best?.all) {
419
+ chosen = c.best;
420
+ cover = true;
421
+ }
422
+ }
423
+ // A better attempt that left a hold facing what it left unattacked unfunded: once more,
424
+ // with those holds reserved first and those territories left alone.
425
+ const retry = found.bestUnfunded;
426
+ if (!cover && retry && (!chosen || better(retry, chosen) > 0)) {
427
+ const again = reserve(new Set(retry.left)).search();
428
+ restore(start);
429
+ if (again.best && (!chosen || better(again.best, chosen) > 0)) {
430
+ chosen = again.best;
431
+ stay = new Set(retry.left);
432
+ }
433
+ }
434
+ if (!chosen)
435
+ return false;
436
+ const coverBefore = new Map(coverKeep);
437
+ const committed = reserve(stay, cover);
438
+ committed.commit(chosen);
439
+ // #179: in an FFA, price the elimination before it stands: the players its land would make me
440
+ // border, and the frontier cost before and after (each border's hold need next turn, the
441
+ // victim's threat gone). A buffer whose removal costs more than a turn of my income, and more
442
+ // than the income its land adds pays back in PAYBACK_TURNS turns, is left standing.
443
+ if (chosen.all && !pressure && profile.format === 'ffa' && profile.opponents >= 2) {
444
+ const next = [...new Set(ts.flatMap((t) => neighborsOf(g, t)))].sort(byNum);
445
+ const exposed = next.filter((n) => {
446
+ const o = ownerOf(n);
447
+ return o !== undefined && o !== p && foe(o) && !neighborsOf(g, n).some((x) => mineSet.has(x));
448
+ });
449
+ if (exposed.length) {
450
+ const after = new Set([...mineSet, ...ts]);
451
+ const delta = frontierDelta(mineSet, ts, (x) => (mineSet.has(x) ? stayAt(x) : (survivorsAt.get(x) ?? 0))).armies;
452
+ const gain = Math.max(0, incomeGain(after));
453
+ const limit = Math.max(paybackTurns * gain, income);
454
+ const who = [...new Set(exposed.map((n) => ownerOf(n)))].sort(byNum);
455
+ const exposure = `taking ${ts.map(label).join(', ')} makes me border ${who
456
+ .map((q) => `player ${q}'s ${exposed.filter((n) => ownerOf(n) === q).map(label).join(', ')}`)
457
+ .join(' and ')}`;
458
+ const shown = Math.round(delta);
459
+ const cost = `the frontier's hold cost changes by ${shown >= 0 ? '+' : ''}${shown} armies (its own threat gone)`;
460
+ if (delta > limit) {
461
+ restore(start);
462
+ coverKeep.clear();
463
+ for (const [k, v] of coverBefore)
464
+ coverKeep.set(k, v);
465
+ for (const t of ts)
466
+ spared.add(t);
467
+ rationale.push(`Not finishing off player ${p} (#179): it is a buffer: ${exposure}, and ${cost}, more than a turn of my income (${income}) and more than the +${gain} its land adds pays back in ${paybackTurns} turns.`);
468
+ return false;
469
+ }
470
+ rationale.push(`Elimination price (#179): ${exposure}; ${cost}, within ${limit} (a turn of my income, or ${paybackTurns} turns of the +${gain} its land adds).`);
471
+ }
472
+ }
473
+ const { attacked, falls, left } = chosen;
474
+ const local = attacked.filter((t) => reachOn.get(t) < deployP);
475
+ /** How each attack is sized: for the full deploy, or (Local Deployment, #179) what can reach it. */
476
+ const sizedFor = local.length ? `the part of its ${deployText} that can reach it (Local Deployment)` : `its full ${deployText}`;
477
+ if (local.length)
478
+ rationale.push(`Local Deployment (#179): player ${p}'s bonus pools pay only into their own territories, so ${local.map((t) => `${label(t)} can be reinforced with ~${reachOn.get(t)}`).join(', ')} at most, and ${local.length === 1 ? 'its attack is' : 'their attacks are'} sized for that.`);
479
+ // The territories left unattacked stay ordinary (non-worst-case) targets.
480
+ for (const t of left) {
481
+ worstCase.delete(t);
482
+ const tg = start.targets.get(t);
483
+ if (tg)
484
+ targets.set(t, tg);
485
+ else
486
+ targets.delete(t);
487
+ }
488
+ const names = attacked.map(label).join(', ');
489
+ const rest = left.length
490
+ ? `; ${left.map(label).join(', ')} stay${left.length === 1 ? 's' : ''} unattacked, and no attacking border faces ${left.length === 1 ? 'it' : 'them'}`
491
+ : '';
492
+ if (chosen.all && pressure) {
493
+ const edge = fogged.map(label).join(', ');
494
+ rationale.push(`Pressure player ${p}: take all ${ts.length} of its visible territories (${names}) this turn, each sized for ${sizedFor} landing there; it may hold more in the fog (next to ${edge}), so this is not an elimination.`);
495
+ warnings.push(`Pressuring player ${p} assumes it deploys at most ~${deployP} (its ~${estimateP} estimate ${marginP ? `plus a margin of ${marginP}` : 'with no margin: behind, attacks are sized at the minimum'}); more income than that (unseen bonuses, cards) could still save a territory.`, `player ${p} may hold more territories in the fog (next to ${edge}): taking its ${ts.length} visible territories is pressure, not an elimination.`);
496
+ return true;
497
+ }
498
+ if (chosen.all) {
499
+ finishedOff.add(p);
500
+ rationale.push(`Finish off player ${p}: attack all ${ts.length} of its territories (${names}) this turn, each sized for ${sizedFor} landing there, so it is eliminated ${fogAnywhere ? 'if it holds nothing in the fog, ' : ''}even if it reinforces; the borders facing it need no holding${cover ? ' once my attacks land' : ''}.`);
501
+ if (cover && committed.covers.size)
502
+ rationale.push(`Cover player ${p}'s exits (#179): I am not known to move first, so its stacks may attack before my attacks land; ${[...committed.covers].sort(byNum).map(label).join(', ')} keep${committed.covers.size === 1 ? 's' : ''} what holds against its stacks next to ${committed.covers.size === 1 ? 'it' : 'them'} plus its deploy${bombOn ? ', as if halved by a Bomb first' : ''}, so it cannot break out onto my land.`);
503
+ warnings.push(`Eliminating player ${p} assumes it deploys at most ~${deployP} (its estimate); more income than that (unseen bonuses, cards) could still save one of its territories.`);
504
+ if (fogAnywhere)
505
+ warnings.push(`player ${p} could still hold territories in the fog that border none of its visible ones: taking all ${ts.length} visible ones may not eliminate it.`);
506
+ return true;
507
+ }
508
+ const kept = ts.length - falls;
509
+ const outcome = kept <= 1 ? 'cutting it to one territory' : `taking ${falls} of its ${ts.length}`;
510
+ if (falls === attacked.length)
511
+ rationale.push(`Pressure player ${p}: take ${falls} of its ${ts.length} territories (${names}) this turn, each sized for ${sizedFor} landing there, ${outcome}${rest}.`);
512
+ else {
513
+ const saved = attacked.length - falls;
514
+ rationale.push(`Pressure player ${p}: attack ${attacked.length === ts.length ? 'all' : attacked.length} ${attacked.length === ts.length ? `${ts.length} of its` : `of its ${ts.length}`} territories (${names}) this turn: its ~${deployP} deploy can save at most ${saved} of them, so at least ${falls} fall${falls === 1 ? 's' : ''}, ${outcome}${rest}.`);
515
+ warnings.push(`player ${p} chooses which of ${names} to save (up to ${saved}): what it deploys there survives my attack, next to the borders that attacked it.`);
516
+ }
517
+ warnings.push(`Pressuring player ${p} assumes it deploys at most ~${deployP} (its estimate); more income than that (unseen bonuses, cards) could still save a territory.`);
518
+ return true;
519
+ };
520
+ return { finishOff };
521
+ }
522
+ /** Rule 1s (#61): strike each visible enemy commander next to me, before anything else spends the income. */
523
+ export function commanderStrikes(pc, ps, book, threats, hd, tgt, cap) {
524
+ const { g, s, foe, profile, reserve, deployOf, territories: state, label, mineSet, armiesOf, unitsAt, uncounted, defenceAt, noSplit, myCommanders, } = pc;
525
+ const { warnings, rationale, deployed, avail, captured } = ps;
526
+ const { orderOf, describeOrder, local, roomAt, spareAt } = book;
527
+ const { ownedBy, ownerOf, deployReaching, holdArmies, borderAt } = threats;
528
+ const { stayAt, keepFor } = hd;
529
+ const { targets } = tgt;
530
+ const { mustHold, strikes, worstCase, tryCapture } = cap;
531
+ // ---- 1s. strike an enemy commander (#61) ----
532
+ // Killing a player's commander eliminates it, so a visible enemy commander next to a
533
+ // territory I held at the start of the turn is attacked before anything else spends the
534
+ // income (finishing off, pressure, holds, expansion), under every goal, sized for its
535
+ // armies, the commander's COMMANDER_STRENGTH and its owner's full deploy estimate landing
536
+ // there. Nothing is conceded yet, so a thin border next to it may strike. The owner's other
537
+ // stacks still threaten this turn (attacks interleave). My commander's hold is reserved
538
+ // first; each source keeps what holds it (`keepFor`; nothing when it cannot hold anyway,
539
+ // unless it is my commander's).
540
+ /** Players whose commander is struck this turn: finishing them off is moot. */
541
+ const struck = new Set();
542
+ /** Strikes not made, warned about only when nothing else (finishing off) takes the territory. */
543
+ const unstruck = [];
544
+ for (const t of [...state.keys()].sort(byNum)) {
545
+ const st = state.get(t);
546
+ if (mineSet.has(t) || captured.has(t) || st.armies === null || st.owner.kind !== 'player' || !foe(st.owner.playerId) || uncounted(t))
547
+ continue;
548
+ // B2 (T1): never a truce's covered territory.
549
+ if (pc.truce.noTarget(t))
550
+ continue;
551
+ if (!(st.specialUnits ?? []).some((u) => u.kind === 'commander' && foe(u.playerId)))
552
+ continue;
553
+ const adjacent = neighborsOf(g, t).filter((n) => mineSet.has(n));
554
+ if (!adjacent.length)
555
+ continue;
556
+ const p = st.owner.playerId;
557
+ // #179: under Local Deployment only what can reach the commander's territory (its pools pay elsewhere).
558
+ const deployP = deployReaching(p, [t]);
559
+ const pooled = deployP < deployOf(p);
560
+ const defenders = defenceAt(t) + deployP;
561
+ const cost = captureCost(defenders, s);
562
+ const at = `Player ${p}'s commander on ${label(t)}`;
563
+ const sizing = `its ${armiesOf(t)} armies + the commander's ${COMMANDER_STRENGTH} + ${pooled ? `the ~${deployP} deploy that can reach it (Local Deployment)` : `its owner's full ~${deployP} deploy`}`;
564
+ if (cost === null)
565
+ continue;
566
+ // Only the struck territory stops threatening (once taken). war.app interleaves both
567
+ // players' attacks, so the owner's other stacks still attack this turn: elimination
568
+ // changes next turn's picture, not this one's.
569
+ const gone = (x) => x === t;
570
+ // My commander's must-hold reserve is funded first (rule 1k): what its territory needs
571
+ // against every threat but the struck one; when that does not fit, all that may be
572
+ // deployed there (rule 1k deploys it all there anyway). It is held as a deploy on my
573
+ // commander's territory while the strike is tried, so under Local Deployment it is charged
574
+ // to the pools that can reach it (`roomAt`/`spareAt` see it), not just taken off the budget.
575
+ const held = new Map();
576
+ const hold = (on) => {
577
+ for (const [c, n] of held) {
578
+ const d = (deployed.get(c) ?? 0) + (on ? n : -n);
579
+ if (d > 0)
580
+ deployed.set(c, d);
581
+ else
582
+ deployed.delete(c);
583
+ ps.budget += on ? -n : n;
584
+ }
585
+ };
586
+ for (const c of [...myCommanders].sort(byNum)) {
587
+ const b = borderAt(c, (x) => captured.has(x) || gone(x));
588
+ const n = b ? Math.min(roomAt(c), Math.max(0, holdArmies(b.threat) - unitsAt(c) - stayAt(c))) : 0;
589
+ if (n <= 0)
590
+ continue;
591
+ held.set(c, n);
592
+ deployed.set(c, (deployed.get(c) ?? 0) + n);
593
+ ps.budget -= n;
594
+ }
595
+ hold(false);
596
+ const reserved = [...held.values()].reduce((a, n) => a + n, 0);
597
+ // A source that issues no order yet (No-Split: it may already strike another commander)
598
+ // may strike. Strikes run before triage and every other pass, so no source is conceded or
599
+ // locked yet: those cannot hold a strike back.
600
+ const blocked = (x) => orderOf(x) !== undefined;
601
+ const order = adjacent
602
+ .filter((x) => !blocked(x))
603
+ .map((x) => ({ x, keep: keepFor(x, gone, ps.budget - reserved - reserve) }))
604
+ .sort((a, b) => avail.get(b.x) - b.keep - (avail.get(a.x) - a.keep) || a.x - b.x);
605
+ const prev = targets.get(t);
606
+ targets.set(t, { id: t, cost, enemy: true, sources: adjacent });
607
+ worstCase.set(t, defenders);
608
+ strikes.add(t);
609
+ const reason = `kills player ${p}'s commander, which eliminates it (sized for ${sizing})`;
610
+ // Every source's most, with no keep and no reserve: what the strike could ever be sent.
611
+ const most = new Map(order.map(({ x }) => [x, Math.max(0, avail.get(x)) + Math.max(0, spareAt(x))]));
612
+ hold(true);
613
+ const done = order.some(({ x, keep }) => tryCapture(t, reason, { from: x, keep }));
614
+ /** What may still be deployed on each source with the reserve held back (pools included). */
615
+ const roomLeft = new Map(order.map(({ x }) => [x, Math.max(0, spareAt(x))]));
616
+ hold(false);
617
+ if (done) {
618
+ struck.add(p);
619
+ // #179: a commander kill turns its owner's land neutral where it stands: nothing comes to
620
+ // me directly, and whoever borders it collects. Priced in an FFA, never gated.
621
+ if (profile.format === 'ffa' && profile.opponents >= 2) {
622
+ const land = (ownedBy.get(p) ?? []).filter((x) => x !== t);
623
+ const by = new Map();
624
+ for (const x of land)
625
+ for (const n of neighborsOf(g, x)) {
626
+ const o = ownerOf(n);
627
+ if (o === undefined || o === p || !foe(o))
628
+ continue;
629
+ if (!(by.get(o) ?? []).includes(x))
630
+ by.set(o, [...(by.get(o) ?? []), x]);
631
+ }
632
+ const collectors = [...by].sort((a, b) => a[0] - b[0]).map(([q, xs]) => `player ${q} borders ${[...xs].sort(byNum).map(label).join(', ')}`);
633
+ if (land.length)
634
+ rationale.push(`Commander kill (#179): player ${p}'s land turns neutral where it stands; ${collectors.length ? collectors.join(', ') : 'no other player in view borders it'}, so ${collectors.length ? 'they may collect it' : 'it is mine to take'} (struck all the same: it removes a player).`);
635
+ }
636
+ warnings.push(`Killing player ${p}'s commander on ${label(t)} assumes it deploys at most ~${deployP} (its estimate); more than that (unseen bonuses, cards) could save it.`);
637
+ continue;
638
+ }
639
+ strikes.delete(t);
640
+ worstCase.delete(t);
641
+ if (prev)
642
+ targets.set(t, prev);
643
+ else
644
+ targets.delete(t);
645
+ // Say what actually held it back, so a manual strike can be judged; said only if finishing
646
+ // off does not take it. A keep is named only for a source that could send enough without
647
+ // it and the reserve; the reserve only when it binds (a source could send enough, keep
648
+ // kept, but for it, or dropping that keep alone would not do). With no source able to
649
+ // send enough at all, the strike is unaffordable.
650
+ const could = order.filter(({ x }) => most.get(x) >= cost);
651
+ /** What `x` could send with no keep but the reserve held back (a guard owed is paid first). */
652
+ const unkept = (x) => Math.max(0, avail.get(x) + roomLeft.get(x));
653
+ const limits = [
654
+ ...adjacent.filter(blocked).map((x) => `No-Split: ${label(x)} already ${describeOrder(orderOf(x))}`),
655
+ // The reserve only where it binds: a source could send enough, keep kept, but for it; or
656
+ // dropping the keep alone would not do either (both stand in the way).
657
+ ...(reserved && could.some(({ x, keep }) => most.get(x) - keep >= cost || unkept(x) < cost)
658
+ ? [`${reserved} of the income is held back for my commander's territory`]
659
+ : []),
660
+ ...could
661
+ .filter(({ keep }) => !noSplit && keep > 0)
662
+ .map(({ x, keep }) => `${label(x)} keeps ${keep} to hold ${myCommanders.has(x) ? 'my commander' : 'its other borders'}`),
663
+ // No-Split (#124): the whole stack would go, so a source that must hold sends nothing.
664
+ ...could.flatMap(({ x }) => {
665
+ const h = mustHold(x, t, most.get(x));
666
+ return h ? [`No-Split: ${label(x)} must hold its border and would send its whole stack`] : [];
667
+ }),
668
+ ...(order.length && !could.length
669
+ ? [`unaffordable: at most ${Math.max(...most.values())} attackers from any one territory (every movable army and every deploy)`]
670
+ : []),
671
+ ];
672
+ // Nothing above binds, yet no source could: name what each could actually send (under
673
+ // Local Deployment, its pool room is what stops it).
674
+ if (!limits.length)
675
+ for (const { x } of could)
676
+ limits.push(`${label(x)} can send at most ${unkept(x)}${local ? ` (Local Deployment: only ${roomLeft.get(x)} may be deployed there)` : ''}`);
677
+ // #274 review 2: under No-Split my commander's walk is its territory's one order; a kill that
678
+ // territory alone could make is named, never silently dropped (a 1v1 ends with it).
679
+ const walk = adjacent.find((x) => x === pc.commanderAt?.retreat?.from && orderOf(x)?.commander === true);
680
+ if (walk !== undefined && !could.length && Math.max(0, avail.get(walk)) + Math.max(0, spareAt(walk)) >= cost) {
681
+ unstruck.push({
682
+ t,
683
+ text: `${at} is in reach: ${label(walk)} could send the ${cost} attackers killing it needs (${sizing}), but under No-Split my commander's walk is ${label(walk)}'s one order (#274): not attacked. ${profile.format === '1v1' ? 'Killing it ends the game (a 1v1)' : `Killing it eliminates player ${p}`}: to strike instead, send ${label(walk)} → ${label(t)} by hand, and my commander stays on ${label(walk)}.`,
684
+ });
685
+ continue;
686
+ }
687
+ unstruck.push({
688
+ t,
689
+ text: `${at} is in reach, but killing it needs ${cost} attackers (${sizing}), more than my territories next to it can send this turn${limits.length ? ` (${limits.join('; ')})` : ''}: not attacked.`,
690
+ });
691
+ }
692
+ return { struck, unstruck };
693
+ }
694
+ /** Rule 1e (#45, #60, #201): finish off or pressure each opponent in reach, fewest territories first. */
695
+ export function finishOffPass(pc, ps, book, threats, tgt, cap, finishOff, struck) {
696
+ const { g, me, s, income, profile, auto, pressureFactor, marginFor, guarded, deployOf, label, mineSet, armiesOf, uncounted, noSplit, } = pc;
697
+ const { warnings, rationale, locked, spared, unabsorbed, absorbLines } = ps;
698
+ const { orderOf } = book;
699
+ const { ownedBy, fogEdge, inReach } = threats;
700
+ const { movableFor } = cap;
701
+ const { targets } = tgt;
702
+ if (guarded) {
703
+ const candidates = [...ownedBy.keys()]
704
+ .filter((p) => inReach(p) && !struck.has(p) && !ownedBy.get(p).some(uncounted))
705
+ .sort((a, b) => ownedBy.get(a).length - ownedBy.get(b).length ||
706
+ ownedBy.get(a).reduce((n, t) => n + armiesOf(t), 0) - ownedBy.get(b).reduce((n, t) => n + armiesOf(t), 0) ||
707
+ a - b);
708
+ // A typical expansion capture: the median cost of the visible neutrals next to me.
709
+ const neutralCosts = [...targets.values()].filter((tg) => !tg.enemy).map((tg) => tg.cost).sort(byNum);
710
+ const expansionCost = neutralCosts.length ? neutralCosts[(neutralCosts.length - 1) >> 1] : null;
711
+ /**
712
+ * Each of `p`'s visible territories, sized for its full deploy plus the pressure margin,
713
+ * costs at most PRESSURE_FACTOR typical expansions (AHEAD_PRESSURE_FACTOR ahead in a 1v1 under
714
+ * the profile, rule 0p.3; with no visible neutral next to me,
715
+ * nothing to compare with: no limit). All or nothing.
716
+ */
717
+ /**
718
+ * #201 (adapting, an FFA with two or more opponents, a leader on strength that is not me):
719
+ * finishing off or pressing a player smaller than me, not the leader, absorbs its income — worth
720
+ * it only when its income added to mine matches the leader's; else the armies are better spent
721
+ * with the others against the leader. A rationale line says which.
722
+ */
723
+ const absorbs = (p) => {
724
+ const r = profile.ranking;
725
+ if (!auto || profile.format !== 'ffa' || profile.opponents < 2 || !r || r.commonThreat === null || p === r.commonThreat)
726
+ return true;
727
+ const row = (q) => r.players.find((x) => x.playerId === q);
728
+ const mineRow = row(me);
729
+ const theirs = row(p);
730
+ const lead = row(r.commonThreat);
731
+ if (!mineRow || !theirs || !lead || theirs.strength >= mineRow.strength)
732
+ return true;
733
+ const with_ = income + theirs.income;
734
+ if (with_ >= lead.income) {
735
+ // Said once, and kept only when an attack on player `p` is made (checked once the orders are final).
736
+ if (!absorbLines.has(p)) {
737
+ const line = `Absorb player ${p} (#201): its ~${theirs.income} income brings mine from ${income} to ${with_}, matching leader player ${lead.playerId}'s ~${lead.income}.`;
738
+ absorbLines.set(p, line);
739
+ rationale.push(line);
740
+ }
741
+ return true;
742
+ }
743
+ unabsorbed.add(p);
744
+ for (const t of ownedBy.get(p) ?? [])
745
+ spared.add(t);
746
+ rationale.push(`Not finishing off player ${p} (#201): player ${lead.playerId} leads the free-for-all on ~${lead.income} income; absorbing player ${p}'s ~${theirs.income} brings mine from ${income} to ${with_}, short of it — the others are better spent against the leader.`);
747
+ return false;
748
+ };
749
+ const pressureAffordable = (p) => {
750
+ const d = deployOf(p);
751
+ if (expansionCost === null)
752
+ return [];
753
+ // #120: a capture over the limit displaces no expansion when the armies already on one source
754
+ // beyond what holds it pay for all of it (no deploys): it is waived, each source paying once
755
+ // (never under No-Split, where it takes that source's one order).
756
+ const idle = new Map();
757
+ const waived = [];
758
+ for (const t of [...ownedBy.get(p)].sort(byNum)) {
759
+ const cost = captureCost(armiesOf(t) + d + marginFor(d), s) ?? Infinity;
760
+ if (cost <= pressureFactor * expansionCost)
761
+ continue;
762
+ // Under No-Split the source's one order is what the capture displaces: no waiver.
763
+ if (noSplit)
764
+ return null;
765
+ const from = neighborsOf(g, t)
766
+ .filter((x) => mineSet.has(x) && !locked.has(x) && !orderOf(x))
767
+ .map((x) => ({ x, left: idle.get(x) ?? Math.max(0, movableFor(x, t)) }))
768
+ .filter(({ left }) => left >= cost)
769
+ .sort((a, b) => b.left - a.left || a.x - b.x)[0];
770
+ if (!from)
771
+ return null;
772
+ idle.set(from.x, from.left - cost);
773
+ waived.push({ t, from: from.x, cost });
774
+ }
775
+ return waived;
776
+ };
777
+ // #201: a smaller player holding a unit the board gives no strength for cannot be finished off
778
+ // (no finishing-off candidate), but absorbing it is judged the same way: its counted territories are
779
+ // spared when that would not catch the leader.
780
+ for (const p of [...ownedBy.keys()].sort(byNum))
781
+ if (inReach(p) && !struck.has(p) && ownedBy.get(p).some(uncounted))
782
+ absorbs(p);
783
+ for (const p of candidates) {
784
+ if (!absorbs(p))
785
+ continue;
786
+ const edge = fogEdge(p);
787
+ if (edge.length) {
788
+ // Fog is a reason not to claim elimination, not to skip a cheap capture (#60).
789
+ const waived = pressureAffordable(p);
790
+ if (waived && finishOff(p, false, edge)) {
791
+ if (waived.length)
792
+ rationale.push(`Pressure on player ${p} is not priced against expansion (${pressureFactor}× a typical neutral capture, ${pressureFactor * expansionCost}): ${waived
793
+ .map((w) => `${label(w.t)} (${w.cost}) is paid from idle armies on ${label(w.from)}`)
794
+ .join(', ')}, so it displaces no expansion.`);
795
+ continue;
796
+ }
797
+ if (finishOff(p, true))
798
+ warnings.push(`player ${p} may hold more territories in the fog (next to ${edge.map(label).join(', ')}): finishing it off is not attempted, though its ${ownedBy.get(p).length} visible territories could all be taken this turn.`);
799
+ continue;
800
+ }
801
+ finishOff(p, false);
802
+ }
803
+ }
804
+ }
805
+ /** The strikes not made, the borders the strikes and finishing off relieve, and triage on what is left. */
806
+ export function relieveCaptured(pc, ps, threats, hd, unstruck, book) {
807
+ const { g, label, myCommanders } = pc;
808
+ const { warnings, rationale, captured } = ps;
809
+ const { borders, borderAt } = threats;
810
+ const { assessThreats, triage } = hd;
811
+ for (const { t, text } of unstruck)
812
+ if (!captured.has(t))
813
+ warnings.push(text);
814
+ // The borders those captures (a strike, finishing off) relieve: re-judged without the
815
+ // territories taken. A struck player's other stacks still threaten: attacks interleave, so
816
+ // its elimination changes next turn, not this one.
817
+ const fallen = (n) => captured.has(n);
818
+ if (captured.size)
819
+ for (const id of [...borders.keys()]) {
820
+ if (!neighborsOf(g, id).some(fallen))
821
+ continue;
822
+ const b = borderAt(id, fallen);
823
+ if (b)
824
+ borders.set(id, b);
825
+ else
826
+ borders.delete(id);
827
+ }
828
+ // #274: the territory my commander walks from holds it until my first order runs: after the
829
+ // strikes (a struck stack threatens nothing there), before triage (plan/commander.ts).
830
+ commanderTransit(pc, ps, book, threats, fallen);
831
+ assessThreats();
832
+ triage();
833
+ // #274: a commander that walks says so in its order and the first warning; one that stays says why.
834
+ if (pc.commanderAt && !pc.commanderAt.retreat)
835
+ rationale.push(commanderStaysLine(pc.commanderAt, label));
836
+ else if (!pc.commanderAt && myCommanders.size)
837
+ rationale.push(`My commander stays on ${[...myCommanders].map(label).join(', ')}: with more than one commander of mine, none is walked to safety.`);
838
+ }
839
+ /** #165: with the guard off, one army breaks a bonus on an empty enemy territory next to mine. */
840
+ export function guardOffBreaks(pc, ps, book, hd, tgt) {
841
+ const { g, board, me, allies, reserve, label, bonusName, mineSet, unitsAt, uncounted, guard, chanceOf, noSplit } = pc;
842
+ const { rationale, avail, spared, captured, moves, survivorsAt, captureOrder, captureUndo } = ps;
843
+ const { coverOf, gainWith, deploy, roomAt } = book;
844
+ const { conceded, keepFor, twoStepKeep } = hd;
845
+ const { targets, repulsed } = tgt;
846
+ // ---- #165: guard off — an empty enemy territory that breaks a bonus ----
847
+ // With One Army Must Stand Guard off, an enemy territory next to mine standing at 0 armies (no
848
+ // special unit) falls to one army; when its owner holds a positive bonus it is in, that one army
849
+ // breaks the bonus. Every goal, after the holds and before any other capture: one army from the
850
+ // neighbour with the most to spare beyond what holds it once the target falls (a conceded border's
851
+ // armies are lost anyway), else one deployed on a neighbour that is not conceded. Never one that
852
+ // lowers income, nor under No-Split (an order sends the whole stack). It is sized for the board as
853
+ // it stands: if the owner deploys there first, the one army is lost.
854
+ if (!guard && !noSplit) {
855
+ const empties = guardOffExposure({ graph: g, board, me, friends: allies, deploys: [], moves: [] }).breaks;
856
+ for (const e of empties) {
857
+ const n = e.territoryId;
858
+ if (captured.has(n) || spared.has(n) || uncounted(n) || unitsAt(n) > 0 || gainWith([n]) < 0)
859
+ continue;
860
+ // B2 (T1): never a truce's covered territory.
861
+ if (pc.truce.noTarget(n))
862
+ continue;
863
+ // #240 review: one army is the attack a territory my attacks failed on, its owner reinforcing
864
+ // it, is never sent: it is a target only at its sure size (rule 2), or not attacked.
865
+ if (repulsed.has(n)) {
866
+ rationale.push(`One Army Must Stand Guard is off and ${label(n)} stands at 0, but my attacks on it failed before, its owner reinforcing it: no one-army attack there (#240).`);
867
+ continue;
868
+ }
869
+ const near = neighborsOf(g, n).filter((x) => mineSet.has(x));
870
+ const spareOf = (x) => Math.max(0, avail.get(x) - Math.max(keepFor(x, (y) => y === n), twoStepKeep(x, (y) => y === n), coverOf(x)));
871
+ let src = near.map((x) => ({ x, spare: spareOf(x) })).filter((o) => o.spare >= 1).sort((a, b) => b.spare - a.spare || a.x - b.x)[0]?.x;
872
+ let bought = 0;
873
+ if (src === undefined && ps.budget - reserve >= 1) {
874
+ src = near.filter((x) => !conceded.has(x) && avail.get(x) >= 0 && roomAt(x) >= 1).sort((a, b) => avail.get(b) - avail.get(a) || a - b)[0];
875
+ if (src !== undefined) {
876
+ deploy(src, 1);
877
+ bought = 1;
878
+ }
879
+ }
880
+ if (src === undefined)
881
+ continue;
882
+ const from = src;
883
+ avail.set(from, avail.get(from) - 1);
884
+ captured.add(n);
885
+ survivorsAt.set(n, 1);
886
+ captureOrder.push(n);
887
+ captureUndo.set(n, () => avail.set(from, avail.get(from) + 1));
888
+ if (!targets.has(n))
889
+ targets.set(n, { id: n, cost: 1, enemy: true, sources: near });
890
+ const reason = `One Army Must Stand Guard is off and ${label(n)} stands at 0: an attack breaks player ${e.playerId}'s bonus ${bonusName(e.bonusId)} (+${e.value}) unless it deploys there first`;
891
+ moves.push({ from, to: n, armies: 1, kind: 'attack', reason, winChance: chanceOf(1, 0) });
892
+ rationale.push(`Attack ${label(n)} from ${label(from)} with 1${bought ? ' (deploy 1 there)' : ''}: ${reason}.`);
893
+ }
894
+ }
895
+ }
896
+ /** Rule 0p.3c (#72, #120, #201): the 1v1 strike stack's border, chosen before the leftover deploy. */
897
+ export function chooseStrikeStack(pc, ps, book, threats, open, stays) {
898
+ const { g, income, profile, auto, goal, estimates, deployOf, incomeOfPlayer, paybackTurns, territories: state, label, mine, armiesOf, unitsAt, defenceAt, completedBy, inFocus, guard, rates, costAt, noSplit, } = pc;
899
+ const { rationale, captured, combined, staged } = ps;
900
+ const { guardAt, heldNow, gainWith, orderOf, roomAt } = book;
901
+ const { reinforcementAt, holdArmies, threatAt, facing } = threats;
902
+ // Concentrate (#72, adapting in a 1v1 facing the opponent): the spare deploys go to one strike stack
903
+ // on the border facing the strongest opponent (the highest income estimate, tracked when its
904
+ // track is trusted), the stack that keeps the most there, rather than to comfort margins.
905
+ // A 1v1 rule: in an FFA or a team game the comfort margins keep the leftover (several fronts).
906
+ // Chosen even when holds and captures leave no leftover (#102): the stack is still spent.
907
+ let stack;
908
+ /**
909
+ * No-Split (#124): `x`'s one order when it is a small expansion a strike may take over — a single
910
+ * attack on a neutral that completes no bonus this turn, stages none and is not focused.
911
+ */
912
+ const smallExpansion = (x) => {
913
+ const m = orderOf(x);
914
+ if (!m || m.kind !== 'attack' || !captured.has(m.to) || combined.has(m.to))
915
+ return undefined;
916
+ if (state.get(m.to)?.owner.kind !== 'neutral' || staged.has(m.to) || inFocus(m.to))
917
+ return undefined;
918
+ const now = heldNow();
919
+ const before = completedBy(new Set([...now].filter((y) => y !== m.to)));
920
+ return completedBy(now).some((id) => !before.includes(id)) ? undefined : m;
921
+ };
922
+ /** The stack on `x` a strike could send: what stays, plus a small expansion's armies (No-Split). */
923
+ const stackAt = (x) => stays(x) + (smallExpansion(x)?.armies ?? 0);
924
+ if (auto && profile.format === '1v1' && goal !== 'defend' && facing.size) {
925
+ const player = [...facing]
926
+ .map((p) => ({ p, e: estimates.get(p) }))
927
+ .sort((a, b) => (b.e?.estimate ?? 0) - (a.e?.estimate ?? 0) || a.p - b.p)[0];
928
+ /** The opponent's territories next to `x` a strike could aim at. */
929
+ const aims = (x) => neighborsOf(g, x).filter((n) => {
930
+ const st = state.get(n);
931
+ return !captured.has(n) && st?.owner.kind === 'player' && st.owner.playerId === player.p && st.armies !== null;
932
+ });
933
+ const fronts = mine
934
+ .filter((x) => open(x) &&
935
+ // No-Split: a territory whose one order is not a small expansion has nothing left to strike with.
936
+ (!orderOf(x) || smallExpansion(x) !== undefined) &&
937
+ aims(x).length > 0)
938
+ .sort((a, b) => stackAt(b) - stackAt(a) || a - b);
939
+ /**
940
+ * #120: the best strike `x` could make this turn with every leftover army on it — an adjacent
941
+ * target sized for its defenders plus what its owner may deploy there first (rule 3) — and the
942
+ * armies it would have to spare, after what holds `x` once that target falls. `null` when none
943
+ * fits.
944
+ */
945
+ const bestStrike = (x) => {
946
+ const room = Math.max(0, Math.min(ps.budget, roomAt(x)));
947
+ let best = null;
948
+ for (const n of aims(x)) {
949
+ const extra = reinforcementAt(n);
950
+ const cost = costAt(n, defenceAt(n) + extra);
951
+ if (cost === null || gainWith([n]) < 0)
952
+ continue;
953
+ const threat = Math.max(threatAt(x, (y) => captured.has(y) || y === n)?.threat ?? 0, deployOf(player.p));
954
+ const hold = Math.max(0, holdArmies(threat) - unitsAt(x));
955
+ const can = stackAt(x) + room - guardAt(x);
956
+ const spare = Math.min(can - cost, stackAt(x) + room - cost - hold);
957
+ if (spare < 0)
958
+ continue;
959
+ if (!best || spare > best.spare || (spare === best.spare && n < best.n))
960
+ best = { n, cost, extra, spare, can };
961
+ }
962
+ return best;
963
+ };
964
+ // Rule 0p.3c (#120): the stack goes where it can strike — the border with the most to spare
965
+ // after its best strike — and only with no border able to strike, to the one holding the most
966
+ // armies (live, 180 armies fed the front facing the opponent's biggest stack while a strike on
967
+ // a 1-army territory elsewhere was affordable every turn).
968
+ const able = noSplit ? [] : fronts.flatMap((x) => {
969
+ const b = bestStrike(x);
970
+ return b ? [{ x, ...b }] : [];
971
+ });
972
+ able.sort((a, b) => b.spare - a.spare || stackAt(b.x) - stackAt(a.x) || a.x - b.x);
973
+ const pick = able[0];
974
+ // #201: with no border able to strike this turn, the multi-turn forecast (`forecastBorder`):
975
+ // the border whose stack, with the leftover and then the income every turn, breaks the
976
+ // opponent's biggest stack beside it soonest (its owner deploying there every turn too); ties,
977
+ // and none breaking within the horizon, keep the border holding the most armies.
978
+ const forecastPick = (() => {
979
+ if (pick || noSplit || fronts.length < 2)
980
+ return undefined;
981
+ const rows = fronts.flatMap((x) => {
982
+ const at = aims(x).sort((a, b) => armiesOf(b) + unitsAt(b) - (armiesOf(a) + unitsAt(a)) || a - b)[0];
983
+ const theirs = armiesOf(at) + unitsAt(at);
984
+ const f = forecastBorder({
985
+ mine: stackAt(x) + Math.max(0, Math.min(ps.budget, roomAt(x))),
986
+ theirs,
987
+ myIncome: income,
988
+ theirIncome: incomeOfPlayer(player.p),
989
+ turns: paybackTurns,
990
+ settings: { offensiveKillRate: rates.offensiveKillRate, defensiveKillRate: rates.defensiveKillRate, oneArmyStandsGuard: guard === 1 },
991
+ });
992
+ return f.outcome === 'breaks' && f.turn !== null ? [{ x, at, theirs, turn: f.turn }] : [];
993
+ });
994
+ rows.sort((a, b) => a.turn - b.turn || stackAt(b.x) - stackAt(a.x) || a.x - b.x);
995
+ const best = rows[0];
996
+ if (!best)
997
+ return undefined;
998
+ const most = fronts[0];
999
+ const other = rows.find((r) => r.x === most);
1000
+ if (best.x === most || (other && other.turn === best.turn))
1001
+ return undefined;
1002
+ 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`}.`);
1003
+ return best.x;
1004
+ })();
1005
+ const id = pick?.x ?? forecastPick ?? fronts[0];
1006
+ if (pick) {
1007
+ const most = fronts[0];
1008
+ 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
1009
+ ? `, 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'}`
1010
+ : ''}.`);
1011
+ }
1012
+ if (id !== undefined)
1013
+ stack = {
1014
+ id,
1015
+ player: player.p,
1016
+ income: player.e?.estimate ?? MIN_ENEMY_DEPLOY,
1017
+ source: player.e?.source === 'tracked' ? 'tracked' : player.e?.source === 'observed' ? 'observed' : 'estimated',
1018
+ };
1019
+ }
1020
+ return { stack, smallExpansion };
1021
+ }
1022
+ /** #102: spend the strike stack on the enemy territories next to it, once the leftover deploy is in. */
1023
+ export function spendStrikeStack(pc, ps, input, book, threats, tgt, cap, strikeStack, poolDeployed, holdLocked, smallExpansion) {
1024
+ const { g, me, foe, deployOf, territories: state, label, bonusName, mineSet, unitsAt, uncounted, defenceAt, bonusTs, completedBy, rates, chanceOf, costAt, noSplit, myCommanders, } = pc;
1025
+ const { warnings, rationale, avail, locked, captured, combined, moves, incoming, survivorsAt, captureOrder, captureUndo, } = ps;
1026
+ const { guardAt, coverOf, heldNow, gainWith, orderOf, valueOf } = book;
1027
+ const { reinforcementAt, holdArmies, threatAt } = threats;
1028
+ const { breakable, offence, skipOffence } = tgt;
1029
+ const { mustHold, strikes, worstCase } = cap;
1030
+ // ---- spend the strike stack (#102) ----
1031
+ // Once rule 0p.3c builds a strike stack, it attacks every adjacent enemy territory it can take
1032
+ // at the plan's win chance (the ordinary capture sizing; rule 4c re-checked as its captures
1033
+ // accumulate), breaking or retaking a bonus first (re-ranked after each capture: a bonus breaks
1034
+ // once), then by bonus value, then cheapest, then id — while what stays on it holds against the threat
1035
+ // left after those attacks (rule 1's arithmetic: the captured territories no longer threaten
1036
+ // it). It grows (deploy, no attack) only when nothing in reach is worth taking.
1037
+ if (strikeStack) {
1038
+ const S = strikeStack.id;
1039
+ if (strikeStack.deployed === 0)
1040
+ 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.`);
1041
+ const prev = new Map((input.previousBoard?.territories ?? []).map((t) => [t.territoryId, t]));
1042
+ /** Bonuses I held in full on the previous board and no longer do: lost, and retakable. */
1043
+ const lost = new Set(g.map.bonuses
1044
+ .filter((b) => {
1045
+ const ts = bonusTs.get(b.id) ?? [];
1046
+ if (b.value <= 0 || !ts.length || ts.every((t) => mineSet.has(t)))
1047
+ return false;
1048
+ return ts.every((t) => {
1049
+ const was = visibleState(prev.get(t));
1050
+ return was?.owner.kind === 'player' && was.owner.playerId === me;
1051
+ });
1052
+ })
1053
+ .map((b) => b.id));
1054
+ const candidates = [];
1055
+ for (const n of neighborsOf(g, S)) {
1056
+ const st = state.get(n);
1057
+ if (captured.has(n) || st?.owner.kind !== 'player' || !foe(st.owner.playerId) || st.armies === null || uncounted(n))
1058
+ continue;
1059
+ // B2 (T1): never a truce's covered territory.
1060
+ if (pc.truce.noTarget(n))
1061
+ continue;
1062
+ // #240: a territory my attacks failed on repeatedly is sized for its owner's deploy (#240
1063
+ // review: and ranked on its plain cost, like any other).
1064
+ const cost = costAt(n);
1065
+ const size = tgt.costFor(n);
1066
+ // Never a capture that lowers income (rule 4c): it completes a negative bonus. Re-checked
1067
+ // below against the strike's own captures, which can complete one only together.
1068
+ if (cost === null || size === null || gainWith([n]) < 0)
1069
+ continue;
1070
+ const owner = st.owner.playerId;
1071
+ candidates.push({
1072
+ id: n,
1073
+ cost,
1074
+ size,
1075
+ chance: chanceOf(size, defenceAt(n)),
1076
+ breaks: breakable.filter((b) => b.player === owner && bonusTs.get(b.bonusId).includes(n)),
1077
+ retakes: [...lost].filter((id) => bonusTs.get(id).includes(n)).sort(byNum),
1078
+ });
1079
+ }
1080
+ /** Captures planned from the stack so far, in order. */
1081
+ const plannedHere = new Set();
1082
+ /** The opponent bonuses `c` breaks: only the first member of each to fall this turn breaks it. */
1083
+ const breaksOf = (c) => c.breaks.filter((b) => !bonusTs.get(b.bonusId).some((t) => t !== c.id && captured.has(t)));
1084
+ const strikeValue = (c) => Math.max(0, ...breaksOf(c).map((b) => b.value), ...c.retakes.map((id) => g.bonusById.get(id).value));
1085
+ /** What taking `c` does, against the captures planned so far (a retake completes only with every member held). */
1086
+ const effectOf = (c) => {
1087
+ const held = heldNow();
1088
+ held.add(c.id);
1089
+ const effects = [
1090
+ ...breaksOf(c).map((b) => `breaks ${b.probable ? 'probable ' : ''}enemy bonus ${bonusName(b.bonusId)} (+${b.value} from player ${b.player})`),
1091
+ ...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`),
1092
+ ];
1093
+ return effects.length ? effects.join('; ') : null;
1094
+ };
1095
+ const rank = () => [...candidates].sort((a, b) => Number(breaksOf(b).length + b.retakes.length > 0) - Number(breaksOf(a).length + a.retakes.length > 0) ||
1096
+ strikeValue(b) - strikeValue(a) ||
1097
+ a.cost - b.cost ||
1098
+ a.id - b.id);
1099
+ /** What may never leave the stack this turn: a Local Deployment pool's deploys (#103). */
1100
+ const pinned = poolDeployed.get(S) ?? 0;
1101
+ /**
1102
+ * The threat on the stack once `gone` (and this turn's other captures) fall, and the armies that
1103
+ * hold it. Never below the opponent's deploy alone: orders interleave, so it may land its deploy
1104
+ * on a target before my attack resolves, and that territory then still borders the stack.
1105
+ */
1106
+ const holdAfter = (gone) => {
1107
+ const th = threatAt(S, (x) => captured.has(x) || gone.has(x));
1108
+ const threat = Math.max(th?.threat ?? 0, deployOf(strikeStack.player));
1109
+ return { threat, need: Math.max(0, holdArmies(threat) - unitsAt(S)) };
1110
+ };
1111
+ const taken = [];
1112
+ const refused = new Map();
1113
+ let sent = 0;
1114
+ /**
1115
+ * No-Split (#124): the stack's one order goes to the strike on `t`, not to the small expansion
1116
+ * `m` it already made: that capture is taken back, and its armies rejoin the stack.
1117
+ */
1118
+ const dropExpansion = (m, t) => {
1119
+ const undo = captureUndo.get(m.to);
1120
+ if (undo)
1121
+ undo();
1122
+ else
1123
+ avail.set(S, avail.get(S) + m.armies);
1124
+ captured.delete(m.to);
1125
+ survivorsAt.delete(m.to);
1126
+ moves.splice(moves.indexOf(m), 1);
1127
+ const head = `Attack ${label(m.to)} from ${label(S)} with `;
1128
+ for (let i = rationale.length - 1; i >= 0; i--)
1129
+ if (rationale[i].startsWith(head))
1130
+ rationale.splice(i, 1);
1131
+ 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.`);
1132
+ skipOffence(m.to, `No-Split: ${label(S)}'s one order goes to the strike on ${label(t)}`);
1133
+ };
1134
+ for (let again = true; again;) {
1135
+ again = false;
1136
+ for (const c of rank()) {
1137
+ if (plannedHere.has(c.id))
1138
+ continue;
1139
+ if (gainWith([c.id]) < 0) {
1140
+ const held = heldNow();
1141
+ held.add(c.id);
1142
+ const negs = completedBy(held)
1143
+ .filter((id) => g.bonusById.get(id).value < 0 && bonusTs.get(id).includes(c.id))
1144
+ .map((id) => `negative bonus ${bonusName(id)} (${g.bonusById.get(id).value})`);
1145
+ refused.set(c.id, `with this turn's other captures it lowers next income: it completes ${negs.join(', ')} (rule 4c)`);
1146
+ continue;
1147
+ }
1148
+ const expansion = noSplit && !taken.length ? smallExpansion(S) : undefined;
1149
+ if (noSplit && ((orderOf(S) && !expansion) || taken.length)) {
1150
+ refused.set(c.id, `No-Split: ${label(S)} issues one order this turn`);
1151
+ continue;
1152
+ }
1153
+ if (noSplit) {
1154
+ // The whole stack goes (#124): nothing stays to hold S but the guard, so it strikes only
1155
+ // when it need not hold (it protects nothing, or the strike leaves no visible threat to it).
1156
+ const whole = avail.get(S) + (expansion?.armies ?? 0);
1157
+ if (pinned > 0) {
1158
+ refused.set(c.id, `No-Split: the ${pinned} Local Deployment armies defending ${label(S)} would leave with the whole stack`);
1159
+ continue;
1160
+ }
1161
+ if (c.size > whole) {
1162
+ refused.set(c.id, `it needs ${c.size}, more than the ${Math.max(0, whole)} the stack can send`);
1163
+ continue;
1164
+ }
1165
+ const h = mustHold(S, c.id, whole);
1166
+ if (h) {
1167
+ 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'})`);
1168
+ continue;
1169
+ }
1170
+ if (expansion)
1171
+ dropExpansion(expansion, c.id);
1172
+ const armies = avail.get(S);
1173
+ plannedHere.add(c.id);
1174
+ refused.delete(c.id);
1175
+ taken.push({ c, effect: effectOf(c), value: strikeValue(c), armies, chance: chanceOf(armies, defenceAt(c.id)) });
1176
+ avail.set(S, 0);
1177
+ sent += armies;
1178
+ captured.add(c.id);
1179
+ survivorsAt.set(c.id, armies - straightKills(defenceAt(c.id), rates.defensiveKillRate));
1180
+ captureOrder.push(c.id);
1181
+ again = true;
1182
+ break;
1183
+ }
1184
+ const gone = new Set([...plannedHere, c.id]);
1185
+ const { threat, need } = holdAfter(gone);
1186
+ // #179: what covers a finished-off player's exit stays too.
1187
+ const movable = avail.get(S) - Math.max(pinned, coverOf(S));
1188
+ const stay = avail.get(S) + guardAt(S) + (incoming.get(S) ?? 0) - c.size;
1189
+ if (c.size > movable) {
1190
+ refused.set(c.id, `it needs ${c.size}, more than the ${Math.max(0, movable)} the stack can send`);
1191
+ continue;
1192
+ }
1193
+ if (stay < need) {
1194
+ refused.set(c.id, `it would leave the stack ${stay}, below the ${need} that hold it against the ~${threat} threat after the attacks`);
1195
+ continue;
1196
+ }
1197
+ const effect = effectOf(c);
1198
+ const value = strikeValue(c);
1199
+ plannedHere.add(c.id);
1200
+ refused.delete(c.id);
1201
+ taken.push({ c, effect, value, armies: c.size, chance: c.chance });
1202
+ avail.set(S, avail.get(S) - c.size);
1203
+ sent += c.size;
1204
+ captured.add(c.id);
1205
+ survivorsAt.set(c.id, c.size - straightKills(defenceAt(c.id), rates.defensiveKillRate));
1206
+ captureOrder.push(c.id);
1207
+ again = true;
1208
+ break;
1209
+ }
1210
+ }
1211
+ // #120: each attack is then sized for its defenders plus what their owner may deploy there
1212
+ // first, in the order taken, while the stack still covers it and keeps its hold after every
1213
+ // attack. One the stack cannot cover keeps its size (its warning gives the reinforced odds).
1214
+ const reinforced = new Map();
1215
+ // #240 review: a repulsed territory was costed at that size when the stack took it (and No-Split
1216
+ // sends at least as much): it is sized for its owner's deploy already, and says so.
1217
+ for (const x of taken) {
1218
+ const rep = tgt.repulsed.get(x.c.id);
1219
+ // #272 review: one sized below its owner's deploy estimate is no worst case (#120 below may still size it up).
1220
+ if (!rep?.sure || x.armies < rep.cost)
1221
+ continue;
1222
+ worstCase.set(x.c.id, rep.defenders + rep.extra);
1223
+ reinforced.set(x.c.id, rep.extra);
1224
+ }
1225
+ if (!noSplit) {
1226
+ const { need } = holdAfter(new Set());
1227
+ const room = () => Math.min(avail.get(S) - Math.max(pinned, coverOf(S)), avail.get(S) + guardAt(S) + (incoming.get(S) ?? 0) - need);
1228
+ // The stack's earlier attacks on a player (a break or counter-attack from it) first.
1229
+ for (const m of moves) {
1230
+ if (m.from !== S || m.kind !== 'attack' || combined.has(m.to) || worstCase.has(m.to) || strikes.has(m.to))
1231
+ continue;
1232
+ const extra = reinforcementAt(m.to);
1233
+ const full = extra > 0 ? costAt(m.to, defenceAt(m.to) + extra) : null;
1234
+ if (full === null || full <= m.armies || full - m.armies > room())
1235
+ continue;
1236
+ const add = full - m.armies;
1237
+ const before = m.armies;
1238
+ avail.set(S, avail.get(S) - add);
1239
+ m.armies = full;
1240
+ m.winChance = chanceOf(full, defenceAt(m.to));
1241
+ if (survivorsAt.has(m.to))
1242
+ survivorsAt.set(m.to, survivorsAt.get(m.to) + add);
1243
+ worstCase.set(m.to, defenceAt(m.to) + extra);
1244
+ const w = warnings.indexOf(`Attack on enemy ${label(m.to)} assumes its owner does not reinforce it first.`);
1245
+ if (w >= 0)
1246
+ warnings.splice(w, 1);
1247
+ 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.`);
1248
+ }
1249
+ for (const x of taken) {
1250
+ const extra = reinforcementAt(x.c.id);
1251
+ const full = extra > 0 ? costAt(x.c.id, defenceAt(x.c.id) + extra) : null;
1252
+ if (full === null || full <= x.armies)
1253
+ continue;
1254
+ const add = full - x.armies;
1255
+ if (add > room())
1256
+ continue;
1257
+ avail.set(S, avail.get(S) - add);
1258
+ sent += add;
1259
+ x.armies = full;
1260
+ x.chance = chanceOf(full, defenceAt(x.c.id));
1261
+ survivorsAt.set(x.c.id, survivorsAt.get(x.c.id) + add);
1262
+ worstCase.set(x.c.id, defenceAt(x.c.id) + extra);
1263
+ reinforced.set(x.c.id, extra);
1264
+ }
1265
+ }
1266
+ // What stays on the stack is its hold: an efficient-size top-up (S2) never draws on it, and
1267
+ // the transfer step never moves it (its captures can leave it interior; it may have got no deploys).
1268
+ if (taken.length) {
1269
+ holdLocked.add(S);
1270
+ locked.add(S);
1271
+ }
1272
+ const { threat: finalThreat, need: finalNeed } = holdAfter(new Set());
1273
+ const stays = avail.get(S) + guardAt(S) + (incoming.get(S) ?? 0);
1274
+ for (const { c, effect, value, armies, chance } of taken) {
1275
+ const reason = `the strike stack ${effect ?? 'takes an adjacent enemy territory'}`;
1276
+ moves.push({ from: S, to: c.id, armies, kind: 'attack', reason, winChance: chance });
1277
+ const extra = reinforced.get(c.id);
1278
+ if (extra === undefined)
1279
+ warnings.push(`Attack on enemy ${label(c.id)} assumes its owner does not reinforce it first.`);
1280
+ const keeps = noSplit
1281
+ ? `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'}`
1282
+ : `the stack keeps ${stays}, enough to hold against the ~${finalThreat} threat after the attacks (needs ${finalNeed})`;
1283
+ const sized = extra === undefined
1284
+ ? ''
1285
+ : ` — 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)`;
1286
+ 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}.`);
1287
+ offence.set(`strike:${c.id}`, {
1288
+ target: c.id,
1289
+ kind: 'strike-attack',
1290
+ cost: armies,
1291
+ value,
1292
+ taken: true,
1293
+ why: `from the strike stack ${label(S)} with ${armies} (win chance ${pct(chance)}): ${effect ?? 'takes an adjacent enemy territory'}`,
1294
+ });
1295
+ }
1296
+ for (const c of rank()) {
1297
+ if (plannedHere.has(c.id))
1298
+ continue;
1299
+ const effect = effectOf(c);
1300
+ offence.set(`strike:${c.id}`, {
1301
+ target: c.id,
1302
+ kind: 'strike-attack',
1303
+ cost: c.size,
1304
+ value: strikeValue(c),
1305
+ taken: false,
1306
+ why: `not made from the strike stack ${label(S)} — ${refused.get(c.id) ?? 'not worth it'}${effect ? `: ${effect}` : ''}`,
1307
+ });
1308
+ }
1309
+ const builds = `the spare deploys build one strike stack facing player ${strikeStack.player}, the strongest opponent (~${strikeStack.income} income, ${strikeStack.source})`;
1310
+ if (!taken.length) {
1311
+ const held = candidates.length
1312
+ ? candidates.map((c) => `${label(c.id)}: ${refused.get(c.id) ?? 'not worth it'}`).join('; ')
1313
+ : 'no visible enemy territory next to it can be taken';
1314
+ rationale.push(`Grow the strike stack ${label(S)}: nothing next to it is worth taking this turn (${held}).`);
1315
+ }
1316
+ if (strikeStack.deployed > 0 || taken.length)
1317
+ offence.set(`strike:${S}`, {
1318
+ target: S,
1319
+ kind: 'strike',
1320
+ cost: strikeStack.deployed,
1321
+ value: strikeStack.income,
1322
+ taken: taken.length > 0,
1323
+ why: taken.length
1324
+ ? `${builds}; it attacks ${taken.map(({ c }) => label(c.id)).join(', ')} this turn (${sent} armies sent)`
1325
+ : `${builds}; it grows: nothing next to it is worth taking this turn`,
1326
+ });
1327
+ }
1328
+ }
1329
+ /** #167: adapting in an FFA with a clear army lead, idle stacks take the weak enemy territories beside them. */
1330
+ export function leadStrikes(pc, ps, book, threats, hd, tgt, cap, holdLocked, strikeStack) {
1331
+ const { g, foe, profile, auto, balanced, territories: state, label, bonusName, mine, mineSet, unitsAt, uncounted, defenceAt, bonusTs, rates, chanceOf, costAt, noSplit, armyLead, leadLever, leadText, myCommanders, } = pc;
1332
+ const { rationale, avail, spared, captured, moves, survivorsAt, captureOrder, captureUndo } = ps;
1333
+ const { gainWith } = book;
1334
+ const { reinforcementAt } = threats;
1335
+ const { conceded, keepFor, twoStepKeep } = hd;
1336
+ const { breakable, targets } = tgt;
1337
+ const { worstCase } = cap;
1338
+ // ---- #167: lead strikes ----
1339
+ // Adapting in a free-for-all with two or more opponents, under `balanced`, when my visible armies
1340
+ // are more than SECOND_FRONT_LEAD × the largest opponent's in view: rule 0p.2 is off, and every
1341
+ // enemy territory next to mine (no special unit on it, never one whose capture lowers income) is
1342
+ // attacked from the territory of mine beside it with the most to spare — armies beyond what holds
1343
+ // it once the target falls (rule 1's arithmetic, #172's two-step keep too; never a hold, a conceded
1344
+ // border, my commander's territory or the strike stack; no deploys: the leftover has spent the
1345
+ // income, and a positive bonus's enemy member was already a step in the bonus passes, #203) — when
1346
+ // that covers an attack sized for its defenders plus what its owner may deploy there first (rule
1347
+ // 3's #120 sizing, so it lands for sure). Breaks first, then a step into a positive bonus, then
1348
+ // cheapest, then id. Not under No-Split (an order carries the whole stack).
1349
+ /** A lead strike's source: armies on `x` beyond what holds it once `n` falls (also named by the "Not attacking" line). */
1350
+ const leadSpareFor = (x, n) => {
1351
+ if (!mineSet.has(x) || holdLocked.has(x) || conceded.has(x) || myCommanders.has(x) || x === strikeStack?.id)
1352
+ return 0;
1353
+ const gone = (m) => m === n;
1354
+ return Math.max(0, avail.get(x) - Math.max(keepFor(x, gone), twoStepKeep(x, gone)));
1355
+ };
1356
+ if (auto && balanced && profile.format === 'ffa' && profile.opponents >= 2) {
1357
+ if (leadLever)
1358
+ rationale.push(`FFA army lead: my ${armyLead.my} armies in view are ${Number.isFinite(armyLead.ratio) ? `${leadText()} player ${armyLead.rival}'s ${armyLead.theirs}, the most of any opponent` : `against no opposing army in view`} (more than ${SECOND_FRONT_LEAD}×): no second-front rule — idle stacks beside weak enemy territories attack them, a lever, not a risk.`);
1359
+ if (leadLever && !noSplit) {
1360
+ const candidates = [...new Set(mine.flatMap((x) => neighborsOf(g, x)))]
1361
+ .filter((n) => {
1362
+ const st = state.get(n);
1363
+ return (!mineSet.has(n) &&
1364
+ !captured.has(n) &&
1365
+ // #179: a buffer left standing is taken by no pass this turn.
1366
+ !spared.has(n) &&
1367
+ st?.owner.kind === 'player' &&
1368
+ foe(st.owner.playerId) &&
1369
+ // B2 (T1): never a truce's covered territory.
1370
+ !pc.truce.noTarget(n) &&
1371
+ st.armies !== null &&
1372
+ !uncounted(n) &&
1373
+ unitsAt(n) === 0);
1374
+ })
1375
+ .map((n) => {
1376
+ const p = state.get(n).owner.playerId;
1377
+ const d = defenceAt(n);
1378
+ const extra = reinforcementAt(n);
1379
+ const breaks = breakable.find((b) => b.player === p && bonusTs.get(b.bonusId).includes(n));
1380
+ const step = g.map.bonuses.find((b) => b.value > 0 && bonusTs.get(b.id).includes(n) && !breaks);
1381
+ return { n, p, d, extra, cost: costAt(n, d + extra), breaks, step };
1382
+ })
1383
+ .filter((c) => c.cost !== null)
1384
+ .sort((a, b) => Number(!a.breaks) - Number(!b.breaks) || Number(!a.step) - Number(!b.step) || a.cost - b.cost || a.n - b.n);
1385
+ for (const c of candidates) {
1386
+ if (captured.has(c.n) || gainWith([c.n]) < 0)
1387
+ continue;
1388
+ const cost = c.cost;
1389
+ const src = neighborsOf(g, c.n)
1390
+ .filter((x) => mineSet.has(x))
1391
+ .map((x) => ({ x, spare: leadSpareFor(x, c.n) }))
1392
+ .filter((o) => o.spare >= cost)
1393
+ .sort((a, b) => b.spare - a.spare || a.x - b.x)[0];
1394
+ if (!src)
1395
+ continue;
1396
+ avail.set(src.x, avail.get(src.x) - cost);
1397
+ captured.add(c.n);
1398
+ worstCase.set(c.n, c.d + c.extra);
1399
+ survivorsAt.set(c.n, cost - straightKills(c.d + c.extra, rates.defensiveKillRate));
1400
+ captureOrder.push(c.n);
1401
+ captureUndo.set(c.n, () => avail.set(src.x, avail.get(src.x) + cost));
1402
+ if (!targets.has(c.n))
1403
+ targets.set(c.n, { id: c.n, cost, enemy: true, sources: neighborsOf(g, c.n).filter((x) => mineSet.has(x)) });
1404
+ const effect = c.breaks
1405
+ ? `breaks ${c.breaks.probable ? 'probable ' : ''}enemy bonus ${bonusName(c.breaks.bonusId)} (+${c.breaks.value} from player ${c.p})`
1406
+ : c.step
1407
+ ? `a step into bonus ${bonusName(c.step.id)} (+${c.step.value})`
1408
+ : `takes a territory of player ${c.p}`;
1409
+ const reason = `army lead: ${effect}, sure even if player ${c.p} deploys its ~${c.extra} there first (${c.d} + ${c.extra} defenders), with armies ${label(src.x)} does not need to hold`;
1410
+ moves.push({ from: src.x, to: c.n, armies: cost, kind: 'attack', reason, winChance: chanceOf(cost, c.d) });
1411
+ rationale.push(`Attack ${label(c.n)} from ${label(src.x)} with ${cost}: ${reason}.`);
1412
+ }
1413
+ }
1414
+ }
1415
+ return { leadSpareFor };
1416
+ }