@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,1195 @@
1
+ // The capture passes of a planning pass (#133): R3's completion check, No-Split's must-hold
2
+ // (#124), the capture helper and combined (multi-source) captures (R4, rule 3a), and the bonus
3
+ // passes — pass 1 completes a bonus this turn, pass 2 advances one a capture at a time (rule
4
+ // 4c(c), rule 4d's frontier budget). planPass runs the passes, the strikes and pass 3 with them.
5
+ import { bonusTerritories } from '../bonuses.js';
6
+ import { armiesToTake, straightKills } from '../combat.js';
7
+ import { captureCost } from './shared.js';
8
+ import { byNum } from './util.js';
9
+ import { denialLine, emptyEnemyLine } from './vacated.js';
10
+ /** The capture rules, the capture helper and the bonus passes, in the order planPass defined them. */
11
+ export function capturesPhase(pc, ps, pass, book, threats, hd, tgt) {
12
+ const c0 = captureRules(pc, ps, book, threats, hd);
13
+ const c1 = { ...c0, ...captureHelper(pc, ps, pass, book, threats, hd, tgt, c0) };
14
+ const c2 = { ...c1, ...bonusPasses(pc, ps, book, hd, tgt, c1) };
15
+ return c2;
16
+ }
17
+ /** R3: a completion must leave a frontier I can hold; No-Split (#124): a stack that must hold. */
18
+ export function captureRules(pc, ps, book, threats, hd) {
19
+ const { g, s, foe, goal, guarded, reserve, deployOf, territories: state, label, bonusName, mine, mineSet, armiesOf, unitsAt, defenceAt, bonusTs, completedBy, guard, toTake, noSplit, myCommanders, } = pc;
20
+ const { warnings, rationale, deployed, avail, captured, survivorsAt, incoming } = ps;
21
+ const { guardAt, valueOf } = book;
22
+ const { holdArmies, nextTurnAt, exposure, borderAt } = threats;
23
+ const { conceded, keptIncome } = hd;
24
+ // ---- R3: a completion must leave a frontier I can hold ----
25
+ /**
26
+ * "Not completed" warning and rationale, by bonus: kept outside `warnings`/`rationale`
27
+ * so a rolled-back pass cannot drop them. A refusal is not final — the next income
28
+ * grows as other bonuses complete — so they are emitted at the end only for bonuses
29
+ * the plan did not complete after all.
30
+ */
31
+ const notCompleted = new Map();
32
+ /**
33
+ * Called with `t` just captured (`survivors` armies move in): for every bonus this
34
+ * capture completes, the deploys its exposed members still need next turn to
35
+ * hold must fit my projected next income (plus this turn's leftover, for members
36
+ * I held at the start: a fresh capture cannot be deployed to). Otherwise the
37
+ * bonus is lost immediately: refused under `balanced`/`defend`, warned otherwise.
38
+ * The total need is checked, not each member alone: holding the bonus needs every
39
+ * exposed member held. The leftover is as of this check; a later capture this turn
40
+ * may still spend it (defence funds held borders first, so this is rarely material).
41
+ */
42
+ const defensible = (t, survivors) => {
43
+ const after = new Set([...mine, ...captured]);
44
+ const completes = g.map.bonuses
45
+ .filter((b) => {
46
+ const ts = bonusTerritories(g, b.id);
47
+ return b.value > 0 && ts.includes(t) && ts.every((x) => after.has(x));
48
+ })
49
+ .sort((a, b) => a.id - b.id);
50
+ if (!completes.length)
51
+ return true;
52
+ const nextIncome = keptIncome(after);
53
+ const spare = Math.max(0, ps.budget - reserve);
54
+ const stays = (m) => {
55
+ if (mineSet.has(m))
56
+ return avail.get(m) + guardAt(m) + (incoming.get(m) ?? 0);
57
+ if (m === t)
58
+ return survivors;
59
+ // An earlier capture this turn: the survivors of its finishing attack.
60
+ return survivorsAt.get(m) ?? 0;
61
+ };
62
+ /**
63
+ * #128: what holding `m` next turn needs that it would not have needed anyway. A member I held
64
+ * at the start that is exposed either way (its armies before any attack leaves it, against the
65
+ * threat without this turn's captures) only adds its need beyond that: refusing the completion
66
+ * would not save it.
67
+ */
68
+ const either = (m) => {
69
+ if (!mineSet.has(m))
70
+ return 0;
71
+ const th = nextTurnAt(m, (n) => captured.has(n) && n !== t && !mineSet.has(n));
72
+ if (!th)
73
+ return 0;
74
+ return Math.max(0, holdArmies(th.threat) - armiesOf(m) - (deployed.get(m) ?? 0) - unitsAt(m));
75
+ };
76
+ const exposedOf = (id) => exposure(bonusTerritories(g, id), (n) => captured.has(n), stays).map((e) => ({ ...e, added: Math.max(0, e.need - either(e.id)) }));
77
+ // #128: every bonus this turn's earlier captures completed shares the same next income — two
78
+ // completions that each fit it may not fit it together.
79
+ const ids = new Set(completes.map((b) => b.id));
80
+ const earlier = new Map();
81
+ for (const e of completedBy(after)
82
+ .filter((id) => !ids.has(id) && g.bonusById.get(id).value > 0 && !bonusTs.get(id).every((x) => mineSet.has(x)))
83
+ .flatMap(exposedOf))
84
+ earlier.set(e.id, Math.max(earlier.get(e.id) ?? 0, e.added));
85
+ let ok = true;
86
+ for (const b of completes) {
87
+ const exposed = exposedOf(b.id);
88
+ const total = exposed.reduce((sum, e) => sum + e.added, 0);
89
+ const before = [...earlier].reduce((n, [id, need]) => n + (exposed.some((e) => e.id === id) ? 0 : need), 0);
90
+ const held = exposed.filter((e) => mineSet.has(e.id)).reduce((sum, e) => sum + e.added, 0);
91
+ const anyway = exposed.filter((e) => e.added < e.need);
92
+ // A completion that adds no exposure (total 0) is never refused: refusing it saves nothing,
93
+ // whatever the earlier completions need (it only adds income).
94
+ if (total === 0 || total + before <= nextIncome + Math.min(spare, held)) {
95
+ if (anyway.length && guarded)
96
+ rationale.push(`Complete bonus ${bonusName(b.id)} though ${anyway.map((e) => label(e.id)).join(', ')} may fall next turn: ${anyway.length === 1 ? 'it is' : 'they are'} exposed whether or not it is completed, so refusing would save nothing.`);
97
+ continue;
98
+ }
99
+ const worst = [...exposed].sort((a, b) => b.added - a.added || b.need - a.need || a.id - b.id)[0];
100
+ const head = `completing ${bonusName(b.id)} leaves ${label(worst.id)} indefensible (player ${worst.player} can take it for ${worst.take}; next income ${nextIncome})`;
101
+ if (guarded) {
102
+ if (!notCompleted.has(b.id)) {
103
+ notCompleted.set(b.id, {
104
+ warning: `${head}: not completed`,
105
+ why: `Do not complete bonus ${bonusName(b.id)}: holding its frontier next turn needs ${total} more armies (${exposed.map((e) => `${label(e.id)} ${e.added}`).join(', ')})${before ? `, on top of the ${before} this turn's other completions need` : ''}, more than the next income of ${nextIncome}${held ? ` plus the ${Math.min(spare, held)} left this turn` : ''}, so it would fall next turn; the armies stay for defence.`,
106
+ });
107
+ }
108
+ ok = false;
109
+ }
110
+ else {
111
+ const w = `${head}: completed anyway (goal ${goal} ignores defence)`;
112
+ if (!warnings.includes(w))
113
+ warnings.push(w);
114
+ }
115
+ }
116
+ return ok;
117
+ };
118
+ // ---- No-Split: the whole stack moves (#124) ----
119
+ /**
120
+ * No-Split (#124): an order sends `x`'s whole stack, so only the guard (and armies withdrawn into
121
+ * it) stay. `x` must hold — it issues no order — when it protects something (a bonus, income, my
122
+ * commander), is not conceded, and what stays would fall to the visible threat left once this
123
+ * turn's captures land. The target `t` stops threatening only when the `sent` armies take it for
124
+ * sure even if its owner deploys there first. `null` when the order may go (always with No-Split off).
125
+ */
126
+ const mustHold = (x, t, sent) => {
127
+ if (!noSplit || conceded.has(x))
128
+ return null;
129
+ const value = valueOf(x);
130
+ if (value <= 0 && !myCommanders.has(x))
131
+ return null;
132
+ const st = state.get(t);
133
+ const owner = st?.owner.kind === 'player' && foe(st.owner.playerId) ? st.owner.playerId : undefined;
134
+ const sure = owner === undefined || (captureCost(defenceAt(t) + deployOf(owner), s) ?? Infinity) <= sent;
135
+ const b = borderAt(x, (n) => captured.has(n) || ps.assumeGone(n) || (n === t && sure));
136
+ if (!b)
137
+ return null;
138
+ const stays = guard + (incoming.get(x) ?? 0);
139
+ if ((toTake(stays + unitsAt(x)) ?? Infinity) > b.threat)
140
+ return null;
141
+ return { from: x, value, stays, threat: b.threat };
142
+ };
143
+ /** A No-Split warning: `h.from` must hold, so `what` is not planned. Never repeated. */
144
+ const warnHold = (h, what) => {
145
+ const w = `No-Split: ${label(h.from)} must hold (${h.value > 0 ? `protects +${h.value}` : 'my commander stands there'}): an order would send its whole stack, leaving ${h.stays} against the ~${h.threat} threat, so ${what}.`;
146
+ if (!warnings.includes(w))
147
+ warnings.push(w);
148
+ };
149
+ return { notCompleted, defensible, mustHold, warnHold };
150
+ }
151
+ /** The capture helper (tryCapture) and combined (multi-source) captures (R4, rule 3a). */
152
+ export function captureHelper(pc, ps, pass, book, threats, hd, tgt, prev) {
153
+ const { g, s, reserve, label, bonusName, mine, mineSet, armiesOf, unitsAt, defenceAt, rates, chanceOf, luck, noSplit, myCommanders, armiesBehind, costAt, toTake, } = pc;
154
+ const { warnings, rationale, deployed, avail, locked, spared, captured, combined, moves, survivorsAt, captureOrder, captureUndo, incoming, } = ps;
155
+ const { coverOf, orderOf, warnSplit, deploy, spareAt, local } = book;
156
+ const { borderAt, safeAtStart, holdArmies } = threats;
157
+ const { conceded, heldBorders, keepFor, stayAt, twoStepBound, twoStepCite, twoStepHold, twoStepKeep } = hd;
158
+ const { targets, leadSteps, leadTry, leadNote, skipOffence, badTrades, repulsed } = tgt;
159
+ const { defensible, mustHold, warnHold } = prev;
160
+ // ---- capture helper ----
161
+ /** How far a combined capture of a player's territory trades below even (see `ps.evenTradesOnly`). */
162
+ let belowEven;
163
+ /** #214 review: the last {@link tryCombined} built a combined capture and R3 refused it. */
164
+ let combinedR3 = false;
165
+ /** #214 review: bare steps are tried in this run (planTurn's check run turns them off). */
166
+ const bareOn = !pass.shared.noBare;
167
+ /**
168
+ * #214 review: lead steps captured at their bare cost (some may be undone later), for planTurn's
169
+ * check that they cost no hold, and the entry each one's failed sure try left in `leadTry`.
170
+ */
171
+ const bareTaken = new Set();
172
+ /**
173
+ * Armies on my `x` free to attack `t`: my commander's territory keeps what holds it (rule 1k),
174
+ * and so does a border that held at the start of the turn and is not conceded (#121: one surplus
175
+ * per territory — a capture never spends the garrison that holds a safe border).
176
+ */
177
+ const movableFor = (x, t) => avail.get(x) - keepOf(x, t);
178
+ /**
179
+ * What `x` keeps back from an attack on `t` (see {@link movableFor}), and (#172) what a stack two
180
+ * steps away needs it to keep — the larger, never both; an attack on the territory in between
181
+ * cuts that reach.
182
+ */
183
+ const keepOf = (x, t) => {
184
+ const near = myCommanders.has(x) || (!ps.spendKeeps && safeAtStart.has(x) && !conceded.has(x)) ? keepFor(x, (n) => n === t) : 0;
185
+ const far = ps.spendKeeps || pass.relaxAttacks ? 0 : twoStepKeep(x, (n) => n === t);
186
+ if (far > near)
187
+ twoStepBound.add(x);
188
+ // #179: a covered exit keeps its cover whatever the pass (conceded or not, keeps spent or not).
189
+ return Math.max(near, far, coverOf(x));
190
+ };
191
+ /**
192
+ * #214: the other members a completion in progress (pass 1, all or nothing) plans this turn. A
193
+ * step from a conceded border that completes a bonus together with them is covered by #122's
194
+ * exception: if any of them fails, the whole completion is undone.
195
+ */
196
+ const siblings = new Set();
197
+ /**
198
+ * A conceded border attacks out only with the armies already on it (it is never deployed to),
199
+ * unless every territory I hold is conceded, when there is nowhere better, or (#122) the capture
200
+ * completes a bonus the border is in — with the members already taken or (#214) the sibling
201
+ * steps the same completion plans: rule 1c then keeps it, so it is not given up.
202
+ */
203
+ const concededSourceBase = (x, t, cost) => movableFor(x, t) >= cost ||
204
+ mine.every((id) => conceded.has(id)) ||
205
+ g.map.bonuses.some((b) => {
206
+ const ts = bonusTerritories(g, b.id);
207
+ return (b.value > 0 &&
208
+ ts.includes(x) &&
209
+ ts.includes(t) &&
210
+ ts.every((y) => y === t || mineSet.has(y) || captured.has(y) || siblings.has(y)));
211
+ });
212
+ /**
213
+ * #214: a lead step (#203) may be funded from this turn's deploy on a conceded border too, as
214
+ * #212 lets it attack out of a held one: the deploy there is sized for the attack and leaves
215
+ * with it (the border stays conceded: nothing is spent on its hold). Left out, the closest
216
+ * bonus's enemy member beside a conceded border had no source at all, and the deploy went to a
217
+ * farther bonus. Never my commander's territory (rule 1k: it is never conceded either).
218
+ */
219
+ const leadConceded = (x, t) => leadSteps.has(t) && conceded.has(x) && !myCommanders.has(x);
220
+ /**
221
+ * #214: lead steps captured on that allowance alone (a conceded source funded from this turn's
222
+ * deploy, the capture completing nothing it is in). Pass 2 tries the bonus's completion before
223
+ * taking one alone.
224
+ */
225
+ const fundedOnConceded = new Set();
226
+ const concededSource = (x, t, cost) => concededSourceBase(x, t, cost) || leadConceded(x, t);
227
+ /**
228
+ * #212: a lead step (#203) may attack out of a border held under `balanced` — locked so its armies
229
+ * stay put for its hold — when this turn's deploy covers the attack and the hold together. Left
230
+ * locked, the closest bonus's enemy member beside a held stack had no source at all, and the
231
+ * deploy went to a farther bonus. Never my commander's territory (rule 1k: nothing leaves it).
232
+ */
233
+ const holdSource = (x, t) => leadSteps.has(t) && locked.has(x) && !conceded.has(x) && !myCommanders.has(x);
234
+ /**
235
+ * What a held border `x` keeps once the lead step on `t` leaves (in `avail` terms; it may exceed
236
+ * the armies there: the deploy covers the rest): what holds it against the threat left once `t`
237
+ * is taken, and at least what {@link keepOf} keeps.
238
+ */
239
+ const holdKeep = (x, t) => {
240
+ const b = borderAt(x, (n) => captured.has(n) || n === t);
241
+ const need = b ? Math.max(0, holdArmies(b.threat) - unitsAt(x)) : 0;
242
+ return Math.max(need - (stayAt(x) - avail.get(x)), keepOf(x, t));
243
+ };
244
+ /** Enemy commanders' territories attacked as a commander strike (rule 1s): exempt from R3. */
245
+ const strikes = new Set();
246
+ /** #272: captures out of a conceded border into a bonus (plan/conceded-out.ts), which R3 does not refuse. */
247
+ const r3Exempt = new Set();
248
+ /**
249
+ * Defenders assumed at a target attacked to finish its owner off: its armies plus that
250
+ * owner's full deploy estimate (the worst case). Other targets: their armies now.
251
+ */
252
+ const worstCase = new Map();
253
+ /** Players this plan eliminates (rule 1e, every territory taken for sure), for the move-order caveat (#127). */
254
+ const finishedOff = new Set();
255
+ const defendersAt = (t) => worstCase.get(t) ?? defenceAt(t);
256
+ /**
257
+ * #240 review: the defenders a capture's survivors and trade are judged against. A repulsed
258
+ * territory sized for its owner's deploy (its worst case, so no "assumes" warning) is judged against
259
+ * the defenders there now, as the plan without the evidence judges it — whose #120 sizing adds
260
+ * survivors over those same defenders — so the evidence changes what is sent, never how the
261
+ * capture ranks or whether R3 keeps it. Every other target: {@link defendersAt}.
262
+ */
263
+ const defendersSeen = (t) => {
264
+ const rep = leadSteps.has(t) ? undefined : repulsed.get(t);
265
+ return rep && worstCase.get(t) === rep.defenders + rep.extra ? defenceAt(t) : defendersAt(t);
266
+ };
267
+ /**
268
+ * Capture `t` from its best source. A conceded border is never deployed to: it attacks
269
+ * out only with the armies already on it (unless every territory I hold is conceded,
270
+ * when there is nowhere better). `force` names the source (it may be locked) and the
271
+ * armies on it that stay out of the attack. `fromConceded` (rule 4e only) names the one conceded
272
+ * border that may attack out with deploys too: they leave with the attack. `bare` (#214): a lead
273
+ * step toward the closest bonus or in a completion, which may be retried at its bare cost.
274
+ */
275
+ const tryCapture = (t, reason, force, fromConceded, bare = false) => {
276
+ // B2 (T1): a truce's covered territory is never captured, whichever pass asks.
277
+ if (pc.truce.noTarget(t))
278
+ return false;
279
+ // #203: a lead step lands even if its owner deploys there first (its survivors counted so) —
280
+ // assumed while it is tried, kept only when it is taken.
281
+ const lead = leadSteps.get(t);
282
+ // #240: a territory my attacks failed on repeatedly, its owner reinforcing it, is sized the same way.
283
+ // #240 review: not while rule 4e's contact ranking tries it at its plain size (ps.plainRepulsed).
284
+ const rep = lead === undefined && !ps.plainRepulsed ? repulsed.get(t) : undefined;
285
+ // #272 review: a repulsed size below the owner's deploy estimate is sent, but is no worst case.
286
+ const sized = lead ?? (rep?.sure ? rep : undefined);
287
+ const fresh = !worstCase.has(t);
288
+ const sure = sized !== undefined && fresh;
289
+ if (sure)
290
+ worstCase.set(t, sized.defenders + sized.extra);
291
+ shortAt = undefined;
292
+ belowEven = undefined;
293
+ combinedR3 = false;
294
+ // #240 review: the target ranks on its plain cost; the capture sends at least the sure size
295
+ // (finish-off may size it larger itself), and is not made when that does not fit.
296
+ const ranked = targets.get(t);
297
+ if (rep && rep.cost > ranked.cost)
298
+ targets.set(t, { ...ranked, cost: rep.cost });
299
+ let ok = captureOnce(t, reason, force, fromConceded);
300
+ if (rep)
301
+ targets.set(t, ranked);
302
+ if (sure && !ok)
303
+ worstCase.delete(t);
304
+ // #240 review: the sure size of a repulsed territory the turn cannot fund now may still be paid
305
+ // from the leftover, as the plan without the evidence pays its #120 sizing (after the holds and the
306
+ // reserve). When the source's armies and the whole budget could reach it, the capture is taken at
307
+ // its plain size, pending: planTurn drops it once the margin has run if it is still short of the
308
+ // sure size. A refusal (R3, a trade, a hold) stands, as for the sure try.
309
+ const shortNow = shortAt;
310
+ if (rep &&
311
+ fresh &&
312
+ !ok &&
313
+ shortNow?.from !== undefined &&
314
+ shortNow.spare + Math.max(0, ps.budget) >= rep.cost &&
315
+ ps.refusal === undefined &&
316
+ belowEven === undefined &&
317
+ !combinedR3) {
318
+ shortAt = undefined;
319
+ ok = captureOnce(t, reason, force, fromConceded);
320
+ if (ok)
321
+ ps.repulsedPending.add(t);
322
+ }
323
+ // #214: a step toward the closest bonus (or in a completion) the turn cannot fund at its sure
324
+ // cost is retried at its bare cost — a sure capture of the defenders standing there now, the
325
+ // basis rule 4f ranks the bonuses on. No worst case: #120's warning then says what it faces if
326
+ // the owner deploys there first. Never a territory my attacks failed on repeatedly (#240 review:
327
+ // it is attacked only at the size that lands). Only a funding shortfall retries (an R3 or trade refusal of the
328
+ // sure step stands), and the target keeps its sure cost for every later try.
329
+ // #214 review: shortAt is set before tryCombined runs, so a combined capture refused for a
330
+ // below-even trade (belowEven) or by R3 (combinedR3, which sets no refusal) is a refusal too.
331
+ if (bareOn && lead !== undefined && !repulsed.has(t) && sure && bare && !ok && shortAt !== undefined && ps.refusal === undefined && belowEven === undefined && !combinedR3) {
332
+ const tg = targets.get(t);
333
+ const cheap = costAt(t);
334
+ const note = leadNote(t);
335
+ if (cheap !== null && cheap < tg.cost && reason.endsWith(note)) {
336
+ targets.set(t, { ...tg, cost: cheap });
337
+ shortAt = undefined;
338
+ ok = captureOnce(t, reason.slice(0, reason.length - note.length) + leadNote(t, tg.cost), force, fromConceded);
339
+ targets.set(t, tg);
340
+ if (ok)
341
+ bareTaken.add(t);
342
+ }
343
+ }
344
+ if (lead) {
345
+ // Set inside captureOnce (control flow does not see it).
346
+ const short = shortAt;
347
+ const r = ps.refusal;
348
+ if (ok)
349
+ leadTry.delete(t);
350
+ else if (r?.kind === 'r3')
351
+ leadTry.set(t, { kind: 'r3' });
352
+ else if (r?.kind === 'trade')
353
+ leadTry.set(t, { kind: 'trade', lost: r.lost, killed: r.killed });
354
+ else if (short)
355
+ leadTry.set(t, { kind: 'short', ...short });
356
+ }
357
+ return ok;
358
+ };
359
+ /**
360
+ * #203: the source the last {@link captureOnce} found short, what it could spare and what deploy
361
+ * could reach it then; #212: for a held border, `hold` is what its hold still lacked (its spare is 0).
362
+ */
363
+ let shortAt;
364
+ const captureOnce = (t, reason, force, fromConceded) => {
365
+ ps.refusal = undefined;
366
+ fundedOnConceded.delete(t);
367
+ if (spared.has(t))
368
+ return false;
369
+ const tg = targets.get(t);
370
+ // My commander's territory keeps what holds it (rule 1k). Under No-Split nothing is kept: the
371
+ // whole stack moves, and a territory that must hold issues no order (#124).
372
+ const spare = (x) => noSplit
373
+ ? avail.get(x)
374
+ : force
375
+ ? avail.get(x) - Math.max(force.keep, coverOf(x))
376
+ : holdSource(x, t)
377
+ ? avail.get(x) - holdKeep(x, t)
378
+ : movableFor(x, t);
379
+ if (force && orderOf(force.from))
380
+ return false;
381
+ /** No-Split: why `x` must hold instead (it would send at least the capture's cost). */
382
+ const held = (x) => mustHold(x, t, Math.max(avail.get(x), tg.cost));
383
+ if (force) {
384
+ // The caller says why (another source may still take it).
385
+ const h = held(force.from);
386
+ if (h) {
387
+ ps.refusal = { kind: 'must-hold', ...h };
388
+ return false;
389
+ }
390
+ }
391
+ const open = (x) => (!locked.has(x) || (!force && holdSource(x, t))) && (!conceded.has(x) || x === fromConceded || concededSource(x, t, tg.cost));
392
+ // No-Split (#124): a covered exit (#179) issues no order — it would send its whole stack.
393
+ const usable = (x) => open(x) && !held(x) && !(noSplit && coverOf(x) > 0);
394
+ const sources = force
395
+ ? [force.from]
396
+ : tg.sources.filter((x) => usable(x) && !orderOf(x)).sort((a, b) => avail.get(b) - avail.get(a) || a - b);
397
+ const needAt = (x) => Math.max(0, tg.cost - spare(x));
398
+ // Sorted by armies, the first source needs the fewest deploys; under Local Deployment
399
+ // another may have more room (its bonus pool), so take the first that can afford it. #212: a
400
+ // held border's armies are not all free, so a lead step takes the first source that can afford
401
+ // it, else the one needing the fewest deploys.
402
+ const src = local || leadSteps.has(t)
403
+ ? (sources.find((x) => needAt(x) <= spareAt(x)) ??
404
+ (leadSteps.has(t) ? [...sources].sort((a, b) => needAt(a) - needAt(b) || a - b)[0] : sources[0]))
405
+ : sources[0];
406
+ const need = src === undefined ? Infinity : needAt(src);
407
+ // No single source can afford it: try a combined capture (never for a forced source).
408
+ if (src === undefined || need > spareAt(src)) {
409
+ shortAt =
410
+ src === undefined
411
+ ? {
412
+ spare: 0,
413
+ reach: 0,
414
+ // #212: why no neighbour could attack it, for the skip line.
415
+ ...(leadSteps.has(t)
416
+ ? {
417
+ blocked: [...tg.sources].sort(byNum).map((x) => ({
418
+ from: x,
419
+ why: (myCommanders.has(x)
420
+ ? 'commander'
421
+ : orderOf(x)
422
+ ? 'order'
423
+ : // Unreachable today: a locked border left is a holdSource (so open), a
424
+ // conceded one is funded from deploy (#214), and only No-Split fails
425
+ // `usable` otherwise, which turns lead steps off. Kept so the label
426
+ // stays exhaustive if that ever changes.
427
+ 'locked'),
428
+ })),
429
+ }
430
+ : {}),
431
+ }
432
+ : {
433
+ from: src,
434
+ spare: Math.max(0, spare(src)),
435
+ reach: Math.max(0, spareAt(src)),
436
+ ...(holdSource(src, t) && spare(src) < 0 ? { hold: -spare(src) } : {}),
437
+ };
438
+ if (force)
439
+ return false;
440
+ if (tryCombined(t, reason))
441
+ return true;
442
+ const trade = belowEven;
443
+ // No-Split: name a source that could have taken it alone but already issues an order.
444
+ // Its order already carries its whole stack (#124): count that stack as what it could have sent.
445
+ const split = tg.sources.find((x) => usable(x) && orderOf(x) && Math.max(0, needAt(x) - orderOf(x).armies) <= spareAt(x));
446
+ // No-Split: or one that could, but must hold its border (#124).
447
+ const holder = split === undefined ? tg.sources.find((x) => open(x) && !orderOf(x) && held(x) && needAt(x) <= spareAt(x)) : undefined;
448
+ if (split !== undefined) {
449
+ warnSplit(split, `the attack on ${label(t)} is not planned`);
450
+ ps.refusal = { kind: 'split', from: split };
451
+ }
452
+ else if (holder !== undefined) {
453
+ const h = held(holder);
454
+ warnHold(h, `the attack on ${label(t)} is not planned`);
455
+ ps.refusal = { kind: 'must-hold', ...h };
456
+ }
457
+ else if (trade)
458
+ ps.refusal = { kind: 'trade', ...trade };
459
+ return false;
460
+ }
461
+ // #121: the deploys beyond what the attack alone needs keep a safe border holding.
462
+ // #212: a held border's are what it keeps for its hold.
463
+ const fromHold = !force && holdSource(src, t);
464
+ const forHold = noSplit || force || fromHold ? 0 : Math.min(need, keepOf(src, t));
465
+ // #172: the source keeps what a stack two steps away needs (when that binds, not its border's hold).
466
+ const far = noSplit || force || ps.spendKeeps || pass.relaxAttacks ? null : twoStepHold(src, (n) => n === t);
467
+ const farKeep = far ? twoStepKeep(src, (n) => n === t) : 0;
468
+ const farBinds = far !== null && farKeep > 0 && farKeep >= keepOf(src, t);
469
+ // #214: judged on the state the source was opened under, before the attack spends it.
470
+ const viaLead = !fromHold && !force && need > 0 && src !== fromConceded && leadConceded(src, t) && !concededSourceBase(src, t, tg.cost);
471
+ deploy(src, need);
472
+ // No-Split: the whole stack goes, every army deployed there so far included (#124).
473
+ const sent = noSplit ? Math.max(tg.cost, avail.get(src)) : tg.cost;
474
+ avail.set(src, avail.get(src) - sent);
475
+ captured.add(t);
476
+ const survivors = sent - straightKills(defendersSeen(t), rates.defensiveKillRate);
477
+ // A commander strike is never refused by R3: killing the commander eliminates a player.
478
+ if (!strikes.has(t) && !r3Exempt.has(t) && !defensible(t, survivors)) {
479
+ // Undo: under a guarded goal a bonus that falls next turn is not completed.
480
+ avail.set(src, avail.get(src) + sent - need);
481
+ const left = (deployed.get(src) ?? 0) - need;
482
+ if (left > 0)
483
+ deployed.set(src, left);
484
+ else
485
+ deployed.delete(src);
486
+ ps.budget += need;
487
+ captured.delete(t);
488
+ ps.refusal = { kind: 'r3' };
489
+ return false;
490
+ }
491
+ survivorsAt.set(t, survivors);
492
+ captureOrder.push(t);
493
+ captureUndo.set(t, () => avail.set(src, avail.get(src) + sent));
494
+ moves.push({ from: src, to: t, armies: sent, kind: 'attack', reason, winChance: chanceOf(sent, defenceAt(t)) });
495
+ if (tg.enemy && !worstCase.has(t))
496
+ warnings.push(`Attack on enemy ${label(t)} assumes its owner does not reinforce it first.`);
497
+ rationale.push(`Attack ${label(t)} from ${label(src)} with ${sent}${need ? ` (deploy ${need} there)` : ''}${sent > tg.cost ? `, the whole stack (No-Split; ${tg.cost} would take it)` : ''}: ${reason}.`);
498
+ if (fromHold) {
499
+ // #212: the deploy garrisons it too: its hold is funded (no hold pass deploys there again).
500
+ heldBorders.add(src);
501
+ const th = borderAt(src, (n) => captured.has(n));
502
+ if (th)
503
+ rationale.push(`${label(src)} keeps ${stayAt(src)} to hold its border against the ~${th.threat} threat once the attack on ${label(t)} leaves: it is held, and the deploy covers the attack and the hold together (#212).`);
504
+ }
505
+ else if (viaLead) {
506
+ fundedOnConceded.add(t);
507
+ rationale.push(`${label(src)} is conceded, but the deploy there leaves with the attack on ${label(t)}: a lead step into a bonus (rule 4f's order) may be funded on a conceded source, the deploy sized for the attack alone (#214).`);
508
+ }
509
+ else if (farBinds)
510
+ rationale.push(twoStepCite(src, far, (c) => `The attack on ${label(t)} leaves ${label(src)} ${c}.`));
511
+ else if (forHold > 0) {
512
+ const th = borderAt(src, (n) => captured.has(n));
513
+ if (th)
514
+ rationale.push(`Deploy ${forHold} to ${label(src)} so it still holds its border after the attack on ${label(t)} (${stayAt(src)} stay against a threat of ${th.threat}).`);
515
+ }
516
+ return true;
517
+ };
518
+ if (reserve)
519
+ rationale.push(`Hold a reserve of ${reserve} out of captures.`);
520
+ // ---- 3a. combined (multi-source) captures (R4) ----
521
+ /**
522
+ * The cheapest combined capture of `t` (fewest sources) under exact 0%-luck,
523
+ * straight-round arithmetic, or `null` when even every eligible source together
524
+ * (plus the deploys left) cannot take it.
525
+ */
526
+ const combinedPlan = (t) => {
527
+ const tg = targets.get(t);
528
+ // A commander takes no partial damage, so softening one is not plain arithmetic: never combined.
529
+ if (unitsAt(t) > 0)
530
+ return null;
531
+ const eligible = tg.sources
532
+ .filter((x) => !locked.has(x) &&
533
+ !conceded.has(x) &&
534
+ !myCommanders.has(x) &&
535
+ avail.get(x) > 0 &&
536
+ !orderOf(x) &&
537
+ !(noSplit && coverOf(x) > 0) &&
538
+ !mustHold(x, t, avail.get(x)))
539
+ .sort((a, b) => avail.get(b) - avail.get(a) || a - b);
540
+ const off = rates.offensiveKillRate;
541
+ const def = rates.defensiveKillRate;
542
+ for (let k = 2; k <= eligible.length; k++) {
543
+ const finisher = eligible[0];
544
+ let left = defendersAt(t);
545
+ // The defenders there now: under a worst case (more assumed) a softener must not take
546
+ // it either if the reinforcement never comes.
547
+ let real = armiesOf(t);
548
+ const softeners = [];
549
+ for (const x of eligible.slice(1, k).sort(byNum)) {
550
+ // Never kill the last defender: the finisher's attack is the one that moves in. Under
551
+ // No-Split the whole stack goes (#124): a stack that would kill the last one is no softener.
552
+ // #121: a safe border keeps what holds it (its survivors come home, but may arrive late).
553
+ let a = noSplit ? avail.get(x) : Math.min(avail.get(x), movableFor(x, t));
554
+ while (a > 0 && straightKills(a, off) >= Math.min(left, real)) {
555
+ if (noSplit)
556
+ a = 0;
557
+ else
558
+ a--;
559
+ }
560
+ const kills = straightKills(a, off);
561
+ if (a <= 0 || kills <= 0)
562
+ continue;
563
+ const lost = Math.min(a, straightKills(left, def));
564
+ softeners.push({ from: x, armies: a, kills, before: left, survivors: a - lost });
565
+ left -= kills;
566
+ real -= kills;
567
+ }
568
+ if (!softeners.length)
569
+ continue;
570
+ const take = armiesToTake(left, rates);
571
+ if (take === null)
572
+ return null;
573
+ // No-Split: the finisher sends its whole stack too.
574
+ const armies = noSplit ? Math.max(take, avail.get(finisher)) : take;
575
+ // #121: the finisher keeps what holds a safe border too; deploys cover the rest.
576
+ const need = Math.max(0, armies - (noSplit ? avail.get(finisher) : movableFor(finisher, t)));
577
+ if (need > spareAt(finisher))
578
+ continue;
579
+ const survivors = armies - straightKills(left, def);
580
+ return { softeners, finisher, armies, need, left, survivors };
581
+ }
582
+ return null;
583
+ };
584
+ const tryCombined = (t, reason) => {
585
+ belowEven = undefined;
586
+ combinedR3 = false;
587
+ const plan = combinedPlan(t);
588
+ if (!plan)
589
+ return false;
590
+ const tg = targets.get(t);
591
+ const n = plan.softeners.length + 1;
592
+ if (luck > 0 || (s.roundingMode !== undefined && s.roundingMode !== 'StraightRound')) {
593
+ const why = luck > 0 ? `luck is ${Math.round(luck * 100)}%` : `this game uses ${s.roundingMode} rounding`;
594
+ const w = `Multi-source capture of ${label(t)} skipped: no single source can afford its ${tg.cost}, and ${n} sources together could only at 0% luck under straight rounding, but ${why}.`;
595
+ if (!warnings.includes(w))
596
+ warnings.push(w);
597
+ return false;
598
+ }
599
+ // Rule 0p.3 (#72): behind on armies, no trade below even. The softeners lose more than
600
+ // they kill by design (each attacks a stack larger than it can take), so a combined capture
601
+ // of a player's territory can lose more than the whole stack it destroys.
602
+ // Rule 4e in contact (#107) asks the same of its enemy captures.
603
+ const even = (armiesBehind || ps.evenTradesOnly) && tg.enemy;
604
+ if (even) {
605
+ const lost = plan.softeners.reduce((n, x) => n + x.armies - x.survivors, 0) + plan.armies - plan.survivors;
606
+ const killed = plan.softeners.reduce((n, x) => n + x.kills, 0) + plan.left;
607
+ if (lost > killed) {
608
+ if (armiesBehind) {
609
+ if (!badTrades.has(t))
610
+ badTrades.set(t, { lost, killed });
611
+ skipOffence(t, `a trade below even while behind on armies (loses ${lost} for ${killed})`);
612
+ }
613
+ belowEven = { lost, killed };
614
+ return false;
615
+ }
616
+ }
617
+ // #265 review: what each source keeps back from this attack (#121, #172, #179), read before the
618
+ // capture lands, so a later rebalance never spends it. Not under No-Split: the rebalance never
619
+ // runs there, no keep sizes a whole-stack order, and reading one marks a two-step hold that
620
+ // shaped nothing as binding (keepOf records it for the report).
621
+ const keeps = noSplit
622
+ ? new Map()
623
+ : new Map([...plan.softeners.map((x) => x.from), plan.finisher].map((x) => [x, keepOf(x, t)]));
624
+ const before = { avail: new Map(avail), incoming: new Map(incoming), deployed: new Map(deployed), budget: ps.budget };
625
+ deploy(plan.finisher, plan.need);
626
+ for (const x of plan.softeners) {
627
+ avail.set(x.from, avail.get(x.from) - x.armies);
628
+ incoming.set(x.from, (incoming.get(x.from) ?? 0) + x.survivors);
629
+ }
630
+ avail.set(plan.finisher, avail.get(plan.finisher) - plan.armies);
631
+ captured.add(t);
632
+ if (!defensible(t, plan.survivors)) {
633
+ for (const [k, v] of before.avail)
634
+ avail.set(k, v);
635
+ incoming.clear();
636
+ for (const [k, v] of before.incoming)
637
+ incoming.set(k, v);
638
+ deployed.clear();
639
+ for (const [k, v] of before.deployed)
640
+ deployed.set(k, v);
641
+ ps.budget = before.budget;
642
+ captured.delete(t);
643
+ combinedR3 = true;
644
+ return false;
645
+ }
646
+ survivorsAt.set(t, plan.survivors);
647
+ combined.add(t);
648
+ captureOrder.push(t);
649
+ captureUndo.set(t, () => {
650
+ for (const x of plan.softeners) {
651
+ avail.set(x.from, avail.get(x.from) + x.armies);
652
+ incoming.set(x.from, (incoming.get(x.from) ?? 0) - x.survivors);
653
+ }
654
+ avail.set(plan.finisher, avail.get(plan.finisher) + plan.armies);
655
+ });
656
+ for (const x of plan.softeners)
657
+ moves.push({
658
+ from: x.from,
659
+ to: t,
660
+ armies: x.armies,
661
+ kind: 'attack',
662
+ reason: `wears ${label(t)} down for a combined capture (${reason})`,
663
+ winChance: chanceOf(x.armies, x.before),
664
+ });
665
+ moves.push({
666
+ from: plan.finisher,
667
+ to: t,
668
+ armies: plan.armies,
669
+ kind: 'attack',
670
+ reason,
671
+ winChance: chanceOf(plan.armies, plan.left),
672
+ });
673
+ if (tg.enemy && !worstCase.has(t))
674
+ warnings.push(`Attack on enemy ${label(t)} assumes its owner does not reinforce it first.`);
675
+ const order = [...plan.softeners.map((x) => x.from), plan.finisher].map(label).join(', then ');
676
+ warnings.push(`The capture of ${label(t)} combines ${n} attacks that must run in this order (${order}): the first ${n === 2 ? 'one fails' : `${n - 1} fail`} by design, only wearing the defenders down; the arithmetic is exact only at 0% luck under straight rounding.`);
677
+ rationale.push(combinedLine(t, plan, reason));
678
+ combinedPlans.set(t, { plan, reason, start: defendersAt(t), real: armiesOf(t), keeps, even });
679
+ return true;
680
+ };
681
+ /** The rationale line of a combined capture (rule 3a). */
682
+ const combinedLine = (t, plan, reason) => `Attack ${label(t)} with ${plan.softeners.length + 1} attacks (no single source can afford its ${targets.get(t).cost}): ${plan.softeners
683
+ .map((x) => `from ${label(x.from)} with ${x.armies} (kills ${x.kills} of ${x.before}; ${x.survivors} survive and stay)`)
684
+ .join(', then ')}, then from ${label(plan.finisher)} with ${plan.armies}${plan.need ? ` (deploy ${plan.need} there)` : ''}, taking the last ${plan.left}: ${reason}.`;
685
+ /**
686
+ * #265: each combined capture as built — the defenders it was sized on (`start`; `real`, those
687
+ * standing there now), what each source kept back from it (`keeps`: keepOf, #121/#172/#179; empty under No-Split) and
688
+ * whether it had to trade at least even (`even`, rule 0p.3 / 4e) — for {@link rebalanceCombined}.
689
+ * An entry whose moves have changed since (a restore, a capture undone) is ignored there.
690
+ */
691
+ const combinedPlans = new Map();
692
+ /**
693
+ * #265: once the captures are known, a combined capture one of whose sources is a weak member of
694
+ * a bonus this turn completes (`weakMember`, plan/completed.ts) is rebalanced at the same kills to
695
+ * leave armies on it: every split of the same sources that still takes the target — each softener
696
+ * killing fewer than the defenders it meets, the finisher taking the rest with no new deploy,
697
+ * landing at least as many survivors — and leaves every other source as it held (never below
698
+ * what it kept back when the capture was built — the #121 safe-border keep, the #172 two-step
699
+ * hold, the #179 cover — and a border that held after the captures still holds), never trading
700
+ * below even where the capture had to (rule 0p.3 / 4e), is judged by the armies it leaves on the
701
+ * weak members up to their holds, then the smallest change, then the fewest armies lost: once the
702
+ * members hold, no more is moved. Only one that leaves them more is taken. Live, a 14 + 18 capture could have been 15 + 17
703
+ * for the same kills and left its 1-army member beside an enemy that could deploy 5 one more army.
704
+ * Never under No-Split (each order sends its whole stack) and only at the 0%-luck straight-round
705
+ * arithmetic a combined capture is built on. `stays` is planPass's view of a territory's armies.
706
+ */
707
+ const rebalanceCombined = (weakMember, stays) => {
708
+ if (noSplit)
709
+ return;
710
+ const off = rates.offensiveKillRate;
711
+ const def = rates.defensiveKillRate;
712
+ for (const t of [...combined].sort(byNum)) {
713
+ const rec = combinedPlans.get(t);
714
+ if (!rec || !captured.has(t))
715
+ continue;
716
+ const { plan, reason, start, real, keeps, even } = rec;
717
+ const attackOf = (from, armies) => moves.find((m) => m.kind === 'attack' && m.to === t && m.from === from && m.armies === armies);
718
+ const softMoves = plan.softeners.map((x) => attackOf(x.from, x.armies));
719
+ const finMove = attackOf(plan.finisher, plan.armies);
720
+ if (!finMove || softMoves.some((m) => !m))
721
+ continue;
722
+ if (moves.filter((m) => m.kind === 'attack' && m.to === t).length !== plan.softeners.length + 1)
723
+ continue;
724
+ const sources = [...plan.softeners.map((x) => x.from), plan.finisher];
725
+ const weak = new Map(sources.flatMap((x) => {
726
+ const w = weakMember(x);
727
+ return w ? [[x, w]] : [];
728
+ }));
729
+ if (!weak.size)
730
+ continue;
731
+ const orig = new Map([...plan.softeners.map((x) => [x.from, x.armies]), [plan.finisher, plan.armies]]);
732
+ const origSurv = new Map(plan.softeners.map((x) => [x.from, x.survivors]));
733
+ const staysNow = new Map(sources.map((x) => [x, stays(x)]));
734
+ /** A source's armies after a split: `sent` out, `back` of its softener survivors home. */
735
+ const after = (x, sent, back) => staysNow.get(x) - (sent - orig.get(x)) + (back - (origSurv.get(x) ?? 0));
736
+ /** Whether a source other than a weak member is left as it held: never weaker, or still holding (what it sends is capped by `cap`). */
737
+ const fine = (x, left) => {
738
+ if (left >= staysNow.get(x))
739
+ return true;
740
+ const b = borderAt(x, (n) => captured.has(n));
741
+ if (!b)
742
+ return true;
743
+ const held = (toTake(staysNow.get(x) + unitsAt(x)) ?? Infinity) > b.threat;
744
+ return held && (toTake(left + unitsAt(x)) ?? Infinity) > b.threat;
745
+ };
746
+ const kept = (x, left) => Math.min(left, staysNow.get(x) + weak.get(x).need);
747
+ // A weak member never sends more (judge refuses it); any other source spends only what it
748
+ // did not keep back when the capture was built.
749
+ const cap = (x) => orig.get(x) + (weak.has(x) ? avail.get(x) : Math.max(0, avail.get(x) - keeps.get(x)));
750
+ const judge = (soft, armies, left) => {
751
+ const survivors = armies - straightKills(left, def);
752
+ if (survivors < plan.survivors)
753
+ return null;
754
+ let score = 0;
755
+ let lost = armies - survivors;
756
+ let change = Math.abs(armies - plan.armies);
757
+ for (const x of [...soft.map((y) => ({ from: y.from, sent: y.armies, back: y.survivors })), { from: plan.finisher, sent: armies, back: 0 }]) {
758
+ const left2 = after(x.from, x.sent, x.back);
759
+ if (weak.has(x.from)) {
760
+ if (left2 < staysNow.get(x.from))
761
+ return null;
762
+ score += kept(x.from, left2);
763
+ }
764
+ else if (!fine(x.from, left2))
765
+ return null;
766
+ }
767
+ for (const y of soft) {
768
+ lost += y.armies - y.survivors;
769
+ change += Math.abs(y.armies - orig.get(y.from));
770
+ }
771
+ // Every split kills all `start` defenders.
772
+ if (even && lost > start)
773
+ return null;
774
+ return { soft, armies, left, survivors, score, lost, change };
775
+ };
776
+ const better = (a, b) => !b || a.score > b.score || (a.score === b.score && (a.change < b.change || (a.change === b.change && a.lost < b.lost)));
777
+ let best = judge(plan.softeners, plan.armies, plan.left);
778
+ if (!best)
779
+ continue;
780
+ const baseline = best.score;
781
+ let tried = 0;
782
+ const walk = (i, left, realLeft, soft) => {
783
+ if (++tried > 100_000)
784
+ return;
785
+ if (i === plan.softeners.length) {
786
+ const armies = armiesToTake(left, rates);
787
+ if (armies === null || armies < 1 || armies > cap(plan.finisher))
788
+ return;
789
+ const s2 = judge(soft, armies, left);
790
+ if (s2 && better(s2, best))
791
+ best = s2;
792
+ return;
793
+ }
794
+ const x = plan.softeners[i].from;
795
+ for (let a = 1; a <= cap(x); a++) {
796
+ const kills = straightKills(a, off);
797
+ if (kills >= Math.min(left, realLeft))
798
+ break;
799
+ if (kills <= 0)
800
+ continue;
801
+ const lost = Math.min(a, straightKills(left, def));
802
+ walk(i + 1, left - kills, realLeft - kills, [...soft, { from: x, armies: a, kills, before: left, survivors: a - lost }]);
803
+ }
804
+ };
805
+ walk(0, start, real, []);
806
+ const chosen = best;
807
+ if (!chosen || chosen.score <= baseline)
808
+ continue;
809
+ // Apply: the moves, what each source has left, the survivors home and on the target.
810
+ for (const [k, y] of chosen.soft.entries()) {
811
+ const was = plan.softeners[k];
812
+ avail.set(y.from, avail.get(y.from) - (y.armies - was.armies));
813
+ incoming.set(y.from, (incoming.get(y.from) ?? 0) + (y.survivors - was.survivors));
814
+ const m = softMoves[k];
815
+ m.armies = y.armies;
816
+ m.winChance = chanceOf(y.armies, y.before);
817
+ }
818
+ avail.set(plan.finisher, avail.get(plan.finisher) - (chosen.armies - plan.armies));
819
+ finMove.armies = chosen.armies;
820
+ finMove.winChance = chanceOf(chosen.armies, chosen.left);
821
+ survivorsAt.set(t, chosen.survivors);
822
+ const next = { softeners: chosen.soft, finisher: plan.finisher, armies: chosen.armies, need: plan.need, left: chosen.left, survivors: chosen.survivors };
823
+ const line = rationale.indexOf(combinedLine(t, plan, reason));
824
+ if (line >= 0)
825
+ rationale[line] = combinedLine(t, next, reason);
826
+ combinedPlans.set(t, { plan: next, reason, start, real, keeps, even });
827
+ captureUndo.set(t, () => {
828
+ for (const x of next.softeners) {
829
+ avail.set(x.from, avail.get(x.from) + x.armies);
830
+ incoming.set(x.from, (incoming.get(x.from) ?? 0) - x.survivors);
831
+ }
832
+ avail.set(next.finisher, avail.get(next.finisher) + next.armies);
833
+ });
834
+ const changed = [...next.softeners.map((x) => [x.from, x.armies]), [next.finisher, next.armies]]
835
+ .filter(([x, a]) => a !== orig.get(x))
836
+ .map(([x, a]) => `${label(x)} ${a}, not ${orig.get(x)}`);
837
+ changed[0] = changed[0].replace(/ (\d+), not/, ' sends $1, not');
838
+ const killed = start;
839
+ const held = [...weak.entries()]
840
+ .map(([x, w]) => {
841
+ const left = stays(x);
842
+ return `${label(x)}, a member of bonus ${bonusName(w.bonusId)} completed this turn, keeps ${left} against the ~${w.threat} threat${(toTake(left + unitsAt(x)) ?? Infinity) > w.threat ? ' (it holds)' : ''}`;
843
+ })
844
+ .join('; ');
845
+ rationale.push(`Rebalance the combined capture of ${label(t)}: ${changed.join(', and ')} — the same ${killed} killed — so ${held}.`);
846
+ }
847
+ };
848
+ return { belowEven, movableFor, keepOf, concededSource, siblings, fundedOnConceded, strikes, r3Exempt, worstCase, finishedOff, defendersAt, defendersSeen, tryCapture, shortAt, captureOnce, combinedPlan, tryCombined, rebalanceCombined, bareOn, bareTaken };
849
+ }
850
+ /** Pass 1 (complete a bonus, all or nothing) and pass 2 (advance one a capture at a time, rule 4c(c), 4d). */
851
+ export function bonusPasses(pc, ps, book, hd, tgt, prev) {
852
+ const { g, s, guarded, paybackTurns, territories: state, label, bonusName, mineSet, incomeGain, incomeAfter, defenceAt, bonusTs, completedBy, inFocus, } = pc;
853
+ const { warnings, rationale, deployed, avail, captured, combined, moves, survivorsAt, captureOrder, staged, incoming, } = ps;
854
+ const { heldNow, gainWith } = book;
855
+ const { heldBorders, keptIncome, stayAt } = hd;
856
+ const { targets, leadSteps, leadTry, leadNote, bonusTarget, frontierDelta, targetScoreCost, frontierOf, startHold, toFinish, byCloseness, committing, denials, emptyEnemies, } = tgt;
857
+ const { worstCase, tryCapture, siblings, fundedOnConceded, bareOn } = prev;
858
+ // ---- pass 1: complete a bonus this turn (all or nothing) ----
859
+ /** Snapshot the captures, deploys and notes so far; the result undoes everything since. */
860
+ const snapshot = () => {
861
+ const snap = {
862
+ budget: ps.budget,
863
+ anchor: ps.anchor,
864
+ deployed: new Map(deployed),
865
+ avail: new Map(avail),
866
+ incoming: new Map(incoming),
867
+ combined: new Set(combined),
868
+ survivorsAt: new Map(survivorsAt),
869
+ staged: new Map(staged),
870
+ worstCase: new Map(worstCase),
871
+ heldBorders: new Set(heldBorders),
872
+ captureOrder: captureOrder.length,
873
+ moves: moves.length,
874
+ rationale: rationale.length,
875
+ warnings: warnings.length,
876
+ };
877
+ return () => {
878
+ ps.budget = snap.budget;
879
+ ps.anchor = snap.anchor;
880
+ deployed.clear();
881
+ for (const [k, v] of snap.deployed)
882
+ deployed.set(k, v);
883
+ for (const [k, v] of snap.avail)
884
+ avail.set(k, v);
885
+ incoming.clear();
886
+ for (const [k, v] of snap.incoming)
887
+ incoming.set(k, v);
888
+ for (const m of moves.splice(snap.moves))
889
+ captured.delete(m.to);
890
+ combined.clear();
891
+ for (const t of snap.combined)
892
+ combined.add(t);
893
+ survivorsAt.clear();
894
+ for (const [k, v] of snap.survivorsAt)
895
+ survivorsAt.set(k, v);
896
+ staged.clear();
897
+ for (const [k, v] of snap.staged)
898
+ staged.set(k, v);
899
+ // A lead step's sure sizing (#203) goes with its undone capture.
900
+ worstCase.clear();
901
+ for (const [k, v] of snap.worstCase)
902
+ worstCase.set(k, v);
903
+ // A held border a lead step garrisoned (#212) is owed its hold again.
904
+ heldBorders.clear();
905
+ for (const k of snap.heldBorders)
906
+ heldBorders.add(k);
907
+ captureOrder.length = snap.captureOrder;
908
+ rationale.length = snap.rationale;
909
+ warnings.length = snap.warnings;
910
+ };
911
+ };
912
+ /** `last` (#214): a step the completion tries after its siblings, whatever it costs. */
913
+ const complete = (p, last) => {
914
+ if (!p.completable)
915
+ return;
916
+ const todo = p.remaining
917
+ .filter((t) => !captured.has(t))
918
+ .sort((a, b) => Number(a === last) - Number(b === last) || targets.get(a).cost - targets.get(b).cost || a - b);
919
+ if (!todo.length)
920
+ return;
921
+ const first = moves.length;
922
+ const restore = snapshot();
923
+ const before = incomeGain(heldNow());
924
+ const worth = p.net === p.value ? `+${p.value}` : `+${p.value}, net +${p.net}`;
925
+ // #214: each step counts the others this completion plans (it is undone whole if one fails).
926
+ for (const t of todo)
927
+ siblings.add(t);
928
+ const why = (t) => `completes bonus ${bonusName(p.bonusId)} (${worth})${leadNote(t)}`;
929
+ let ok = todo.every((t) => tryCapture(t, why(t)));
930
+ // #214: when the sure-sized steps cannot all be funded, the completion is tried again: every
931
+ // step at its sure size first (one that fails is passed over), then the ones that failed with a
932
+ // lead step retried at its bare cost — so a bare step never takes the deploy another step's
933
+ // sure size would have had.
934
+ if (!ok && bareOn && todo.some((t) => leadSteps.has(t))) {
935
+ // #214 review: a retry that fails too must not leave the skip line reading a state it undid:
936
+ // a bare step it took erased its member's "its bonus's step …" entry, and a sibling found
937
+ // short after it was measured with that step's deploy spent. Those go back to what the sure
938
+ // try said; a refusal the retry found (R3, a trade) stands.
939
+ const afterSure = new Map(leadTry);
940
+ restore();
941
+ const failed = todo.filter((t) => !tryCapture(t, why(t)));
942
+ let bareLanded = false;
943
+ ok = failed.every((t) => {
944
+ const landed = tryCapture(t, why(t), undefined, undefined, true);
945
+ bareLanded ||= landed;
946
+ return landed;
947
+ });
948
+ if (!ok)
949
+ for (const t of todo) {
950
+ const now = leadTry.get(t);
951
+ const was = afterSure.get(t);
952
+ if (now === undefined ? was !== undefined : now.kind === 'short' && bareLanded && was !== undefined)
953
+ leadTry.set(t, was);
954
+ }
955
+ }
956
+ siblings.clear();
957
+ // Rule 4c: completing it must not lower income (its members' negative bonuses included).
958
+ if (ok && !p.focus && incomeGain(heldNow()) < before) {
959
+ const net = incomeGain(heldNow()) - before;
960
+ restore();
961
+ const line = `Do not complete bonus ${bonusName(p.bonusId)} (${worth}): with this turn's other captures it changes income by ${net} (its members complete negative bonuses).`;
962
+ // Pass 2's retry (#214) may refuse what pass 1 already did: say it once.
963
+ if (!rationale.includes(line))
964
+ rationale.push(line);
965
+ return;
966
+ }
967
+ if (ok) {
968
+ // The leftover's expansion stack is a finisher, never a combined capture's softener: its extra
969
+ // armies would only come home (No-Split: leave with its failing attack).
970
+ const done = moves.slice(first);
971
+ const finisher = done.find((m, i) => m.kind === 'attack' && !done.slice(i + 1).some((o) => o.kind === 'attack' && o.to === m.to));
972
+ ps.anchor ??= (finisher ?? moves[first])?.from;
973
+ return;
974
+ }
975
+ restore();
976
+ };
977
+ // ---- pass 2: advance a bonus one capture at a time ----
978
+ /** Bonuses whose staging was refused (rule 4c(c)), so the rationale says it once. */
979
+ const unstaged = new Set();
980
+ /**
981
+ * Rule 4c(c): capturing `t` toward `p` lowers income this turn. It is a staging step, taken
982
+ * only when the bonus completes within PAYBACK_TURNS (k turns: its other missing members'
983
+ * capture cost / the income left after this step, rounded up, at least 1; none left:
984
+ * refused) and the penalties until then —
985
+ * at most k × every penalty its missing members carry — are repaid by its net worth within
986
+ * PAYBACK_TURNS turns of completion. Returns the capture's reason and rationale line, or
987
+ * `null` when refused.
988
+ */
989
+ const stage = (p, t) => {
990
+ const rest = p.remaining.filter((x) => x !== t && !captured.has(x));
991
+ let restCost = 0;
992
+ for (const x of rest) {
993
+ const st = state.get(x);
994
+ restCost += !st || st.owner.kind === 'unknown' || st.armies === null ? Infinity : (captureCost(defenceAt(x), s) ?? Infinity);
995
+ }
996
+ const penalty = p.value - p.net;
997
+ const step = gainWith([t]);
998
+ // The income left once this step (and this turn's other captures) lands: the staging
999
+ // capture itself lowers it, so the turns to finish are counted at that income (#70).
1000
+ const after = incomeAfter(new Set([...heldNow(), t]));
1001
+ const turns = after > 0 ? Math.max(1, Math.ceil(restCost / after)) : Infinity;
1002
+ const interim = turns * penalty;
1003
+ if (turns <= paybackTurns && interim <= paybackTurns * p.net) {
1004
+ return {
1005
+ note: `Stage bonus ${bonusName(p.bonusId)} with ${label(t)} (${step} income until it completes): its other ${rest.length} missing member${rest.length === 1 ? '' : 's'} cost ${restCost}, ~${turns} turns at income ${after} (after this step); ${turns} turns × ${penalty} = ${interim} of penalties at most, repaid within ${paybackTurns} turns of completion (${paybackTurns} × +${p.net} = ${paybackTurns * p.net}).`,
1006
+ reason: `stages bonus ${bonusName(p.bonusId)} (+${p.value}, net +${p.net} once complete; ${step} income until then)`,
1007
+ };
1008
+ }
1009
+ if (!unstaged.has(p.bonusId)) {
1010
+ unstaged.add(p.bonusId);
1011
+ rationale.push(`Do not take ${label(t)} toward bonus ${bonusName(p.bonusId)}: it costs ${step} income until the bonus completes, ${restCost === Infinity
1012
+ ? 'and the rest of the bonus cannot be costed (fog)'
1013
+ : `~${turns} turns away (${restCost} armies at income ${after} after this step); ${turns} × ${penalty} = ${interim} of penalties is not repaid by ${paybackTurns} × +${p.net}`}.`);
1014
+ }
1015
+ return null;
1016
+ };
1017
+ /**
1018
+ * Captures rule 4d's budget stopped, with the frontier they would have left (for the warning;
1019
+ * dropped, with their rationale lines, if a later pass takes them after all).
1020
+ */
1021
+ const stopped = [];
1022
+ /**
1023
+ * #281: vacated territories (and, the owner's extension, empty enemy territories on the same front)
1024
+ * rule 4d let through though they add a border facing an enemy, with the rationale line the report
1025
+ * states for each one the plan still takes.
1026
+ */
1027
+ const denied = new Map();
1028
+ /** The start of rule 4d's rationale line for a stopped `t` (one per attempt that differed). */
1029
+ const stoppedLine = (t) => `Do not take ${label(t)}: it adds a border facing an enemy without completing a bonus,`;
1030
+ /**
1031
+ * Rule 4d's frontier budget, judged with `t` just captured: under a guarded goal, a capture
1032
+ * that adds a border facing an enemy without completing a bonus (and not focused) is stopped
1033
+ * when holding the frontier next turn would then need more than the next income, and more than
1034
+ * it needed at the start of the turn. Returns the rationale line when stopped, else `null`.
1035
+ */
1036
+ const outgrows = (t) => {
1037
+ if (!guarded || inFocus(t))
1038
+ return null;
1039
+ const held = heldNow();
1040
+ if (completedBy(held).some((id) => g.bonusById.get(id).value > 0 && bonusTs.get(id).includes(t)))
1041
+ return null;
1042
+ const stays = (x) => (mineSet.has(x) ? stayAt(x) : (survivorsAt.get(x) ?? 0));
1043
+ const without = new Set([...held].filter((x) => x !== t));
1044
+ if (frontierDelta(without, [t], stays).enemy <= 0)
1045
+ return null;
1046
+ const f = frontierOf(held, stays);
1047
+ const next = keptIncome(held);
1048
+ const start = startHold();
1049
+ if (f.holdCost <= next || f.holdCost <= start)
1050
+ return null;
1051
+ // #281: land a static seat left, which a live stack beside it takes free next turn: the border
1052
+ // comes either way, so the hold cost alone never refuses it (the capture still spends only what
1053
+ // stands above its source's hold).
1054
+ const d = denials.get(t);
1055
+ if (d) {
1056
+ denied.set(t, denialLine(pc, t, d));
1057
+ return null;
1058
+ }
1059
+ // #281 (the owner's extension): an empty enemy territory whose border faces only what my borders
1060
+ // beside it already face moves the front one step; a border to a new stack is judged as any.
1061
+ const e = emptyEnemies.get(t);
1062
+ if (e?.sameFront) {
1063
+ denied.set(t, emptyEnemyLine(pc, t, e));
1064
+ return null;
1065
+ }
1066
+ const why = `${stoppedLine(t)} and the frontier would then need ${f.holdCost} next turn to hold (${f.enemyBorders} enemy-facing borders), more than the next income of ${next} and more than the ${start} it needed at the start of the turn.`;
1067
+ if (!stopped.some((x) => x.t === t))
1068
+ stopped.push({ t, holdCost: f.holdCost, income: next });
1069
+ return why;
1070
+ };
1071
+ /**
1072
+ * Capture `t` for expansion, unless rule 4d's frontier budget stops it (then everything is undone).
1073
+ * `bare` (#214): a lead step toward the closest bonus, which may be retried at its bare cost.
1074
+ * `force` (rule 5b, #218): the source, and the armies on it that stay out of the attack.
1075
+ */
1076
+ const tryExpand = (t, reason, bare = false, force) => {
1077
+ const restore = snapshot();
1078
+ if (!tryCapture(t, reason, force, undefined, bare))
1079
+ return false;
1080
+ const why = outgrows(t);
1081
+ if (why === null)
1082
+ return true;
1083
+ restore();
1084
+ if (leadSteps.has(t))
1085
+ leadTry.set(t, { kind: 'frontier' });
1086
+ if (!rationale.includes(why))
1087
+ rationale.push(why);
1088
+ return false;
1089
+ };
1090
+ const advance = (p) => {
1091
+ /**
1092
+ * #214: the bonus closest to completion (rule 4f's order: the first with a step still to take),
1093
+ * whose lead steps may be retried at their bare cost — the cost it was ranked on.
1094
+ */
1095
+ // #214 review: only while rule 4f commits to the closest bonus — otherwise `byCloseness` is
1096
+ // just the score order, and its first bonus is not the closest.
1097
+ const closest = bareOn && committing && byCloseness.find((q) => q.remaining.some((x) => bonusTarget(x) && !captured.has(x))) === p;
1098
+ const todo = p.remaining
1099
+ .filter((t) => bonusTarget(t) && !captured.has(t))
1100
+ .sort((a, b) => targetScoreCost(a) - targetScoreCost(b) || targets.get(a).cost - targets.get(b).cost || a - b);
1101
+ /**
1102
+ * Whether a step funded on a conceded source was met (once: its bonus's completion was tried,
1103
+ * then the step was weighed; any later one is taken as it comes).
1104
+ */
1105
+ let whole = false;
1106
+ /** Everything a run of steps changes, for {@link weigh}; the result undoes it. */
1107
+ const checkpoint = () => {
1108
+ const restore = snapshot();
1109
+ const tried = new Map(leadTry);
1110
+ const stops = stopped.length;
1111
+ const refused = new Set(unstaged);
1112
+ return () => {
1113
+ restore();
1114
+ leadTry.clear();
1115
+ for (const [k, v] of tried)
1116
+ leadTry.set(k, v);
1117
+ stopped.length = stops;
1118
+ unstaged.clear();
1119
+ for (const k of refused)
1120
+ unstaged.add(k);
1121
+ };
1122
+ };
1123
+ /**
1124
+ * #214 review: a step funded on a conceded source alone, its bonus's completion refused, is
1125
+ * taken now or after the bonus's other steps, whichever plans more captures (a tie: whichever
1126
+ * leaves more of this turn's deploy; a tie again: after). Taken first, it could sink most of
1127
+ * the deploy into the conceded border and crowd out a sibling a held border funds for less;
1128
+ * taken last, it could lose a pair that fits only in its order. Runs the rest of `queue` too.
1129
+ */
1130
+ const weigh = (t, rest, bare) => {
1131
+ const back = checkpoint();
1132
+ run([t, ...rest], bare);
1133
+ const now = { captures: captured.size, budget: ps.budget };
1134
+ back();
1135
+ run([...rest, t], bare);
1136
+ if (captured.size > now.captures || (captured.size === now.captures && ps.budget >= now.budget))
1137
+ return;
1138
+ back();
1139
+ run([t, ...rest], bare);
1140
+ };
1141
+ /** `bare` (#214): the closest bonus's second round, its lead steps retried at their bare cost. */
1142
+ const run = (queue, bare = false) => {
1143
+ for (let i = 0; i < queue.length; i++) {
1144
+ const t = queue[i];
1145
+ if (captured.has(t))
1146
+ continue;
1147
+ const lead = leadSteps.get(t);
1148
+ // #203: a lead step never lowers income (as a lead strike).
1149
+ if (lead && gainWith([t]) < 0)
1150
+ continue;
1151
+ const stepping = !lead && !p.focus && gainWith([t]) < 0 ? stage(p, t) : undefined;
1152
+ if (stepping === null)
1153
+ continue;
1154
+ const worth = p.net === p.value ? `+${p.value}` : `+${p.value}, net +${p.net}`;
1155
+ const reason = (stepping?.reason ?? `advances bonus ${bonusName(p.bonusId)} (${worth}, ${toFinish(p.cost, p.fogged, p.fogEach)})`) + leadNote(t);
1156
+ // Only a lead step (#203) can be funded on a conceded source.
1157
+ const before = whole || !lead ? undefined : snapshot();
1158
+ const tried = before && new Map(leadTry);
1159
+ if (!tryExpand(t, reason, bare))
1160
+ continue;
1161
+ if (before && fundedOnConceded.has(t)) {
1162
+ /*
1163
+ * #214: a step funded on a conceded source completes nothing on its own, and taken first it
1164
+ * can block the completion: rule 1c's guard then judges the sibling's capture with the deploy
1165
+ * already sunk into the conceded border (and refuses it), or the sibling alone is stopped by
1166
+ * rule 4d. The bonus is completed whole instead when pass 1 can with that step last (it then
1167
+ * completes the bonus under #122's exception, and the guard judges the completion as such);
1168
+ * only otherwise is the step weighed against the bonus's other steps.
1169
+ */
1170
+ whole = true;
1171
+ before();
1172
+ complete(p, t);
1173
+ if (p.remaining.every((x) => captured.has(x)))
1174
+ return;
1175
+ leadTry.clear();
1176
+ for (const [k, v] of tried)
1177
+ leadTry.set(k, v);
1178
+ weigh(t, queue.slice(i + 1), bare);
1179
+ return;
1180
+ }
1181
+ ps.anchor ??= moves[moves.length - 1].from;
1182
+ if (stepping) {
1183
+ staged.set(t, p.bonusId);
1184
+ rationale.push(stepping.note);
1185
+ }
1186
+ }
1187
+ };
1188
+ run(todo);
1189
+ // #214: the closest bonus's lead steps the sure sizing could not fund are retried at their bare
1190
+ // cost, once every step has had its sure try (a bare step never takes a sure one's deploy).
1191
+ if (closest)
1192
+ run(todo.filter((t) => leadSteps.has(t) && !captured.has(t)), true);
1193
+ };
1194
+ return { snapshot, complete, unstaged, stage, stopped, stoppedLine, denied, outgrows, tryExpand, advance };
1195
+ }