@chrischall/warapp-mcp 0.7.0 → 0.8.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 (53) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +2 -2
  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 +76 -13
  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 +513 -0
  14. package/dist/analysis/plan/doomed-out.js +135 -0
  15. package/dist/analysis/plan/estimates.js +3 -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/stand-still.js +5 -3
  25. package/dist/analysis/plan/state.js +12 -0
  26. package/dist/analysis/plan/strike-stack.js +467 -0
  27. package/dist/analysis/plan/strike.js +3 -463
  28. package/dist/analysis/plan/targets.js +213 -26
  29. package/dist/analysis/plan/threats.js +12 -4
  30. package/dist/analysis/plan/transfers.js +24 -1
  31. package/dist/analysis/plan/two-move.js +1 -1
  32. package/dist/analysis/plan/withdraw.js +316 -0
  33. package/dist/analysis/planner.js +54 -11
  34. package/dist/analysis/player.js +4 -0
  35. package/dist/analysis/relations.js +8 -2
  36. package/dist/analysis/stress.js +1 -1
  37. package/dist/bundle.js +8008 -7184
  38. package/dist/my-games.js +2 -0
  39. package/dist/open-games.js +94 -10
  40. package/dist/tools/card-advice.js +26 -11
  41. package/dist/tools/card-support-advice.js +17 -1
  42. package/dist/tools/check-plan.js +2 -1
  43. package/dist/tools/commander-check.js +2 -1
  44. package/dist/tools/decision-capture.js +4 -2
  45. package/dist/tools/join-game.js +44 -8
  46. package/dist/tools/live.js +33 -5
  47. package/dist/tools/open-games.js +2 -2
  48. package/dist/tools/picks.js +120 -47
  49. package/dist/tools/turn.js +43 -4
  50. package/dist/version.js +1 -1
  51. package/manifest.json +1 -1
  52. package/package.json +1 -1
  53. package/server.json +2 -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
+ }
@@ -514,9 +514,10 @@
514
514
  // and counts. The leftover's revival may still hold a capped border after all. Off under a `defend`
515
515
  // goal the caller gave, and with `options.holdCap: false` (tests of earlier hold rules use it).
516
516
  // 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
517
+ // of my complete bonuses containing it, plus (#122) its share of every
518
+ // incomplete bonus containing it that I am building (#425: one it is my only way into
519
+ // included — it used to count whole, whatever stood on the rest; now its share, and nothing
520
+ // 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
521
  // size, one decimal, when every missing member is a visible neutral and finishing it passes
521
522
  // rule 4's economy tests (PAYBACK_TURNS, WASTELAND_FACTOR); #298: or when the missing members
522
523
  // are visible neutrals and visible foe territories, one of them a foe's movable stack beside the
@@ -828,6 +829,11 @@
828
829
  // absorbed by its own neighbours' growth) and is now cheaper to take than it
829
830
  // was; never under `expand`/`defend`). Fogged or unknown neighbours are never attacked — they
830
831
  // produce a warning.
832
+ // #430 (owner decision of 2026-11-22): under `balanced`, the opponents' territories that retake
833
+ // a bonus I held in full on `previousBoard` are bonus targets too, in every format, when the retake
834
+ // completes it this turn (every missing member in view, beside mine), costs at most RETAKE_VALUE_TURNS
835
+ // (5) × its value, and the profile does not read me behind; it ranks as any completion, so a stronger hold
836
+ // funds first (plan/targets.ts, `retakeMembers`).
831
837
  // 3. Capture cost (#126): the fewest armies whose exact `winChance` reaches the capture's
832
838
  // chance — certain (chance 1) means every roll and rounding takes it: `armiesToTake` at 0%
833
839
  // luck under straight rounding, one army more where weighted-random rounding could round a
@@ -942,7 +948,10 @@
942
948
  // scored by its net worth (rule 4c), not its value, in every test above.
943
949
  // One owner per bonus (PLAN-TEAMS C3.3): a positive bonus with a member my teammate visibly
944
950
  // 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
951
+ // not (a focus on it is ignored with a warning); its other members are plain expansion — unless
952
+ // (#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
953
+ // advanced, the teammate's left for them to hand over (a Gift), never completable while they
954
+ // stand; an uneconomic one is still skipped as before. The
946
955
  // plan's `team.sharedBonuses` (plan/team.ts) lists each such bonus I hold members of too, and
947
956
  // who holds the most (`nearer`), from the start-of-turn board. No-team plans are unchanged.
948
957
  // Team focus (PLAN-TEAMS C3.4): with my teammates' entered orders read (V5, unverified), a
@@ -1018,7 +1027,13 @@
1018
1027
  // bonuses this turn's earlier captures completed share the same next income (their added
1019
1028
  // needs count too). Then: under `balanced`/`defend` the capture is
1020
1029
  // refused (warning "… indefensible …: not completed"); under `expand` and
1021
- // `complete-bonus` it is made with a warning. Under `balanced`/`defend` a bonus's
1030
+ // `complete-bonus` it is made with a warning. #422, the payback exemption: a completion whose
1031
+ // losses — the attackers its captures into the bonus lose this turn plus the armies left on the
1032
+ // members that would fall — are at most the bonus's value is made anyway (a "Complete bonus …
1033
+ // (#422)" line): held at the end of this turn, the bonus pays that value next turn even if it
1034
+ // falls after. Such a bonus keeps no conceded border (rule 1c), gets no #122 garrison or #265
1035
+ // weak-member call, and the leftover never rides an attack onto a member it may lose (#288).
1036
+ // Under `balanced`/`defend` a bonus's
1022
1037
  // score is value / (capture cost + DEFENSE_DISCOUNT × that defence cost).
1023
1038
  // 4d. Frontier cost (#71). Every capture pays for the frontier it adds, in armies: for each
1024
1039
  // territory it touches (the capture and its held neighbours), its border cost after minus
@@ -1076,6 +1091,10 @@
1076
1091
  // rule 4e's contact fallback, where 4d is only a cost (#114), runs it too. The plan reports `gates` (each gate's
1077
1092
  // need and armies, conceded ones marked, the summed need, what stands on them, the per-gate deficit, the next
1078
1093
  // income and the shortfall) and warns when its own captures open a gate the income cannot hold.
1094
+ // #426 (draft): a no-loss neutral (its defenders kill none of my attackers, `noLossNeutral`) is taken
1095
+ // by pass 3 even in an uneconomic bonus, and rule 4d lets one through when only the fog faces its new
1096
+ // border and the hold it adds is at most 1× the next income (`outgrows`, not in a 1v1); a stack idle two
1097
+ // turns beside one is warned of (plan/free-capture.ts).
1079
1098
  // 4e. Never stand still (#104, #107; every goal but `complete-bonus`, after pass 3). A plan that
1080
1099
  // makes no capture at all (no expansion, break, finishing off or strike) in the opening or
1081
1100
  // expansion phase takes one neutral capture toward a positive bonus (net > 0, never a negative
@@ -1325,6 +1344,10 @@
1325
1344
  // S …, the C sent leave L, above the H that hold it …"); a capture removes rule 4e's
1326
1345
  // stand-still warning, and a refused try leaves no line.
1327
1346
  // 6. Idle armies on interior territories transfer one step toward the front,
1347
+ // When no front and no territory not mine is reachable without crossing a border the plan concedes (the
1348
+ // last neutral taken, the enemy past those borders; owner 2026-11-22, golden s246), an idle interior stack
1349
+ // walks up behind the conceded borders on the way to the enemy — never into one, never into a territory an
1350
+ // attack leaves from this turn or one beside a rival at the start of the turn — and waits beside them (#367).
1328
1351
  // only into territories held at the start of the turn and never into, or
1329
1352
  // measured through, a conceded border
1330
1353
  // (unless `idleTransfers` is off: the planner's own switch, not war.app's AllowTransferOnly,
@@ -1646,12 +1669,14 @@ import { neutralizeSeats, seatTerritories, staticSeats } from './static-seats.js
1646
1669
  import { deployBook } from './plan/orders.js';
1647
1670
  import { holdsPhase, priorOnlyHold } from './plan/holds.js';
1648
1671
  import { threatsPhase } from './plan/threats.js';
1672
+ import { applyShortGates } from './plan/horizon.js';
1649
1673
  import { targetsPhase } from './plan/targets.js';
1650
1674
  import { capturesPhase } from './plan/captures.js';
1651
1675
  import { completedMembers } from './plan/completed.js';
1652
1676
  import { chooseStrikeStack, leadStrikes, spendStrikeStack, strikesPhase } from './plan/strike.js';
1653
1677
  import { contestedBonuses } from './plan/stockpile.js';
1654
- import { afterLeftoverCaptures, plainEconomy, plainEligible } from './plan/after-leftover.js';
1678
+ import { warnIdleBesideFree } from './plan/free-capture.js';
1679
+ import { afterLeftoverCaptures, onlyNoLoss, plainEconomy, plainEligible } from './plan/after-leftover.js';
1655
1680
  import { fundFromSecondSizing } from './plan/second-sizing.js';
1656
1681
  import { leftoverDeploy } from './plan/leftover.js';
1657
1682
  import { fillSecondLine, guardOffRaids } from './plan/guard-off.js';
@@ -1660,6 +1685,7 @@ import { stageTwoMove, twoMoveStages } from './plan/two-move.js';
1660
1685
  import { addEmptyEnemyTargets, dropEmptyEnemyTargets, foggedLastSeen, plainOrderCosts, raceLine, raceTargets, tryEmptyEnemy, withoutTransit } from './plan/vacated.js';
1661
1686
  import { spendUnderCap } from './plan/cap-spend.js';
1662
1687
  import { attackOutOfConceded } from './plan/conceded-out.js';
1688
+ import { doomedConcededOut } from './plan/doomed-out.js';
1663
1689
  import { captureInsteadOfHold } from './plan/capture-instead.js';
1664
1690
  import { transfers } from './plan/transfers.js';
1665
1691
  import { scheduleOrders, strikeOrderPriority } from './plan/move-order.js';
@@ -1669,9 +1695,11 @@ import { newPlanState } from './plan/state.js';
1669
1695
  import { teamFocusLine, teamReport } from './plan/team.js';
1670
1696
  import { applyBorderCaps, armiesFreed, partnerFronts, reportBreakLosses, reportTruce, trucePass, warnTruceNeutrals } from './plan/relations.js';
1671
1697
  export * from './plan/shared.js';
1698
+ export * from './plan/observe.js';
1699
+ export * from './plan/deploy-estimates.js';
1672
1700
  export { alliesOf, planEnemyEstimates } from './plan/estimates.js';
1673
1701
  export { TRUCE_RELAX_VALUE } from './plan/relations.js';
1674
- export { SPREAD_INCOME_SLACK, SPREAD_LAST_TURN, SPREAD_TERRITORIES } from './plan/targets.js';
1702
+ export { HOLDS_BONUS_MIN_VALUE, SPREAD_INCOME_SLACK, SPREAD_LAST_TURN, SPREAD_TERRITORIES } from './plan/targets.js';
1675
1703
  /** Passes that refine the cut set (#172) before falling back to the plan that cuts nothing. */
1676
1704
  const TWO_STEP_PASSES = 3;
1677
1705
  /** Passes that learn which territories in between end held (#172) before none is counted held. */
@@ -1990,6 +2018,9 @@ function planPass(input, pass) {
1990
2018
  const local = pools !== null && pools.bonuses.length > 0;
1991
2019
  // ---- 1t. threat trend, 1. defence (plan/threats.ts) ----
1992
2020
  const threats = threatsPhase(pc, ps, input, book.valueOf);
2021
+ // #432: a 1v1 whose gates are short at the start judges its captures on a shorter payback horizon from here on
2022
+ // (every capture test after this reads `pc.capturePaybackTurns`; holds keep `paybackTurns`).
2023
+ applyShortGates(pc, ps, threats);
1993
2024
  const { growthOf, reinforcementAt, borders, facing, borderAt } = threats;
1994
2025
  // ---- 1. holds, #172, 1h, 1b, 1c, #122 garrisons (plan/holds.ts) ----
1995
2026
  const hd = holdsPhase(pc, ps, book, threats, pass);
@@ -2761,6 +2792,8 @@ function planPass(input, pass) {
2761
2792
  // #272: a conceded border attacks out for a free step into a bonus before it withdraws (and
2762
2793
  // before rule 1c re-values the borders, so one whose bonus this completes is kept).
2763
2794
  attackOutOfConceded(pc, ps, book, hd, tgt, caps);
2795
+ // #431: a doomed conceded stack with nowhere to withdraw to attacks out or merges instead of standing.
2796
+ doomedConcededOut(pc, ps, book, hd, tgt, caps, threats);
2764
2797
  reconsider();
2765
2798
  withdraw();
2766
2799
  }
@@ -2788,6 +2821,9 @@ function planPass(input, pass) {
2788
2821
  // before rule 1c re-values the borders, so one whose bonus this completes is kept).
2789
2822
  if (acting)
2790
2823
  attackOutOfConceded(pc, ps, book, hd, tgt, caps);
2824
+ // #431: as under `balanced`.
2825
+ if (acting)
2826
+ doomedConcededOut(pc, ps, book, hd, tgt, caps, threats);
2791
2827
  reconsider();
2792
2828
  if (acting)
2793
2829
  withdraw();
@@ -2830,16 +2866,20 @@ function planPass(input, pass) {
2830
2866
  const reach = Math.max(...neighborsOf(g, t.id).filter((x) => avail.has(x)).map((x) => (avail.get(x) ?? 0) + roomAt(x)));
2831
2867
  if (reach >= t.cost)
2832
2868
  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.`
2869
+ ? `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.`
2834
2870
  : `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
2871
  continue;
2836
2872
  }
2837
2873
  }
2838
2874
  // #281 × #282: a denial is never sourced from the territory my commander walks from (its transit hold).
2875
+ // #426: a no-loss capture in a bonus too costly to finish says why it is taken all the same.
2876
+ const reason = onlyNoLoss(pc, tgt, t.id)
2877
+ ? `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)`
2878
+ : 'expands territory';
2839
2879
  if (tgt.denials.has(t.id))
2840
- withoutTransit(pc, tgt, t.id, () => tryExpand(t.id, 'expands territory'));
2880
+ withoutTransit(pc, tgt, t.id, () => tryExpand(t.id, reason));
2841
2881
  else
2842
- tryExpand(t.id, 'expands territory');
2882
+ tryExpand(t.id, reason);
2843
2883
  }
2844
2884
  dropEmptyEnemyTargets(ps, tgt, empties);
2845
2885
  }
@@ -2938,7 +2978,8 @@ function planPass(input, pass) {
2938
2978
  /** Territories locked before the leftover deploy: holds, kept and standing borders, withdrawals. */
2939
2979
  const holdLocked = new Set(locked);
2940
2980
  /** 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);
2981
+ // #431: a border a doomed stack left gets no leftover, whatever else it is.
2982
+ const open = (id) => (!conceded.has(id) || mayHold.has(id)) && !ps.doomedOut.has(id);
2942
2983
  /** Armies that stay on a border after its deploys, outgoing moves and incoming withdrawals. */
2943
2984
  const stays = (id) => avail.get(id) + guardAt(id) + (incoming.get(id) ?? 0);
2944
2985
  // ---- #265: a combined capture leaves armies on a weak member of a bonus it completes (plan/captures.ts) ----
@@ -3330,6 +3371,8 @@ function planPass(input, pass) {
3330
3371
  placeCommanderMove(pc, ps);
3331
3372
  // ---- expected, frontier, two-step holds, gambled and shared borders (plan/report.ts) ----
3332
3373
  const expected = reportExpected(pc, ps, book, threats, hd, tgt, caps);
3374
+ // #426: a stack idle two turns beside a no-loss neutral (plan/free-capture.ts), report only.
3375
+ warnIdleBesideFree(pc, ps, tgt, input.previousBoard);
3333
3376
  // ---- offence report (#72), the warnings after the deploys, "Not attacking" (#167) (plan/report.ts) ----
3334
3377
  const { sentAt } = reportOffence(pc, ps, book, threats, hd, tgt, holdLocked, leadSpareFor);
3335
3378
  // ---- 7. schedule the moves (#127), the exits (#179), Order Priority (plan/move-order.ts) ----
@@ -98,6 +98,10 @@ export function armyCapPoolsUncertainty(c, localDeployments) {
98
98
  }
99
99
  /** What the army cap's figure rests on: six live cases, and the card armies' place (from the client's guide, unverified). */
100
100
  export const ARMY_CAP_BASIS = "the formula is verified by six live cases (2026-11-15: received 41, 49, 25, 27 and 71 where the cap bit, among them the binding case sent through warapp_submit_turn, and a room of 61 it did not bind), the cap taken on this turn's income; Reinforcement card armies are outside it (the client's guide: they are not income and always pay in full, unverified live)";
101
+ /** #433: the game's own base income (`MinimumArmyBonus`; 0 and 3 exist), the default only when it does not say. One accessor for the planner and the stress test. */
102
+ export function gameBaseIncome(settings) {
103
+ return Math.max(0, Math.floor(settings?.baseIncome ?? settings?.minimumArmyBonus ?? DEFAULT_BASE_INCOME));
104
+ }
101
105
  /** {@link IncomeRules} from a game's settings (the defaults when it does not say). */
102
106
  export function incomeRules(settings) {
103
107
  return { base: settings?.minimumArmyBonus ?? DEFAULT_BASE_INCOME, per: settings?.bonusArmyPer ?? 0 };
@@ -1,4 +1,4 @@
1
- import { carriesTeam } from '../teams.js';
1
+ import { carriesTeam, teammatesOf } from '../teams.js';
2
2
  import { bonusTerritories } from './bonuses.js';
3
3
  import { bfsDistances, neighborsOf } from './graph.js';
4
4
  import { ownerShown, OWNERS_SHOWN_FOG, visibleState, } from './plan/shared.js';
@@ -606,7 +606,13 @@ export function planRelationsFrom(input) {
606
606
  card: 'Diplomacy',
607
607
  });
608
608
  }
609
- const open = new Set(input.agreements.filter((a) => !TERMINAL_STATUSES.has(a.status)).map((a) => a.with));
609
+ // #435: a teammate's quiet border is no tacit truce (#246): left out like a partner with an open
610
+ // agreement, as warapp_get_relations already did — plan_turn, check_plan and advise_diplomacy listed them.
611
+ const self = players.find((p) => p.id === me);
612
+ const open = new Set([
613
+ ...input.agreements.filter((a) => !TERMINAL_STATUSES.has(a.status)).map((a) => a.with),
614
+ ...(self ? teammatesOf(players, self).map((p) => p.id) : []),
615
+ ]);
610
616
  return { relations, tacit: tacitTruces({ graph, boards: input.boards, me, exclude: open }) };
611
617
  }
612
618
  // ---------- B3: pricing a deal (docs/PLAN-TEAMS.md section 8 B3) ----------
@@ -134,7 +134,7 @@ export function stressPlan(input) {
134
134
  const pools = input.localDeployments ? couldHoldBonusPools(graph, input.opponents.map((o) => o.id), shownOwner) : undefined;
135
135
  const deployOn = (opp, on) => {
136
136
  const all = Math.max(0, Math.floor(opp.deploy));
137
- return pools ? enemyDeployReaching(all, freeIncome(opp.base ?? 0, DEFAULT_BASE_INCOME, opp.card ?? 0), pools.get(opp.id) ?? [], [on], input.perTerritoryIncome === true) : all;
137
+ return pools ? enemyDeployReaching(all, freeIncome(opp.base ?? 0, input.baseIncome ?? DEFAULT_BASE_INCOME, opp.card ?? 0), pools.get(opp.id) ?? [], [on], input.perTerritoryIncome === true) : all;
138
138
  };
139
139
  /** Luck-free: `sent` armies (and a commander, when it goes along) take `t` as it stands. */
140
140
  const breaks = (sent, withCommander, t) => breaksLuckFree(sent, withCommander, t, { offensiveKillRate: off, defensiveKillRate: def });