@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,651 @@
1
+ import { analyzeBonus, bonusTerritories } from '../bonuses.js';
2
+ import { straightKills } from '../combat.js';
3
+ import { bfsDistances, neighborsOf } from '../graph.js';
4
+ import { DEFENSE_DISCOUNT, HIDDEN_POOL_INCOMES, NEUTRAL_BORDER_COST, ownerShown, TRACKED_MIN_TURNS, visibleState, WASTELAND_FACTOR, } from './shared.js';
5
+ import { teammateAt } from './state.js';
6
+ import { byNum } from './util.js';
7
+ import { denialsOf, emptyEnemiesOf } from './vacated.js';
8
+ /** The targets, the frontier costs and the bonus plans, in the order planPass defined them. */
9
+ export function targetsPhase(pc, ps, input, threats, hd) {
10
+ const c0 = breakTargets(pc, input);
11
+ const c1 = { ...c0, ...captureTargets(pc, ps, input, threats, c0) };
12
+ const c2 = { ...c1, ...frontierCosts(pc, threats, hd, c1) };
13
+ const c3 = { ...c2, ...bonusScoring(pc, ps, threats, c2) };
14
+ const c4 = { ...c3, ...closestBonus(pc, ps, input, c3) };
15
+ // #281: the vacated land worth denying and (the owner's extension) the empty enemy territories
16
+ // pass 3 may take, each judged once on the board as it stands.
17
+ const denials = denialsOf(pc);
18
+ const emptyEnemies = emptyEnemiesOf(pc, input.previousBoard, threats.reinforcementAt, (t) => c4.targets.has(t) || c4.repulsed.has(t) || pc.truce.noTarget(t));
19
+ return { ...c4, denials, emptyEnemies };
20
+ }
21
+ /** The enemy bonuses I could break and the counter-attacks (under `balanced`, #72). */
22
+ export function breakTargets(pc, input) {
23
+ const { g, me, foe, balanced, territories: state, mineSet, unitsAt, costAt } = pc;
24
+ // ---- enemy bonuses I could break (under `balanced`) ----
25
+ // A bonus is breakable when every territory in it is visible and held by one enemy, or (#72)
26
+ // when the opponent tracker infers it behind the fog: its track (over at least
27
+ // TRACKED_MIN_TURNS observed turns) lists it in every combination of bonuses that fits the
28
+ // opponent's income gap (all of them listed), or in its single best fit (the first listed, with
29
+ // fewer bonuses than the next), and on this board every member
30
+ // is that opponent's or hidden. Such a break is "probable".
31
+ const breakable = [];
32
+ const breakMember = new Set();
33
+ if (balanced) {
34
+ for (const b of [...g.map.bonuses].sort((x, y) => x.id - y.id)) {
35
+ const ts = bonusTerritories(g, b.id);
36
+ if (b.value <= 0 || !ts.length)
37
+ continue;
38
+ const owners = new Set();
39
+ let visible = true;
40
+ for (const t of ts) {
41
+ const st = state.get(t);
42
+ if (st?.owner.kind !== 'player' || !foe(st.owner.playerId) || st.armies === null)
43
+ visible = false;
44
+ else
45
+ owners.add(st.owner.playerId);
46
+ }
47
+ if (visible && owners.size === 1) {
48
+ breakable.push({ bonusId: b.id, value: b.value, player: [...owners][0] });
49
+ for (const t of ts)
50
+ breakMember.add(t);
51
+ continue;
52
+ }
53
+ // Inferred (#72): one opponent's visible members, the rest hidden, and its track fits it.
54
+ if (owners.size !== 1)
55
+ continue;
56
+ const player = [...owners][0];
57
+ const hiddenOrTheirs = ts.every((t) => {
58
+ const st = ownerShown(state.get(t));
59
+ return st === undefined || (st.owner.kind === 'player' && st.owner.playerId === player);
60
+ });
61
+ if (!hiddenOrTheirs)
62
+ continue;
63
+ const tr = input.tracks?.find((x) => x.playerId === player);
64
+ const fits = tr && tr.income !== null && tr.turns.length >= TRACKED_MIN_TURNS ? tr.inferred?.candidates : undefined;
65
+ if (!fits?.length)
66
+ continue;
67
+ // "Every" only when the tracker listed every fit (no "and N more"). The best fit must be
68
+ // strictly smaller than the next: equal-sized fits are ordered only by bonus id.
69
+ const more = tr.inferred.more;
70
+ const inEvery = more === 0 && fits.every((c) => c.bonusIds.includes(b.id));
71
+ const single = fits.length === 1 && more === 0;
72
+ const inBest = fits[0].bonusIds.includes(b.id) && (single || (fits[1] !== undefined && fits[0].bonusIds.length < fits[1].bonusIds.length));
73
+ if (!inEvery && !inBest)
74
+ continue;
75
+ breakable.push({
76
+ bonusId: b.id,
77
+ value: b.value,
78
+ player,
79
+ probable: inEvery
80
+ ? 'in every combination of bonuses that fits its income gap'
81
+ : 'in the best fit of its income gap',
82
+ });
83
+ for (const t of ts)
84
+ breakMember.add(t);
85
+ }
86
+ }
87
+ // ---- counter-attacks (under `balanced`, #72) ----
88
+ // An enemy stack next to me that shrank since the previous board by attacking me: visible on
89
+ // both boards under the same owner (F1, #69), every neighbour visible on both, one of them a
90
+ // territory I held on both, every neighbour that was neither mine nor its owner's unchanged in
91
+ // owner and armies (else it may have expanded or hit a third player), and the shrink not
92
+ // absorbed by its own neighbours' growth (a transfer). The boards cannot tell its attack on me
93
+ // from my failed attack on it (both shrink it next to me), so the rationale says "fighting me":
94
+ // either way it is cheaper to take now. When it is now cheaper to take than it was, it is a strike candidate scored like
95
+ // a break (rule 4a). A member of a breakable bonus is a break instead.
96
+ const counterAt = new Map();
97
+ if (balanced && input.previousBoard) {
98
+ const before = new Map(input.previousBoard.territories.map((t) => [t.territoryId, t]));
99
+ const heldBy = (st, p) => st?.owner.kind === 'player' && st.owner.playerId === p;
100
+ for (const [id, st] of [...state].sort((a, b) => a[0] - b[0])) {
101
+ if (st.owner.kind !== 'player' || !foe(st.owner.playerId) || st.armies === null || breakMember.has(id))
102
+ continue;
103
+ const p = st.owner.playerId;
104
+ const ns = neighborsOf(g, id);
105
+ if (!ns.some((n) => mineSet.has(n)))
106
+ continue;
107
+ const was = visibleState(before.get(id));
108
+ if (!heldBy(was, p) || was.armies <= st.armies)
109
+ continue;
110
+ if (!ns.every((n) => visibleState(state.get(n)) && visibleState(before.get(n))))
111
+ continue;
112
+ if (!ns.some((n) => mineSet.has(n) && heldBy(before.get(n), me)))
113
+ continue;
114
+ // Pinned on me: every neighbour that was neither mine nor theirs keeps its owner and armies.
115
+ // A neutral it took (an expansion) or a third player it hit could have spent the shrink.
116
+ const elsewhere = ns.some((n) => {
117
+ const a = state.get(n);
118
+ const b = before.get(n);
119
+ if (heldBy(b, me) || heldBy(b, p))
120
+ return false;
121
+ const owner = (x) => (x.owner.kind === 'player' ? x.owner.playerId : x.owner.kind);
122
+ return owner(a) !== owner(b) || a.armies !== b.armies;
123
+ });
124
+ if (elsewhere)
125
+ continue;
126
+ const absorbed = ns.reduce((sum, n) => {
127
+ const a = state.get(n);
128
+ const b = before.get(n);
129
+ return heldBy(a, p) && heldBy(b, p) ? sum + Math.max(0, a.armies - b.armies) : sum;
130
+ }, 0);
131
+ if (was.armies - st.armies <= absorbed)
132
+ continue;
133
+ const costNow = costAt(id);
134
+ const costThen = costAt(id, was.armies + unitsAt(id));
135
+ if (costNow === null || costThen === null || costNow >= costThen)
136
+ continue;
137
+ counterAt.set(id, { player: p, from: was.armies, to: st.armies, costNow, costThen });
138
+ }
139
+ }
140
+ return { breakable, breakMember, counterAt };
141
+ }
142
+ /** Rule 2: the targets next to mine, and the lead steps into a bonus on an army lead (#203). */
143
+ export function captureTargets(pc, ps, input, threats, prev) {
144
+ const { g, foe, profile, auto, goal, balanced, territories: state, label, mineSet, unitsAt, uncounted, uncountedKind, defenceAt, bonusTs, costAt, noSplit, leadLever, leadText, } = pc;
145
+ const { warnings, rationale } = ps;
146
+ const { reinforcementAt, hiddenFoe, hiddenMovable, hiddenPool } = threats;
147
+ const { breakMember, counterAt } = prev;
148
+ // ---- 2. targets ----
149
+ const targets = new Map();
150
+ /**
151
+ * #240: territories my attacks failed on repeatedly while their owner reinforced them
152
+ * (`input.repulsed`, {@link repulsedAttacks}): still that opponent's, armies in view, next to mine,
153
+ * its owner able to deploy there. Every capture of one is sized for its defenders plus that deploy
154
+ * (#120's sure sizing) — #272: or plus the most its owner reinforced it on those failed turns, when less — and is not made when that size does not fit; a rationale line names the
155
+ * failed turns. #240 review: its target keeps its plain cost, so every ranking (the bonus passes,
156
+ * breaks and counter-attacks, rule 4e's fallback) treats it as the plan without the evidence does
157
+ * — the sure size only decides whether it fits and what is sent ({@link sizeOf}). Ranked on the sure
158
+ * size, a target that fitted dropped behind a worse one (under No-Split the whole stack went anyway).
159
+ */
160
+ /**
161
+ * `sure` (#272 review): `extra` is the owner's whole deploy estimate, so the capture lands even if it
162
+ * deploys there first — a worst case (no "assumes" warning; rule 6 counts the target as held). False
163
+ * when the most it reinforced it by is below the estimate: the attack is sized for that, but a larger
164
+ * deploy can still repel it, so it is no worst case and is judged like any other attack on a player.
165
+ */
166
+ const repulsed = new Map();
167
+ for (const r of input.repulsed ?? []) {
168
+ const t = r.territoryId;
169
+ const st = state.get(t);
170
+ if (st?.owner.kind !== 'player' || st.owner.playerId !== r.playerId || !foe(r.playerId) || st.armies === null)
171
+ continue;
172
+ if (uncounted(t) || !neighborsOf(g, t).some((n) => mineSet.has(n)))
173
+ continue;
174
+ const defenders = defenceAt(t);
175
+ const estimate = reinforcementAt(t);
176
+ // #272: sized for what its owner actually put there on those failed turns (after + my kills −
177
+ // before; a transfer in counts), the most of them, never above its deploy estimate. Live, an
178
+ // owner that had reinforced by 4 and 3 was sized for its ~29 deploy (95 armies) and not attacked;
179
+ // a two-step of 14 then 24 took it next turn against 5.
180
+ const seen = Math.max(...r.attacks.map((a) => a.after + a.kills - a.before));
181
+ const extra = Math.min(estimate, seen);
182
+ const cost = costAt(t, defenders + extra);
183
+ if (extra <= 0 || cost === null)
184
+ continue;
185
+ repulsed.set(t, { player: r.playerId, defenders, extra, cost, sure: extra >= estimate });
186
+ const turns = r.attacks.map((a) => a.turn);
187
+ const listed = turns.length > 1 ? `${turns.slice(0, -1).join(', ')} and ${turns[turns.length - 1]}` : `${turns[0]}`;
188
+ const size = extra < estimate
189
+ ? `the most it reinforced it by on those turns, ~${extra}, below its owner's ~${estimate} deploy estimate (${defenders} + ${extra} defenders, ${cost} armies: a larger deploy there can still repel it, so it is no sure capture), or not made (#240, #272)`
190
+ : `its owner's ~${extra} deploy there (${defenders} + ${extra} defenders, ${cost} armies), or not made (#240)`;
191
+ rationale.push(`My attacks on ${label(t)} failed on turns ${listed}, player ${r.playerId} reinforcing it each time (${r.attacks
192
+ .map((a) => `${a.armies} against ${a.before}, ${a.after} after`)
193
+ .join('; ')}): a further attack is sized for ${size}.`);
194
+ }
195
+ /** A capture's cost of `t` (its ordinary sizing), or #240's sure one for a repulsed territory. */
196
+ const costFor = (t) => repulsed.get(t)?.cost ?? costAt(t);
197
+ /**
198
+ * #240 review: what a capture of target `t` must send — its cost, or a repulsed territory's sure
199
+ * size. Fit checks use it; rankings use the target's cost. `cost`: the target's cost when it may
200
+ * no longer be a target (rule 4e drops the enemy targets it added and did not take).
201
+ */
202
+ const sizeOf = (t, cost) => repulsed.get(t)?.cost ?? cost ?? targets.get(t).cost;
203
+ /**
204
+ * #203: adapting in a free-for-all on a big army lead (the lead strikes' conditions, #167), an
205
+ * enemy member of a positive bonus next to mine (no special unit on it) is a step into that bonus
206
+ * like a neutral one — sized like a lead strike (its defenders plus what its owner may deploy
207
+ * there first), so the bonus passes fund it from this turn's deploy in rule 4f's order, under the
208
+ * Local Deployment pools. Left to the lead strikes, which run once the income is spent, the
209
+ * closest bonus's enemy member lost its deploy to a farther bonus's step.
210
+ */
211
+ const leadSteps = new Map();
212
+ const leadStepsOn = auto && balanced && profile.format === 'ffa' && profile.opponents >= 2 && leadLever && !noSplit;
213
+ const leadTry = new Map();
214
+ /**
215
+ * #203: a lead step's capture reason names it, in every bonus pass that takes it. #214: `sure`
216
+ * given, the step was retried at its bare cost (the sure one could not be funded): the note says
217
+ * what it is sized for, and what would be sure.
218
+ */
219
+ const leadNote = (t, sure) => {
220
+ const lead = leadSteps.get(t);
221
+ if (!lead)
222
+ return '';
223
+ const head = ` — player ${lead.player}'s member, taken on my army lead (${leadText()}): `;
224
+ return sure === undefined
225
+ ? `${head}sure even if player ${lead.player} deploys its ~${lead.extra} there first (${lead.defenders} + ${lead.extra} defenders)`
226
+ : `${head}sized for the ${lead.defenders} defenders there now: ${sure} would be sure even if player ${lead.player} deploys its ~${lead.extra} there first, more than this turn can fund (#214)`;
227
+ };
228
+ for (const t of [...g.territoryById.keys()].sort(byNum)) {
229
+ if (mineSet.has(t))
230
+ continue;
231
+ const sources = neighborsOf(g, t).filter((n) => mineSet.has(n));
232
+ if (!sources.length)
233
+ continue;
234
+ const st = state.get(t);
235
+ const hiddenOwner = hiddenFoe(t);
236
+ if (hiddenOwner !== undefined) {
237
+ // #164: Dense / Heavy fog shows the owner and hides the armies.
238
+ const tr = input.tracks?.find((x) => x.playerId === hiddenOwner);
239
+ const pool = hiddenPool(hiddenOwner);
240
+ const capped = pool.cap !== null && pool.unexplained > pool.cap;
241
+ const bound = tr && tr.unexplained !== null
242
+ ? `up to ${hiddenMovable(hiddenOwner)} armies there (player ${hiddenOwner}'s unaccounted armies from the tracker${capped
243
+ ? `, ${pool.unexplained} in all, at most ${HIDDEN_POOL_INCOMES} turns of its income in one place: the rest is taken as spread over its hidden territories, and a larger bank there would not show`
244
+ : ''}, counted once per border however many of its hidden territories touch it) beyond the guard`
245
+ : 'the guard alone there (no tracker figure for its unaccounted armies)';
246
+ warnings.push(`${label(t)} (player ${hiddenOwner}) borders my ${sources.map(label).join(', ')} and its armies are hidden by the fog: the threat from it counts ${bound} plus its deploy, and the win chance of an attack into it is unknown, so none is planned.`);
247
+ continue;
248
+ }
249
+ if (!st || st.owner.kind === 'unknown' || st.armies === null) {
250
+ warnings.push(`Fogged territory ${label(t)} borders my ${sources.map(label).join(', ')}: its armies are unknown (fog), so no attack is planned.`);
251
+ continue;
252
+ }
253
+ if (st.owner.kind === 'available')
254
+ continue;
255
+ // A teammate's territory is never a target (#128), nor a truce's covered territory (B2, T1).
256
+ if (st.owner.kind === 'player' && (!foe(st.owner.playerId) || pc.truce.noTarget(t)))
257
+ continue;
258
+ if (uncounted(t)) {
259
+ warnings.push(`${label(t)} holds ${uncountedKind(t)}, whose strength the board does not carry: its defence is unknown, so no attack is planned on it.`);
260
+ continue;
261
+ }
262
+ const enemy = st.owner.kind === 'player';
263
+ if (enemy && goal !== 'complete-bonus' && !(balanced && (breakMember.has(t) || counterAt.has(t)))) {
264
+ if (!leadStepsOn || unitsAt(t) > 0 || !g.map.bonuses.some((b) => b.value > 0 && bonusTs.get(b.id).includes(t)))
265
+ continue;
266
+ const defenders = defenceAt(t);
267
+ const extra = reinforcementAt(t);
268
+ const sure = costAt(t, defenders + extra);
269
+ if (sure === null)
270
+ continue;
271
+ leadSteps.set(t, { player: st.owner.playerId, defenders, extra });
272
+ targets.set(t, { id: t, cost: sure, enemy, sources });
273
+ continue;
274
+ }
275
+ // #240 review: a repulsed territory too ranks on its plain cost (its sure size is sent: sizeOf).
276
+ const cost = costAt(t);
277
+ if (cost === null)
278
+ continue;
279
+ targets.set(t, { id: t, cost, enemy, sources });
280
+ }
281
+ // Bonus passes work toward my own bonuses; under `balanced` enemy targets are only break candidates.
282
+ // #203: a lead step is a bonus target too.
283
+ const bonusTarget = (t) => targets.has(t) && !(balanced && targets.get(t).enemy && !leadSteps.has(t));
284
+ return { targets, leadSteps, leadStepsOn, leadTry, leadNote, bonusTarget, repulsed, costFor, sizeOf };
285
+ }
286
+ /** Rule 4d: what a capture adds to the frontier (#71), and the offence report (#72). */
287
+ export function frontierCosts(pc, threats, hd, prev) {
288
+ const { g, guarded, mineSet, armiesOf, unitsAt, defenceAt, rates } = pc;
289
+ const { holdArmies, nextTurnAt } = threats;
290
+ const { conceded, stood } = hd;
291
+ const { targets } = prev;
292
+ // ---- 4d. frontier cost (#71) ----
293
+ /** Armies a capture of `t` leaves there: its attack's survivors. */
294
+ const survivorsOf = (t) => targets.get(t).cost - Math.round((defenceAt(t) * rates.defensiveKillRate) / 100);
295
+ /**
296
+ * `x` as a border when I hold `held` with `have` armies on it: a border when a neighbour is not
297
+ * held; facing an enemy when a visible enemy is next to it, and then `need` is the deploys it
298
+ * needs next turn to hold (the R3 arithmetic: threat = movable + max(deploy, growth) per player).
299
+ */
300
+ const borderOf = (x, held, have) => {
301
+ if (neighborsOf(g, x).every((n) => held.has(n)))
302
+ return { border: false, enemy: false, need: 0 };
303
+ // G2: next turn's threat — a player a Diplomacy card shields me from only this turn counts.
304
+ const th = nextTurnAt(x, (n) => held.has(n));
305
+ if (!th)
306
+ return { border: true, enemy: false, need: 0 };
307
+ const units = mineSet.has(x) ? unitsAt(x) : 0;
308
+ return { border: true, enemy: true, need: Math.max(0, holdArmies(th.threat) - have - units) };
309
+ };
310
+ /**
311
+ * A border's cost in armies: {@link NEUTRAL_BORDER_COST}, plus its hold need when it faces an
312
+ * enemy under a guarded goal (`expand` and `complete-bonus` ignore defence, as in R3).
313
+ */
314
+ const borderCost = (b, withNeed = true) => b.border ? NEUTRAL_BORDER_COST + (guarded && withNeed ? b.need : 0) : 0;
315
+ /**
316
+ * The marginal frontier of adding `adds` to `base` (#71), in armies: the cost of every border
317
+ * the capture touches after it (the captures and their held neighbours) minus their cost
318
+ * before. Borders it opens add, borders it closes (a neighbour whose last outside neighbour it
319
+ * takes) subtract. `haveOf` gives the armies on each territory (a capture: its survivors).
320
+ * `needOnAdds` false leaves the captures' own hold need out (R3's defence cost already counts it).
321
+ */
322
+ const frontierDelta = (base, adds, haveOf, needOnAdds = true) => {
323
+ const after = new Set([...base, ...adds]);
324
+ const touched = new Set(adds);
325
+ for (const t of adds)
326
+ for (const n of neighborsOf(g, t))
327
+ if (base.has(n))
328
+ touched.add(n);
329
+ let armies = 0;
330
+ let enemy = 0;
331
+ for (const x of touched) {
332
+ const now = borderOf(x, after, haveOf(x));
333
+ armies += borderCost(now, needOnAdds || base.has(x));
334
+ enemy += Number(now.enemy);
335
+ if (!base.has(x))
336
+ continue;
337
+ const was = borderOf(x, base, haveOf(x));
338
+ armies -= borderCost(was);
339
+ enemy -= Number(was.enemy);
340
+ }
341
+ return { armies, enemy };
342
+ };
343
+ /** Each target's frontier cost captured alone from my holdings at the start of the turn. */
344
+ const edgeCost = new Map([...targets.keys()].map((t) => [t, frontierDelta(mineSet, [t], (x) => (x === t ? survivorsOf(t) : armiesOf(x))).armies]));
345
+ /** A capture's cost in a score: its armies plus its frontier, at least one army (a cost of 0 stays 0). */
346
+ const scoreCost = (cost, frontier) => (cost > 0 ? Math.max(1, cost + frontier) : 0);
347
+ /** A target's cost in a score: its capture cost plus the frontier it adds alone. */
348
+ const targetScoreCost = (t) => scoreCost(targets.get(t).cost, edgeCost.get(t));
349
+ /**
350
+ * A break's or counter-attack's cost in a score (#72): it only has to land, not survive the
351
+ * counter-attack, so the captured territory's own hold need is left out. The rest of the
352
+ * frontier change stays: its border weight, and my borders around it (the threat it removes).
353
+ */
354
+ const landScoreCost = (t) => scoreCost(targets.get(t).cost, frontierDelta(mineSet, [t], (x) => (x === t ? survivorsOf(t) : armiesOf(x)), false).armies);
355
+ // ---- offence report (#72) ----
356
+ /** The offensive options considered, by kind and target, in the order they were found. */
357
+ const offence = new Map();
358
+ /** Why an offensive capture was not made, by target (the first reason wins). */
359
+ const offenceSkip = new Map();
360
+ const skipOffence = (t, why) => {
361
+ if (!offenceSkip.has(t))
362
+ offenceSkip.set(t, why);
363
+ };
364
+ /** Captures of a player's territory refused as a trade below even (rule 0p.3), by target. */
365
+ const badTrades = new Map();
366
+ /**
367
+ * The frontier when I hold `held`: borders, those facing an enemy, and the deploys they need next
368
+ * turn to hold. A conceded border counts as a border but not in the hold cost: the plan gives it
369
+ * up rather than pay for it (a garrison that still stands, #59, is held and counts).
370
+ */
371
+ const frontierOf = (held, haveOf) => {
372
+ let borders = 0;
373
+ let enemyBorders = 0;
374
+ let holdCost = 0;
375
+ for (const x of [...held].sort(byNum)) {
376
+ const b = borderOf(x, held, haveOf(x));
377
+ borders += Number(b.border);
378
+ enemyBorders += Number(b.enemy);
379
+ if (!conceded.has(x) || stood.has(x))
380
+ holdCost += b.need;
381
+ }
382
+ return { borders, enemyBorders, holdCost };
383
+ };
384
+ /** The frontier's hold cost at the start of the turn (my armies then; today's concessions left out). */
385
+ const startHold = () => frontierOf(mineSet, armiesOf).holdCost;
386
+ return { survivorsOf, borderOf, borderCost, frontierDelta, edgeCost, scoreCost, targetScoreCost, landScoreCost, offence, offenceSkip, skipOffence, badTrades, frontierOf, startHold };
387
+ }
388
+ /** Bonus scoring (rule 4, R3, #70, #101, #125, #167): the bonuses worth working toward, best first. */
389
+ export function bonusScoring(pc, ps, threats, prev) {
390
+ const { g, s, opts, guarded, focus, paybackTurns, territories: state, label, mineSet, armiesOf, defenceAt, completedOver, territoryShare, rates, costOf, costAt, econCostAt, } = pc;
391
+ const { rationale } = ps;
392
+ const { exposure } = threats;
393
+ const { targets, bonusTarget, survivorsOf, frontierDelta, scoreCost } = prev;
394
+ // ---- bonus scoring ----
395
+ /** "N armies to finish", naming the fogged members counted in it (#101). */
396
+ const fogNote = (fogged, each) => fogged ? ` (${fogged} fogged member${fogged === 1 ? '' : 's'} counted at ${each} each)` : '';
397
+ const toFinish = (cost, fogged, each) => `${cost} armies to finish${fogNote(fogged, each)}`;
398
+ const plans = [];
399
+ /** #167: the share of the map's territories that started as wastelands, and what one costs to take and loses. */
400
+ const wasteShare = s.wastelands && s.wastelands.count > 0 && s.wastelands.size > 0 && g.territoryById.size > 0
401
+ ? Math.min(1, s.wastelands.count / g.territoryById.size)
402
+ : 0;
403
+ const wasteCost = wasteShare > 0 ? (costOf(s.wastelands.size) ?? Infinity) : 0;
404
+ const wasteLoss = wasteShare > 0 ? Math.min(wasteCost - 1, straightKills(s.wastelands.size, rates.defensiveKillRate)) + 1 : 0;
405
+ /** Every positive bonus worth completing (net > 0) still missing members: its armies to finish (rule 4e). */
406
+ const finishCost = new Map();
407
+ const economicMember = new Set();
408
+ const uneconomicMember = new Set();
409
+ /** Missing members of a negative bonus (not focused): plain expansion never steps into one. */
410
+ const negativeMember = new Set();
411
+ /** #201: a remembered neutral's rationale line (its index) and the bonuses it names. */
412
+ const rememberedSaid = new Map();
413
+ for (const b of [...g.map.bonuses].sort((x, y) => x.id - y.id)) {
414
+ const isFocus = focus.has(b.id);
415
+ const ts = bonusTerritories(g, b.id);
416
+ const remaining = ts.filter((t) => !mineSet.has(t));
417
+ if (b.value < 0 && !isFocus) {
418
+ // Completing it would cut income: never plan into it (an economic
419
+ // membership elsewhere still wins — see the pass-3 filter).
420
+ for (const t of remaining) {
421
+ uneconomicMember.add(t);
422
+ negativeMember.add(t);
423
+ }
424
+ continue;
425
+ }
426
+ if (b.value <= 0 && !isFocus)
427
+ continue;
428
+ if (!remaining.length)
429
+ continue;
430
+ // PLAN-TEAMS C3.3: a bonus pays only the player holding every member, so one with a member my
431
+ // teammate visibly holds is not mine to complete (plan/team.ts reports the shared ones).
432
+ const mates = remaining.filter((t) => teammateAt(pc, t));
433
+ if (mates.length) {
434
+ if (remaining.some(bonusTarget) || isFocus)
435
+ rationale.push(`Skip bonus ${b.name} (#${b.id}): my teammate holds ${mates.map(label).join(', ')}, and a bonus pays only the player holding all of it.`);
436
+ if (isFocus)
437
+ ps.warnings.push(`Focus on bonus ${b.name} (#${b.id}) ignored: my teammate holds ${mates.map(label).join(', ')} (one owner per bonus).`);
438
+ continue;
439
+ }
440
+ // Cluster as a unit (#70): the negative bonuses its missing members complete come off its
441
+ // worth (on a map without negative bonuses, net = value).
442
+ const rest = new Set(remaining);
443
+ const penalties = completedOver((x) => mineSet.has(x) || rest.has(x), remaining).filter((id) => id !== b.id && g.bonusById.get(id).value < 0);
444
+ const penalty = penalties.reduce((n, id) => n + g.bonusById.get(id).value, 0);
445
+ // #125: its missing members' per-territory income (Extra Armies for Territories) is income too.
446
+ const perGain = territoryShare(remaining.length);
447
+ const net = b.value + penalty + perGain;
448
+ if (penalty < 0 && remaining.some(bonusTarget))
449
+ rationale.push(`Bonus ${b.name} (#${b.id}) (+${b.value}) is worth +${net} net once complete: its missing members also complete ${penalties.length} negative bonus${penalties.length === 1 ? '' : 'es'} (${penalty}), and each step short of completion only adds penalties.`);
450
+ if (net <= 0 && !isFocus) {
451
+ for (const t of remaining)
452
+ uneconomicMember.add(t);
453
+ if (remaining.some(bonusTarget))
454
+ rationale.push(`Skip bonus ${b.name} (#${b.id}): completing it costs more income than it pays (net ${net}).`);
455
+ continue;
456
+ }
457
+ // Armies to finish (#101): every missing member's capture cost. A fogged member counts at its
458
+ // bonus's costliest visible missing member (it cannot be costed, and counting it as free made
459
+ // the figure jump when it came into view); with none visible, the bonus cannot be costed.
460
+ let cost = 0;
461
+ let worst = 0;
462
+ let fogged = 0;
463
+ // #125: the economy test charges the armies lost, not the armies sent.
464
+ let loss = 0;
465
+ let worstLoss = 0;
466
+ for (const t of remaining) {
467
+ const st = state.get(t);
468
+ if (!st || st.owner.kind === 'unknown' || st.armies === null) {
469
+ // #201: a neutral the picking board showed keeps its size (an owner the fog shows is not one).
470
+ const was = opts.rememberedNeutrals?.get(t);
471
+ if (was === undefined || (st && st.owner.kind === 'player')) {
472
+ fogged++;
473
+ continue;
474
+ }
475
+ const c = costAt(t, was) ?? Infinity;
476
+ cost += c;
477
+ worst = Math.max(worst, c);
478
+ const l = Math.min(c - 1, straightKills(was, rates.defensiveKillRate)) + 1;
479
+ loss += l;
480
+ worstLoss = Math.max(worstLoss, l);
481
+ if (remaining.some(bonusTarget)) {
482
+ // Said once per territory, naming every bonus it is costed in.
483
+ const said = rememberedSaid.get(t);
484
+ const tail = `${label(t)}, fogged now, was a neutral of ${was} on the picking board (#201): costed at that.`;
485
+ if (said) {
486
+ said.bonuses.push(`${b.name} (#${b.id})`);
487
+ rationale[said.at] = `${said.bonuses.join(', ')}: ${tail}`;
488
+ }
489
+ else {
490
+ rememberedSaid.set(t, { at: rationale.length, bonuses: [`${b.name} (#${b.id})`] });
491
+ rationale.push(`${b.name} (#${b.id}): ${tail}`);
492
+ }
493
+ }
494
+ continue;
495
+ }
496
+ const c = costAt(t) ?? Infinity;
497
+ cost += c;
498
+ worst = Math.max(worst, c);
499
+ const l = econCostAt(t);
500
+ loss += l;
501
+ worstLoss = Math.max(worstLoss, l);
502
+ }
503
+ let fogEach = fogged ? (fogged < remaining.length ? worst : Infinity) : 0;
504
+ let fogLoss = fogged ? (fogged < remaining.length ? worstLoss : Infinity) : 0;
505
+ // #167: with automatic Wastelands, a fogged member may be one: its expected surcharge over an
506
+ // ordinary member is (wastelands ÷ territories on the map) × (a wasteland's cost − this one's).
507
+ if (wasteShare > 0 && fogged && Number.isFinite(fogEach)) {
508
+ const extra = Math.ceil(wasteShare * Math.max(0, wasteCost - fogEach));
509
+ const extraLoss = Math.ceil(wasteShare * Math.max(0, wasteLoss - fogLoss));
510
+ if (extra > 0) {
511
+ fogEach += extra;
512
+ fogLoss += extraLoss;
513
+ if (remaining.some(bonusTarget))
514
+ rationale.push(`${b.name} (#${b.id}): its ${fogged} fogged member${fogged === 1 ? '' : 's'} may be ${fogged === 1 ? 'a wasteland' : 'wastelands'} (${s.wastelands.count} of the map's ${g.territoryById.size} territories start at ${s.wastelands.size}): +${extra * fogged} armies expected.`);
515
+ }
516
+ }
517
+ cost += fogged * fogEach;
518
+ loss += fogged * fogLoss;
519
+ if (b.value > 0)
520
+ finishCost.set(b.id, { cost, value: b.value, net, fogged, fogEach });
521
+ const economic = isFocus || (loss <= paybackTurns * net && worstLoss <= WASTELAND_FACTOR * net);
522
+ for (const t of remaining)
523
+ (economic ? economicMember : uneconomicMember).add(t);
524
+ if (!remaining.some(bonusTarget))
525
+ continue;
526
+ if (!economic) {
527
+ rationale.push(`Skip bonus ${b.name} (#${b.id}): uneconomic for +${net === b.value ? b.value : `${b.value} (net +${net})`} (${toFinish(cost, fogged, fogEach)}, losing ~${loss}; ${worstLoss} lost on its costliest territory).`);
528
+ continue;
529
+ }
530
+ // R3: what holding the completed bonus's frontier would cost next turn (each
531
+ // remaining member holding the survivors of its capture, mine their armies now).
532
+ let defenseCost = 0;
533
+ if (guarded && remaining.every(bonusTarget)) {
534
+ const rem = new Set(remaining);
535
+ const exposed = exposure(ts, (n) => rem.has(n), (m) => {
536
+ if (!rem.has(m))
537
+ return armiesOf(m);
538
+ const c = targets.get(m).cost;
539
+ return c - straightKills(defenceAt(m), rates.defensiveKillRate);
540
+ });
541
+ defenseCost = exposed.reduce((sum, e) => sum + e.need, 0);
542
+ if (defenseCost > 0)
543
+ rationale.push(`Bonus ${b.name} (#${b.id}) needs ~${defenseCost} more armies next turn to hold its frontier once completed (${exposed.map((e) => `${label(e.id)} ${e.need}`).join(', ')}): its score is +${b.value} / (${cost} + ${DEFENSE_DISCOUNT} × ${defenseCost}).`);
544
+ }
545
+ // #71: the frontier its missing members add (their hold need left out when R3 judged it).
546
+ const reach = remaining.filter((t) => targets.has(t));
547
+ const frontier = frontierDelta(mineSet, reach, (x) => (mineSet.has(x) ? armiesOf(x) : survivorsOf(x)), !(guarded && remaining.every(bonusTarget))).armies;
548
+ plans.push({
549
+ bonusId: b.id,
550
+ value: b.value,
551
+ focus: isFocus,
552
+ remaining,
553
+ completable: remaining.every(bonusTarget),
554
+ cost,
555
+ borders: analyzeBonus(g, b.id).borderTerritoryIds.length,
556
+ defenseCost,
557
+ net,
558
+ frontier,
559
+ fogged,
560
+ fogEach,
561
+ });
562
+ }
563
+ const ratio = (p) => {
564
+ const cost = scoreCost(p.cost + DEFENSE_DISCOUNT * p.defenseCost, p.frontier);
565
+ return cost > 0 ? p.net / cost : Infinity;
566
+ };
567
+ plans.sort((a, b) => Number(b.focus) - Number(a.focus) || ratio(b) - ratio(a) || a.borders - b.borders || a.bonusId - b.bonusId);
568
+ return { fogNote, toFinish, plans, wasteShare, wasteCost, wasteLoss, finishCost, economicMember, uneconomicMember, negativeMember, rememberedSaid, ratio };
569
+ }
570
+ /** #101: commit to the bonus closest to completion; a break's retake check. */
571
+ export function closestBonus(pc, ps, input, prev) {
572
+ const { g, me, income, profile, territories: state, label, bonusName, mine, mineSet, bonusTs, toTake } = pc;
573
+ const { rationale } = ps;
574
+ const { fogNote, plans } = prev;
575
+ // ---- #101: commit to the closest bonus ----
576
+ // While no bonus is held (and in the opening and expansion phases), expansion goes to the bonus
577
+ // closest to completion — fewest turns to finish at this income (its armies to finish, counting
578
+ // the members I hold, over the income) — then the next closest, instead of one capture into each
579
+ // of several large bonuses by value per army. Bonuses as close as each other keep the score order
580
+ // (value per army, rule 4), except that a bonus advanced last turn (a member captured since
581
+ // `previousBoard`) keeps priority unless another is strictly closer. Focused bonuses come first.
582
+ const holdsBonus = g.map.bonuses.some((b) => {
583
+ const ts = bonusTs.get(b.id);
584
+ return b.value > 0 && ts.length > 0 && ts.every((t) => mineSet.has(t));
585
+ });
586
+ // #132: in an FFA, contact with one front still leaves neutrals to expand into: keep committing
587
+ // while any neutral borders a territory of mine.
588
+ const neutralsInReach = profile.format === 'ffa' && mine.some((t) => neighborsOf(g, t).some((n) => state.get(n)?.owner.kind === 'neutral'));
589
+ const committing = !holdsBonus || profile.phase === 'opening' || profile.phase === 'expansion' || neutralsInReach;
590
+ const advancedLast = new Set();
591
+ if (input.previousBoard) {
592
+ const before = new Map(input.previousBoard.territories.map((t) => [t.territoryId, t]));
593
+ for (const p of plans) {
594
+ const took = bonusTs.get(p.bonusId).some((t) => {
595
+ const o = before.get(t)?.owner;
596
+ return mineSet.has(t) && o !== undefined && o.kind !== 'unknown' && !(o.kind === 'player' && o.playerId === me);
597
+ });
598
+ if (took)
599
+ advancedLast.add(p.bonusId);
600
+ }
601
+ }
602
+ /**
603
+ * #125: the layers a bonus's missing members are reached in — the farthest one's distance from
604
+ * what I hold. A capture's armies attack no further this turn, so a chain takes a turn a layer
605
+ * however cheap its members are.
606
+ */
607
+ const fromMine = bfsDistances(g, mine);
608
+ const depthOf = (p) => Math.max(0, ...p.remaining.map((t) => fromMine.get(t) ?? 0));
609
+ /** Turns to finish a bonus at this income, and at least its depth (with no income, its armies to finish). */
610
+ const turnsOf = (p) => (income > 0 ? Math.max(Math.ceil(p.cost / income), depthOf(p)) : p.cost);
611
+ const scoreRank = new Map(plans.map((p, i) => [p.bonusId, i]));
612
+ /** Bonus plans closest to completion first (focus first; ties: advanced last turn, then the score order). */
613
+ const byCloseness = committing
614
+ ? [...plans].sort((a, b) => Number(b.focus) - Number(a.focus) ||
615
+ turnsOf(a) - turnsOf(b) ||
616
+ Number(advancedLast.has(b.bonusId)) - Number(advancedLast.has(a.bonusId)) ||
617
+ scoreRank.get(a.bonusId) - scoreRank.get(b.bonusId))
618
+ : plans;
619
+ const turnsText = (p) => {
620
+ const n = turnsOf(p);
621
+ const deep = n > Math.ceil(p.cost / income) ? ` (${n} layers deep)` : '';
622
+ return income > 0 ? `${n} turn${n === 1 ? '' : 's'}${deep}` : 'no income';
623
+ };
624
+ if (committing && byCloseness.length > 1) {
625
+ const why = holdsBonus
626
+ ? `${profile.phase[0].toUpperCase()}${profile.phase.slice(1)} phase${profile.phase === 'opening' || profile.phase === 'expansion' ? '' : ', neutrals in reach'}`
627
+ : 'No bonus held';
628
+ rationale.push(`${why}: expansion goes to the bonus closest to completion first — ${byCloseness
629
+ .map((p, i) => `${bonusName(p.bonusId)} ${i ? p.cost : `${p.cost} armies to finish`}${fogNote(p.fogged, p.fogEach)}, ${turnsText(p)}${i || income <= 0 ? '' : ` at income ${income}`}`)
630
+ .join(', ')} — and a farther bonus gets only armies the closer ones cannot use.`);
631
+ const top = byCloseness.find((p) => !p.focus);
632
+ for (const p of byCloseness.filter((x) => advancedLast.has(x.bonusId))) {
633
+ if (p === top)
634
+ rationale.push(`${bonusName(p.bonusId)} keeps priority: I advanced it last turn, and no bonus is strictly closer to completion.`);
635
+ else if (top && !p.focus && turnsOf(top) < turnsOf(p))
636
+ rationale.push(`${bonusName(p.bonusId)}, advanced last turn, gives way to ${bonusName(top.bonusId)}: it is strictly closer to completion (${turnsText(top)} to finish against ${turnsText(p)}).`);
637
+ }
638
+ }
639
+ /**
640
+ * A break's retake check, by its target: the warning it raised (if any) and what it was
641
+ * judged on, so a top-up that adds survivors re-judges it.
642
+ */
643
+ const retakeChecks = new Map();
644
+ const retakeWarning = (t, bonusId, survivors, counter) => {
645
+ const take = toTake(survivors);
646
+ return take !== null && take <= counter
647
+ ? `${label(t)} can be retaken after it breaks ${bonusName(bonusId)}: ${survivors} survivors need ${take} to take, against ~${counter} next turn.`
648
+ : undefined;
649
+ };
650
+ return { holdsBonus, neutralsInReach, committing, advancedLast, fromMine, depthOf, turnsOf, scoreRank, byCloseness, turnsText, retakeChecks, retakeWarning };
651
+ }