@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,1631 @@
1
+ // The holds of a planning pass (#133): which threatened territories of mine to hold and which to
2
+ // concede (rule 1, 1a, 1k), the stacks two steps away (#172), held-bonus units and their floor tier
3
+ // (rule 1h, #51, #118), the withdrawals from conceded borders (rule 1b), the concessions this
4
+ // turn's captures make worth keeping (rule 1c, R2) and the garrisons of bonuses completed this
5
+ // turn (#122). Defined once the threats are read; planPass runs them between the capture passes.
6
+ import { carriesTeam } from '../../teams.js';
7
+ import { bonusTerritories } from '../bonuses.js';
8
+ import { bfsDistances, neighborsOf } from '../graph.js';
9
+ import { chargeDeploys } from '../local-deploy.js';
10
+ import { twoStepReaches } from '../lookahead.js';
11
+ import { BREACH_WEIGHT, CITE_CLOSE, CITE_OPEN, CITE_SEP, CONCEDE_FACTOR, nearMissMargin, } from './shared.js';
12
+ import { capRoom, relaxedFor } from './relations.js';
13
+ import { byNum } from './util.js';
14
+ /** #235: the most territories a cut-off line names. */
15
+ const MAX_CUT_NAMED = 4;
16
+ /**
17
+ * Define the holds of one pass, step by step in planPass's order. Nothing here deploys, moves or
18
+ * says anything yet: planPass runs assessThreats, triage, withdraw, reconsider and
19
+ * garrisonCompleted where the capture passes need them.
20
+ */
21
+ export function holdsPhase(pc, ps, book, threats, pass) {
22
+ const hb = {
23
+ threatened: [], conceded: new Set(), units: [], holds: [], kept: new Set(), garrisoned: new Set(),
24
+ pendingLocks: new Set(), completable: new Map(),
25
+ };
26
+ const h0 = holdBasics(pc, ps, book, threats);
27
+ soloLeaderHolds(pc, ps, book, threats, h0);
28
+ const h1 = { ...h0, ...twoStepHolds(pc, ps, book, threats, hb, pass, h0) };
29
+ const h2 = { ...h1, ...holdOrConcede(pc, ps, book, threats, hb, h1) };
30
+ const h3 = { ...h2, ...heldBonusUnits(pc, ps, book, threats, hb, h2) };
31
+ const h4 = { ...h3, ...floorTier(pc, ps, book, threats, hb, h3) };
32
+ const h5 = { ...h4, ...withdrawals(pc, ps, book, threats, hb, h4) };
33
+ const h6 = { ...h5, ...reconsiderAndGarrison(pc, ps, book, threats, hb, h5) };
34
+ return { ...hb, ...h6 };
35
+ }
36
+ /** Rule 1's threatened borders, rule 1a's economic test, and what stays on or must stay on a territory of mine. */
37
+ export function holdBasics(pc, ps, book, threats) {
38
+ const { profile, unitsAt, myCommanders } = pc;
39
+ const { avail, coverKeep, captured, incoming } = ps;
40
+ const { guardAt } = book;
41
+ const { holdArmies, borderAt } = threats;
42
+ /**
43
+ * Rule 1a's economic test: its hold costs more than CONCEDE_FACTOR × its worth. Never for a
44
+ * border just taken from a weak opponent, nor (#122) in the opening when the hold costs no more
45
+ * than the armies already there — a start is the whole position then, and the top-up saves at
46
+ * least as many as it spends (live, three starts around an enemy start were each stripped for
47
+ * want of 2 armies, and neutrals attacked out of each).
48
+ */
49
+ const uneconomic = (t) => t.recentFrom === undefined &&
50
+ t.holdCost > CONCEDE_FACTOR * t.worth &&
51
+ !(profile.phase === 'opening' && t.holdCost <= t.have);
52
+ /** Armies that stay on my `id` after this turn's deploys, outgoing moves and incoming withdrawals so far. */
53
+ const stayAt = (id) => avail.get(id) + guardAt(id) + (incoming.get(id) ?? 0);
54
+ /**
55
+ * Armies (in `avail` terms) that must stay on my `x` for it to hold against the visible
56
+ * threat next to it (its special units counted; the territories `gone` says fall this turn
57
+ * left out: once taken they threaten nothing); 0 with no enemy next to it. When it cannot
58
+ * hold on what it has: everything on my commander's territory (rule 1k: nothing leaves it),
59
+ * else everything only if `room` deploys would make it hold, and nothing otherwise (triage
60
+ * would concede it, so keeping its armies home saves nothing). Armies withdrawn into it count
61
+ * only when I am known to move first (#215, {@link lateArrivals}).
62
+ */
63
+ const keepFor = (x, gone, room = Infinity) => {
64
+ const a = avail.get(x);
65
+ const covering = Math.max(0, Math.min(a, coverKeep.get(x) ?? 0));
66
+ const b = borderAt(x, (n) => captured.has(n) || gone(n));
67
+ if (!b)
68
+ return covering;
69
+ const need = Math.max(0, holdArmies(b.threat) - unitsAt(x));
70
+ // #215: armies withdrawn into it hold it only if I move first: sized for the worse order.
71
+ const short = need - (stayAt(x) - lateArrivals(pc, ps, x));
72
+ if (short > room && !myCommanders.has(x))
73
+ return covering;
74
+ return Math.max(covering, a - Math.max(0, Math.min(a, -short)));
75
+ };
76
+ return { uneconomic, stayAt, keepFor };
77
+ }
78
+ /**
79
+ * #235: I lead the FFA (#201), so a border is held against every adjacent opponent together — but
80
+ * only while that pays. A border whose joint hold costs more than CONCEDE_FACTOR × its worth (rule
81
+ * 1a's test) or more than the whole income, while its hold against the strongest single opponent
82
+ * passes both, is sized for that opponent instead (`ps.soloHeld`, read by `borderAt`), as in any FFA: two players landing
83
+ * on it in one turn is #128's warning, never the cost that concedes it (live: a 23-stack that held
84
+ * against each neighbour alone was conceded on the two together and withdrawn as the first order).
85
+ * Never my commander's territory (rule 1k holds it against everything). A member of a bonus I hold
86
+ * in full is judged with its bonus, as rule 1h's unit judges it (#235 review): when the unit sized for
87
+ * them together costs more than the income — it can never be held whole, so rule 1h concedes it — while
88
+ * the unit sized for the strongest single opponent pays (within PAYBACK_TURNS × its value and
89
+ * CONCEDE_FACTOR × its worth, and the income), every member that sizing lowers is sized so, unless
90
+ * another bonus I hold that can be held whole on the joint sizing also holds it. #235 review 2: any other
91
+ * held bonus rule 1h does not fund whole up front (it fits the income and pays) may be conceded — another
92
+ * member hopeless, or the captures leaving too little to hold it whole (#118) — and its members then
93
+ * judged alone; so each member it lowers takes the per-border test on its value without that bonus,
94
+ * exactly the judgement it gets with no bonus. Only a member of a bonus funded whole up front keeps
95
+ * #201's joint sizing.
96
+ */
97
+ export function soloLeaderHolds(pc, ps, book, threats, prev) {
98
+ const { g, ffaLeader, paybackTurns, label, bonusName, unitsAt, toTake, myCommanders } = pc;
99
+ const { valueOf, stakeAt, pools } = book;
100
+ const { borders, borderAt, safeAtStart } = threats;
101
+ const { uneconomic, stayAt } = prev;
102
+ if (!ffaLeader)
103
+ return;
104
+ /** A member of a positive bonus I hold in full: rule 1h's units decide it (#51, #118). */
105
+ const inHeldBonus = (t) => g.map.bonuses.some((b) => {
106
+ if (b.value <= 0)
107
+ return false;
108
+ const ts = bonusTerritories(g, b.id);
109
+ return ts.includes(t) && ts.every((x) => ps.holdings.has(x));
110
+ });
111
+ const costFor = (have, threat) => {
112
+ let d = 0;
113
+ while ((toTake(have + d) ?? Infinity) <= threat)
114
+ d++;
115
+ return d;
116
+ };
117
+ /** Size my `id` for its strongest single opponent (`line` says why), as `borderAt` reads it. */
118
+ const soloSize = (id, line) => {
119
+ const have = stayAt(id);
120
+ const units = unitsAt(id);
121
+ ps.soloHeld.set(id, line);
122
+ const solo = borderAt(id, () => false);
123
+ if (solo)
124
+ borders.set(id, solo);
125
+ if ((toTake(have + units) ?? Infinity) > (solo?.threat ?? 0))
126
+ safeAtStart.add(id);
127
+ };
128
+ /**
129
+ * The per-border test: `b` (worth `value`) sized for its strongest single opponent — the line
130
+ * that says so — when its joint hold is dear or above the income while its single hold passes
131
+ * both; null otherwise (one conceded either way, or one that holds jointly, keeps #201's sizing).
132
+ */
133
+ const judgeAlone = (b, value) => {
134
+ if (b.alone === undefined || !b.split)
135
+ return null;
136
+ const have = stayAt(b.id);
137
+ const units = unitsAt(b.id);
138
+ const joint = costFor(have + units, b.threat);
139
+ const single = costFor(have + units, b.alone);
140
+ if (single >= joint)
141
+ return null;
142
+ const worth = value + (have + stakeAt(b.id)) / paybackTurns;
143
+ const recent = threats.recentlyTakenFrom(b.id);
144
+ const judged = (threat, holdCost) => ({
145
+ id: b.id, have, threat, holdCost, value, worth, units, ...(recent !== undefined && recent === b.player ? { recentFrom: recent } : {}),
146
+ });
147
+ const dear = uneconomic(judged(b.threat, joint));
148
+ if (!dear && joint <= ps.budget)
149
+ return null;
150
+ // Only a border the single opponent's hold keeps: one conceded either way keeps #201's sizing.
151
+ if (uneconomic(judged(b.alone, single)) || single > ps.budget)
152
+ return null;
153
+ return `I lead this free-for-all (#201), but holding ${label(b.id)} against players ${b.split.players.join(' and ')} attacking together needs ${joint} (protects +${value}, worth ~${Math.round(worth * 10) / 10}): ${dear ? 'more than CONCEDE_FACTOR × its worth' : `more than the ${ps.budget} I can deploy`}, so it is sized for the strongest single opponent (~${b.alone}), as FFA players attack alone (#235)${single ? `: it needs ${single}` : ': it holds on what it has'}.`;
154
+ };
155
+ for (const b of [...borders.values()].sort((x, y) => x.id - y.id)) {
156
+ if (myCommanders.has(b.id) || inHeldBonus(b.id))
157
+ continue;
158
+ const line = judgeAlone(b, valueOf(b.id));
159
+ if (line)
160
+ soloSize(b.id, line);
161
+ }
162
+ // #235 review: a bonus I hold in full, judged whole as rule 1h's unit judges it.
163
+ const local = pools !== null && pools.bonuses.length > 0;
164
+ /** Each held bonus: its members the single-opponent sizing lowers, and whether its joint unit fits the income. */
165
+ const judged = [];
166
+ /** The line each bonus sized for the strongest single opponent gives its members. */
167
+ const soloLines = new Map();
168
+ for (const bonus of [...g.map.bonuses].sort((x, y) => x.id - y.id)) {
169
+ const ts = bonusTerritories(g, bonus.id);
170
+ if (bonus.value <= 0 || !ts.length || !ts.every((x) => ps.holdings.has(x)))
171
+ continue;
172
+ // Its threatened members, my commander's left out (rule 1k holds it whatever it costs).
173
+ const members = ts.filter((t) => borders.has(t) && !myCommanders.has(t)).sort(byNum);
174
+ if (!members.length)
175
+ continue;
176
+ let joint = 0;
177
+ let single = 0;
178
+ let worth = bonus.value;
179
+ let recent = false;
180
+ const lowered = [];
181
+ for (const t of members) {
182
+ const b = borders.get(t);
183
+ const have = stayAt(t) + unitsAt(t);
184
+ const j = costFor(have, b.threat);
185
+ const one = b.alone !== undefined && b.split ? costFor(have, b.alone) : j;
186
+ joint += j;
187
+ single += one;
188
+ if (one < j)
189
+ lowered.push(t);
190
+ worth += (stayAt(t) + stakeAt(t)) / paybackTurns;
191
+ const from = threats.recentlyTakenFrom(t);
192
+ if (from !== undefined && from === b.player)
193
+ recent = true;
194
+ }
195
+ const pool = local ? (pools.bonuses.find((p) => p.bonusId === bonus.id)?.value ?? 0) : 0;
196
+ const pays = (cost) => {
197
+ const net = Math.max(0, cost - pool);
198
+ return net <= paybackTurns * bonus.value && (recent || net <= CONCEDE_FACTOR * worth) && cost <= ps.budget;
199
+ };
200
+ const fits = joint <= ps.budget;
201
+ // Rule 1h funds it whole up front on the joint sizing: it pays and fits the income.
202
+ const whole = fits && pays(joint);
203
+ judged.push({ bonusId: bonus.id, value: bonus.value, lowered, fits, whole });
204
+ if (!fits && lowered.length && pays(single)) {
205
+ soloLines.set(bonus.id, `I lead this free-for-all (#201), but holding bonus ${bonusName(bonus.id)} (+${bonus.value}) against players attacking together needs ${joint}: more than the ${ps.budget} I can deploy, so its borders are sized for the strongest single opponent, as FFA players attack alone (#235)${single ? `: they need ${single}` : ': they hold on what they have'}.`);
206
+ }
207
+ }
208
+ for (const j of judged) {
209
+ const line = soloLines.get(j.bonusId);
210
+ if (!line)
211
+ continue;
212
+ for (const t of j.lowered) {
213
+ // A border another held bonus can hold whole against them together keeps #201's sizing.
214
+ if (judged.some((o) => o !== j && o.fits && bonusTerritories(g, o.bonusId).includes(t)))
215
+ continue;
216
+ if (!ps.soloHeld.has(t))
217
+ soloSize(t, line);
218
+ }
219
+ }
220
+ // #235 review 2: a bonus neither sized so nor funded whole up front on the joint sizing may be
221
+ // conceded (another member hopeless, or the captures leaving too little), and rule 1h then judges
222
+ // each member alone. So a member it lowers takes the per-border test on its own value, less every
223
+ // such bonus that contains it: exactly the judgement it gets with no bonus, so a held bonus never
224
+ // leaves a border less protected than none. A member of a bonus funded whole keeps #201's sizing.
225
+ for (const j of judged) {
226
+ if (soloLines.has(j.bonusId) || j.whole)
227
+ continue;
228
+ for (const t of j.lowered) {
229
+ if (ps.soloHeld.has(t) || judged.some((o) => o.whole && bonusTerritories(g, o.bonusId).includes(t)))
230
+ continue;
231
+ const lost = judged
232
+ .filter((o) => !soloLines.has(o.bonusId) && bonusTerritories(g, o.bonusId).includes(t))
233
+ .reduce((n, o) => n + o.value, 0);
234
+ const line = judgeAlone(borders.get(t), Math.max(0, valueOf(t) - lost));
235
+ if (line)
236
+ soloSize(t, line);
237
+ }
238
+ }
239
+ }
240
+ /** #172: the holds a stack two steps away asks of a territory worth guarding, and how an order cites them. */
241
+ export function twoStepHolds(pc, ps, book, threats, hb, pass, prev) {
242
+ const { g, board, me, s, opts, income, game: ctx, foe, deployOf, territories: state, label, mineSet, cardArmies, unitsAt, bonusTs, bonusesWith, heldAtStart, myCommanders, truce, } = pc;
243
+ const { avail, captured } = ps;
244
+ const { pools } = book;
245
+ const local = pools !== null && pools.bonuses.length > 0;
246
+ const { holdArmies, borderAt } = threats;
247
+ const { conceded } = hb;
248
+ const { stayAt } = prev;
249
+ // ---- #172: two steps away ----
250
+ /**
251
+ * What my `t` protects against a stack two steps away: the bonuses I hold in full that contain
252
+ * it (net of negative ones, floored at 0) — and, with my commander there, everything. A
253
+ * territory protecting nothing is never held against a reach (its armies serve the front).
254
+ */
255
+ const heldBonusValueMemo = new Map();
256
+ const heldBonusValue = (t) => {
257
+ let v = heldBonusValueMemo.get(t);
258
+ if (v === undefined) {
259
+ v = 0;
260
+ for (const id of bonusesWith.get(t) ?? [])
261
+ if (bonusTs.get(id).every((x) => heldAtStart.has(x)))
262
+ v += g.bonusById.get(id).value;
263
+ heldBonusValueMemo.set(t, (v = Math.max(0, v)));
264
+ }
265
+ return v;
266
+ };
267
+ const guardsTwoStep = (t) => myCommanders.has(t) || heldBonusValue(t) > 0;
268
+ /**
269
+ * Every two-step reach to a territory of mine worth guarding (lookahead.ts, as check_plan), by
270
+ * territory: found once per {@link planTurn} (it depends only on the start board) and shared by
271
+ * its passes, each of which filters it by its own plan ({@link twoStepHold}).
272
+ */
273
+ /**
274
+ * Territories whose two-step hold an order cited (see {@link twoStepCite}), with the hold it
275
+ * met: each is stated once, at the end, with the stay the plan ends on.
276
+ */
277
+ const twoStepCited = new Map();
278
+ /**
279
+ * Armies rule 6 moves into each territory of mine (staging and idle interior transfers), which
280
+ * {@link stayAt}'s `incoming` leaves out: they end the plan there, so a two-step hold counts them.
281
+ */
282
+ const arrived = new Map();
283
+ /** {@link stayAt} with rule 6's arrivals: what stays on my `t` once every order has run. */
284
+ const finalStayAt = (t) => stayAt(t) + (arrived.get(t) ?? 0);
285
+ /**
286
+ * Territories whose two-step hold kept back armies some order could otherwise have used (an
287
+ * attack's size, a softener, a finisher, a top-up): each is explained at the end, unless an
288
+ * order already said so.
289
+ */
290
+ const twoStepBound = new Set();
291
+ const twoStepAt = (t) => {
292
+ if (!pass.shared.reaches) {
293
+ const byTerritory = new Map();
294
+ const teams = new Map();
295
+ for (const p of ctx.players ?? [])
296
+ if (carriesTeam(p.team))
297
+ teams.set(p.id, p.team);
298
+ const opponents = [
299
+ // T9 (D3): a player a Diplomacy card shields me from only this turn is a foe again next turn.
300
+ ...new Set(board.territories.flatMap((x) => x.owner.kind === 'player' && (foe(x.owner.playerId) || truce.lookAheadFoes.has(x.owner.playerId)) && x.armies !== null ? [x.owner.playerId] : [])),
301
+ ]
302
+ .sort(byNum)
303
+ .map((id) => ({ id, deploy: deployOf(id) }));
304
+ const reaches = twoStepReaches({
305
+ graph: g,
306
+ board,
307
+ me,
308
+ opponents,
309
+ settings: {
310
+ ...(s.offensiveKillRate !== undefined ? { offensiveKillRate: s.offensiveKillRate } : {}),
311
+ ...(s.defensiveKillRate !== undefined ? { defensiveKillRate: s.defensiveKillRate } : {}),
312
+ ...(s.luckModifier !== undefined ? { luckModifier: s.luckModifier } : {}),
313
+ ...(s.roundingMode !== undefined ? { roundingMode: s.roundingMode } : {}),
314
+ ...(s.oneArmyStandsGuard !== undefined ? { oneArmyStandsGuard: s.oneArmyStandsGuard } : {}),
315
+ ...(s.multiAttack !== undefined ? { multiAttack: s.multiAttack } : {}),
316
+ },
317
+ ...(teams.size ? { teams } : {}),
318
+ ...(opts.movesFirst !== undefined ? { firstMover: opts.movesFirst ? 'me' : 'opponent' } : {}),
319
+ only: guardsTwoStep,
320
+ });
321
+ for (const r of reaches)
322
+ byTerritory.set(r.territory, [...(byTerritory.get(r.territory) ?? []), r]);
323
+ pass.shared.reaches = byTerritory;
324
+ }
325
+ return pass.shared.reaches.get(t) ?? [];
326
+ };
327
+ /**
328
+ * #172: the armies that stay on my `t` (in {@link stayAt} terms) to hold against the strongest
329
+ * stack that can reach it next turn by taking the territory in between this turn, and that
330
+ * reach; `null` when none binds. A reach through, or from, a territory this turn takes (or
331
+ * `gone` says falls) is cut, and so is one through a territory of mine the plan does not concede
332
+ * (its own one-step hold covers it), and so is one it cannot hold even with next turn's whole
333
+ * income deployed there. One-step holds are separate: callers take the larger, never both.
334
+ */
335
+ /**
336
+ * Whether my `v`, in between a reach and its target, is held — kept and holding its own border —
337
+ * as the plan's end decides it (see {@link settledPass}): learned from an earlier pass, else
338
+ * judged by the concession so far and checked at the end.
339
+ */
340
+ const viaHeld = (v) => {
341
+ const d = pass.viaNever ? false : (pass.viaHeld.get(v) ?? !conceded.has(v));
342
+ const seen = pass.viaSeen.get(v);
343
+ if (seen !== undefined && seen !== d)
344
+ pass.viaMixed = true;
345
+ pass.viaSeen.set(v, d);
346
+ return d;
347
+ };
348
+ const twoStepHold = (t, gone = () => false, final = false) => {
349
+ if (!mineSet.has(t) || conceded.has(t) || !guardsTwoStep(t))
350
+ return null;
351
+ let best = null;
352
+ for (const r of twoStepAt(t)) {
353
+ if (captured.has(r.via) || captured.has(r.from) || gone(r.via) || gone(r.from))
354
+ continue;
355
+ // Taken by an order of this plan that lands later (planTurn's refining passes).
356
+ if (pass.cut.has(r.via) || pass.cut.has(r.from))
357
+ continue;
358
+ // Through a territory of mine the plan holds: that is its border's one-step hold, not this.
359
+ if (mineSet.has(r.via) && viaHeld(r.via))
360
+ continue;
361
+ // Measured as a one-step hold is (holdArmies: under luck or weighted-random rounding, it
362
+ // falls at most HOLD_FALL_CHANCE of the time), never below check_plan's luck-free `needs`.
363
+ const needs = Math.max(r.needs, holdArmies(r.power));
364
+ const stay = Math.max(0, needs - unitsAt(t));
365
+ // Hopeless — not even what is there now and what next turn can deploy there make it hold:
366
+ // keeping its armies home saves nothing (as {@link keepFor} judges a one-step hold). Judged
367
+ // by `t`'s own stay: rule 6's arrivals do not make a hold worth keeping `t`'s armies for
368
+ // (they already cover it, and counting them would make the decision depend on whether the
369
+ // transfer in runs before `t`'s own order). Only the end of the plan (`final`), deciding
370
+ // whether a hold an order cited still applies, counts them.
371
+ if ((final ? finalStayAt(t) : stayAt(t)) + nextRoomAt(t) < stay)
372
+ continue;
373
+ if (!best || stay > best.stay)
374
+ best = { stay, needs, reach: r };
375
+ }
376
+ if (!best || best.stay <= 0)
377
+ return null;
378
+ pass.used = true;
379
+ return best;
380
+ };
381
+ /**
382
+ * What next turn could deploy on my `t`, card armies aside: the whole income, or under Local
383
+ * Deployment only what may land there — the pools of the bonuses holding it and the free rest.
384
+ */
385
+ const nextRoomAt = (t) => {
386
+ const whole = Math.max(0, income - cardArmies);
387
+ if (!local)
388
+ return whole;
389
+ const own = pools.bonuses.filter((b) => b.territoryIds.includes(t)).reduce((n, b) => n + b.value, 0);
390
+ return Math.min(whole, Math.max(0, pools.anywhere - cardArmies) + own);
391
+ };
392
+ /** {@link twoStepHold} in `avail` terms: what of `t`'s movable armies stays (0 with none). */
393
+ const twoStepKeep = (t, gone) => {
394
+ const h = twoStepHold(t, gone);
395
+ if (!h)
396
+ return 0;
397
+ const a = avail.get(t);
398
+ return a - Math.max(0, Math.min(a, stayAt(t) - h.stay));
399
+ };
400
+ /**
401
+ * An order that keeps `t`'s two-step hold (#172) names it, without numbers: the hold is stated
402
+ * once, at the end ({@link twoStepNote}), with the stay the plan ends on — a stay read mid-plan
403
+ * disagrees with the orders after it. `clause` renders the rationale text that names it; the
404
+ * text is marked, so the end of the plan keeps it only if the hold still applies then (a later
405
+ * capture or a smaller stay can end it), and puts `fallback` in its place otherwise (by default
406
+ * nothing; a line that is only the citation falls back to a plain account of what it kept).
407
+ */
408
+ const twoStepCite = (t, h, clause, fallback = '') => {
409
+ twoStepCited.set(t, h);
410
+ return `${CITE_OPEN}${t}${CITE_SEP}${clause('its hold against a stack two steps away')}${CITE_SEP}${fallback}${CITE_CLOSE}`;
411
+ };
412
+ /**
413
+ * The rationale clause for a two-step hold (#172), at the end of the plan: the armies the plan
414
+ * ends with there (rule 6's arrivals included), its special units named, since they count toward
415
+ * what it needs. A hold kept short of that (kept because next turn's deploy can make up the rest)
416
+ * says how many more to bring.
417
+ */
418
+ const twoStepNote = (t, h) => {
419
+ const r = h.reach;
420
+ const kept = finalStayAt(t);
421
+ const units = unitsAt(t);
422
+ const short = h.needs - units - kept;
423
+ const near = nearHoldAt(t);
424
+ // #192: the one-step hold (or #128's) already pins at least what the reach needs: "kept N"
425
+ // would read as if this hold claimed them, so the line says they are held already.
426
+ if (near && near.needs >= h.needs)
427
+ return `already held against the adjacent stack (~${near.threat}; it needs ${near.needs} to hold): player ${r.opponent} can reach it next turn from ${label(r.from)} via ${label(r.via)} (~${r.attackers} attacking; the two-step reach needs ${h.needs}${short > 0 ? `; bring ${short} more next turn` : ''})`;
428
+ return `kept ${kept} on ${label(t)}${units ? ` (with its special units, worth ${units})` : ''}: player ${r.opponent} can reach it next turn from ${label(r.from)} via ${label(r.via)} (~${r.attackers} attacking; it needs ${h.needs} to hold${short > 0 ? `; bring ${short} more next turn` : ''})`;
429
+ };
430
+ /**
431
+ * #192: the one-step hold on my `t` once every order has run — against the stacks beside it
432
+ * this turn's captures leave, or (#128) while an attack on a player beside it is pending, as if
433
+ * those attacks fail — as what it needs (special units included) and the threat; `null` with
434
+ * no enemy beside it.
435
+ */
436
+ const nearHoldAt = (t) => {
437
+ const pending = neighborsOf(g, t).some((x) => captured.has(x) && state.get(x)?.owner.kind === 'player');
438
+ const b = pending ? borderAt(t, () => false) : borderAt(t, (x) => captured.has(x));
439
+ return b ? { needs: holdArmies(b.threat), threat: b.threat } : null;
440
+ };
441
+ return { twoStepCited, arrived, twoStepBound, twoStepHold, twoStepKeep, twoStepCite, twoStepNote };
442
+ }
443
+ /** Rule 1a: judge each threatened border, hold it or concede it, and say why (rule 1k's commander included). */
444
+ export function holdOrConcede(pc, ps, book, threats, hb, prev) {
445
+ const { goal, paybackTurns, label, unitsAt, bombOn, toTake, myCommanders } = pc;
446
+ const { warnings, rationale, locked } = ps;
447
+ const { deploy, valueOf, stakeAt, cutOff, breachAt } = book;
448
+ const { borders, recentlyTakenFrom } = threats;
449
+ const { threatened, conceded } = hb;
450
+ const { stayAt } = prev;
451
+ /**
452
+ * Fill `threatened` from `borders`, judging each by the armies that stay on it (its
453
+ * armies at the start of the turn unless a finishing-off attack already left).
454
+ */
455
+ /** #235: the borders whose cut is already named. */
456
+ const cutNoted = new Set();
457
+ /** #275: the borders whose breach is already named. */
458
+ const breachNoted = new Set();
459
+ /** Rule 1a's pre-deploy threat warning per border, restated once the deploys are known. */
460
+ const threatWarnings = new Map();
461
+ const assessThreats = () => {
462
+ for (const b of borders.values()) {
463
+ const have = stayAt(b.id);
464
+ const units = unitsAt(b.id);
465
+ const take = toTake(have + units);
466
+ if (take === null || take > b.threat)
467
+ continue;
468
+ const text = `${label(b.id)} (${have} armies${units ? ' and my commander' : ''}) could be taken next turn: player ${b.player} ${b.chain ? `can attack it with ~${b.chain.armies} armies by a Multi-Attack chain from ${label(b.chain.path[0])} (its deploy included)` : `has ${b.movable} movable armies next to it plus ~${b.growth > b.deploy ? `${b.growth} (its growth per turn)` : `${b.deploy} deploy`}`}, and ${bombOn ? toTake(Math.floor(have / 2) + units) : take} would do${b.split ? ` — sent as separate attacks (${b.split.attacks.join(' then ')}), its stacks take up to ${b.split.takes}` : ''}${bombOn ? ' once a Bomb halves it (an opponent may hold one)' : ''}.`;
469
+ // #201: a border sized for the expected attack is restated against its worst case, never
470
+ // called held when the worst case still takes it.
471
+ threatWarnings.set(b.id, { text, threat: b.worst ?? b.threat });
472
+ warnings.push(text);
473
+ // armiesToTake grows at least one army per ~(100 / offensive kill rate) defenders, so this ends.
474
+ let d = 1;
475
+ while ((toTake(have + units + d) ?? Infinity) <= b.threat)
476
+ d++;
477
+ const value = valueOf(b.id);
478
+ // #235: a border whose loss cuts my holdings in two protects what it cuts off. Named only when
479
+ // that can change the judgement: income, or at least PAYBACK_TURNS armies (one army of worth) —
480
+ // never a 1-army leaf (its 0.1 of worth was named on most plans, #235 review).
481
+ const cut = cutOff(b.id);
482
+ if (cut && (cut.income > 0 || cut.armies >= paybackTurns) && !cutNoted.has(b.id)) {
483
+ cutNoted.add(b.id);
484
+ const named = cut.ids.slice(0, MAX_CUT_NAMED).map(label).join(', ');
485
+ const more = cut.ids.length > MAX_CUT_NAMED ? ` and ${cut.ids.length - MAX_CUT_NAMED} more` : '';
486
+ rationale.push(`${label(b.id)} links my holdings: losing it cuts off ${named}${more} (${cut.armies} armies${cut.income > 0 ? `, +${cut.income} income` : ''}) from the rest, so ${cut.income > 0 ? `it protects +${cut.income} more and ` : ''}its worth counts those ${cut.armies} armies (/ ${paybackTurns} turns) (#235).`);
487
+ }
488
+ // #275: with the guard off, a border whose breach opens earning territory behind it says so.
489
+ const breach = breachAt(b.id);
490
+ if (breach && !breachNoted.has(b.id)) {
491
+ breachNoted.add(b.id);
492
+ const named = breach.ids.slice(0, MAX_CUT_NAMED).map(label).join(', ');
493
+ const more = breach.ids.length > MAX_CUT_NAMED ? ` and ${breach.ids.length - MAX_CUT_NAMED} more` : '';
494
+ rationale.push(`${label(b.id)} alone shields ${named}${more} within two moves behind it (+${breach.income} income): with the guard off a breach walks straight in, so its value counts ${BREACH_WEIGHT * 100}% of that (+${breach.worth}) (#275).`);
495
+ }
496
+ const from = recentlyTakenFrom(b.id);
497
+ threatened.push({
498
+ id: b.id,
499
+ have,
500
+ threat: b.threat,
501
+ holdCost: d,
502
+ value,
503
+ worth: value + (have + stakeAt(b.id)) / paybackTurns,
504
+ ...(from !== undefined && from === b.player ? { recentFrom: from } : {}),
505
+ units,
506
+ ...(myCommanders.has(b.id) ? { critical: true } : {}),
507
+ });
508
+ }
509
+ threatened.sort((a, b) => Number(b.critical === true) - Number(a.critical === true) ||
510
+ Number(b.recentFrom !== undefined) - Number(a.recentFrom !== undefined) ||
511
+ b.worth / b.holdCost - a.worth / a.holdCost ||
512
+ a.holdCost - b.holdCost ||
513
+ a.id - b.id);
514
+ };
515
+ const acting = goal === 'defend';
516
+ const concedeUnaffordable = (t, left) => {
517
+ conceded.add(t.id);
518
+ warnings.push(`${label(t.id)} cannot be held with the ${left} armies left to deploy (needs ${t.holdCost}, protects +${t.value}): conceded`);
519
+ };
520
+ /** Said only once its hold is actually deployed. */
521
+ const noteRecent = (t) => {
522
+ if (t.recentFrom !== undefined)
523
+ rationale.push(`${label(t.id)} was captured from player ${t.recentFrom} last turn, and that opponent is weak: it is not conceded economically (conceding hands it back for free).`);
524
+ };
525
+ /** What stays on a held border, for the rationale: its armies, and my commander when it stands there. */
526
+ const heldStack = (t) => `${t.have + t.holdCost} armies${t.units ? ' and my commander' : ''}`;
527
+ /** The borders a hold deployed to, by the player threatening them (for the #69 rationale). */
528
+ const heldAgainst = new Map();
529
+ const hold = (t) => {
530
+ noteRecent(t);
531
+ deploy(t.id, t.holdCost);
532
+ locked.add(t.id);
533
+ const by = borders.get(t.id)?.player;
534
+ if (by !== undefined)
535
+ heldAgainst.set(by, (heldAgainst.get(by) ?? new Set()).add(t.id));
536
+ rationale.push(`Deploy ${t.holdCost + (t.given ?? 0)} to ${label(t.id)} so it holds (protects +${t.value}): ${heldStack(t)} need ${toTake(t.have + t.units + t.holdCost)} to take, above the ~${t.threat} threat.`);
537
+ };
538
+ return { threatWarnings, assessThreats, acting, concedeUnaffordable, noteRecent, heldStack, heldAgainst, hold };
539
+ }
540
+ /** Rule 1h (#51): every bonus I hold in full with a threatened border is one unit, held whole or conceded. */
541
+ export function heldBonusUnits(pc, ps, book, threats, hb, prev) {
542
+ const { g, paybackTurns, label, bonusName, incomeAfter, toTake } = pc;
543
+ const { warnings, rationale, locked } = ps;
544
+ const { deploy, undeploy, pools, roomAt, stakeAt } = book;
545
+ const local = pools !== null && pools.bonuses.length > 0;
546
+ const { expectedAt } = threats;
547
+ const { threatened, conceded, units } = hb;
548
+ const { noteRecent, hold } = prev;
549
+ // ---- 1h. held-bonus units (#51) ----
550
+ // #128: what the plan can count on excludes the borders it concedes, and those of a held bonus
551
+ // it has not decided to hold whole yet (contested, #118): R3 runs before that is settled.
552
+ /**
553
+ * #128: the next income the plan can count on — {@link incomeAfter} without the borders it
554
+ * concedes (it does not plan to hold them, so the bonuses they break do not pay for anything).
555
+ * R3, rule 4d and the frontier report use it.
556
+ */
557
+ const keptIncome = (after) => incomeAfter(new Set([...after].filter((t) => !conceded.has(t) && !units.some((u) => (u.conceded || u.contested) && u.members.some((m) => m.id === t)))));
558
+ /** Borders a funded unit (or an individual hold) already holds. */
559
+ const heldBorders = new Set();
560
+ /** My commander's borders whose whole hold rule 1k deployed. */
561
+ const commanderHeld = new Set();
562
+ /** Local Deployment: the armies bonus `id`'s own pool holds this turn (0 with the flag off). */
563
+ const poolOf = (id) => (local ? (pools.bonuses.find((p) => p.bonusId === id)?.value ?? 0) : 0);
564
+ const buildUnits = () => {
565
+ for (const b of [...g.map.bonuses].sort((x, y) => x.id - y.id)) {
566
+ const ts = bonusTerritories(g, b.id);
567
+ if (b.value <= 0 || !ts.length || !ts.every((x) => ps.holdings.has(x)))
568
+ continue;
569
+ const members = threatened.filter((t) => ts.includes(t.id)).sort((x, y) => x.id - y.id);
570
+ if (!members.length)
571
+ continue;
572
+ // My commander's border, once its hold is funded (rule 1k), is held whatever it costs: a
573
+ // sunk cost the unit no longer pays, and a stack it no longer saves, so it is left out of
574
+ // the unit's cost and its payback test. A hold rule 1k could not fully fund still counts.
575
+ const paying = members.filter((m) => !commanderHeld.has(m.id));
576
+ const cost = paying.reduce((n, m) => n + m.holdCost, 0);
577
+ const worth = b.value + paying.reduce((n, m) => n + (m.have + stakeAt(m.id)) / paybackTurns, 0);
578
+ // It pays back within PAYBACK_TURNS, and (as rule 1a asks of every border) costs at
579
+ // most CONCEDE_FACTOR × its worth, unless a member was just taken from a weak opponent.
580
+ const recent = members.some((m) => m.recentFrom !== undefined);
581
+ // Local Deployment (#103): the bonus's own armies can be deployed nowhere else, so
582
+ // spending them on its defence costs nothing — only what holding it needs beyond them.
583
+ const pool = poolOf(b.id);
584
+ const net = Math.max(0, cost - pool);
585
+ units.push({
586
+ bonusId: b.id,
587
+ value: b.value,
588
+ members,
589
+ cost,
590
+ pool,
591
+ net,
592
+ worth,
593
+ loss: net > paybackTurns * b.value ? 'payback' : !recent && net > CONCEDE_FACTOR * worth ? 'factor' : null,
594
+ conceded: false,
595
+ floored: false,
596
+ contested: false,
597
+ });
598
+ }
599
+ };
600
+ /** A threatened border still owned by a unit not conceded (it is held or conceded with it). */
601
+ const inLiveUnit = (id) => units.some((u) => !u.conceded && u.members.some((m) => m.id === id));
602
+ /** `t` judged on its own: its protected value less the bonuses of the units conceded with it. */
603
+ const residual = (t) => {
604
+ const lost = units.filter((u) => u.conceded && u.members.some((m) => m.id === t.id)).reduce((n, u) => n + u.value, 0);
605
+ const value = Math.max(0, t.value - lost);
606
+ return { ...t, value, worth: value + (t.have + stakeAt(t.id)) / paybackTurns };
607
+ };
608
+ const unitBorders = (u) => `${u.members.length} threatened border${u.members.length === 1 ? '' : 's'}`;
609
+ /**
610
+ * Concede `u` as a whole, then judge each of its members no other live unit owns on its
611
+ * own merits (`single`, quietly: other bonuses, per-territory income, the stack it saves).
612
+ * One warning: rule 1a's for a one-border unit that stays conceded (so it names the full
613
+ * value it protects), else "conceding <bonus>: holding all N borders needs X, …".
614
+ */
615
+ const concedeUnit = (u, loss, single) => {
616
+ u.conceded = true;
617
+ for (const m of u.members)
618
+ if (!heldBorders.has(m.id) && !inLiveUnit(m.id))
619
+ single(residual(m), true);
620
+ const [only] = u.members;
621
+ if (u.members.length === 1) {
622
+ if (conceded.has(only.id) && !heldBorders.has(only.id))
623
+ warnings.push(loss.economic
624
+ ? `${label(only.id)} cannot be held economically (needs ${only.holdCost}, protects +${only.value}): conceded`
625
+ : `${label(only.id)} cannot be held with the ${loss.left} armies left to deploy (needs ${only.holdCost}, protects +${only.value}): conceded`);
626
+ return;
627
+ }
628
+ const why = loss.economic === false
629
+ ? `more than the ${loss.left} armies left to deploy`
630
+ : loss.economic === 'payback'
631
+ ? `more than it pays back in ${paybackTurns} turns (${paybackTurns} × +${u.value} = ${paybackTurns * u.value})`
632
+ : `more than ${CONCEDE_FACTOR} × its worth (~${Math.round(u.worth * 10) / 10})`;
633
+ const needs = u.pool > 0 && loss.economic ? `${u.cost} (${u.net} beyond its own ${Math.min(u.pool, u.cost)} local armies)` : `${u.cost}`;
634
+ warnings.push(`conceding bonus ${bonusName(u.bonusId)} (+${u.value}): holding all ${u.members.length} threatened borders (${u.members.map((m) => label(m.id)).join(', ')}) needs ${needs}, ${why}`);
635
+ };
636
+ /** The armies `u` may still deploy, for its warning: a one-border unit's room (pools respected). */
637
+ const leftFor = (u) => {
638
+ if (u.members.length === 1)
639
+ return roomAt(u.members[0].id);
640
+ if (!local)
641
+ return ps.budget;
642
+ // Local Deployment: what may be deployed on its borders together (pools respected).
643
+ const given = u.members.map((m) => {
644
+ const n = roomAt(m.id);
645
+ deploy(m.id, n);
646
+ return { id: m.id, n };
647
+ });
648
+ for (const x of given)
649
+ undeploy(x.id, x.n);
650
+ return given.reduce((n, x) => n + x.n, 0);
651
+ };
652
+ /**
653
+ * Deploy every hold of `u` not yet funded, or nothing: false when they do not all fit.
654
+ * `each` may take over one member's hold (attacking on top of it), given the deploys
655
+ * the members after it still need; it returns false to leave it a plain hold.
656
+ */
657
+ const fundUnit = (u, each, line) => {
658
+ // A commander border rule 1k could not fully hold is still owed (it cannot be deployed to further).
659
+ const todo = u.members.filter((m) => !heldBorders.has(m.id) || (m.critical && !commanderHeld.has(m.id)));
660
+ const cost = todo.reduce((n, m) => n + m.holdCost, 0);
661
+ if (cost > ps.budget)
662
+ return false;
663
+ if (local) {
664
+ // Pools: each hold must fit its own territory's room, the earlier ones deployed.
665
+ const done = [];
666
+ for (const m of todo) {
667
+ if (m.holdCost > roomAt(m.id)) {
668
+ for (const d of done)
669
+ undeploy(d.id, d.holdCost);
670
+ return false;
671
+ }
672
+ deploy(m.id, m.holdCost);
673
+ done.push(m);
674
+ }
675
+ for (const d of done)
676
+ undeploy(d.id, d.holdCost);
677
+ }
678
+ const one = u.members.length === 1;
679
+ // What this unit deploys itself: a border another unit already holds costs it nothing (its
680
+ // own floor, #118, counts as its own).
681
+ const own = cost + todo.reduce((n, m) => n + (m.given ?? 0), 0);
682
+ const needs = !todo.length
683
+ ? u.members.every((m) => commanderHeld.has(m.id))
684
+ ? `${one ? 'is' : 'are'} already held for my commander`
685
+ : `${one ? 'is' : 'are'} already held for another bonus`
686
+ : own < u.cost
687
+ ? `need${one ? 's' : ''} ${own} more (${u.cost - own} already deployed for another bonus)`
688
+ : `need${one ? 's' : ''} ${own} in all`;
689
+ rationale.push(line ??
690
+ `Hold bonus ${bonusName(u.bonusId)} (+${u.value}) whole: its ${unitBorders(u)} ${needs} (it pays back within ${paybackTurns} turns), before any capture that completes no bonus.`);
691
+ let rest = cost;
692
+ for (const m of todo) {
693
+ rest -= m.holdCost;
694
+ if (!each?.(m, rest))
695
+ hold(m);
696
+ heldBorders.add(m.id);
697
+ }
698
+ return true;
699
+ };
700
+ /**
701
+ * Rule 1h near miss (issue #59), when {@link fundUnit} cannot cover `u`: give each of its
702
+ * borders not yet held what may still be deployed there, up to its hold cost (pools
703
+ * respected). It is kept — those deploys stay, nothing is withdrawn — when the total is
704
+ * short by at most {@link nearMissMargin} of the need, or when every short border still
705
+ * holds against the expected attack ({@link expectedAt}: movable + deploy estimate, not the
706
+ * trend's worst case). Otherwise every deploy is rolled back: false.
707
+ */
708
+ const fundNearMiss = (u) => {
709
+ const todo = u.members.filter((m) => !heldBorders.has(m.id));
710
+ if (!todo.length)
711
+ return false;
712
+ const given = todo.map((m) => {
713
+ const n = Math.max(0, Math.min(m.holdCost, roomAt(m.id)));
714
+ deploy(m.id, n);
715
+ return { m, n };
716
+ });
717
+ // A floor already deployed (#118) counts toward both, as if deployed here.
718
+ const need = todo.reduce((n, m) => n + m.holdCost + (m.given ?? 0), 0);
719
+ const total = given.reduce((n, x) => n + x.n + (x.m.given ?? 0), 0);
720
+ const short = need - total;
721
+ const margin = nearMissMargin(need);
722
+ const shortOnes = given.filter((x) => x.n < x.m.holdCost);
723
+ const holdsExpected = shortOnes.every((x) => (toTake(x.m.have + x.n) ?? Infinity) > expectedAt(x.m.id));
724
+ if (short > margin && !holdsExpected) {
725
+ for (const x of given)
726
+ if (x.n > 0)
727
+ undeploy(x.m.id, x.n);
728
+ return false;
729
+ }
730
+ const expected = Math.max(...shortOnes.map((x) => expectedAt(x.m.id)));
731
+ const why = short <= margin
732
+ ? `short by ${short}, within the near-miss margin of ${Math.round(margin * 10) / 10}`
733
+ : `enough to hold against the expected ~${expected} attack (movable + deploy estimate), not the worst case`;
734
+ const one = todo.length === 1;
735
+ warnings.push(`Bonus ${bonusName(u.bonusId)} (+${u.value}) is held though short: its ${todo.length} threatened border${one ? '' : 's'} need${one ? 's' : ''} ${need}, only ${total} left to deploy, so ${total ? `all ${total} go there` : 'its armies stay'} (${why}); ${shortOnes.map((x) => label(x.m.id)).join(', ')} may fall.`);
736
+ for (const { m, n } of given) {
737
+ noteRecent(m);
738
+ locked.add(m.id);
739
+ heldBorders.add(m.id);
740
+ rationale.push(n + (m.given ?? 0) > 0
741
+ ? `Deploy ${n + (m.given ?? 0)} to ${label(m.id)} so bonus ${bonusName(u.bonusId)} (+${u.value}) is not conceded: ${m.have + n} armies need ${toTake(m.have + n)} to take, against the ~${m.threat} threat (its armies stay: withdrawing them would guarantee the loss).`
742
+ : `Keep the armies on ${label(m.id)} so bonus ${bonusName(u.bonusId)} (+${u.value}) is not conceded: ${m.have} armies need ${toTake(m.have)} to take, against the ~${m.threat} threat.`);
743
+ }
744
+ return true;
745
+ };
746
+ return {
747
+ keptIncome, heldBorders, commanderHeld, buildUnits, unitBorders, concedeUnit, leftFor, fundUnit, fundNearMiss,
748
+ };
749
+ }
750
+ /** Rule 1h's floor tier and one shared deploy (#118), the contested units, and the triage that runs them all. */
751
+ export function floorTier(pc, ps, book, threats, hb, prev) {
752
+ const { g, goal, balanced, guarded, paybackTurns, label, bonusName, toTake, bonusTs, mineSet, income } = pc;
753
+ const { warnings, rationale, locked, captured, avail } = ps;
754
+ const { deploy, undeploy, pools, roomAt } = book;
755
+ const local = pools !== null && pools.bonuses.length > 0;
756
+ const { chainAt, stacksAt, borders } = threats;
757
+ const { threatened, conceded, units, holds, pendingLocks, completable } = hb;
758
+ /**
759
+ * #215 review: `id` is a member of a positive bonus this turn's captures may complete without
760
+ * it — every missing member a capture target next to another territory of mine, and its armies
761
+ * to finish within this turn's income plus the armies on those territories (kept, `id` sends
762
+ * none) — so rule 1c may keep `id` (and the leftover garrison it) once the captures are known.
763
+ */
764
+ const mayComplete = (id) => g.map.bonuses.some((b) => {
765
+ const cost = completable.get(b.id);
766
+ const ts = bonusTs.get(b.id) ?? [];
767
+ if (cost === undefined || b.value <= 0 || !ts.includes(id))
768
+ return false;
769
+ const sourcesOf = (x) => neighborsOf(g, x).filter((n) => mineSet.has(n) && n !== id);
770
+ const missing = ts.filter((x) => !mineSet.has(x));
771
+ // A member only `id` reaches is completed out of `id` itself: no reason to keep it locked.
772
+ if (missing.some((x) => !sourcesOf(x).length))
773
+ return false;
774
+ const near = new Set(missing.flatMap(sourcesOf));
775
+ return cost <= income + [...near].reduce((n, x) => n + avail.get(x), 0);
776
+ });
777
+ const { uneconomic, acting, concedeUnaffordable, heldStack, hold, heldBorders, commanderHeld, buildUnits, unitBorders, concedeUnit, leftFor, fundUnit, fundNearMiss, } = prev;
778
+ // ---- 1h. floor tier and one shared deploy (#118) ----
779
+ // One enemy deploy lands on one target. Sizing every border of a held bonus for the whole of
780
+ // it conceded every bonus once the deploy outgrew them, though the stacks already next to the
781
+ // borders could take none. So a held bonus first gets its floor — every threatened border beats
782
+ // the armies already next to it — and, when it is not then held whole, what is left is spread
783
+ // over its borders so the deploy must be aimed at a border to break it.
784
+ /**
785
+ * The most movable armies (special units included) one enemy player has next to my `t`: its
786
+ * visible stacks, and (#164) its hidden pool once per border and its stacks that left view, as
787
+ * {@link forceAt} counts them — a hidden stack is armies already there, not deploy to aim.
788
+ * #199: a Multi-Attack chain of a stack's armies alone (no deploy) lands armies already there too.
789
+ */
790
+ const adjacentMovable = (t) => {
791
+ const gone = (n) => captured.has(n);
792
+ const byPlayer = stacksAt(t, gone, false);
793
+ const chain = chainAt(t, gone, true)?.armies ?? 0;
794
+ return Math.max(0, chain, ...[...byPlayer.values()].map((p) => p.stacks.reduce((n, x) => n + x.movable, 0)));
795
+ };
796
+ /** The deploys `m` needs to beat the armies already next to it (never more than its hold cost). */
797
+ const floorOf = (m) => {
798
+ const movable = adjacentMovable(m.id);
799
+ let d = 0;
800
+ while (d < m.holdCost && (toTake(m.have + m.units + d) ?? Infinity) <= movable)
801
+ d++;
802
+ return d;
803
+ };
804
+ /** Deploy `n` to `m` as part of its hold: what it has grows and what its hold still needs shrinks. */
805
+ const give = (m, n) => {
806
+ deploy(m.id, n);
807
+ m.have += n;
808
+ m.holdCost -= n;
809
+ m.given = (m.given ?? 0) + n;
810
+ };
811
+ /**
812
+ * Fund the floors of `us` — units about to be conceded — best value per army first (ties:
813
+ * cheaper, then its first border's id), all of a unit's floor or none; a unit whose floor is
814
+ * funded is `floored`.
815
+ */
816
+ const floorUnits = (us) => {
817
+ const need = (u) => u.members.filter((m) => !commanderHeld.has(m.id)).map((m) => ({ m, f: floorOf(m) }));
818
+ // A floor only helps where the deploy must choose: against a player with one threatened
819
+ // border of mine to aim at, all of its deploy lands there, and a floor alone saves nothing.
820
+ const targetsOf = new Map();
821
+ for (const t of threatened) {
822
+ const p = borders.get(t.id)?.player;
823
+ if (p !== undefined)
824
+ targetsOf.set(p, (targetsOf.get(p) ?? 0) + 1);
825
+ }
826
+ const spread = (u) => u.members.every((m) => (targetsOf.get(borders.get(m.id)?.player ?? -1) ?? 0) >= 2);
827
+ const order = us
828
+ .filter(spread)
829
+ .map((u) => ({ u, cost: need(u).reduce((n, x) => n + x.f, 0) }))
830
+ .sort((a, b) => (b.cost ? b.u.value / b.cost : Infinity) - (a.cost ? a.u.value / a.cost : Infinity) || a.cost - b.cost || a.u.members[0].id - b.u.members[0].id);
831
+ for (const { u } of order) {
832
+ // Recomputed: a border shared with a unit floored before it already has its floor.
833
+ const todo = need(u).filter((x) => x.f > 0);
834
+ if (todo.reduce((n, x) => n + x.f, 0) > ps.budget)
835
+ continue;
836
+ const done = [];
837
+ let fits = true;
838
+ for (const x of todo) {
839
+ if (x.f > roomAt(x.m.id)) {
840
+ fits = false;
841
+ break;
842
+ }
843
+ give(x.m, x.f);
844
+ done.push(x);
845
+ }
846
+ if (!fits) {
847
+ for (const x of done) {
848
+ undeploy(x.m.id, x.f);
849
+ x.m.have -= x.f;
850
+ x.m.holdCost += x.f;
851
+ x.m.given = (x.m.given ?? 0) - x.f;
852
+ }
853
+ continue;
854
+ }
855
+ u.floored = true;
856
+ rationale.push(...done.map((x) => `Floor for bonus ${bonusName(u.bonusId)} (+${u.value}): deploy ${x.f} to ${label(x.m.id)} so its ${x.m.have} armies beat the ${adjacentMovable(x.m.id)} already next to it (${toTake(x.m.have + x.m.units)} to take): one enemy deploy lands on one target, so every border first holds against what is already there.`));
857
+ }
858
+ };
859
+ /**
860
+ * #122: would `u` survive on `left` armies short of its whole hold — kept as a near miss (short
861
+ * by at most {@link nearMissMargin}) or floored (every border faces a player with two or more
862
+ * targets, and its floor fits)? An estimate for rule 1h.3's starve check: `left` is pool-aware
863
+ * under Local Deployment (the caller passes what may be deployed on its borders), but the
864
+ * expected-attack test of the near miss and `fundable`'s greedy order are left out.
865
+ */
866
+ const keptShort = (u, left) => {
867
+ const todo = u.members.filter((m) => !heldBorders.has(m.id));
868
+ const need = todo.reduce((n, m) => n + m.holdCost, 0);
869
+ if (need - left <= nearMissMargin(need))
870
+ return 'near';
871
+ const targetsOf = new Map();
872
+ for (const t of threatened) {
873
+ const p = borders.get(t.id)?.player;
874
+ if (p !== undefined)
875
+ targetsOf.set(p, (targetsOf.get(p) ?? 0) + 1);
876
+ }
877
+ const spread = todo.every((m) => (targetsOf.get(borders.get(m.id)?.player ?? -1) ?? 0) >= 2);
878
+ return spread && todo.reduce((n, m) => n + floorOf(m), 0) <= left ? 'floor' : null;
879
+ };
880
+ /** Keep a floored unit that is not held whole (#118): its borders stay, nothing is withdrawn. */
881
+ const contest = (u) => {
882
+ u.contested = true;
883
+ for (const m of u.members)
884
+ locked.add(m.id);
885
+ };
886
+ /** A unit that cannot be held whole now: floored and kept when it can be (#118), else conceded whole. */
887
+ const floorOrConcede = (u, left, single) => {
888
+ floorUnits([u]);
889
+ if (u.floored)
890
+ contest(u);
891
+ else
892
+ concedeUnit(u, { economic: false, left }, single);
893
+ };
894
+ /** Its borders' threat beyond the armies already next to them: the opponent's deploy (or growth). */
895
+ const deployShare = (m) => m.threat - adjacentMovable(m.id);
896
+ /**
897
+ * After the captures (the better use of the armies): hold each contested unit whole when what
898
+ * is left covers it (best worth per army first), else spread what is left over the borders
899
+ * still short, one army at a time to the one the opponent's deploy breaks most cheaply (ties:
900
+ * the higher bonus value, then id), each up to its full hold.
901
+ */
902
+ /** A member of a unit conceded after the captures, judged on its own (rule 1a, against what is left). */
903
+ const singleLate = (t, quiet) => {
904
+ if (t.critical)
905
+ return;
906
+ if (uneconomic(t)) {
907
+ conceded.add(t.id);
908
+ if (!quiet)
909
+ warnings.push(`${label(t.id)} cannot be held economically (needs ${t.holdCost}, protects +${t.value}): conceded`);
910
+ return;
911
+ }
912
+ const room = roomAt(t.id);
913
+ if (t.holdCost > room) {
914
+ if (quiet)
915
+ conceded.add(t.id);
916
+ else
917
+ concedeUnaffordable(t, room);
918
+ return;
919
+ }
920
+ hold(t);
921
+ heldBorders.add(t.id);
922
+ };
923
+ /** Armies the opponent's deploy needs on my `m` to take it, with `have` armies there. */
924
+ const breakCostWith = (m, have) => (toTake(have + m.units) ?? Infinity) - adjacentMovable(m.id);
925
+ /**
926
+ * The bonus value the opponents' best response takes from the floored units in `us`, given
927
+ * the armies on each border: per player, its one deploy split to break the most value (each
928
+ * unit broken through its cheapest short border facing that player; a 0/1 knapsack), as
929
+ * `guaranteedFalls` sizes a single budget on offence.
930
+ */
931
+ const bestResponse = (us, have, short) => {
932
+ const players = new Map();
933
+ for (const u of us)
934
+ for (const m of u.members) {
935
+ if (!short(m))
936
+ continue;
937
+ const p = borders.get(m.id)?.player;
938
+ if (p === undefined)
939
+ continue;
940
+ const c = Math.max(0, breakCostWith(m, have.get(m) ?? m.have));
941
+ // B2 T2: a border relaxed for `p` faces its stacks with no deploy, so no share of the deploy
942
+ // it lands elsewhere breaks it here (plan/relations.ts, relaxedFor).
943
+ if (c > 0 && relaxedFor(ps, m.id, p))
944
+ continue;
945
+ const e = players.get(p) ?? { deploy: 0, items: new Map() };
946
+ e.deploy = Math.max(e.deploy, deployShare(m));
947
+ e.items.set(u, Math.min(e.items.get(u) ?? Infinity, c));
948
+ players.set(p, e);
949
+ }
950
+ let loss = 0;
951
+ const by = [];
952
+ for (const [player, { deploy, items }] of [...players].sort((a, b) => a[0] - b[0])) {
953
+ const d = Math.max(0, Math.floor(deploy));
954
+ const best = Array.from({ length: d + 1 }, () => ({ value: 0, cost: 0, units: [] }));
955
+ for (const [u, c] of items) {
956
+ if (c > d)
957
+ continue;
958
+ for (let x = d; x >= c; x--) {
959
+ const prev = best[x - c];
960
+ const cand = { value: prev.value + u.value, cost: prev.cost + c, units: [...prev.units, u] };
961
+ const cur = best[x];
962
+ if (cand.value > cur.value || (cand.value === cur.value && cand.cost < cur.cost))
963
+ best[x] = cand;
964
+ }
965
+ }
966
+ const pick = best[d];
967
+ loss += pick.value;
968
+ if (pick.value > 0)
969
+ by.push({ player, deploy: d, units: pick.units, of: [...items.keys()], cost: pick.cost, value: pick.value });
970
+ }
971
+ return { loss, by };
972
+ };
973
+ const bestResponseLoss = (us, have, short) => bestResponse(us, have, short).loss;
974
+ /**
975
+ * #275 (b), the second trigger: a border of a held bonus conceded beside the stack of an opponent
976
+ * whose estimate a tripwire broke. Nothing that pays +1 goes ahead of it (the 20/80 game, turns 17–19:
977
+ * 58 armies to a +1 wasteland beside the stack while each gate was conceded): what is left to deploy
978
+ * goes there before any capture, one army at a time to the gate that deploy breaks most cheaply (ties:
979
+ * the higher bonus value, then id), each up to its hold. `short` are the contested units the whole holds
980
+ * could not cover (left to #118's concession after the captures otherwise); conceded units are those
981
+ * triage already gave up. A gate that gets armies is no longer conceded or contested (nothing is
982
+ * withdrawn from it, no later concession); a warning says what still takes it. A gate the stacks beside
983
+ * it take with no deploy at all gets nothing unless what is left makes it need some of the deploy.
984
+ */
985
+ const fillUntrustedGates = (short) => {
986
+ const untrustedBy = (m) => {
987
+ const b = borders.get(m.id);
988
+ return b !== undefined && pc.untrustedAt(b.player, m.id) > 0 ? b.player : undefined;
989
+ };
990
+ const gates = [
991
+ ...new Set([
992
+ ...units.filter((u) => u.conceded).flatMap((u) => u.members.filter((m) => conceded.has(m.id))),
993
+ ...short.flatMap((u) => u.members),
994
+ ]),
995
+ ]
996
+ .filter((m) => !heldBorders.has(m.id) && !m.critical && untrustedBy(m) !== undefined)
997
+ .sort((a, b) => a.id - b.id);
998
+ if (!gates.length)
999
+ return;
1000
+ const valueAt = (m) => Math.max(0, ...units.filter((u) => u.members.includes(m)).map((u) => u.value));
1001
+ const given = new Map();
1002
+ // Review of #275: a gate the stacks beside it take with no deploy at all is lost whatever goes there, so
1003
+ // it gets armies only when what is left can make it need some of the deploy (`firstStand`, all of it or
1004
+ // none); otherwise it stays conceded and the armies stay behind it (withdrawals, the second line).
1005
+ const firstStand = (m) => {
1006
+ let d = 0;
1007
+ while (d < m.holdCost && breakCostWith(m, m.have + d) <= 0)
1008
+ d++;
1009
+ return d;
1010
+ };
1011
+ for (const m of [...gates].sort((a, b) => breakCostWith(a, a.have) - breakCostWith(b, b.have) || valueAt(b) - valueAt(a) || a.id - b.id)) {
1012
+ const d = firstStand(m);
1013
+ if (d === 0 || d > Math.min(ps.budget, roomAt(m.id)))
1014
+ continue;
1015
+ give(m, d);
1016
+ given.set(m, d);
1017
+ }
1018
+ const standing = gates.filter((m) => breakCostWith(m, m.have) > 0);
1019
+ while (ps.budget > 0) {
1020
+ const next = standing
1021
+ .filter((m) => m.holdCost > 0 && roomAt(m.id) > 0)
1022
+ .sort((a, b) => breakCostWith(a, a.have) - breakCostWith(b, b.have) || valueAt(b) - valueAt(a) || a.id - b.id)[0];
1023
+ if (!next)
1024
+ break;
1025
+ give(next, 1);
1026
+ given.set(next, (given.get(next) ?? 0) + 1);
1027
+ }
1028
+ for (const [m, n] of [...given].sort((a, b) => a[0].id - b[0].id)) {
1029
+ conceded.delete(m.id);
1030
+ locked.add(m.id);
1031
+ // Drop its concession warning: it is no longer conceded.
1032
+ const conceding = `${label(m.id)} cannot be held `;
1033
+ for (let i = warnings.length - 1; i >= 0; i--)
1034
+ if (warnings[i].startsWith(conceding) && warnings[i].endsWith(': conceded'))
1035
+ warnings.splice(i, 1);
1036
+ const player = untrustedBy(m);
1037
+ const bonuses = units.filter((u) => u.members.includes(m)).map((u) => `${bonusName(u.bonusId)} (+${u.value})`).join(', ');
1038
+ rationale.push(`Deploy ${m.given ?? n} to ${label(m.id)}, a border of held bonus ${bonuses}, before any capture: player ${player}'s estimate is untrusted (#275), so nothing that pays less goes ahead of the gate beside its stack (${m.have} armies, ${toTake(m.have + m.units)} to take).`);
1039
+ if (m.holdCost <= 0)
1040
+ heldBorders.add(m.id);
1041
+ else
1042
+ warnings.push(`${label(m.id)} is not conceded though short: player ${player}'s estimate is untrusted (#275), and against its figure the border needs ${m.holdCost} more, so it still falls to a deploy of ${Math.max(0, breakCostWith(m, m.have))} or more there; every army left went there rather than to expansion.`);
1043
+ }
1044
+ // A contested unit a gate of which got armies is settled here: #118's later concession would undo it.
1045
+ for (const u of short)
1046
+ if (u.members.some((m) => given.has(m)))
1047
+ u.contested = false;
1048
+ // A unit none of whose members is still conceded is no longer conceded as a whole: drop its warning.
1049
+ for (const u of units) {
1050
+ if (!u.conceded || u.members.some((m) => conceded.has(m.id)) || !u.members.some((m) => given.has(m)))
1051
+ continue;
1052
+ const conceding = `conceding bonus ${bonusName(u.bonusId)} (+${u.value}):`;
1053
+ for (let i = warnings.length - 1; i >= 0; i--)
1054
+ if (warnings[i].startsWith(conceding))
1055
+ warnings.splice(i, 1);
1056
+ }
1057
+ };
1058
+ /**
1059
+ * `wholeOnly` (#215, rule 0p.1: a 1v1 in contact, before the first advance): only hold each
1060
+ * contested unit whole that pays back within PAYBACK_TURNS (one CONCEDE_FACTOR made contested)
1061
+ * and that what is left covers (best worth per army first, never weighed against spreading) — no
1062
+ * concession, no spread — leaving the rest contested for the call after the captures.
1063
+ * `'untrusted'` (#275 b): the same, before any capture, for each contested unit a border of which faces
1064
+ * an opponent whose estimate a tripwire broke (sized for its untrusted figure), whether or not it pays
1065
+ * back: while the estimate is untrusted the gate is held before expansion, never left to what it leaves.
1066
+ */
1067
+ const settleContested = (mode = false) => {
1068
+ const wholeOnly = mode !== false;
1069
+ const facesUntrusted = (u) => u.members.some((m) => {
1070
+ const b = borders.get(m.id);
1071
+ return !heldBorders.has(m.id) && b !== undefined && pc.untrustedAt(b.player, m.id) > 0;
1072
+ });
1073
+ const open = units.filter((u) => u.contested && !u.conceded && (mode === 'untrusted' ? facesUntrusted(u) : !wholeOnly || u.loss !== 'payback'));
1074
+ if (!open.length) {
1075
+ if (mode === 'untrusted')
1076
+ fillUntrustedGates([]);
1077
+ return;
1078
+ }
1079
+ const need = (u) => u.members.filter((m) => !heldBorders.has(m.id)).reduce((n, m) => n + m.holdCost, 0);
1080
+ const ratio = (u) => u.worth / Math.max(1, need(u));
1081
+ const order = [...open].sort((a, b) => ratio(b) - ratio(a) || a.members[0].id - b.members[0].id);
1082
+ // Holding one floored unit whole can leave the others thinner than spreading the same
1083
+ // armies over all of them: simulate both and keep whole holds unless spreading loses less
1084
+ // to the opponents' best response (Local Deployment: whole holds, pools decide the room).
1085
+ const simulate = (wholeFirst) => {
1086
+ let b = ps.budget;
1087
+ const have = new Map();
1088
+ const left = new Map();
1089
+ for (const u of open)
1090
+ for (const m of u.members)
1091
+ if (!heldBorders.has(m.id)) {
1092
+ have.set(m, m.have);
1093
+ left.set(m, m.holdCost);
1094
+ }
1095
+ let lost = 0;
1096
+ for (const u of order) {
1097
+ if (u.floored && !wholeFirst)
1098
+ continue;
1099
+ const ms = u.members.filter((m) => (left.get(m) ?? 0) > 0);
1100
+ const more = ms.reduce((n, m) => n + left.get(m), 0);
1101
+ if (more <= b) {
1102
+ b -= more;
1103
+ for (const m of ms) {
1104
+ have.set(m, have.get(m) + left.get(m));
1105
+ left.set(m, 0);
1106
+ }
1107
+ }
1108
+ else if (!u.floored)
1109
+ lost += u.value;
1110
+ }
1111
+ const floored = open.filter((u) => u.floored);
1112
+ const valueAt = (m) => Math.max(0, ...floored.filter((u) => u.members.includes(m)).map((u) => u.value));
1113
+ const fill = [...new Set(floored.flatMap((u) => u.members))].filter((m) => left.has(m));
1114
+ while (b > 0) {
1115
+ const next = fill
1116
+ .filter((m) => left.get(m) > 0)
1117
+ .sort((x, y) => breakCostWith(x, have.get(x)) - breakCostWith(y, have.get(y)) || valueAt(y) - valueAt(x) || x.id - y.id)[0];
1118
+ if (!next)
1119
+ break;
1120
+ have.set(next, have.get(next) + 1);
1121
+ left.set(next, left.get(next) - 1);
1122
+ b--;
1123
+ }
1124
+ return lost + bestResponseLoss(floored, have, (m) => (left.get(m) ?? 0) > 0);
1125
+ };
1126
+ // wholeOnly: whole holds first, whatever spreading would save — what is left is spread after the captures.
1127
+ const spreadFloored = !wholeOnly && !local && open.some((u) => u.floored) && simulate(false) < simulate(true);
1128
+ for (const u of order) {
1129
+ if (u.floored && spreadFloored)
1130
+ continue;
1131
+ const more = need(u);
1132
+ const floored = u.members.some((m) => (m.given ?? 0) > 0);
1133
+ const why = u.loss === 'payback'
1134
+ ? `more than it pays back in ${paybackTurns} turns`
1135
+ : u.loss === 'factor'
1136
+ ? `more than ${CONCEDE_FACTOR} × its worth`
1137
+ : null;
1138
+ if (more <= ps.budget &&
1139
+ fundUnit(u, undefined, `Hold bonus ${bonusName(u.bonusId)} (+${u.value}) whole: ${floored ? 'past its floor ' : ''}its ${unitBorders(u)} need${u.members.length === 1 ? 's' : ''} ${more}${floored ? ' more' : ''}${why ? ` (${why})` : ''}, ${mode === 'untrusted'
1140
+ ? `before any capture: player ${[...new Set(u.members.flatMap((m) => { const b = borders.get(m.id); return b && pc.untrustedAt(b.player, m.id) > 0 ? [b.player] : []; }))].sort((a, b) => a - b).join(', ')}'s estimate is untrusted (#275), so the border is held ahead of expansion.`
1141
+ : wholeOnly
1142
+ ? 'before any expansion that completes no bonus (1v1 in contact: an advance ranks below every hold).'
1143
+ : 'and nothing else this turn uses those armies.'}`)) {
1144
+ u.contested = false;
1145
+ continue;
1146
+ }
1147
+ if (wholeOnly)
1148
+ continue;
1149
+ // Not floored (one target for the deploy): the old concession, now that the captures had their turn.
1150
+ if (!u.floored) {
1151
+ u.contested = false;
1152
+ concedeUnit(u, u.loss ? { economic: u.loss } : { economic: false, left: leftFor(u) }, singleLate);
1153
+ // As a conceded border always could: it may still attack out (rule 1a).
1154
+ for (const m of u.members)
1155
+ if (conceded.has(m.id))
1156
+ locked.delete(m.id);
1157
+ }
1158
+ }
1159
+ if (mode === 'untrusted')
1160
+ fillUntrustedGates(open.filter((u) => u.contested));
1161
+ if (wholeOnly)
1162
+ return;
1163
+ const short = units
1164
+ .filter((u) => u.contested && !u.conceded)
1165
+ .flatMap((u) => u.members.filter((m) => !heldBorders.has(m.id)).map((m) => ({ m, u })));
1166
+ const value = (m) => Math.max(...short.filter((x) => x.m === m).map((x) => x.u.value));
1167
+ const members = [...new Set(short.map((x) => x.m))];
1168
+ const given = new Map();
1169
+ const breakCost = (m) => breakCostWith(m, m.have);
1170
+ if (spreadFloored)
1171
+ rationale.push(`Spread what is left over the floored bonuses' borders rather than hold one whole: against the opponent's best use of its deploy that loses less.`);
1172
+ while (ps.budget > 0) {
1173
+ const next = members
1174
+ .filter((m) => m.holdCost > 0 && roomAt(m.id) > 0)
1175
+ .sort((a, b) => breakCost(a) - breakCost(b) || value(b) - value(a) || a.id - b.id)[0];
1176
+ if (!next)
1177
+ break;
1178
+ give(next, 1);
1179
+ given.set(next, (given.get(next) ?? 0) + 1);
1180
+ }
1181
+ for (const [m, n] of [...given].sort((a, b) => a[0].id - b[0].id))
1182
+ rationale.push(m.holdCost <= 0
1183
+ ? `Deploy ${n} more to ${label(m.id)} so it holds (${m.have} armies, ${toTake(m.have + m.units)} to take, above the ~${m.threat} threat).`
1184
+ : `Deploy ${n} more to ${label(m.id)} against the one shared deploy: ${m.have} armies, so player ${borders.get(m.id)?.player}'s deploy needs ${breakCost(m)} of its ~${deployShare(m)} there to take it.`);
1185
+ for (const m of members)
1186
+ if (m.holdCost <= 0)
1187
+ heldBorders.add(m.id);
1188
+ const stillShort = [];
1189
+ for (const u of units) {
1190
+ if (!u.contested || u.conceded)
1191
+ continue;
1192
+ const left = u.members.filter((m) => !heldBorders.has(m.id));
1193
+ if (!left.length) {
1194
+ u.contested = false;
1195
+ continue;
1196
+ }
1197
+ stillShort.push(u);
1198
+ warnings.push(`Bonus ${bonusName(u.bonusId)} (+${u.value}) is not safe against the whole enemy deploy (its ${unitBorders(u)} would need ${left.reduce((n, m) => n + m.holdCost, 0)} more), but it is not conceded: every border beats the armies already next to it, so it falls only to armies deployed against it — ${left.map((m) => `${label(m.id)} (${m.have} armies; ${breakCost(m)} of the ~${deployShare(m)} deploy take it)`).join(', ')}.`);
1199
+ }
1200
+ // Read together, the lines above can suggest one deploy breaks only one bonus: say what
1201
+ // each opponent's best use of its one deploy breaks (the same knapsack the spread used).
1202
+ const have = new Map(stillShort.flatMap((u) => u.members.map((m) => [m, m.have])));
1203
+ for (const r of bestResponse(stillShort, have, (m) => !heldBorders.has(m.id)).by) {
1204
+ const list = (us) => {
1205
+ const names = us.map((u) => bonusName(u.bonusId));
1206
+ return `bonus${names.length > 1 ? 'es' : ''} ${names.length > 1 ? `${names.slice(0, -1).join(', ')} and ${names.at(-1)}` : names[0]}`;
1207
+ };
1208
+ const what = r.units.length === r.of.length ? `${list(r.units)}${r.units.length > 1 ? ' at once' : ''}` : `${r.units.length} of ${list(r.of)}`;
1209
+ warnings.push(`Player ${r.player}'s ~${r.deploy} deploy can still break ${what} (${r.cost} of it needed): +${r.value} at risk this turn.`);
1210
+ }
1211
+ };
1212
+ const triage = () => {
1213
+ // ---- 1k. my commander's border is must-hold (#61) ----
1214
+ // Losing the commander eliminates me: its border is never conceded, and it is held
1215
+ // first, under every goal. When the hold does not fit, everything left that may be
1216
+ // deployed there goes there, and nothing leaves it.
1217
+ for (const t of threatened) {
1218
+ if (!t.critical)
1219
+ continue;
1220
+ heldBorders.add(t.id);
1221
+ locked.add(t.id);
1222
+ const room = roomAt(t.id);
1223
+ if (t.holdCost <= room) {
1224
+ deploy(t.id, t.holdCost);
1225
+ commanderHeld.add(t.id);
1226
+ rationale.push(`Deploy ${t.holdCost} to ${label(t.id)}: my commander stands there, so it must hold (losing the commander eliminates me): ${heldStack(t)} need ${toTake(t.have + t.units + t.holdCost)} to take, above the ~${t.threat} threat.`);
1227
+ continue;
1228
+ }
1229
+ deploy(t.id, room);
1230
+ // #274: said first. A commander that cannot walk away holds here; one walking here says so first instead.
1231
+ const stuck = pc.commanderAt !== undefined && pc.commanderAt.retreat === undefined && !pc.commanderAt.pinned && pc.commanderAt.territory === t.id;
1232
+ warnings.unshift(`My commander's territory ${label(t.id)} cannot be made safe this turn: it needs ${t.holdCost} more armies against the ~${t.threat} threat, but only ${room} can be deployed there. ${room ? `All ${room} go there, and` : 'Still,'} nothing leaves it (losing the commander eliminates me; it is never conceded)${stuck ? ': no territory of mine farther from every enemy is reachable through my land, so it cannot walk away' : ''}.`);
1233
+ }
1234
+ let triageBudget = ps.budget;
1235
+ buildUnits();
1236
+ if (goal === 'expand')
1237
+ for (const u of units)
1238
+ if (!u.loss)
1239
+ warnings.push(`goal expand does not defend held bonus ${bonusName(u.bonusId)} (+${u.value}) first: holding its ${unitBorders(u)} needs ${u.cost} (it pays back within ${paybackTurns} turns).`);
1240
+ if (!guarded)
1241
+ units.length = 0;
1242
+ /** The per-border triage of rule 1a. */
1243
+ const single = (t, quiet = false) => {
1244
+ // My commander's border is already held (rule 1k).
1245
+ if (t.critical)
1246
+ return;
1247
+ const left = Math.min(acting ? ps.budget : triageBudget, local ? roomAt(t.id) : Infinity);
1248
+ if (uneconomic(t)) {
1249
+ conceded.add(t.id);
1250
+ if (!quiet)
1251
+ warnings.push(`${label(t.id)} cannot be held economically (needs ${t.holdCost}, protects +${t.value}): conceded`);
1252
+ return;
1253
+ }
1254
+ if (balanced) {
1255
+ // #215: a hold no deploy this turn can pay for is conceded now, not left to the greedy
1256
+ // step: locked as a pending hold, its armies could not attack out (a border taken last
1257
+ // turn from a weak opponent, exempt from the economic test, sat on 7 armies beside a 2-army
1258
+ // member of an enemy bonus while the deploy went elsewhere). The budget only shrinks from
1259
+ // here, so the greedy step could never have held it.
1260
+ // Never quiet here: under `balanced` this triage runs only non-quietly (quiet concessions
1261
+ // go through the greedy step's `singleNow` / `singleLate`).
1262
+ // #215 review: not a member of a bonus this turn's captures may complete — conceded now, it
1263
+ // attacked out (under No-Split with its whole stack) before rule 1c kept it for the completed
1264
+ // bonus, empty. Left pending, the greedy step concedes it and decides once the captures are
1265
+ // known (planner.ts `concedePending`).
1266
+ if (t.holdCost > left && !mayComplete(t.id))
1267
+ return concedeUnaffordable(t, left);
1268
+ // Its armies stay put until the greedy step decides: holding assumes they are all there.
1269
+ holds.push(t);
1270
+ if (!locked.has(t.id))
1271
+ pendingLocks.add(t.id);
1272
+ locked.add(t.id);
1273
+ return;
1274
+ }
1275
+ if (t.holdCost > left) {
1276
+ if (quiet)
1277
+ conceded.add(t.id);
1278
+ else
1279
+ concedeUnaffordable(t, left);
1280
+ return;
1281
+ }
1282
+ triageBudget -= t.holdCost;
1283
+ if (acting) {
1284
+ hold(t);
1285
+ heldBorders.add(t.id);
1286
+ }
1287
+ };
1288
+ // #118: CONCEDE_FACTOR and the payback test concede a floored unit only when the armies have
1289
+ // a better use: it is kept, and held whole after the captures if what is left covers it.
1290
+ const losing = units.filter((u) => u.loss);
1291
+ floorUnits(losing);
1292
+ for (const u of losing)
1293
+ contest(u);
1294
+ const items = [
1295
+ ...units.filter((u) => !u.conceded && !u.contested).map((unit) => ({ unit })),
1296
+ ...threatened.filter((t) => !units.some((u) => u.members.some((m) => m.id === t.id))).map((border) => ({ border })),
1297
+ ];
1298
+ if (!acting) {
1299
+ // Under `balanced` the units compete in the greedy step; their members stay put.
1300
+ for (const u of units)
1301
+ if (!u.conceded && !u.contested)
1302
+ for (const m of u.members)
1303
+ locked.add(m.id);
1304
+ for (const it of items)
1305
+ if ('border' in it)
1306
+ single(it.border);
1307
+ return;
1308
+ }
1309
+ // `defend`: units and single borders by worth per army (a recent capture first).
1310
+ const key = (it) => 'unit' in it
1311
+ ? { recent: it.unit.members.some((m) => m.recentFrom !== undefined), ratio: it.unit.worth / it.unit.net, cost: it.unit.cost, id: it.unit.members[0].id }
1312
+ : { recent: it.border.recentFrom !== undefined, ratio: it.border.worth / it.border.holdCost, cost: it.border.holdCost, id: it.border.id };
1313
+ items.sort((a, b) => {
1314
+ const x = key(a);
1315
+ const y = key(b);
1316
+ return Number(y.recent) - Number(x.recent) || y.ratio - x.ratio || x.cost - y.cost || x.id - y.id;
1317
+ });
1318
+ for (const it of items) {
1319
+ if ('border' in it) {
1320
+ if (!heldBorders.has(it.border.id) && !conceded.has(it.border.id))
1321
+ single(it.border);
1322
+ continue;
1323
+ }
1324
+ if (!fundUnit(it.unit) && !fundNearMiss(it.unit))
1325
+ floorOrConcede(it.unit, leftFor(it.unit), single);
1326
+ }
1327
+ };
1328
+ return { keptShort, floorOrConcede, settleContested, triage, mayComplete };
1329
+ }
1330
+ /**
1331
+ * #215: I am known to move first (#127) — from a source the hold sizing trusts: one the user gave,
1332
+ * not the award of picks' unverified rule (`movesFirstUnverified`, #215 review) — and no opponent
1333
+ * may hold an Order Priority card (`opponentsMayHoldOrderPriority`, #215 review): played, it puts
1334
+ * its first order (an all-in on a border) before my first.
1335
+ */
1336
+ export const knownFirst = (pc) => pc.opts.movesFirst === true && pc.opts.movesFirstUnverified !== true && pc.opts.opponentsMayHoldOrderPriority !== true;
1337
+ /**
1338
+ * #215: the armies withdrawn into my `id` this turn (rule 1b) that a hold may count only if I move
1339
+ * first. A transfer in is my own order: when the opponent moves first, its first order — an all-in
1340
+ * on `id` — runs before any of mine. So unless I am known to move first (#127, {@link knownFirst})
1341
+ * they are late, and a hold sized for the worse order leaves them out. 0 when I am known to move first.
1342
+ */
1343
+ export function lateArrivals(pc, ps, id) {
1344
+ return knownFirst(pc) ? 0 : withdrawnInto(ps, id);
1345
+ }
1346
+ /**
1347
+ * #215 review: the armies a worse-order hold on my `id` leaves out. When the opponent moves first,
1348
+ * its first order runs before ALL of mine: the armies withdrawn into `id` are not there yet, and
1349
+ * the armies `id` sends out by its own orders are still there. After my orders have run, the
1350
+ * withdrawal is in and those armies are gone (the hold #127 sized). A move out of a territory is
1351
+ * scheduled after the moves into it (schedule.ts), so the worse of the two is the withdrawal less
1352
+ * what leaves: `max(0, late − sent out)`. 0 when I am known to move first.
1353
+ */
1354
+ export function lateNet(pc, ps, id) {
1355
+ const late = lateArrivals(pc, ps, id);
1356
+ return late <= 0 ? 0 : Math.max(0, late - sentOut(ps, id));
1357
+ }
1358
+ /** #215 review: the armies my `id` sends out by its own orders this turn (attacks and transfers). */
1359
+ export function sentOut(ps, id) {
1360
+ return ps.moves.reduce((n, m) => (m.from === id ? n + m.armies : n), 0);
1361
+ }
1362
+ /**
1363
+ * #215: the armies withdrawn into my `id` this turn (rule 1b), whatever the move order. Only
1364
+ * withdrawal transfers count (#215 review): `incoming` also carries a softener's survivors that come
1365
+ * home and No-Split extras, which beside an idle transfer in (rule 6) would read as withdrawn.
1366
+ */
1367
+ export function withdrawnInto(ps, id) {
1368
+ const sent = ps.moves.reduce((n, m) => (m.kind === 'transfer' && m.to === id && m.reason === 'withdraws from a conceded border' ? n + m.armies : n), 0);
1369
+ return Math.max(0, Math.min(ps.incoming.get(id) ?? 0, sent));
1370
+ }
1371
+ /** Rule 1b: withdraw from conceded borders (and Order Priority when a withdrawal must go first). */
1372
+ export function withdrawals(pc, ps, book, threats, hb, prev) {
1373
+ const { g, label, bonusName, mine, mineSet, unitsAt, toTake, noSplit } = pc;
1374
+ const { warnings, rationale, avail, locked, moves, incoming } = ps;
1375
+ const { coverOf, orderOf, warnSplit, pools, valueOf } = book;
1376
+ const local = pools !== null && pools.bonuses.length > 0;
1377
+ const { expectedAt, borders } = threats;
1378
+ const { conceded, units } = hb;
1379
+ const { stayAt, unitBorders } = prev;
1380
+ // ---- 1b. withdraw from conceded borders ----
1381
+ ps.cardAdvice = null;
1382
+ /** Conceded borders of a held bonus whose garrison stays (it holds against the expected attack). */
1383
+ const stood = new Set();
1384
+ /** Bonuses whose Local Deployment concession warning (#103) is already given. */
1385
+ const warnedLocal = new Set();
1386
+ /** Local Deployment (#103): conceded borders of a held bonus that might still hold; the leftover may go there. */
1387
+ const mayHold = new Set();
1388
+ /** Local Deployment: the armies every pool containing `id` holds this turn. */
1389
+ const poolsAt = (id) => local ? pools.bonuses.filter((p) => p.territoryIds.includes(id)).reduce((n, p) => n + p.value, 0) : 0;
1390
+ /** A border no deploy this turn can hold: its hold needs more than its pools and every free army. */
1391
+ const lostAnywayAt = (m) => local && m.holdCost > poolsAt(m.id) + pools.anywhere;
1392
+ /** A held bonus that falls whatever this turn deploys: one of its threatened borders cannot be held. */
1393
+ const lostAnyway = (u) => u.members.some(lostAnywayAt);
1394
+ const withdraw = () => {
1395
+ if (!conceded.size)
1396
+ return;
1397
+ const withdrawals = [];
1398
+ const keep = (id) => mineSet.has(id) && !conceded.has(id);
1399
+ // Borders that can hold: mine, not conceded, next to something not mine.
1400
+ const holding = mine.filter((id) => keep(id) && neighborsOf(g, id).some((n) => !mineSet.has(n)));
1401
+ for (const t of [...conceded].sort(byNum)) {
1402
+ // #179: a covered exit keeps its cover; only the rest may leave.
1403
+ const n = avail.get(t) - coverOf(t);
1404
+ // No-Split (#124): a transfer sends the whole stack, so a covered exit sends none.
1405
+ if (n <= 0 || (noSplit && coverOf(t) > 0))
1406
+ continue;
1407
+ // Issue #59: a held bonus's border keeps its garrison while it still holds against the
1408
+ // expected attack — withdrawing it would guarantee the loss.
1409
+ const held = g.map.bonuses
1410
+ .filter((b) => {
1411
+ const ts = bonusTerritories(g, b.id);
1412
+ return b.value > 0 && ts.includes(t) && ts.every((x) => mineSet.has(x));
1413
+ })
1414
+ .sort((a, b) => a.id - b.id);
1415
+ const stays = stayAt(t);
1416
+ const take = toTake(stays) ?? Infinity;
1417
+ const expected = expectedAt(t);
1418
+ if (held.length && take > expected) {
1419
+ locked.add(t);
1420
+ stood.add(t);
1421
+ rationale.push(`Keep the ${n} movable armies on ${label(t)} (not withdrawn): it is a border of held bonus ${held.map((b) => bonusName(b.id)).join(', ')}, and its ${stays} armies need ${take} to take, above the expected ~${expected} attack (movable + deploy estimate).`);
1422
+ continue;
1423
+ }
1424
+ // Local Deployment (#103): a conceded held bonus keeps its garrisons unless it truly
1425
+ // cannot be held — some threatened border needs more than its pools and every free army
1426
+ // could give it. Withdrawing turns "might lose it" into "certainly loses it".
1427
+ if (local && held.length) {
1428
+ const mine1 = units.filter((u) => u.conceded && u.members.some((m) => m.id === t));
1429
+ const maybe = mine1.filter((u) => !lostAnyway(u));
1430
+ if (maybe.length) {
1431
+ locked.add(t);
1432
+ stood.add(t);
1433
+ mayHold.add(t);
1434
+ for (const u of maybe) {
1435
+ if (warnedLocal.has(u.bonusId))
1436
+ continue;
1437
+ warnedLocal.add(u.bonusId);
1438
+ warnings.push(`Bonus ${bonusName(u.bonusId)} (+${u.value}) is conceded but might still hold: each of its ${unitBorders(u)} could be held with its own ${u.pool} local armies and the ${pools.anywhere} free ones, so its garrisons stay and its local armies defend it (withdrawing would make the loss certain); it may fall.`);
1439
+ }
1440
+ rationale.push(`Keep the ${n} movable armies on ${label(t)} (not withdrawn): bonus ${maybe.map((u) => bonusName(u.bonusId)).join(', ')} might still hold under Local Deployment, and withdrawing would guarantee the loss.`);
1441
+ continue;
1442
+ }
1443
+ for (const u of mine1) {
1444
+ if (warnedLocal.has(u.bonusId))
1445
+ continue;
1446
+ warnedLocal.add(u.bonusId);
1447
+ const worst = u.members.find((m) => lostAnywayAt(m));
1448
+ warnings.push(`Bonus ${bonusName(u.bonusId)} (+${u.value}) cannot be held: ${label(worst.id)} needs ${worst.holdCost}, more than its own ${poolsAt(worst.id)} local armies and all ${pools.anywhere} free ones could give it, so its garrisons withdraw (it is lost either way).`);
1449
+ }
1450
+ }
1451
+ // B2 (T5): never onto a truce's capped border past its cap.
1452
+ const options = neighborsOf(g, t)
1453
+ .filter((c) => keep(c) && capRoom(pc, ps, c, withdrawals) >= n)
1454
+ .map((c) => {
1455
+ const dist = bfsDistances(g, [c], { passable: keep });
1456
+ let best = Infinity;
1457
+ let value = 0;
1458
+ for (const h of holding) {
1459
+ const d = dist.get(h);
1460
+ if (d === undefined)
1461
+ continue;
1462
+ if (d < best || (d === best && valueOf(h) > value))
1463
+ [best, value] = [d, valueOf(h)];
1464
+ }
1465
+ return { id: c, best, value };
1466
+ })
1467
+ .sort((a, b) => a.best - b.best || b.value - a.value || a.id - b.id);
1468
+ const to = options[0];
1469
+ if (!to) {
1470
+ const capped = neighborsOf(g, t).some((c) => keep(c) && capRoom(pc, ps, c, withdrawals) < n);
1471
+ warnings.push(`${label(t)} is conceded and has nowhere to withdraw to${capped ? ' (a truce caps the armies on the borders beside it)' : ''}: its ${n} movable armies stay.`);
1472
+ continue;
1473
+ }
1474
+ // #118: a border of a bonus I hold in full keeps its garrison — those armies kill attackers
1475
+ // where they stand — unless withdrawing them makes another valued border hold this turn.
1476
+ // (Under Local Deployment rule 1b's pool test above decides instead.)
1477
+ if (held.length && !local) {
1478
+ const dest = borders.get(to.id);
1479
+ const at = stayAt(to.id) + unitsAt(to.id);
1480
+ const makesHold = dest !== undefined &&
1481
+ !conceded.has(to.id) &&
1482
+ valueOf(to.id) > 0 &&
1483
+ (toTake(at) ?? Infinity) <= dest.threat &&
1484
+ (toTake(at + n) ?? Infinity) > dest.threat;
1485
+ if (!makesHold) {
1486
+ locked.add(t);
1487
+ stood.add(t);
1488
+ rationale.push(`Keep the ${n} movable armies on ${label(t)} (not withdrawn): it is a border of held bonus ${held.map((b) => bonusName(b.id)).join(', ')}, and withdrawing them would make no other valued border hold this turn, while there they kill attackers.`);
1489
+ continue;
1490
+ }
1491
+ }
1492
+ if (orderOf(t)) {
1493
+ warnSplit(t, `its ${n} remaining armies are not withdrawn to ${label(to.id)}`);
1494
+ locked.add(t);
1495
+ continue;
1496
+ }
1497
+ avail.set(t, avail.get(t) - n);
1498
+ locked.add(t);
1499
+ const reason = 'withdraws from a conceded border';
1500
+ withdrawals.push({ from: t, to: to.id, armies: n, kind: 'transfer', reason });
1501
+ incoming.set(to.id, (incoming.get(to.id) ?? 0) + n);
1502
+ rationale.push(`Withdraw ${n} from ${label(t)} to ${label(to.id)}: ${reason}, toward a border that holds.`);
1503
+ warnings.push(`The withdrawal from ${label(t)} only executes if ${label(t)} is still mine when the order runs; play Order Priority so it goes first.`);
1504
+ ps.cardAdvice = 'order-priority';
1505
+ }
1506
+ // Withdrawals go first: they only execute while the border is still mine.
1507
+ moves.unshift(...withdrawals);
1508
+ };
1509
+ return { stood, mayHold, withdraw };
1510
+ }
1511
+ /** Rule 1c (R2): reconsider concessions after the capture passes; #122: garrison a bonus completed this turn. */
1512
+ export function reconsiderAndGarrison(pc, ps, book, threats, hb, prev) {
1513
+ const { g, guarded, reserve, paybackTurns, label, bonusName, mine, mineSet, unitsAt, toTake, myCommanders } = pc;
1514
+ const { warnings, rationale, deployed, locked, captured, moves } = ps;
1515
+ const { orderOf, deploy, pools, valueCache, cutCache, breachCache, valueOf } = book;
1516
+ const local = pools !== null && pools.bonuses.length > 0;
1517
+ const { borders } = threats;
1518
+ const { conceded, kept, garrisoned } = hb;
1519
+ const { stayAt, heldBorders } = prev;
1520
+ // ---- 1c. reconsider concessions after the capture passes (R2) ----
1521
+ // Triage ran before captures were known, so a border in a bonus this turn's
1522
+ // captures complete was valued +0 and conceded. Re-value every border against
1523
+ // the holdings after the captures; a conceded border in a bonus completed this
1524
+ // turn is kept (never withdrawn from) and garrisoned from the leftover.
1525
+ const reconsider = () => {
1526
+ if (!captured.size)
1527
+ return;
1528
+ ps.holdings = new Set([...mine, ...captured]);
1529
+ valueCache.clear();
1530
+ cutCache.clear();
1531
+ breachCache.clear();
1532
+ if (!conceded.size)
1533
+ return;
1534
+ for (const t of [...conceded].sort(byNum)) {
1535
+ // Already withdrawn from (rule 1b ran first): its armies are gone, and it stays conceded.
1536
+ if (moves.some((m) => m.from === t && m.reason === 'withdraws from a conceded border'))
1537
+ continue;
1538
+ const completes = g.map.bonuses
1539
+ .filter((b) => {
1540
+ const ts = bonusTerritories(g, b.id);
1541
+ return b.value > 0 && ts.includes(t) && ts.every((x) => ps.holdings.has(x)) && !ts.every((x) => mineSet.has(x));
1542
+ })
1543
+ .sort((a, b) => a.id - b.id);
1544
+ if (!completes.length)
1545
+ continue;
1546
+ conceded.delete(t);
1547
+ kept.add(t);
1548
+ locked.add(t);
1549
+ // Drop its concession warning: it is no longer conceded.
1550
+ const conceding = `${label(t)} cannot be held `;
1551
+ for (let i = warnings.length - 1; i >= 0; i--)
1552
+ if (warnings[i].startsWith(conceding) && warnings[i].endsWith(': conceded'))
1553
+ warnings.splice(i, 1);
1554
+ rationale.push(`Keep ${label(t)} (not conceded): this turn's captures complete ${completes.map((b) => `bonus ${b.name} (#${b.id}) (+${b.value})`).join(', ')}, so it protects +${valueOf(t)}.`);
1555
+ }
1556
+ };
1557
+ // (Under `defend` the withdrawal runs after the capture passes, once `reconsider` has
1558
+ // kept any border this turn's captures make valuable; it still goes first in the orders.)
1559
+ // ---- #122: a bonus completed this turn is garrisoned like a held one (rule 1h) ----
1560
+ // Its members I held at the start of the turn that face an enemy would otherwise get only the
1561
+ // leftover (rule 1c), after every advance had spent the income: live, completed bonuses stood
1562
+ // beside enemies on 1-army borders and never paid a turn. So once a capture completes a bonus,
1563
+ // its threatened members are held whole right away — before any later capture — when the holds
1564
+ // pay for themselves as a held bonus's do (cost ≤ PAYBACK_TURNS × value and ≤ CONCEDE_FACTOR ×
1565
+ // its worth) and fit what may still be deployed; otherwise they are left to the leftover as
1566
+ // before. Captured members are not garrisoned: next turn's deploys land before any attack.
1567
+ /** Bonuses whose garrison was judged (funded or not), so each is judged once. */
1568
+ const garrisonJudged = new Set();
1569
+ /** Do these deploys fit together what may still be deployed (the budget, and the pools under Local Deployment)? */
1570
+ const fitsTogether = (adds) => {
1571
+ if (adds.reduce((n, x) => n + x.d, 0) > ps.budget)
1572
+ return false;
1573
+ if (!local)
1574
+ return true;
1575
+ const next = new Map(deployed);
1576
+ for (const x of adds)
1577
+ next.set(x.id, (next.get(x.id) ?? 0) + x.d);
1578
+ return chargeDeploys(pools, next).anywhereUsed <= pools.anywhere;
1579
+ };
1580
+ const garrisonCompleted = () => {
1581
+ if (!guarded || !captured.size)
1582
+ return;
1583
+ const after = new Set([...mine, ...captured]);
1584
+ for (const b of [...g.map.bonuses].sort((x, y) => x.id - y.id)) {
1585
+ if (b.value <= 0 || garrisonJudged.has(b.id))
1586
+ continue;
1587
+ const ts = bonusTerritories(g, b.id);
1588
+ if (!ts.length || !ts.every((x) => after.has(x)) || ts.every((x) => mineSet.has(x)))
1589
+ continue;
1590
+ garrisonJudged.add(b.id);
1591
+ const todo = [];
1592
+ let have = 0;
1593
+ let split = false;
1594
+ for (const t of ts) {
1595
+ const border = borders.get(t);
1596
+ if (!mineSet.has(t) || !border || heldBorders.has(t) || myCommanders.has(t))
1597
+ continue;
1598
+ const stays = stayAt(t) + unitsAt(t);
1599
+ let d = 0;
1600
+ while ((toTake(stays + d) ?? Infinity) <= border.threat)
1601
+ d++;
1602
+ if (!d)
1603
+ continue;
1604
+ // No-Split: a deploy on a territory that already issues an order leaves with it.
1605
+ if (orderOf(t))
1606
+ split = true;
1607
+ todo.push({ id: t, d, threat: border.threat });
1608
+ have += stays;
1609
+ }
1610
+ if (!todo.length || split)
1611
+ continue;
1612
+ const cost = todo.reduce((n, x) => n + x.d, 0);
1613
+ const worth = b.value + have / paybackTurns;
1614
+ if (cost > paybackTurns * b.value || cost > CONCEDE_FACTOR * worth || cost > ps.budget - reserve)
1615
+ continue;
1616
+ // The pools are checked for the members together: each may fit the free pool on its own
1617
+ // while together they overdraw it.
1618
+ if (!fitsTogether(todo))
1619
+ continue;
1620
+ for (const x of todo) {
1621
+ deploy(x.id, x.d);
1622
+ garrisoned.add(x.id);
1623
+ heldBorders.add(x.id);
1624
+ locked.add(x.id);
1625
+ const stays = stayAt(x.id) + unitsAt(x.id);
1626
+ rationale.push(`Garrison ${label(x.id)} for bonus ${bonusName(b.id)} (+${b.value}), completed this turn: deploy ${x.d} so its ${stays} armies need ${toTake(stays)} to take, above the ~${x.threat} threat — held like a bonus held at the start, before any later capture, not left to the leftover.`);
1627
+ }
1628
+ }
1629
+ };
1630
+ return { reconsider, garrisonCompleted };
1631
+ }