@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,760 @@
1
+ // Rule 5, the leftover deploy (#72, #102, #103, #121, #124, #125, #163, #215, #218, #265, #268; #133): the
2
+ // income no capture or hold took goes, in order, to a conceded border it can make hold after all (its
3
+ // withdrawal taken back; only without a strike stack, where the leftover would buy comfort), to
4
+ // each member of a bonus this turn's captures complete that falls to the enemy beside it (#265), to
5
+ // the borders that fall without the armies withdrawn into them unless I am known to move first
6
+ // (#215), to the borders short of their hold before the strike stack, then to the strike
7
+ // stack, the short borders' comfortable margins (#218: the rest on the step's source when it
8
+ // defends as well; #268: else spread over the borders facing one opponent for equal headroom
9
+ // over its deploy), the step it saves toward, the expansion stack (#218: with no front in view,
10
+ // the territory central to what I hold instead when the stack lies far from it), the most fogged
11
+ // border or the biggest stack — split against a Bomb when it concentrates for
12
+ // nothing — and under Local Deployment each pool's rest inside its bonus. planPass runs it where
13
+ // it ran before: after rule 1c's second reconsideration and the strike stack's choice, before the
14
+ // strike stack is spent.
15
+ import { bonusTerritories } from '../bonuses.js';
16
+ import { bfsDistances, neighborsOf } from '../graph.js';
17
+ import { chargeDeploys } from '../local-deploy.js';
18
+ import { completedMembers } from './completed.js';
19
+ import { COMFORT_MARGIN } from './shared.js';
20
+ /** #218 (comment): hops the expansion stack may lie farther from my farthest border than the centre before the leftover stays central. */
21
+ export const CENTRE_SLACK = 1;
22
+ import { knownFirst, lateArrivals, lateNet } from './holds.js';
23
+ /**
24
+ * The leftover deploy (rule 5). `stack` is the strike stack rule 0p.3c chose (plan/strike.ts),
25
+ * `open` and `stays` planPass's views of a border; it returns the strike stack with the leftover
26
+ * it got (only when the leftover reached it), what each Local Deployment pool put on its border
27
+ * (#103), and the step it saved toward (#125).
28
+ */
29
+ export function leftoverDeploy(pc, ps, book, threats, hd, tgt, saveStep, stack, open, stays) {
30
+ const { g, territories: state, label, bonusName, mine, mineSet, armiesOf, unitsAt, toTake, noSplit, bombOn } = pc;
31
+ const { warnings, rationale, deployed, avail, locked, captured, moves, incoming } = ps;
32
+ const { orderOf, deploy, undeploy, pools, roomAt, valueOf } = book;
33
+ const { borders } = threats;
34
+ const { conceded, kept, garrisoned, stood, threatened, stayAt } = hd;
35
+ const { committing, byCloseness, bonusTarget, targets, repulsed } = tgt;
36
+ // As the deploy book reads it, restated here so TypeScript narrows `pools` wherever it is tested.
37
+ const local = pools !== null && pools.bonuses.length > 0;
38
+ /** The strike stack rule 0p.3c built this turn (#72), and the leftover it got. */
39
+ let strikeStack;
40
+ /** Armies a Local Deployment pool put on each border this turn (#103): never moved out. */
41
+ const poolDeployed = new Map();
42
+ /**
43
+ * #125: the capture to save toward — rule 4e's top step it could not afford, else (rule 4f
44
+ * committing) the closest bonus's cheapest missing member in reach when this turn made no capture
45
+ * into that bonus — and its source: my territory beside it (open, not a softener, issuing no
46
+ * order under No-Split) with the most armies free, ties by id.
47
+ */
48
+ const stepSource = (open, notSoftening) => {
49
+ let step = saveStep;
50
+ if (!step && committing) {
51
+ for (const p of byCloseness) {
52
+ if (p.remaining.some((t) => captured.has(t)))
53
+ return undefined;
54
+ const t = p.remaining
55
+ .filter((x) => bonusTarget(x) && state.get(x)?.owner.kind === 'neutral')
56
+ .sort((a, b) => targets.get(a).cost - targets.get(b).cost || a - b)[0];
57
+ if (t === undefined)
58
+ continue;
59
+ step = { t, bonusId: p.bonusId, cost: targets.get(t).cost };
60
+ break;
61
+ }
62
+ }
63
+ if (!step || captured.has(step.t))
64
+ return undefined;
65
+ const from = neighborsOf(g, step.t)
66
+ .filter((x) => mineSet.has(x) && open(x) && notSoftening(x) && !orderOf(x))
67
+ .sort((a, b) => avail.get(b) - avail.get(a) || a - b)[0];
68
+ if (from === undefined)
69
+ return undefined;
70
+ // Only a step this turn cannot afford: one the plan could take but did not (R3, rule 4c or 4d
71
+ // refused it) is no reason to save. #218 (comment): affording it means sending its cost and
72
+ // still holding the source's border (as rule 4e's hold check judges an attack: armies
73
+ // withdrawn into it count only when I am known to move first) — live, a source that had grown
74
+ // enough to pay for the step by size alone, not for the step and its hold, stopped saving.
75
+ const room = roomAt(from);
76
+ if (avail.get(from) + room < step.cost)
77
+ return { ...step, from };
78
+ const b = threats.borderAt(from, (n) => n === step.t);
79
+ if (!b)
80
+ return undefined;
81
+ const left = stayAt(from) - lateArrivals(pc, ps, from) + room - step.cost;
82
+ if ((toTake(left + unitsAt(from)) ?? Infinity) > b.threat)
83
+ return undefined;
84
+ return { ...step, from, holdThreat: b.threat };
85
+ };
86
+ /** Why the step is saved toward: its size, or (#218 comment) its size and the source's hold together. */
87
+ const cannotAfford = (x) => x.holdThreat === undefined
88
+ ? 'which this turn cannot afford'
89
+ : `which this turn cannot afford and still hold ${label(x.from)} against the ~${x.holdThreat} threat`;
90
+ /** Set by the leftover deploy (rule 5): the step it saved toward, which idle stacks stage toward (rule 6). */
91
+ let staging;
92
+ /**
93
+ * #215: armies withdrawn into a border hold it only if I move first: when the opponent moves
94
+ * first, its first order (an all-in there) runs before my transfer in. Unless I am known to
95
+ * move first, the leftover makes each open border that falls without them hold on its own — the
96
+ * worse order — most at stake first, when it can afford it whole. The steps after it still
97
+ * count the withdrawal (their holds and comfortable margins are judged in the order where it
98
+ * lands in time). One that holds only with the withdrawal is named in the report.
99
+ */
100
+ const worseOrderHolds = () => {
101
+ /**
102
+ * #215 review: what my open `x` (no order of its own under No-Split) needs to hold, or
103
+ * `undefined` when the leftover could not make it hold anyway. `worse`: in the order that is
104
+ * worse for it, the hold this step sizes (`stays − lateNet`: its own orders not yet run,
105
+ * nothing withdrawn into it arrived); otherwise after all my orders (`stays`), the hold the
106
+ * later steps size.
107
+ */
108
+ const fallNeed = (x, worse) => {
109
+ const first = stays(x.id) - (worse ? lateNet(pc, ps, x.id) : 0) + unitsAt(x.id);
110
+ let d = 0;
111
+ while ((toTake(first + d) ?? Infinity) <= x.threat) {
112
+ d++;
113
+ if (d > ps.budget || d > roomAt(x.id))
114
+ return undefined;
115
+ }
116
+ return d;
117
+ };
118
+ /**
119
+ * #215 review: the border my first order withdraws into, unless the opponent is known to move
120
+ * first. Moving first, only that withdrawal lands before the opponent's first order (the
121
+ * zigzag gives it two orders before my second), so a border any other withdrawal goes into
122
+ * falls whoever moves first without its worse-order hold. The schedule puts the largest early
123
+ * move first (ties in decision order, schedule.ts); the withdrawals are the early moves known here.
124
+ */
125
+ const firstInto = pc.opts.movesFirst === false
126
+ ? undefined
127
+ : moves
128
+ .filter((m) => m.kind === 'transfer' && m.reason === 'withdraws from a conceded border' && lateArrivals(pc, ps, m.to) > 0)
129
+ .reduce((a, m) => (!a || m.armies > a.armies ? m : a), undefined)?.to;
130
+ const order = [...borders.values()].sort((x, y) => valueOf(y.id) - valueOf(x.id) || x.id - y.id);
131
+ for (const [i, b] of order.entries()) {
132
+ const late = lateArrivals(pc, ps, b.id);
133
+ // No-Split (#124): a deploy on a territory that issues an order leaves with it, holding nothing.
134
+ if (late <= 0)
135
+ continue;
136
+ if (!open(b.id) || orderOf(b.id)) {
137
+ ps.firstOnlySkip.set(b.id, orderOf(b.id) ? 'order' : 'closed');
138
+ continue;
139
+ }
140
+ // #215 review: its own orders have not run either when the opponent moves first.
141
+ const net = lateNet(pc, ps, b.id);
142
+ const own = stays(b.id) - net + unitsAt(b.id);
143
+ if ((toTake(own) ?? Infinity) > b.threat)
144
+ continue;
145
+ let d = 0;
146
+ while ((toTake(own + d) ?? Infinity) <= b.threat)
147
+ d++;
148
+ // #215 review: never from what another open border needs to hold whoever moves first — the
149
+ // leftover may be what holds it in both orders, and a border that holds only if I move
150
+ // first is not bought with one that then falls whoever does. For a border with nothing
151
+ // withdrawn into it, or the one my first order goes into, that is what the later steps give
152
+ // it (after all my orders). A border another withdrawal goes into falls whoever moves first
153
+ // without its worse-order hold, which it gets here or not at all: it is kept back only from
154
+ // the border my first order goes into, and only while still to come. Two such borders take
155
+ // their turns most at stake first (keeping each one's hold back from the other, neither
156
+ // was held), and one this step has passed had its turn.
157
+ let reserve = 0;
158
+ for (const [j, x] of order.entries()) {
159
+ if (j === i || conceded.has(x.id) || !open(x.id) || orderOf(x.id))
160
+ continue;
161
+ if (x.id === firstInto || lateArrivals(pc, ps, x.id) <= 0)
162
+ reserve += fallNeed(x, false) ?? 0;
163
+ else if (b.id === firstInto && j > i)
164
+ reserve += fallNeed(x, true) ?? 0;
165
+ }
166
+ if (d > ps.budget - reserve || d > roomAt(b.id)) {
167
+ ps.firstOnlySkip.set(b.id, d > ps.budget - reserve ? 'budget' : 'room');
168
+ continue;
169
+ }
170
+ const sent = late - net;
171
+ rationale.push(`Deploy ${d} to ${label(b.id)} so it holds whoever moves first (protects +${valueOf(b.id)}): the ${late} withdrawn into it land after player ${b.player}'s attack if it moves first, and without them its ${own + d - unitsAt(b.id)}${sent > 0 ? ` (the ${sent} its own orders send out not yet gone)` : ''} need ${toTake(own + d)} to take, above the ~${b.threat} threat.`);
172
+ deploy(b.id, d);
173
+ locked.add(b.id);
174
+ }
175
+ };
176
+ /**
177
+ * #121: before any comfort margin, a conceded border that the leftover can make hold is held
178
+ * after all (live, a border short by 2 was conceded while 5 went to one that already held,
179
+ * and it fell with 15 armies). Only where the leftover would otherwise buy comfort margins
180
+ * (no strike stack), from what is left once every held border that would fall as it stands
181
+ * has its hold; best worth per army first. Its withdrawal is taken back, unless the
182
+ * territory it went to needs those armies to hold; a border that attacks out, my
183
+ * commander's, or one whose garrison already stays is not revived.
184
+ * #215 review: it runs before the worse-order step. A conceded border falls whoever moves
185
+ * first, a border the worse-order step sizes only if the opponent does: the worse-order step
186
+ * taking the budget first left the revival short and lost the conceded border under both
187
+ * orders (and, deployed first, made a border read as comfortable so the revival never ran).
188
+ */
189
+ const holdAfterAll = () => {
190
+ /** The withdrawals taken back, by the territory they went to. */
191
+ const takenBack = new Map();
192
+ let falling = 0;
193
+ for (const b of borders.values()) {
194
+ if (conceded.has(b.id) || orderOf(b.id))
195
+ continue;
196
+ let d = 0;
197
+ while ((toTake(stayAt(b.id) + d + unitsAt(b.id)) ?? Infinity) <= b.threat)
198
+ d++;
199
+ falling += d;
200
+ }
201
+ /**
202
+ * #215 review: unless I am known to move first, a withdrawal into an open border without an
203
+ * order lands too late to count when the opponent moves first, so the worse-order step would
204
+ * deploy there what holds it without them. A revival whose withdrawal that border needs may
205
+ * then still go ahead, paying that deploy too: the armies it would need to hold without the
206
+ * withdrawal (0 when it holds anyway or when this does not apply; -1 when it never holds).
207
+ */
208
+ const refillFor = (out) => {
209
+ if (knownFirst(pc))
210
+ return 0;
211
+ const dest = borders.get(out.to);
212
+ if (!dest || conceded.has(out.to) || !open(out.to) || orderOf(out.to))
213
+ return 0;
214
+ const at = stayAt(out.to) + unitsAt(out.to);
215
+ if ((toTake(at) ?? Infinity) <= dest.threat)
216
+ return 0;
217
+ let n = 0;
218
+ while ((toTake(at - out.armies + n) ?? Infinity) <= dest.threat) {
219
+ n++;
220
+ if (n > ps.budget)
221
+ return -1;
222
+ }
223
+ return n;
224
+ };
225
+ const revivable = threatened
226
+ .filter((t) => conceded.has(t.id) &&
227
+ !stood.has(t.id) &&
228
+ !moves.some((m) => m.from === t.id && m.reason !== 'withdraws from a conceded border'))
229
+ .map((t) => {
230
+ const b = borders.get(t.id);
231
+ const out = moves.find((m) => m.from === t.id);
232
+ const back = out?.armies ?? 0;
233
+ let d = 0;
234
+ while ((toTake(stayAt(t.id) + back + d + unitsAt(t.id)) ?? Infinity) <= b.threat)
235
+ d++;
236
+ return { t, d, out, threat: b.threat, refill: out ? refillFor(out) : 0 };
237
+ })
238
+ .filter(({ out, refill }) => {
239
+ if (!out || refill > 0)
240
+ return true;
241
+ // The territory the withdrawal went to keeps holding without it.
242
+ const dest = borders.get(out.to);
243
+ if (!dest || conceded.has(out.to))
244
+ return true;
245
+ const at = stayAt(out.to) + unitsAt(out.to);
246
+ const heldWith = (toTake(at) ?? Infinity) > dest.threat;
247
+ return !heldWith || (toTake(at - out.armies) ?? Infinity) > dest.threat;
248
+ })
249
+ .sort((a, b) => b.t.worth / Math.max(1, b.d + b.refill) - a.t.worth / Math.max(1, a.d + a.refill) ||
250
+ a.d + a.refill - (b.d + b.refill) ||
251
+ a.t.id - b.t.id);
252
+ for (const { t, d, out, threat, refill } of revivable) {
253
+ // A refill is judged again: an earlier revival may have deployed on the same territory.
254
+ const r = out && refill > 0 ? refillFor(out) : 0;
255
+ if (r < 0 || d + r > ps.budget - falling || d > roomAt(t.id) || (out && r > roomAt(out.to)))
256
+ continue;
257
+ if (out) {
258
+ takenBack.set(out.to, (takenBack.get(out.to) ?? 0) + out.armies);
259
+ moves.splice(moves.indexOf(out), 1);
260
+ avail.set(t.id, avail.get(t.id) + out.armies);
261
+ const inc = (incoming.get(out.to) ?? 0) - out.armies;
262
+ if (inc > 0)
263
+ incoming.set(out.to, inc);
264
+ else
265
+ incoming.delete(out.to);
266
+ const line = rationale.findIndex((l) => l.startsWith(`Withdraw ${out.armies} from ${label(t.id)} to `));
267
+ if (line >= 0)
268
+ rationale.splice(line, 1);
269
+ const w = warnings.findIndex((l) => l.startsWith(`The withdrawal from ${label(t.id)} only executes`));
270
+ if (w >= 0)
271
+ warnings.splice(w, 1);
272
+ }
273
+ if (out && r > 0) {
274
+ deploy(out.to, r);
275
+ locked.add(out.to);
276
+ rationale.push(`Deploy ${r} to ${label(out.to)} so it holds without the ${out.armies} ${label(t.id)} would have withdrawn into it (${stayAt(out.to) + unitsAt(out.to)} armies need ${toTake(stayAt(out.to) + unitsAt(out.to))} to take, above the ~${borders.get(out.to).threat} threat): unless I am known to move first they could land too late to count, so this is spent either way, and ${label(t.id)} is held after all.`);
277
+ }
278
+ conceded.delete(t.id);
279
+ const conceding = `${label(t.id)} cannot be held `;
280
+ for (let i = warnings.length - 1; i >= 0; i--)
281
+ if (warnings[i].startsWith(conceding) && warnings[i].endsWith(': conceded'))
282
+ warnings.splice(i, 1);
283
+ if (d > 0)
284
+ deploy(t.id, d);
285
+ locked.add(t.id);
286
+ rationale.push(`Hold ${label(t.id)} after all (not conceded): deploy ${d} there${out ? `, and keep the ${out.armies} that would have withdrawn` : ''}; the leftover covers it before any comfort margin (${stayAt(t.id) + unitsAt(t.id)} armies need ${toTake(stayAt(t.id) + unitsAt(t.id))} to take, above the ~${threat} threat; protects +${t.value}).`);
287
+ }
288
+ if (ps.cardAdvice === 'order-priority' && !moves.some((m) => conceded.has(m.from)))
289
+ ps.cardAdvice = null;
290
+ return takenBack;
291
+ };
292
+ /**
293
+ * #240 review: what the attacks out of `id` on repulsed territories paid at capture time beyond
294
+ * their plain size (the sure size over what takes the defenders standing there now).
295
+ */
296
+ const repulsedSurplus = (id) => moves
297
+ .filter((m) => m.from === id && m.kind === 'attack')
298
+ .reduce((sum, m) => {
299
+ const rep = repulsed.get(m.to);
300
+ const plain = rep ? pc.costAt(m.to) : null;
301
+ return rep && plain !== null && m.armies >= rep.cost ? sum + Math.max(0, rep.cost - plain) : sum;
302
+ }, 0);
303
+ /**
304
+ * #226 review: the leftover deployed on `id` for defence or saving is kept from the #226 margin —
305
+ * except (#240 review) on the source of an attack on a repulsed territory: the plain plan pays the
306
+ * surplus of its sure size from the armies beyond the hold there, and its margin takes the rest
307
+ * beyond the hold, so the margin still takes what the hold does not need (never fewer armies on the
308
+ * attack than without the evidence).
309
+ */
310
+ const keepFromMargin = (id) => {
311
+ if (repulsedSurplus(id) <= 0)
312
+ ps.leftoverKept.add(id);
313
+ };
314
+ /**
315
+ * The open borders short of a comfortable margin, most at stake first (rule 5). `back`: the
316
+ * withdrawals the revival took back, still counted where they were going, as when this was
317
+ * judged before the revival.
318
+ */
319
+ const shortOf = (bs, back = new Map(), asPlain = false) => [...bs]
320
+ // No-Split (#124): a deploy on a territory that issues an order leaves with it, holding nothing.
321
+ .filter((b) => open(b.id) && !orderOf(b.id))
322
+ .map((b) => {
323
+ const at = stays(b.id) + (back.get(b.id) ?? 0) + unitsAt(b.id);
324
+ const take = toTake(at);
325
+ // #240 review: an attack out of it on a repulsed territory paid its sure size at capture
326
+ // time, where the plain plan pays the surplus over the plain size later, from the armies
327
+ // beyond the hold (#120). A border that holds is judged for comfort as the plain plan
328
+ // judged it, with that surplus still on it, so the evidence never shrinks the attack. One
329
+ // that would fall without the surplus stays short (the leftover makes it hold), except
330
+ // `asPlain`, which judges every border as the plain plan did (whether to revive a conceded
331
+ // border first).
332
+ if (take === null || (take <= b.threat && !asPlain))
333
+ return { ...b, take };
334
+ const surplus = repulsedSurplus(b.id);
335
+ return { ...b, take: surplus > 0 ? toTake(at + surplus) : take };
336
+ })
337
+ .filter((b) => b.take !== null && b.take <= COMFORT_MARGIN * b.threat)
338
+ .sort((a, b) => valueOf(b.id) - valueOf(a.id) || a.take / a.threat - b.take / b.threat || a.id - b.id);
339
+ /** #218: the enemy territories next to `id` (visible, not captured this turn), sorted. */
340
+ const foesNext = (id) => neighborsOf(g, id)
341
+ .filter((n) => {
342
+ const st = state.get(n);
343
+ return !captured.has(n) && st?.owner.kind === 'player' && pc.foe(st.owner.playerId);
344
+ })
345
+ .join(',');
346
+ /** #218: the bonuses `id` is a member of, sorted. */
347
+ const bonusesOf = (id) => [...g.bonusById.values()]
348
+ .filter((x) => bonusTerritories(g, x.id).includes(id))
349
+ .map((x) => x.id)
350
+ .sort((x, y) => x - y)
351
+ .join(',');
352
+ /**
353
+ * #218: equal defensive value — the same player's threat, the same size, from the same enemy
354
+ * territories, protecting as much, in the same bonuses: armies on one defend what armies on the
355
+ * other would.
356
+ */
357
+ const sameDefence = (a, b) => a.player === b.player &&
358
+ a.threat === b.threat &&
359
+ Math.abs(valueOf(a.id) - valueOf(b.id)) < 1e-9 &&
360
+ foesNext(a.id) === foesNext(b.id) &&
361
+ bonusesOf(a.id) === bonusesOf(b.id);
362
+ /** #218 (comment): no enemy territory is in view (one this turn attacks included). */
363
+ const noFront = ![...state.values()].some((st) => st.owner.kind === 'player' && pc.foe(st.owner.playerId));
364
+ /**
365
+ * #218 (comment): the territory central to what I hold — open, issuing no order — with the
366
+ * fewest hops (through my own territories) to the farthest of my borders (a territory of mine
367
+ * next to one I do not hold): in my largest connected holding first, then by that farthest
368
+ * distance, then by the sum of the distances to every border, then by id. `ecc` is each of my
369
+ * territories' farthest distance within its holding.
370
+ */
371
+ const centre = () => {
372
+ const isBorder = (x) => neighborsOf(g, x).some((n) => !mineSet.has(n));
373
+ const ecc = new Map();
374
+ const sum = new Map();
375
+ const size = new Map();
376
+ for (const x of [...mine].sort((a, b) => a - b)) {
377
+ const d = bfsDistances(g, [x], { passable: (n) => mineSet.has(n) });
378
+ let far = 0;
379
+ let total = 0;
380
+ for (const [y, k] of d)
381
+ if (isBorder(y)) {
382
+ far = Math.max(far, k);
383
+ total += k;
384
+ }
385
+ ecc.set(x, far);
386
+ sum.set(x, total);
387
+ size.set(x, d.size);
388
+ }
389
+ const id = [...mine]
390
+ .filter((x) => open(x) && !orderOf(x))
391
+ .sort((a, b) => size.get(b) - size.get(a) || ecc.get(a) - ecc.get(b) || sum.get(a) - sum.get(b) || a - b)[0];
392
+ return id === undefined ? undefined : { id, ecc };
393
+ };
394
+ const { weakMember } = completedMembers(pc, ps, threats, open, stays);
395
+ /**
396
+ * #265: a member of a bonus this turn's captures complete that faces an enemy once they land and
397
+ * falls to it (rule 1c kept it, or the #122 garrison could not fund it) is brought to its hold
398
+ * before any comfort margin, the worse-order holds and the strike stack — it falls whoever moves
399
+ * first, and with it the bonus. Live, a 1-army member beside an empty enemy territory that could
400
+ * deploy 5 stood while the leftover went to a border that already held. Most at stake first, and
401
+ * only a hold the leftover covers in full: armies on a member that still falls are lost with it
402
+ * (one it cannot cover keeps its old place in the comfort steps, and is warned of later). A
403
+ * source of an order is passed over only under No-Split (`orderOf`), where a deploy there would
404
+ * leave with its whole-stack order; otherwise its order's size is fixed and the deploy stays, so a
405
+ * combined capture's source the rebalance could not help is topped up here like any member.
406
+ */
407
+ const holdCompletedMembers = () => {
408
+ const weak = [...mine]
409
+ .filter((id) => !orderOf(id))
410
+ .flatMap((id) => {
411
+ const w = weakMember(id);
412
+ return w ? [{ id, ...w }] : [];
413
+ })
414
+ .sort((a, b) => valueOf(b.id) - valueOf(a.id) || a.need - b.need || a.id - b.id);
415
+ for (const w of weak) {
416
+ const d = w.need;
417
+ if (d > ps.budget || d > roomAt(w.id))
418
+ continue;
419
+ deploy(w.id, d);
420
+ locked.add(w.id);
421
+ keepFromMargin(w.id);
422
+ const at = stays(w.id) + unitsAt(w.id);
423
+ rationale.push(`Deploy ${d} of the leftover to ${label(w.id)}: it is a member of bonus ${bonusName(w.bonusId)}, completed this turn, and faces the ~${w.threat} threat once this turn's captures land (protects +${valueOf(w.id)}); its ${at - unitsAt(w.id)} armies need ${toTake(at)} to take, before any comfort margin.`);
424
+ }
425
+ };
426
+ // ---- leftover deploy ----
427
+ // The borders the comfort steps may pick: open before any border is held after all (a revived
428
+ // border's hold is its whole share of the leftover).
429
+ const comfortPool = [...borders.values()].filter((b) => open(b.id));
430
+ // The revival runs only where the leftover would otherwise buy comfort margins (no strike
431
+ // stack, a border short of its margin), and then before the worse-order holds; otherwise the
432
+ // worse-order holds go first, as before.
433
+ // #240 review: judged as the plain plan judged it, so a repulsed attack's sure size revives nothing.
434
+ const reviving = !stack && ps.budget > 0 && shortOf(comfortPool, new Map(), true).length > 0;
435
+ if (!reviving) {
436
+ holdCompletedMembers();
437
+ worseOrderHolds();
438
+ }
439
+ if (ps.budget > 0) {
440
+ const foggedNext = (id) => neighborsOf(g, id).filter((n) => {
441
+ const st = state.get(n);
442
+ return !captured.has(n) && (!st || st.owner.kind === 'unknown' || st.armies === null);
443
+ }).length;
444
+ /** No-Split (#124): an attack that only softens its target; deploys there would leave with it, killing nothing more that matters. */
445
+ const softens = (m) => noSplit && moves.some((o, i) => i > moves.indexOf(m) && o.kind === 'attack' && o.to === m.to);
446
+ const expansion = ps.anchor ?? moves.find((m) => m.kind === 'attack' && !softens(m))?.from;
447
+ /** Not a softener's source (No-Split): the leftover there would only leave with its failing attack. */
448
+ const notSoftening = (x) => {
449
+ const m = orderOf(x);
450
+ return !m || !softens(m);
451
+ };
452
+ const fogged = [...mine].filter((x) => open(x) && notSoftening(x)).sort((a, b) => foggedNext(b) - foggedNext(a) || a - b).find((id) => foggedNext(id) > 0);
453
+ const saving = stepSource(open, notSoftening);
454
+ const biggest = (ids) => [...ids].sort((a, b) => armiesOf(b) + (deployed.get(b) ?? 0) - (armiesOf(a) + (deployed.get(a) ?? 0)) || a - b)[0];
455
+ const takenBack = reviving ? holdAfterAll() : undefined;
456
+ if (reviving) {
457
+ holdCompletedMembers();
458
+ worseOrderHolds();
459
+ }
460
+ const short = shortOf(comfortPool, takenBack);
461
+ // Holds before the strike stack: a border kept for the bonus this turn completes (rule 1c:
462
+ // the leftover is its only garrison) is topped up to a comfortable margin, and any other
463
+ // open border that would fall (its take at or below the threat) to just hold. The stack
464
+ // gets the rest.
465
+ if (stack)
466
+ for (const b of short) {
467
+ const kept1c = kept.has(b.id) || garrisoned.has(b.id);
468
+ const bar = kept1c ? COMFORT_MARGIN * b.threat : b.threat;
469
+ const room = roomAt(b.id);
470
+ let d = 0;
471
+ for (;;) {
472
+ const take = toTake(stays(b.id) + d + unitsAt(b.id));
473
+ if (take === null || take > bar || d >= room)
474
+ break;
475
+ d++;
476
+ }
477
+ if (d <= 0)
478
+ continue;
479
+ rationale.push(`Deploy ${d} to ${label(b.id)} before the strike stack: ${garrisoned.has(b.id)
480
+ ? `it is garrisoned for the bonus this turn completes, topped up to a comfortable margin over the ~${b.threat} threat`
481
+ : kept1c
482
+ ? `it is kept for the bonus this turn completes, and the leftover is its only garrison`
483
+ : `it would fall to the ~${b.threat} threat`} (protects +${valueOf(b.id)}).`);
484
+ deploy(b.id, d);
485
+ keepFromMargin(b.id);
486
+ }
487
+ /**
488
+ * #268: once every short border has its comfortable margin (`marginFirst`: `lead`'s is still to
489
+ * give, the one short border), the rest is spread over the open borders facing `lead`'s opponent
490
+ * alone that protect something, an army at a time to the one that breaks at the smallest deploy —
491
+ * its armies' take less the stacks beside it, which is the deploy it falls to — ties to the most
492
+ * at stake, then by id:
493
+ * the smallest deploy that breaks any of them is as large as it can be (live, the rest on the
494
+ * border protecting the most left two others to break at ~1.5× the estimate, the third at ~3.5×).
495
+ * One opponent picks one border for its deploy, as the border guess (#204) reads it. Spent through
496
+ * the deploy book, so Local Deployment's pools are respected (a border its pool cannot reach gets
497
+ * nothing more). `undefined`, with nothing spent, when fewer than two such borders exist or every
498
+ * army would go to `lead` anyway (the old rule's deploy, kept as it was).
499
+ */
500
+ const headroomSpread = (lead, marginFirst) => {
501
+ const attacksFrom = (id) => moves.some((m) => m.from === id && m.kind === 'attack');
502
+ // My commander's territory is must-hold (#61): the rest stays on it whatever it protects.
503
+ if (attacksFrom(lead.id) || pc.myCommanders.has(lead.id))
504
+ return undefined;
505
+ /** Facing `lead`'s opponent alone: its threat is that player's, and no other opponent's stack is beside it. */
506
+ const one = (b) => b.alone === undefined &&
507
+ (b.split?.players ?? [b.player]).every((x) => x === lead.player) &&
508
+ neighborsOf(g, b.id).every((n) => {
509
+ const st = state.get(n);
510
+ return captured.has(n) || st?.owner.kind !== 'player' || !pc.foe(st.owner.playerId) || st.owner.playerId === lead.player;
511
+ });
512
+ const group = [...borders.values()].filter((b) => b.player === lead.player &&
513
+ one(b) &&
514
+ open(b.id) &&
515
+ !orderOf(b.id) &&
516
+ // A border an attack leaves from takes no spread: armies there may size its attack up
517
+ // (#120) rather than stay. When it is `lead`, the old rule's rest stays on it.
518
+ !attacksFrom(b.id) &&
519
+ // Weighted by what it protects: a border protecting nothing draws no armies from one that
520
+ // protects something (all of them when the one with the most at stake protects nothing).
521
+ (valueOf(b.id) > 0 || valueOf(lead.id) <= 0));
522
+ if (group.length < 2 || !group.some((b) => b.id === lead.id))
523
+ return undefined;
524
+ const got = new Map();
525
+ const give = (id) => {
526
+ deploy(id, 1);
527
+ got.set(id, (got.get(id) ?? 0) + 1);
528
+ };
529
+ if (marginFirst)
530
+ while (ps.budget > 0 && roomAt(lead.id) > 0) {
531
+ const take = toTake(stays(lead.id) + unitsAt(lead.id));
532
+ if (take === null || take > COMFORT_MARGIN * lead.threat)
533
+ break;
534
+ give(lead.id);
535
+ }
536
+ const breaksAt = (b) => {
537
+ const take = toTake(stays(b.id) + unitsAt(b.id));
538
+ return take === null ? Infinity : take - (b.threat - b.deploy);
539
+ };
540
+ while (ps.budget > 0) {
541
+ const next = group
542
+ .filter((b) => roomAt(b.id) > 0)
543
+ .sort((a, b) => breaksAt(a) - breaksAt(b) || valueOf(b.id) - valueOf(a.id) || a.id - b.id)[0];
544
+ if (!next)
545
+ break;
546
+ give(next.id);
547
+ }
548
+ if (got.size === 0 || (got.size === 1 && got.has(lead.id))) {
549
+ for (const [id, n] of got)
550
+ undeploy(id, n);
551
+ return undefined;
552
+ }
553
+ const total = [...got.values()].reduce((a, b) => a + b, 0);
554
+ const parts = group
555
+ .filter((b) => got.has(b.id))
556
+ .sort((a, b) => a.id - b.id)
557
+ .map((b) => `${label(b.id)} +${got.get(b.id)}`);
558
+ const least = Math.min(...group.map(breaksAt));
559
+ rationale.push(`Spread the leftover ${total} over the borders facing player ${lead.player} (#268), so the smallest deploy that breaks one of them is as large as possible: ${parts.join(', ')}${marginFirst ? '' : ', once every short border has its comfortable margin'}: none of them now falls to a deploy of less than ~${least} on top of the stacks beside it (threat arithmetic on the deploys, before any move: the headroom table carries out the whole turn and may differ; ${pc.untrustedAt(lead.player, lead.id) > 0 && pc.untrustedAt(lead.player, lead.id) >= lead.deploy
560
+ ? `sized for ~${lead.deploy} (untrusted, #275)`
561
+ : `the estimate is ~${lead.deploy}, a floor under fog`}); all of it on ${label(lead.id)}, the one with the most at stake (protects +${valueOf(lead.id)}), would leave another to fall to less.`);
562
+ for (const id of got.keys()) {
563
+ locked.add(id);
564
+ keepFromMargin(id);
565
+ }
566
+ return got;
567
+ };
568
+ /** #268: the rest spread by {@link headroomSpread}, already deployed: nothing is left for `where`. */
569
+ let spreadRest;
570
+ let where;
571
+ let why;
572
+ let lock = false;
573
+ /** #163: the leftover concentrates for one attack (strike, saving, expansion): no Bomb split. */
574
+ let concentrating = false;
575
+ /** #218 (comment): the leftover stays central: rule 6 keeps it there, not the armies already there. */
576
+ let central = false;
577
+ /** #226 review: the leftover defends `where` or saves there: the #226 margin leaves it. */
578
+ let defends = false;
579
+ if (stack) {
580
+ lock = true;
581
+ concentrating = true;
582
+ where = stack.id;
583
+ why = `one strike stack on the border facing player ${stack.player}, the strongest opponent (~${stack.income} income, ${stack.source}), not spread`;
584
+ }
585
+ else if (short[0]) {
586
+ defends = true;
587
+ // #218: the source of the step the leftover would save toward, when it is an open border:
588
+ // once every short border has its comfortable margin, the rest goes there when it defends
589
+ // as well as the border the rest would go to, and counts toward the step. A margin itself
590
+ // stays on its border: armies on the source do not make another border comfortable.
591
+ const src = saving && open(saving.from) && !orderOf(saving.from) ? borders.get(saving.from) : undefined;
592
+ const carries = (b) => src !== undefined && (b.id === src.id || sameDefence(b, src));
593
+ // #121: spread to each short border's comfortable margin, in order, before any border gets
594
+ // more (two symmetric borders at an exact hold ended as 16 and 7); the rest goes to the first
595
+ // (#218: or to the source that defends as well).
596
+ let spread = false;
597
+ if (short.length > 1 || (carries(short[0]) && short[0].id !== src.id))
598
+ for (const b of short) {
599
+ const room = roomAt(b.id);
600
+ let d = 0;
601
+ while (d < room) {
602
+ const take = toTake(stays(b.id) + d + unitsAt(b.id));
603
+ if (take === null || take > COMFORT_MARGIN * b.threat)
604
+ break;
605
+ d++;
606
+ }
607
+ if (d <= 0)
608
+ continue;
609
+ rationale.push(`Deploy ${d} of the leftover to ${label(b.id)}: it brings it to a comfortable margin over the ~${b.threat} threat (protects +${valueOf(b.id)}), before any border gets more.`);
610
+ deploy(b.id, d);
611
+ locked.add(b.id);
612
+ keepFromMargin(b.id);
613
+ spread = true;
614
+ }
615
+ lock = true;
616
+ if (carries(short[0])) {
617
+ // #218: the rest goes to the source, at equal defensive value, and saves toward the step.
618
+ where = src.id;
619
+ concentrating = true;
620
+ why = `save toward ${label(saving.t)} (${saving.cost} to take), the next step of bonus ${bonusName(saving.bonusId)}, ${cannotAfford(saving)}${short[0].id === src.id
621
+ ? `; it is also the held border with the most at stake (protects +${valueOf(src.id)})`
622
+ : `; it defends as well as ${label(short[0].id)} would (the same ~${short[0].threat} threat from player ${short[0].player}, protects +${valueOf(short[0].id)})`}${spread ? ', once every short border has its comfortable margin' : ''}`;
623
+ }
624
+ else {
625
+ where = short[0].id;
626
+ spreadRest = headroomSpread(short[0], !spread);
627
+ why = spread
628
+ ? `the rest, once every short border has its comfortable margin, to the one with the most at stake (protects +${valueOf(where)})`
629
+ : `the held border with the most at stake (protects +${valueOf(where)}), still short of a comfortable margin over the ~${short[0].threat} threat`;
630
+ }
631
+ }
632
+ else if (saving) {
633
+ where = saving.from;
634
+ why = `save toward ${label(saving.t)} (${saving.cost} to take), the next step of bonus ${bonusName(saving.bonusId)}, ${cannotAfford(saving)}`;
635
+ defends = true;
636
+ lock = true;
637
+ concentrating = true;
638
+ }
639
+ else if (expansion !== undefined && open(expansion)) {
640
+ // #218 (comment): with no enemy in view there is no front to go to, and a leftover riding
641
+ // the top expansion walks deeper into one region every turn (live: 14 hops from the nearest
642
+ // front two turns later). When the expansion stack is more than CENTRE_SLACK hops farther
643
+ // from my farthest border than the territory central to what I hold, and its attacks land
644
+ // for sure without the leftover, the leftover stays there.
645
+ // Only once its attacks land for sure: under luck the leftover there raises their odds.
646
+ const sure = moves.every((m) => m.from !== expansion || m.kind !== 'attack' || (m.winChance ?? 1) >= 1);
647
+ const c = noFront && sure ? centre() : undefined;
648
+ if (c && c.id !== expansion && (c.ecc.get(expansion) ?? Infinity) > c.ecc.get(c.id) + CENTRE_SLACK) {
649
+ where = c.id;
650
+ why = `no enemy is in view, so there is no front to go to: it stays central to what I hold (at most ${c.ecc.get(c.id)} hops from each of my borders, where the stack working on the top expansion, ${label(expansion)}, is ${c.ecc.get(expansion)} from its farthest), ready for wherever a front opens`;
651
+ central = true;
652
+ }
653
+ else {
654
+ where = expansion;
655
+ why = 'the stack working on the top expansion';
656
+ lock = true;
657
+ concentrating = true;
658
+ }
659
+ }
660
+ else if (fogged !== undefined) {
661
+ where = fogged;
662
+ why = 'the border with the most fogged neighbours';
663
+ }
664
+ else {
665
+ const b = biggest(mine.filter((x) => open(x) && notSoftening(x)));
666
+ if (b !== undefined) {
667
+ where = b;
668
+ why = 'my biggest stack';
669
+ }
670
+ else {
671
+ where = biggest(mine);
672
+ why = 'my biggest stack';
673
+ warnings.push(`Every territory I hold is conceded; the leftover ${ps.budget} goes to ${label(where)} anyway.`);
674
+ }
675
+ }
676
+ let n = roomAt(where);
677
+ if (saving && where === saving.from)
678
+ staging = { t: saving.t, bonusId: saving.bonusId, cost: saving.cost, from: saving.from };
679
+ // #163: an opponent may hold a Bomb: a second stack on another open border facing an enemy takes
680
+ // half the leftover, so one bomb halves only one of them (same opponent first, then the bigger
681
+ // stack, then id). Never a strike, saving or expansion stack: each concentrates for one attack
682
+ // (the strike this turn, #72), and a split would halve it for certain where a bomb only may.
683
+ // #268: a spread rest is already on two or more stacks, which a bomb halves one of.
684
+ if (bombOn && n >= 2 && borders.has(where) && !concentrating && !spreadRest) {
685
+ const facingP = borders.get(where).player;
686
+ const second = [...borders.values()]
687
+ .filter((b) => b.id !== where && open(b.id) && !orderOf(b.id) && notSoftening(b.id) && roomAt(b.id) >= 1)
688
+ .sort((a, b) => Number(b.player === facingP) - Number(a.player === facingP) ||
689
+ stays(b.id) - stays(a.id) ||
690
+ a.id - b.id)[0];
691
+ if (second) {
692
+ const half = Math.min(Math.floor(n / 2), roomAt(second.id));
693
+ rationale.push(`Deploy ${half} of the leftover to ${label(second.id)}: an opponent may hold a Bomb, which halves one stack before any move, so the leftover makes two stacks rather than one (${label(where)} gets the rest).`);
694
+ deploy(second.id, half);
695
+ locked.add(second.id);
696
+ if (defends)
697
+ keepFromMargin(second.id);
698
+ n = roomAt(where);
699
+ }
700
+ }
701
+ if (n > 0 && !spreadRest) {
702
+ rationale.push(`Deploy the leftover ${n} to ${label(where)}: ${why}.`);
703
+ deploy(where, n);
704
+ // Keep a strike or expansion stack there: the transfer step must not walk it back as "idle
705
+ // interior" armies. Only when it got deploys (under Local Deployment it may get none).
706
+ if (lock)
707
+ locked.add(where);
708
+ if (central)
709
+ ps.centralKeep.set(where, (ps.centralKeep.get(where) ?? 0) + n);
710
+ if (defends)
711
+ keepFromMargin(where);
712
+ }
713
+ if (stack)
714
+ strikeStack = { ...stack, deployed: Math.max(0, n) };
715
+ // Local Deployment: what is left of each bonus pool stays inside its bonus, on its
716
+ // most threatened member (not conceded first; ties by id). One charge, taken before
717
+ // any of these deploys: re-charging after each would let the matching spread a
718
+ // pool's armies over an overlapping pool and strand the latter's.
719
+ if (local && ps.budget > 0) {
720
+ const danger = (id) => {
721
+ const b = borders.get(id);
722
+ if (!b)
723
+ return -Infinity;
724
+ return b.threat - (toTake(stays(id) + unitsAt(id)) ?? Infinity);
725
+ };
726
+ // A conceded border whose garrison stays (#59) is still defended: its pool goes there.
727
+ const lost = (id) => conceded.has(id) && !stood.has(id);
728
+ const charged = chargeDeploys(pools, deployed).used;
729
+ for (const p of pools.bonuses) {
730
+ const left = p.value - (charged.get(p.bonusId) ?? 0);
731
+ if (left <= 0)
732
+ continue;
733
+ // #103: a member next to a threatening enemy always beats an interior one, even a
734
+ // border the plan gave up: the pool can be deployed nowhere else.
735
+ const m = [...p.territoryIds].sort((a, b) =>
736
+ // No-Split (#124): a member that issues an order would send the pool away with it.
737
+ Number(orderOf(a) !== undefined) - Number(orderOf(b) !== undefined) ||
738
+ Number(borders.has(b)) - Number(borders.has(a)) ||
739
+ Number(lost(a)) - Number(lost(b)) ||
740
+ danger(b) - danger(a) ||
741
+ a - b)[0];
742
+ rationale.push(`Deploy bonus ${p.name} (#${p.bonusId})'s ${left} to ${label(m)}: Local Deployment keeps them inside the bonus, and it is its most threatened ${borders.has(m) ? 'border' : 'member'}${borders.has(m) ? ' (they stay there this turn)' : ''}.`);
743
+ deploy(m, left);
744
+ // Armies deployed from a pool to defend its border are never moved out the same turn.
745
+ if (borders.has(m)) {
746
+ locked.add(m);
747
+ poolDeployed.set(m, (poolDeployed.get(m) ?? 0) + left);
748
+ }
749
+ }
750
+ }
751
+ if (ps.budget > 0) {
752
+ // Unreachable: the leftover deploy filled `where` to its exact room, so no anywhere
753
+ // armies remain, and each pool's unused room (from one maximum charge) went inside
754
+ // it. Never leave income undeployed — but say the plan breaks the pools.
755
+ warnings.push(`Local Deployment: ${ps.budget} armies could not be placed within the pools; they go to ${label(where)}, which breaks Local Deployment — war.app may refuse this turn.`);
756
+ deploy(where, ps.budget);
757
+ }
758
+ }
759
+ return { strikeStack, poolDeployed, staging };
760
+ }