@chrischall/warapp-mcp 0.7.0 → 0.9.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 (65) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +5 -4
  4. package/dist/analysis/card-support.js +12 -4
  5. package/dist/analysis/coalition.js +55 -0
  6. package/dist/analysis/local-deploy.js +14 -0
  7. package/dist/analysis/opponents.js +2 -1
  8. package/dist/analysis/picks.js +270 -37
  9. package/dist/analysis/plan/after-leftover.js +26 -4
  10. package/dist/analysis/plan/captures.js +86 -14
  11. package/dist/analysis/plan/completed.js +8 -1
  12. package/dist/analysis/plan/conceded-out.js +16 -11
  13. package/dist/analysis/plan/deploy-estimates.js +544 -0
  14. package/dist/analysis/plan/doomed-out.js +135 -0
  15. package/dist/analysis/plan/estimates.js +4 -1
  16. package/dist/analysis/plan/free-capture.js +34 -0
  17. package/dist/analysis/plan/holds.js +8 -309
  18. package/dist/analysis/plan/horizon.js +42 -0
  19. package/dist/analysis/plan/leftover.js +43 -5
  20. package/dist/analysis/plan/observe.js +896 -0
  21. package/dist/analysis/plan/orders.js +35 -1
  22. package/dist/analysis/plan/report.js +10 -4
  23. package/dist/analysis/plan/shared.js +4 -1376
  24. package/dist/analysis/plan/spread-bind.js +49 -0
  25. package/dist/analysis/plan/stand-still.js +5 -3
  26. package/dist/analysis/plan/state.js +12 -0
  27. package/dist/analysis/plan/strike-stack.js +467 -0
  28. package/dist/analysis/plan/strike.js +3 -463
  29. package/dist/analysis/plan/targets.js +219 -28
  30. package/dist/analysis/plan/threats.js +23 -9
  31. package/dist/analysis/plan/transfers.js +24 -1
  32. package/dist/analysis/plan/two-move.js +1 -1
  33. package/dist/analysis/plan/withdraw.js +316 -0
  34. package/dist/analysis/planner.js +106 -43
  35. package/dist/analysis/player.js +4 -0
  36. package/dist/analysis/relations.js +8 -2
  37. package/dist/analysis/stress.js +1 -1
  38. package/dist/bundle.js +4578 -3405
  39. package/dist/cards.js +37 -0
  40. package/dist/my-games.js +2 -0
  41. package/dist/my-orders.js +134 -0
  42. package/dist/open-games.js +94 -10
  43. package/dist/team-cards.js +2 -2
  44. package/dist/team-orders.js +51 -23
  45. package/dist/tools/card-advice.js +57 -13
  46. package/dist/tools/card-support-advice.js +17 -1
  47. package/dist/tools/check-plan.js +2 -1
  48. package/dist/tools/commander-check.js +2 -1
  49. package/dist/tools/decision-capture.js +4 -2
  50. package/dist/tools/index.js +3 -0
  51. package/dist/tools/join-game.js +44 -8
  52. package/dist/tools/live.js +43 -5
  53. package/dist/tools/my-orders.js +110 -0
  54. package/dist/tools/open-games.js +2 -2
  55. package/dist/tools/picks.js +128 -51
  56. package/dist/tools/team-brief.js +1 -1
  57. package/dist/tools/team.js +25 -9
  58. package/dist/tools/turn.js +61 -6
  59. package/dist/tools/uncommit.js +27 -5
  60. package/dist/trend.js +36 -1
  61. package/dist/version.js +1 -1
  62. package/manifest.json +5 -1
  63. package/package.json +1 -1
  64. package/server.json +2 -2
  65. package/skills/warapp-mcp/SKILL.md +9 -2
@@ -0,0 +1,316 @@
1
+ // Withdrawals from conceded borders (rule 1b), the concessions this turn's captures make worth keeping
2
+ // (rule 1c, R2) and the garrisons of bonuses completed this turn (#122) — split from holds.ts, which
3
+ // re-exports it. Also the move-order helpers those rules share (`knownFirst`, `lateNet`, `sentOut`).
4
+ import { bonusTerritories } from '../bonuses.js';
5
+ import { bfsDistances, neighborsOf } from '../graph.js';
6
+ import { chargeDeploys } from '../local-deploy.js';
7
+ import { CONCEDE_FACTOR, } from './shared.js';
8
+ import { capRoom, } from './relations.js';
9
+ import { paybackLive } from './state.js';
10
+ import { byNum } from './util.js';
11
+ /**
12
+ * #215: I am known to move first (#127) — from a source the hold sizing trusts: one the user gave,
13
+ * not the award of picks' unverified rule (`movesFirstUnverified`, #215 review) — and no opponent
14
+ * may hold an Order Priority card (`opponentsMayHoldOrderPriority`, #215 review): played, it puts
15
+ * its first order (an all-in on a border) before my first.
16
+ */
17
+ export const knownFirst = (pc) => pc.opts.movesFirst === true && pc.opts.movesFirstUnverified !== true && pc.opts.opponentsMayHoldOrderPriority !== true;
18
+ /**
19
+ * #215: the armies withdrawn into my `id` this turn (rule 1b) that a hold may count only if I move
20
+ * first. A transfer in is my own order: when the opponent moves first, its first order — an all-in
21
+ * on `id` — runs before any of mine. So unless I am known to move first (#127, {@link knownFirst})
22
+ * they are late, and a hold sized for the worse order leaves them out. 0 when I am known to move first.
23
+ */
24
+ export function lateArrivals(pc, ps, id) {
25
+ return knownFirst(pc) ? 0 : withdrawnInto(ps, id);
26
+ }
27
+ /**
28
+ * #215 review: the armies a worse-order hold on my `id` leaves out. When the opponent moves first,
29
+ * its first order runs before ALL of mine: the armies withdrawn into `id` are not there yet, and
30
+ * the armies `id` sends out by its own orders are still there. After my orders have run, the
31
+ * withdrawal is in and those armies are gone (the hold #127 sized). A move out of a territory is
32
+ * scheduled after the moves into it (schedule.ts), so the worse of the two is the withdrawal less
33
+ * what leaves: `max(0, late − sent out)`. 0 when I am known to move first.
34
+ */
35
+ export function lateNet(pc, ps, id) {
36
+ const late = lateArrivals(pc, ps, id);
37
+ return late <= 0 ? 0 : Math.max(0, late - sentOut(ps, id));
38
+ }
39
+ /** #215 review: the armies my `id` sends out by its own orders this turn (attacks and transfers). */
40
+ export function sentOut(ps, id) {
41
+ return ps.moves.reduce((n, m) => (m.from === id ? n + m.armies : n), 0);
42
+ }
43
+ /**
44
+ * #215: the armies withdrawn into my `id` this turn (rule 1b), whatever the move order. Only
45
+ * withdrawal transfers count (#215 review): `incoming` also carries a softener's survivors that come
46
+ * home and No-Split extras, which beside an idle transfer in (rule 6) would read as withdrawn.
47
+ */
48
+ export function withdrawnInto(ps, id) {
49
+ 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);
50
+ return Math.max(0, Math.min(ps.incoming.get(id) ?? 0, sent));
51
+ }
52
+ /** Rule 1b: withdraw from conceded borders (and Order Priority when a withdrawal must go first). */
53
+ export function withdrawals(pc, ps, book, threats, hb, prev) {
54
+ const { g, label, bonusName, mine, mineSet, unitsAt, toTake, noSplit } = pc;
55
+ const { warnings, rationale, avail, locked, moves, incoming } = ps;
56
+ const { coverOf, orderOf, warnSplit, pools, valueOf } = book;
57
+ const local = pools !== null && pools.bonuses.length > 0;
58
+ const { expectedAt, borders } = threats;
59
+ const { conceded, units } = hb;
60
+ const { stayAt, unitBorders } = prev;
61
+ // ---- 1b. withdraw from conceded borders ----
62
+ ps.cardAdvice = null;
63
+ /** Conceded borders of a held bonus whose garrison stays (it holds against the expected attack). */
64
+ const stood = new Set();
65
+ /** Bonuses whose Local Deployment concession warning (#103) is already given. */
66
+ const warnedLocal = new Set();
67
+ /** Local Deployment (#103): conceded borders of a held bonus that might still hold; the leftover may go there. */
68
+ const mayHold = new Set();
69
+ /** Local Deployment: the armies every pool containing `id` holds this turn. */
70
+ const poolsAt = (id) => local ? pools.bonuses.filter((p) => p.territoryIds.includes(id)).reduce((n, p) => n + p.value, 0) : 0;
71
+ /** A border no deploy this turn can hold: its hold needs more than its pools and every free army. */
72
+ const lostAnywayAt = (m) => local && m.holdCost > poolsAt(m.id) + pools.anywhere;
73
+ /** A held bonus that falls whatever this turn deploys: one of its threatened borders cannot be held. */
74
+ const lostAnyway = (u) => u.members.some(lostAnywayAt);
75
+ const withdraw = () => {
76
+ if (!conceded.size)
77
+ return;
78
+ const withdrawals = [];
79
+ const keep = (id) => mineSet.has(id) && !conceded.has(id);
80
+ // Borders that can hold: mine, not conceded, next to something not mine.
81
+ const holding = mine.filter((id) => keep(id) && neighborsOf(g, id).some((n) => !mineSet.has(n)));
82
+ for (const t of [...conceded].sort(byNum)) {
83
+ // #179: a covered exit keeps its cover; only the rest may leave.
84
+ const n = avail.get(t) - coverOf(t);
85
+ // No-Split (#124): a transfer sends the whole stack, so a covered exit sends none.
86
+ if (n <= 0 || (noSplit && coverOf(t) > 0))
87
+ continue;
88
+ // Issue #59: a held bonus's border keeps its garrison while it still holds against the
89
+ // expected attack — withdrawing it would guarantee the loss.
90
+ const held = g.map.bonuses
91
+ .filter((b) => {
92
+ const ts = bonusTerritories(g, b.id);
93
+ return b.value > 0 && ts.includes(t) && ts.every((x) => mineSet.has(x));
94
+ })
95
+ .sort((a, b) => a.id - b.id);
96
+ const stays = stayAt(t);
97
+ const take = toTake(stays) ?? Infinity;
98
+ const expected = expectedAt(t);
99
+ if (held.length && take > expected) {
100
+ locked.add(t);
101
+ stood.add(t);
102
+ 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).`);
103
+ continue;
104
+ }
105
+ // Local Deployment (#103): a conceded held bonus keeps its garrisons unless it truly
106
+ // cannot be held — some threatened border needs more than its pools and every free army
107
+ // could give it. Withdrawing turns "might lose it" into "certainly loses it".
108
+ if (local && held.length) {
109
+ const mine1 = units.filter((u) => u.conceded && u.members.some((m) => m.id === t));
110
+ const maybe = mine1.filter((u) => !lostAnyway(u));
111
+ if (maybe.length) {
112
+ locked.add(t);
113
+ stood.add(t);
114
+ mayHold.add(t);
115
+ for (const u of maybe) {
116
+ if (warnedLocal.has(u.bonusId))
117
+ continue;
118
+ warnedLocal.add(u.bonusId);
119
+ 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.`);
120
+ }
121
+ 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.`);
122
+ continue;
123
+ }
124
+ for (const u of mine1) {
125
+ if (warnedLocal.has(u.bonusId))
126
+ continue;
127
+ warnedLocal.add(u.bonusId);
128
+ const worst = u.members.find((m) => lostAnywayAt(m));
129
+ 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).`);
130
+ }
131
+ }
132
+ // B2 (T5): never onto a truce's capped border past its cap.
133
+ const options = neighborsOf(g, t)
134
+ .filter((c) => keep(c) && capRoom(pc, ps, c, withdrawals) >= n)
135
+ .map((c) => {
136
+ const dist = bfsDistances(g, [c], { passable: keep });
137
+ let best = Infinity;
138
+ let value = 0;
139
+ for (const h of holding) {
140
+ const d = dist.get(h);
141
+ if (d === undefined)
142
+ continue;
143
+ if (d < best || (d === best && valueOf(h) > value))
144
+ [best, value] = [d, valueOf(h)];
145
+ }
146
+ return { id: c, best, value };
147
+ })
148
+ .sort((a, b) => a.best - b.best || b.value - a.value || a.id - b.id);
149
+ const to = options[0];
150
+ if (!to) {
151
+ const capped = neighborsOf(g, t).some((c) => keep(c) && capRoom(pc, ps, c, withdrawals) < n);
152
+ 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.`);
153
+ continue;
154
+ }
155
+ // #118: a border of a bonus I hold in full keeps its garrison — those armies kill attackers
156
+ // where they stand — unless withdrawing them makes another valued border hold this turn.
157
+ // (Under Local Deployment rule 1b's pool test above decides instead.)
158
+ if (held.length && !local) {
159
+ const dest = borders.get(to.id);
160
+ const at = stayAt(to.id) + unitsAt(to.id);
161
+ const makesHold = dest !== undefined &&
162
+ !conceded.has(to.id) &&
163
+ valueOf(to.id) > 0 &&
164
+ (toTake(at) ?? Infinity) <= dest.threat &&
165
+ (toTake(at + n) ?? Infinity) > dest.threat;
166
+ if (!makesHold) {
167
+ locked.add(t);
168
+ stood.add(t);
169
+ 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.`);
170
+ continue;
171
+ }
172
+ }
173
+ if (orderOf(t)) {
174
+ warnSplit(t, `its ${n} remaining armies are not withdrawn to ${label(to.id)}`);
175
+ locked.add(t);
176
+ continue;
177
+ }
178
+ avail.set(t, avail.get(t) - n);
179
+ locked.add(t);
180
+ const reason = 'withdraws from a conceded border';
181
+ withdrawals.push({ from: t, to: to.id, armies: n, kind: 'transfer', reason });
182
+ incoming.set(to.id, (incoming.get(to.id) ?? 0) + n);
183
+ rationale.push(`Withdraw ${n} from ${label(t)} to ${label(to.id)}: ${reason}, toward a border that holds.`);
184
+ 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.`);
185
+ ps.cardAdvice = 'order-priority';
186
+ }
187
+ // Withdrawals go first: they only execute while the border is still mine.
188
+ moves.unshift(...withdrawals);
189
+ };
190
+ return { stood, mayHold, withdraw };
191
+ }
192
+ /** Rule 1c (R2): reconsider concessions after the capture passes; #122: garrison a bonus completed this turn. */
193
+ export function reconsiderAndGarrison(pc, ps, book, threats, hb, prev) {
194
+ const { g, guarded, reserve, paybackTurns, label, bonusName, mine, mineSet, unitsAt, toTake, myCommanders } = pc;
195
+ const { warnings, rationale, deployed, locked, captured, moves } = ps;
196
+ const { orderOf, deploy, pools, valueCache, cutCache, breachCache, opensCache, valueOf } = book;
197
+ const local = pools !== null && pools.bonuses.length > 0;
198
+ const { borders } = threats;
199
+ const { conceded, kept, garrisoned } = hb;
200
+ const { stayAt, heldBorders } = prev;
201
+ // ---- 1c. reconsider concessions after the capture passes (R2) ----
202
+ // Triage ran before captures were known, so a border in a bonus this turn's
203
+ // captures complete was valued +0 and conceded. Re-value every border against
204
+ // the holdings after the captures; a conceded border in a bonus completed this
205
+ // turn is kept (never withdrawn from) and garrisoned from the leftover.
206
+ const reconsider = () => {
207
+ if (!captured.size)
208
+ return;
209
+ ps.holdings = new Set([...mine, ...captured]);
210
+ valueCache.clear();
211
+ cutCache.clear();
212
+ breachCache.clear();
213
+ opensCache.clear();
214
+ if (!conceded.size)
215
+ return;
216
+ for (const t of [...conceded].sort(byNum)) {
217
+ // Already withdrawn from (rule 1b ran first): its armies are gone, and it stays conceded.
218
+ if (moves.some((m) => m.from === t && m.reason === 'withdraws from a conceded border'))
219
+ continue;
220
+ const completes = g.map.bonuses
221
+ .filter((b) => {
222
+ const ts = bonusTerritories(g, b.id);
223
+ // #422: a payback completion is expected to fall next turn: it keeps no conceded border.
224
+ return (b.value > 0 && !paybackLive(ps, ps.paybackBonuses, b.id) && ts.includes(t) && ts.every((x) => ps.holdings.has(x)) && !ts.every((x) => mineSet.has(x)));
225
+ })
226
+ .sort((a, b) => a.id - b.id);
227
+ if (!completes.length)
228
+ continue;
229
+ conceded.delete(t);
230
+ kept.add(t);
231
+ locked.add(t);
232
+ // Drop its concession warning: it is no longer conceded.
233
+ const conceding = `${label(t)} cannot be held `;
234
+ for (let i = warnings.length - 1; i >= 0; i--)
235
+ if (warnings[i].startsWith(conceding) && warnings[i].endsWith(': conceded'))
236
+ warnings.splice(i, 1);
237
+ 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)}.`);
238
+ }
239
+ };
240
+ // (Under `defend` the withdrawal runs after the capture passes, once `reconsider` has
241
+ // kept any border this turn's captures make valuable; it still goes first in the orders.)
242
+ // ---- #122: a bonus completed this turn is garrisoned like a held one (rule 1h) ----
243
+ // Its members I held at the start of the turn that face an enemy would otherwise get only the
244
+ // leftover (rule 1c), after every advance had spent the income: live, completed bonuses stood
245
+ // beside enemies on 1-army borders and never paid a turn. So once a capture completes a bonus,
246
+ // its threatened members are held whole right away — before any later capture — when the holds
247
+ // pay for themselves as a held bonus's do (cost ≤ PAYBACK_TURNS × value and ≤ CONCEDE_FACTOR ×
248
+ // its worth) and fit what may still be deployed; otherwise they are left to the leftover as
249
+ // before. Captured members are not garrisoned: next turn's deploys land before any attack.
250
+ /** Bonuses whose garrison was judged (funded or not), so each is judged once. */
251
+ const garrisonJudged = new Set();
252
+ /** Do these deploys fit together what may still be deployed (the budget, and the pools under Local Deployment)? */
253
+ const fitsTogether = (adds) => {
254
+ if (adds.reduce((n, x) => n + x.d, 0) > ps.budget)
255
+ return false;
256
+ if (!local)
257
+ return true;
258
+ const next = new Map(deployed);
259
+ for (const x of adds)
260
+ next.set(x.id, (next.get(x.id) ?? 0) + x.d);
261
+ return chargeDeploys(pools, next).anywhereUsed <= pools.anywhere;
262
+ };
263
+ const garrisonCompleted = () => {
264
+ if (!guarded || !captured.size)
265
+ return;
266
+ const after = new Set([...mine, ...captured]);
267
+ for (const b of [...g.map.bonuses].sort((x, y) => x.id - y.id)) {
268
+ // #422: a payback completion is expected to fall next turn: no garrison is thrown after it.
269
+ if (b.value <= 0 || garrisonJudged.has(b.id) || paybackLive(ps, ps.paybackBonuses, b.id))
270
+ continue;
271
+ const ts = bonusTerritories(g, b.id);
272
+ if (!ts.length || !ts.every((x) => after.has(x)) || ts.every((x) => mineSet.has(x)))
273
+ continue;
274
+ garrisonJudged.add(b.id);
275
+ const todo = [];
276
+ let have = 0;
277
+ let split = false;
278
+ for (const t of ts) {
279
+ const border = borders.get(t);
280
+ if (!mineSet.has(t) || !border || heldBorders.has(t) || myCommanders.has(t))
281
+ continue;
282
+ const stays = stayAt(t) + unitsAt(t);
283
+ let d = 0;
284
+ while ((toTake(stays + d) ?? Infinity) <= border.threat)
285
+ d++;
286
+ if (!d)
287
+ continue;
288
+ // No-Split: a deploy on a territory that already issues an order leaves with it.
289
+ if (orderOf(t))
290
+ split = true;
291
+ todo.push({ id: t, d, threat: border.threat });
292
+ have += stays;
293
+ }
294
+ if (!todo.length || split)
295
+ continue;
296
+ const cost = todo.reduce((n, x) => n + x.d, 0);
297
+ const worth = b.value + have / paybackTurns;
298
+ // #421: the strike share holds back captures only, never this garrison.
299
+ if (cost > paybackTurns * b.value || cost > CONCEDE_FACTOR * worth || cost > ps.budget - (reserve - pc.strikeShare))
300
+ continue;
301
+ // The pools are checked for the members together: each may fit the free pool on its own
302
+ // while together they overdraw it.
303
+ if (!fitsTogether(todo))
304
+ continue;
305
+ for (const x of todo) {
306
+ deploy(x.id, x.d);
307
+ garrisoned.add(x.id);
308
+ heldBorders.add(x.id);
309
+ locked.add(x.id);
310
+ const stays = stayAt(x.id) + unitsAt(x.id);
311
+ 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.`);
312
+ }
313
+ }
314
+ };
315
+ return { reconsider, garrisonCompleted };
316
+ }
@@ -17,6 +17,7 @@
17
17
  // 4h. the army cap prices idle armies (#253) .................. plan/cap-spend.ts
18
18
  // 5. the leftover deploy, 3b's short borders (#121) ........... plan/leftover.ts
19
19
  // 5b. a neutral the leftover pays for (#218) ................. plan/after-leftover.ts
20
+ // #319's bind (#416): other expansion waits for the nearest bonus .. plan/spread-bind.ts
20
21
  // 6. transfers, #125 staging ................................. plan/transfers.ts
21
22
  // #277: a held bonus funded from a second sure sizing ......... plan/second-sizing.ts
22
23
  // 7. move order, rule 1s's Order Priority ..................... plan/move-order.ts
@@ -514,9 +515,10 @@
514
515
  // and counts. The leftover's revival may still hold a capped border after all. Off under a `defend`
515
516
  // goal the caller gave, and with `options.holdCap: false` (tests of earlier hold rules use it).
516
517
  // 1a. Triage (every goal). Each threatened border's protected value is the sum
517
- // of my complete bonuses containing it, plus incomplete bonuses containing it
518
- // that I would lose all access to without it, plus (#122) its share of every other
519
- // incomplete bonus containing it that I am building — value × the members I hold ÷ its
518
+ // of my complete bonuses containing it, plus (#122) its share of every
519
+ // incomplete bonus containing it that I am building (#425: one it is my only way into
520
+ // included — it used to count whole, whatever stood on the rest; now its share, and nothing
521
+ // when an enemy holds or roams a member; a fogged member keeps it, owner decision 2026-11-22) — value × the members I hold ÷ its
520
522
  // size, one decimal, when every missing member is a visible neutral and finishing it passes
521
523
  // rule 4's economy tests (PAYBACK_TURNS, WASTELAND_FACTOR); #298: or when the missing members
522
524
  // are visible neutrals and visible foe territories, one of them a foe's movable stack beside the
@@ -828,6 +830,11 @@
828
830
  // absorbed by its own neighbours' growth) and is now cheaper to take than it
829
831
  // was; never under `expand`/`defend`). Fogged or unknown neighbours are never attacked — they
830
832
  // produce a warning.
833
+ // #430 (owner decision of 2026-11-22): under `balanced`, the opponents' territories that retake
834
+ // a bonus I held in full on `previousBoard` are bonus targets too, in every format, when the retake
835
+ // completes it this turn (every missing member in view, beside mine), costs at most RETAKE_VALUE_TURNS
836
+ // (5) × its value, and the profile does not read me behind; it ranks as any completion, so a stronger hold
837
+ // funds first (plan/targets.ts, `retakeMembers`).
831
838
  // 3. Capture cost (#126): the fewest armies whose exact `winChance` reaches the capture's
832
839
  // chance — certain (chance 1) means every roll and rounding takes it: `armiesToTake` at 0%
833
840
  // luck under straight rounding, one army more where weighted-random rounding could round a
@@ -942,7 +949,10 @@
942
949
  // scored by its net worth (rule 4c), not its value, in every test above.
943
950
  // One owner per bonus (PLAN-TEAMS C3.3): a positive bonus with a member my teammate visibly
944
951
  // holds is not scored at all (a bonus pays only the player holding every member), focused or
945
- // not (a focus on it is ignored with a warning); its other members are plain expansion. The
952
+ // not (a focus on it is ignored with a warning); its other members are plain expansion — unless
953
+ // (#435) the Gift card is in play (`game.cardsInPlay`) and I alone hold the most members: then it is mine to work, its other members scored and
954
+ // advanced, the teammate's left for them to hand over (a Gift), never completable while they
955
+ // stand; an uneconomic one is still skipped as before. The
946
956
  // plan's `team.sharedBonuses` (plan/team.ts) lists each such bonus I hold members of too, and
947
957
  // who holds the most (`nearer`), from the start-of-turn board. No-team plans are unchanged.
948
958
  // Team focus (PLAN-TEAMS C3.4): with my teammates' entered orders read (V5, unverified), a
@@ -1018,7 +1028,13 @@
1018
1028
  // bonuses this turn's earlier captures completed share the same next income (their added
1019
1029
  // needs count too). Then: under `balanced`/`defend` the capture is
1020
1030
  // refused (warning "… indefensible …: not completed"); under `expand` and
1021
- // `complete-bonus` it is made with a warning. Under `balanced`/`defend` a bonus's
1031
+ // `complete-bonus` it is made with a warning. #422, the payback exemption: a completion whose
1032
+ // losses — the attackers its captures into the bonus lose this turn plus the armies left on the
1033
+ // members that would fall — are at most the bonus's value is made anyway (a "Complete bonus …
1034
+ // (#422)" line): held at the end of this turn, the bonus pays that value next turn even if it
1035
+ // falls after. Such a bonus keeps no conceded border (rule 1c), gets no #122 garrison or #265
1036
+ // weak-member call, and the leftover never rides an attack onto a member it may lose (#288).
1037
+ // Under `balanced`/`defend` a bonus's
1022
1038
  // score is value / (capture cost + DEFENSE_DISCOUNT × that defence cost).
1023
1039
  // 4d. Frontier cost (#71). Every capture pays for the frontier it adds, in armies: for each
1024
1040
  // territory it touches (the capture and its held neighbours), its border cost after minus
@@ -1076,6 +1092,10 @@
1076
1092
  // rule 4e's contact fallback, where 4d is only a cost (#114), runs it too. The plan reports `gates` (each gate's
1077
1093
  // need and armies, conceded ones marked, the summed need, what stands on them, the per-gate deficit, the next
1078
1094
  // income and the shortfall) and warns when its own captures open a gate the income cannot hold.
1095
+ // #426 (draft): a no-loss neutral (its defenders kill none of my attackers, `noLossNeutral`) is taken
1096
+ // by pass 3 even in an uneconomic bonus, and rule 4d lets one through when only the fog faces its new
1097
+ // border and the hold it adds is at most 1× the next income (`outgrows`, not in a 1v1); a stack idle two
1098
+ // turns beside one is warned of (plan/free-capture.ts).
1079
1099
  // 4e. Never stand still (#104, #107; every goal but `complete-bonus`, after pass 3). A plan that
1080
1100
  // makes no capture at all (no expansion, break, finishing off or strike) in the opening or
1081
1101
  // expansion phase takes one neutral capture toward a positive bonus (net > 0, never a negative
@@ -1208,6 +1228,16 @@
1208
1228
  // at least TWO_MOVE_MIN_VALUE two moves away through a visible neutral is a two-turn completion
1209
1229
  // (cost: that neutral plus the territory); the neutral in between is a `stage` candidate under
1210
1230
  // `balanced` (net over both costs, ranked as an advance), else taken before the advances.
1231
+ // #319 binds (#416, owner 2026-11-22; plan/spread-bind.ts): while #319's opening warning fires, pass-3
1232
+ // plain expansion and advances into other bonuses may not spend deploys, or armies on a territory beside the
1233
+ // nearest bonus's missing members, until that bonus's reachable steps are funded. Holds keep their places.
1234
+ // The nearest bonus is the one the warning names; its reachable steps are its missing members that are
1235
+ // capture targets beside a territory of mine; funded = captured by this plan, after which the rest flows
1236
+ // as before (a step refused for another reason keeps the bind for the turn: the leftover saves toward it).
1237
+ // A stack beside two bonuses' missing members is the nearest bonus's. Bound: other bonuses' advances (pass
1238
+ // 2, the `balanced` advance slots, #439's stage), pass 3 and rule 5b; never the bonus's own members, a
1239
+ // focused bonus, completions, holds, breaks, counters, the 1v1 race, strikes, rule 4e, 4g or 4h. What is
1240
+ // bound may still attack with the armies on my other territories. A "#319 binds the deploys" line says so.
1211
1241
  // 3b. One surplus per territory (#121). A border that holds at the start of the turn (its armies
1212
1242
  // beat its visible threat, rule 1) and is not conceded keeps what holds it, as my commander's
1213
1243
  // territory does (rule 1k): a capture from it spends only its armies above that, plus deploys
@@ -1325,6 +1355,10 @@
1325
1355
  // S …, the C sent leave L, above the H that hold it …"); a capture removes rule 4e's
1326
1356
  // stand-still warning, and a refused try leaves no line.
1327
1357
  // 6. Idle armies on interior territories transfer one step toward the front,
1358
+ // When no front and no territory not mine is reachable without crossing a border the plan concedes (the
1359
+ // last neutral taken, the enemy past those borders; owner 2026-11-22, golden s246), an idle interior stack
1360
+ // walks up behind the conceded borders on the way to the enemy — never into one, never into a territory an
1361
+ // attack leaves from this turn or one beside a rival at the start of the turn — and waits beside them (#367).
1328
1362
  // only into territories held at the start of the turn and never into, or
1329
1363
  // measured through, a conceded border
1330
1364
  // (unless `idleTransfers` is off: the planner's own switch, not war.app's AllowTransferOnly,
@@ -1646,12 +1680,15 @@ import { neutralizeSeats, seatTerritories, staticSeats } from './static-seats.js
1646
1680
  import { deployBook } from './plan/orders.js';
1647
1681
  import { holdsPhase, priorOnlyHold } from './plan/holds.js';
1648
1682
  import { threatsPhase } from './plan/threats.js';
1683
+ import { applyShortGates } from './plan/horizon.js';
1649
1684
  import { targetsPhase } from './plan/targets.js';
1650
1685
  import { capturesPhase } from './plan/captures.js';
1686
+ import { spreadBind } from './plan/spread-bind.js';
1651
1687
  import { completedMembers } from './plan/completed.js';
1652
1688
  import { chooseStrikeStack, leadStrikes, spendStrikeStack, strikesPhase } from './plan/strike.js';
1653
1689
  import { contestedBonuses } from './plan/stockpile.js';
1654
- import { afterLeftoverCaptures, plainEconomy, plainEligible } from './plan/after-leftover.js';
1690
+ import { warnIdleBesideFree } from './plan/free-capture.js';
1691
+ import { afterLeftoverCaptures, onlyNoLoss, plainEconomy, plainEligible } from './plan/after-leftover.js';
1655
1692
  import { fundFromSecondSizing } from './plan/second-sizing.js';
1656
1693
  import { leftoverDeploy } from './plan/leftover.js';
1657
1694
  import { fillSecondLine, guardOffRaids } from './plan/guard-off.js';
@@ -1660,6 +1697,7 @@ import { stageTwoMove, twoMoveStages } from './plan/two-move.js';
1660
1697
  import { addEmptyEnemyTargets, dropEmptyEnemyTargets, foggedLastSeen, plainOrderCosts, raceLine, raceTargets, tryEmptyEnemy, withoutTransit } from './plan/vacated.js';
1661
1698
  import { spendUnderCap } from './plan/cap-spend.js';
1662
1699
  import { attackOutOfConceded } from './plan/conceded-out.js';
1700
+ import { doomedConcededOut } from './plan/doomed-out.js';
1663
1701
  import { captureInsteadOfHold } from './plan/capture-instead.js';
1664
1702
  import { transfers } from './plan/transfers.js';
1665
1703
  import { scheduleOrders, strikeOrderPriority } from './plan/move-order.js';
@@ -1669,9 +1707,11 @@ import { newPlanState } from './plan/state.js';
1669
1707
  import { teamFocusLine, teamReport } from './plan/team.js';
1670
1708
  import { applyBorderCaps, armiesFreed, partnerFronts, reportBreakLosses, reportTruce, trucePass, warnTruceNeutrals } from './plan/relations.js';
1671
1709
  export * from './plan/shared.js';
1710
+ export * from './plan/observe.js';
1711
+ export * from './plan/deploy-estimates.js';
1672
1712
  export { alliesOf, planEnemyEstimates } from './plan/estimates.js';
1673
1713
  export { TRUCE_RELAX_VALUE } from './plan/relations.js';
1674
- export { SPREAD_INCOME_SLACK, SPREAD_LAST_TURN, SPREAD_TERRITORIES } from './plan/targets.js';
1714
+ export { HOLDS_BONUS_MIN_VALUE, SPREAD_INCOME_SLACK, SPREAD_LAST_TURN, SPREAD_TERRITORIES } from './plan/targets.js';
1675
1715
  /** Passes that refine the cut set (#172) before falling back to the plan that cuts nothing. */
1676
1716
  const TWO_STEP_PASSES = 3;
1677
1717
  /** Passes that learn which territories in between end held (#172) before none is counted held. */
@@ -1990,6 +2030,9 @@ function planPass(input, pass) {
1990
2030
  const local = pools !== null && pools.bonuses.length > 0;
1991
2031
  // ---- 1t. threat trend, 1. defence (plan/threats.ts) ----
1992
2032
  const threats = threatsPhase(pc, ps, input, book.valueOf);
2033
+ // #432: a 1v1 whose gates are short at the start judges its captures on a shorter payback horizon from here on
2034
+ // (every capture test after this reads `pc.capturePaybackTurns`; holds keep `paybackTurns`).
2035
+ applyShortGates(pc, ps, threats);
1993
2036
  const { growthOf, reinforcementAt, borders, facing, borderAt } = threats;
1994
2037
  // ---- 1. holds, #172, 1h, 1b, 1c, #122 garrisons (plan/holds.ts) ----
1995
2038
  const hd = holdsPhase(pc, ps, book, threats, pass);
@@ -2007,6 +2050,10 @@ function planPass(input, pass) {
2007
2050
  const { strikes, worstCase, defendersAt, tryCapture, snapshot, complete, tryExpand, advance } = caps;
2008
2051
  /** #439: single-territory bonuses two moves away, each with its neutral in between. */
2009
2052
  const stages = twoMoveStages(pc, tgt);
2053
+ /** #416 part 4: while #319 fires, other advances and pass 3 wait for the nearest bonus's steps (plan/spread-bind.ts). */
2054
+ const bind = spreadBind(pc, ps, tgt);
2055
+ const bound = (exempt, f) => (bind ? bind.bound(exempt, f) : f());
2056
+ const otherBonus = (p) => p.focus || p.bonusId === bind?.bonusId;
2010
2057
  // ---- 1e. finish off an opponent, 1s. strike an enemy commander, #165 guard-off breaks (plan/strike.ts) ----
2011
2058
  const { struck } = strikesPhase(pc, ps, book, threats, hd, tgt, caps);
2012
2059
  // ---- #276: guard off — free retakes and raids one step deeper (plan/guard-off.ts) ----
@@ -2146,12 +2193,12 @@ function planPass(input, pass) {
2146
2193
  worthOf.set(p.bonusId, p.net === p.value ? `+${p.value}` : `+${p.value}, net +${p.net}`);
2147
2194
  if (p.completable)
2148
2195
  candidates.push({ kind: 'complete', score, cost: p.cost, id: p.bonusId, value: p.net, focus: p.focus, borders: p.borders, run: spend(() => complete(p)) });
2149
- candidates.push({ kind: 'advance', score, cost: p.cost, id: p.bonusId, value: p.net, focus: p.focus, borders: p.borders, run: spend(() => advance(p)) });
2196
+ candidates.push({ kind: 'advance', score, cost: p.cost, id: p.bonusId, value: p.net, focus: p.focus, borders: p.borders, run: spend(() => bound(otherBonus(p), () => advance(p))) });
2150
2197
  }
2151
2198
  // #439: a single-territory bonus two moves away is a two-turn completion: its neutral in between
2152
2199
  // competes as an advance does, on the income per army of both captures.
2153
2200
  for (const st of stages)
2154
- candidates.push({ kind: 'stage', score: st.net / st.cost, cost: st.cost, id: st.bonusId, value: st.net, focus: false, borders: 0, target: st.via, run: spend(() => stageTwoMove(pc, ps, st, gainWith, tryExpand)) });
2201
+ candidates.push({ kind: 'stage', score: st.net / st.cost, cost: st.cost, id: st.bonusId, value: st.net, focus: false, borders: 0, target: st.via, run: spend(() => bound(st.bonusId === bind?.bonusId, () => stageTwoMove(pc, ps, st, gainWith, tryExpand))) });
2155
2202
  // #417, the 1v1 race: while a static seat's land is still untaken, its cheap captures rank ahead of
2156
2203
  // rule 0p.1's "expansion last" (`ahead` below); held-bonus gates and my commander's hold go first.
2157
2204
  const races = oneVsOne ? raceTargets(pc, targets, captured) : [];
@@ -2761,6 +2808,8 @@ function planPass(input, pass) {
2761
2808
  // #272: a conceded border attacks out for a free step into a bonus before it withdraws (and
2762
2809
  // before rule 1c re-values the borders, so one whose bonus this completes is kept).
2763
2810
  attackOutOfConceded(pc, ps, book, hd, tgt, caps);
2811
+ // #431: a doomed conceded stack with nowhere to withdraw to attacks out or merges instead of standing.
2812
+ doomedConcededOut(pc, ps, book, hd, tgt, caps, threats);
2764
2813
  reconsider();
2765
2814
  withdraw();
2766
2815
  }
@@ -2774,11 +2823,11 @@ function planPass(input, pass) {
2774
2823
  // #439: the neutral in between toward a single-territory bonus two moves away, before any advance.
2775
2824
  if (goal !== 'complete-bonus')
2776
2825
  for (const st of stages) {
2777
- stageTwoMove(pc, ps, st, gainWith, tryExpand);
2826
+ bound(st.bonusId === bind?.bonusId, () => stageTwoMove(pc, ps, st, gainWith, tryExpand));
2778
2827
  garrisonCompleted();
2779
2828
  }
2780
2829
  for (const p of byCloseness) {
2781
- advance(p);
2830
+ bound(otherBonus(p), () => advance(p));
2782
2831
  garrisonCompleted();
2783
2832
  }
2784
2833
  // #285: as under `balanced`.
@@ -2788,6 +2837,9 @@ function planPass(input, pass) {
2788
2837
  // before rule 1c re-values the borders, so one whose bonus this completes is kept).
2789
2838
  if (acting)
2790
2839
  attackOutOfConceded(pc, ps, book, hd, tgt, caps);
2840
+ // #431: as under `balanced`.
2841
+ if (acting)
2842
+ doomedConcededOut(pc, ps, book, hd, tgt, caps, threats);
2791
2843
  reconsider();
2792
2844
  if (acting)
2793
2845
  withdraw();
@@ -2810,37 +2862,44 @@ function planPass(input, pass) {
2810
2862
  const plainScore = plainOrderCosts(pc, tgt, eligible.map((t) => t.id));
2811
2863
  const rest = eligible.sort((a, b) => plainScore.get(a.id) - plainScore.get(b.id) || a.cost - b.cost || a.id - b.id);
2812
2864
  // Rule 4c: plain expansion never lowers income (a capture completing a negative bonus).
2813
- for (const t of rest) {
2814
- const gain = gainWith([t.id]);
2815
- if (gain < 0 && !inFocus(t.id))
2816
- continue;
2817
- if (tgt.emptyEnemies.has(t.id)) {
2818
- // #281: never one lowering income, focused or not; sized for its owner's deploy (#120).
2819
- if (gain >= 0)
2820
- tryEmptyEnemy(pc, ps, book, tgt, caps, t.id);
2821
- continue;
2822
- }
2823
- // #125: its own economy test. A member of an economic bonus is judged by that bonus; any
2824
- // other capture pays for the armies it loses with the income it adds within PAYBACK_TURNS,
2825
- // and one that adds none may lose at most PLAIN_EXPANSION_LOSS.
2826
- {
2827
- const refused = plainEconomy(pc, tgt, t.id, gain);
2828
- if (refused) {
2829
- const { lost, worth } = refused;
2830
- const reach = Math.max(...neighborsOf(g, t.id).filter((x) => avail.has(x)).map((x) => (avail.get(x) ?? 0) + roomAt(x)));
2831
- if (reach >= t.cost)
2832
- rationale.push(worth > 0
2833
- ? `Do not expand into ${label(t.id)}: it adds +${worth} a turn and loses ~${lost} armies, more than ${paybackTurns} turns of it pay back.`
2834
- : `Do not expand into ${label(t.id)}: it adds no income and loses ~${lost} armies (more than ${PLAIN_EXPANSION_LOSS}), in no bonus worth completing.`);
2835
- continue;
2865
+ // #416: the nearest bonus's own members are its steps; everything else waits under #319's bind.
2866
+ const nearestTs = bind ? new Set(bonusTs.get(bind.bonusId)) : undefined;
2867
+ for (const t of rest)
2868
+ bound(nearestTs?.has(t.id) ?? true, () => {
2869
+ const gain = gainWith([t.id]);
2870
+ if (gain < 0 && !inFocus(t.id))
2871
+ return;
2872
+ if (tgt.emptyEnemies.has(t.id)) {
2873
+ // #281: never one lowering income, focused or not; sized for its owner's deploy (#120).
2874
+ if (gain >= 0)
2875
+ tryEmptyEnemy(pc, ps, book, tgt, caps, t.id);
2876
+ return;
2836
2877
  }
2837
- }
2838
- // #281 × #282: a denial is never sourced from the territory my commander walks from (its transit hold).
2839
- if (tgt.denials.has(t.id))
2840
- withoutTransit(pc, tgt, t.id, () => tryExpand(t.id, 'expands territory'));
2841
- else
2842
- tryExpand(t.id, 'expands territory');
2843
- }
2878
+ // #125: its own economy test. A member of an economic bonus is judged by that bonus; any
2879
+ // other capture pays for the armies it loses with the income it adds within PAYBACK_TURNS,
2880
+ // and one that adds none may lose at most PLAIN_EXPANSION_LOSS.
2881
+ {
2882
+ const refused = plainEconomy(pc, tgt, t.id, gain);
2883
+ if (refused) {
2884
+ const { lost, worth } = refused;
2885
+ const reach = Math.max(...neighborsOf(g, t.id).filter((x) => avail.has(x)).map((x) => (avail.get(x) ?? 0) + roomAt(x)));
2886
+ if (reach >= t.cost)
2887
+ rationale.push(worth > 0
2888
+ ? `Do not expand into ${label(t.id)}: it adds +${worth} a turn and loses ~${lost} armies, more than ${pc.capturePaybackTurns} turns of it pay back.`
2889
+ : `Do not expand into ${label(t.id)}: it adds no income and loses ~${lost} armies (more than ${PLAIN_EXPANSION_LOSS}), in no bonus worth completing.`);
2890
+ return;
2891
+ }
2892
+ }
2893
+ // #281 × #282: a denial is never sourced from the territory my commander walks from (its transit hold).
2894
+ // #426: a no-loss capture in a bonus too costly to finish says why it is taken all the same.
2895
+ const reason = onlyNoLoss(pc, tgt, t.id)
2896
+ ? `expands territory: a no-loss capture (its defenders kill none of the attackers; what lands stays mine), so the cost of finishing its bonus does not stop it (#426)`
2897
+ : 'expands territory';
2898
+ if (tgt.denials.has(t.id))
2899
+ withoutTransit(pc, tgt, t.id, () => tryExpand(t.id, reason));
2900
+ else
2901
+ tryExpand(t.id, reason);
2902
+ });
2844
2903
  dropEmptyEnemyTargets(ps, tgt, empties);
2845
2904
  }
2846
2905
  // ---- 4e. never stand still (#104, #107), the contact fallback (plan/stand-still.ts) ----
@@ -2938,7 +2997,8 @@ function planPass(input, pass) {
2938
2997
  /** Territories locked before the leftover deploy: holds, kept and standing borders, withdrawals. */
2939
2998
  const holdLocked = new Set(locked);
2940
2999
  /** A territory the plan has not given up (or gave up but whose garrison may still hold it). */
2941
- const open = (id) => !conceded.has(id) || mayHold.has(id);
3000
+ // #431: a border a doomed stack left gets no leftover, whatever else it is.
3001
+ const open = (id) => (!conceded.has(id) || mayHold.has(id)) && !ps.doomedOut.has(id);
2942
3002
  /** Armies that stay on a border after its deploys, outgoing moves and incoming withdrawals. */
2943
3003
  const stays = (id) => avail.get(id) + guardAt(id) + (incoming.get(id) ?? 0);
2944
3004
  // ---- #265: a combined capture leaves armies on a weak member of a bonus it completes (plan/captures.ts) ----
@@ -3021,7 +3081,8 @@ function planPass(input, pass) {
3021
3081
  // ---- 5b. a neutral the leftover pays for (#218) (plan/after-leftover.ts) ----
3022
3082
  // The strike stack concentrates for its strike, and a step's source saves toward it: neither spends.
3023
3083
  const keepWhole = new Set([...(strikeStack ? [strikeStack.id] : []), ...(staging ? [staging.from] : [])]);
3024
- const takenAfter = afterLeftoverCaptures(pc, ps, book, threats, hd, tgt, caps, beforeLeftover, keepWhole, poolDeployed);
3084
+ // #416: rule 5b is plain expansion too: under #319's bind it leaves the stacks beside the nearest bonus alone.
3085
+ const takenAfter = bound(false, () => afterLeftoverCaptures(pc, ps, book, threats, hd, tgt, caps, beforeLeftover, keepWhole, poolDeployed));
3025
3086
  // #288: the rest of the leftover offered to another capture rides the expansion stack's attacks
3026
3087
  // after all when rule 5b took nothing from where it was offered.
3027
3088
  if (offered && !moves.some((m) => m.kind === 'attack' && m.from === offered.at && takenAfter.includes(m.to)))
@@ -3330,6 +3391,8 @@ function planPass(input, pass) {
3330
3391
  placeCommanderMove(pc, ps);
3331
3392
  // ---- expected, frontier, two-step holds, gambled and shared borders (plan/report.ts) ----
3332
3393
  const expected = reportExpected(pc, ps, book, threats, hd, tgt, caps);
3394
+ // #426: a stack idle two turns beside a no-loss neutral (plan/free-capture.ts), report only.
3395
+ warnIdleBesideFree(pc, ps, tgt, input.previousBoard);
3333
3396
  // ---- offence report (#72), the warnings after the deploys, "Not attacking" (#167) (plan/report.ts) ----
3334
3397
  const { sentAt } = reportOffence(pc, ps, book, threats, hd, tgt, holdLocked, leadSpareFor);
3335
3398
  // ---- 7. schedule the moves (#127), the exits (#179), Order Priority (plan/move-order.ts) ----