@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,135 @@
1
+ // #431: a doomed conceded stack attacks out or merges instead of standing. Rule 1b withdraws a conceded
2
+ // border's movable armies toward a border that holds; with no neighbour of mine that is not conceded they
3
+ // stayed ("… has nowhere to withdraw to: its N movable armies stay"), even when the expected attack (#59)
4
+ // takes the stack. Then they die where they stand, killing only the defensive share of the attacker. In a
5
+ // finished 3-player FFA (45684504) pocket stacks of ~1,000-1,800 were lost that way, most beside a
6
+ // territory they could have taken.
7
+ //
8
+ // So, after #272's free steps and before rule 1c and rule 1b: a conceded border of mine with no such
9
+ // neighbour, not my commander's, not kept by rule 1c, whose stack the expected attack takes, weighs its
10
+ // options by the exchange model (src/analysis/exchange.ts), each by the armies of mine still standing
11
+ // after the turn plus the enemy armies killed (a neutral's dead are no gain):
12
+ // - stand: nothing of mine survives; the attacker loses the defensive share of the stack (at most the
13
+ // expected attack);
14
+ // - attack out with the whole movable stack into a neighbour it captures against the owner's estimated
15
+ // deploy there (`classifyExchange`'s `estimated` case; never a truce's covered territory, one with a
16
+ // special unit, a dropped member or one lowering income; a #240 repulsed one only at its sure size): the survivors live on;
17
+ // - merge into a neighbouring conceded stack of mine that has nowhere to withdraw to either and that,
18
+ // merged, holds against its own expected attack (a truce cap respected): every army lives on.
19
+ // The best option is taken when it beats standing (a merge first on a tie, then the larger capture). The
20
+ // unmovable rest (a covered exit's cover) stands either way. Not done: an attack that does not capture (its
21
+ // survivors come home to the doomed stack), and whether the territory a capture lands on is itself doomed.
22
+ import { classifyExchange } from '../exchange.js';
23
+ import { neighborsOf } from '../graph.js';
24
+ import { straightKills } from '../combat.js';
25
+ import { keptByCompletion } from './conceded-out.js';
26
+ import { capRoom } from './relations.js';
27
+ import { byNum } from './util.js';
28
+ const MERGES = 'merges a doomed conceded stack into one that holds (#431)';
29
+ const ATTACKS = 'a doomed conceded stack attacks out rather than stand (#431)';
30
+ /** A #431 order: like a withdrawal, it runs only while its border is mine (Order Priority protects it). */
31
+ export const isDoomedOut = (m) => m.reason === MERGES || m.reason === ATTACKS;
32
+ export function doomedConcededOut(pc, ps, book, hd, tgt, caps, threats) {
33
+ const { g, foe, territories: state, label, mineSet, unitsAt, uncounted, defenceAt, toTake, chanceOf, costAt, myCommanders, noSplit, rates, deployOf } = pc;
34
+ const { avail, captured, spared, rationale, warnings, moves, locked, incoming, survivorsAt, captureOrder, captureUndo } = ps;
35
+ const { conceded, stayAt } = hd;
36
+ const { coverOf, gainWith, orderOf } = book;
37
+ const { targets } = tgt;
38
+ const { expectedAt, reinforcementAt } = threats;
39
+ if (!conceded.size)
40
+ return;
41
+ const def = rates.defensiveKillRate;
42
+ /**
43
+ * Rule 1b's test: no neighbour of mine that is not conceded, which a withdrawal could go to. Rule 1c
44
+ * runs after this pass and keeps a conceded border whose bonus this turn's captures complete: rule 1b
45
+ * then withdraws into it as usual, so such a neighbour counts as one to withdraw to.
46
+ */
47
+ const nowhere = (x) => !neighborsOf(g, x).some((c) => mineSet.has(c) && (!conceded.has(c) || keptByCompletion(pc, ps, c)));
48
+ /** What stands on my `x` against the expected attack, and whether that attack takes it. */
49
+ const doom = (x, more = 0) => {
50
+ const stack = stayAt(x) + unitsAt(x) + more;
51
+ const take = toTake(stack);
52
+ const expected = expectedAt(x);
53
+ return { stack, take, expected, doomed: take !== null && expected > 0 && take <= expected };
54
+ };
55
+ for (const x of [...conceded].sort(byNum)) {
56
+ if (!mineSet.has(x) || myCommanders.has(x) || keptByCompletion(pc, ps, x) || !nowhere(x))
57
+ continue;
58
+ // No-Split (#124): a covered exit sends nothing, and a territory with an order sends no other.
59
+ if (noSplit && (coverOf(x) > 0 || orderOf(x)))
60
+ continue;
61
+ const n = (avail.get(x) ?? 0) - (noSplit ? 0 : coverOf(x));
62
+ if (n <= 0)
63
+ continue;
64
+ const d = doom(x);
65
+ if (!d.doomed)
66
+ continue;
67
+ const killsBy = (armies) => Math.min(d.expected, straightKills(Math.max(0, armies), def));
68
+ // The rest that cannot move stands and dies in every option, killing its share.
69
+ const rest = killsBy(d.stack - n);
70
+ const stand = killsBy(d.stack);
71
+ const options = [];
72
+ for (const t of neighborsOf(g, x)) {
73
+ if (mineSet.has(t)) {
74
+ // A merge: into another pocket stack (it keeps its armies too) that then holds.
75
+ if (!conceded.has(t) || !nowhere(t) || capRoom(pc, ps, t) < n)
76
+ continue;
77
+ if (doom(t, n).doomed)
78
+ continue;
79
+ options.push({ kind: 'merge', to: t, value: n + rest });
80
+ continue;
81
+ }
82
+ if (captured.has(t) || spared.has(t) || pc.truce.noTarget(t) || tgt.droppedMembers.has(t))
83
+ continue;
84
+ const st = state.get(t);
85
+ if (!st || st.armies === null || uncounted(t) || unitsAt(t) > 0)
86
+ continue;
87
+ const owner = st.owner;
88
+ const enemy = owner.kind === 'player';
89
+ if (owner.kind === 'player' ? !foe(owner.playerId) : owner.kind !== 'neutral')
90
+ continue;
91
+ if (gainWith([t]) < 0)
92
+ continue;
93
+ const deploy = enemy ? reinforcementAt(t) : 0;
94
+ const income = owner.kind === 'player' ? Math.max(deploy, deployOf(owner.playerId)) : 0;
95
+ const ex = classifyExchange({ attackers: n, defenders: defenceAt(t), deploy, income, rates });
96
+ const e = ex.cases[1];
97
+ // The planner's own sizing (luck, win chance) must agree that the whole stack takes it.
98
+ const cost = costAt(t, defenceAt(t) + deploy);
99
+ // A #240 repulsed territory is attacked at its sure size or not at all.
100
+ if (!e.captures || cost === null || Math.max(cost, tgt.repulsed.get(t)?.cost ?? 0) > n)
101
+ continue;
102
+ options.push({ kind: 'attack', to: t, value: n - e.losses + (enemy ? e.kills : 0) + rest, losses: e.losses, kills: e.kills, deploy, enemy });
103
+ }
104
+ options.sort((a, b) => b.value - a.value || Number(b.kind === 'merge') - Number(a.kind === 'merge') || a.to - b.to);
105
+ const best = options[0];
106
+ if (!best || best.value <= stand)
107
+ continue;
108
+ const head = `${label(x)} is doomed (#431): conceded, nowhere to withdraw to, and its ${d.stack} need ${d.take} to take against the expected ~${d.expected} attack.`;
109
+ avail.set(x, avail.get(x) - n);
110
+ locked.add(x);
111
+ ps.doomedOut.add(x);
112
+ // Like a withdrawal (rule 1b) or rule 4e's attack out, the order only runs while the border is mine.
113
+ warnings.push(`The ${best.kind === 'merge' ? 'merge' : 'attack'} out of ${label(x)} only executes if ${label(x)} is still mine when the order runs; play Order Priority so it goes first.`);
114
+ ps.cardAdvice = 'order-priority';
115
+ if (best.kind === 'merge') {
116
+ locked.add(best.to);
117
+ incoming.set(best.to, (incoming.get(best.to) ?? 0) + n);
118
+ // Like a withdrawal it only runs while the border is still mine: it goes first.
119
+ moves.unshift({ from: x, to: best.to, armies: n, kind: 'transfer', reason: MERGES });
120
+ rationale.push(`${head} Merge its ${n} into ${label(best.to)}, which then holds (${doom(best.to).stack} need ${doom(best.to).take} to take against ~${expectedAt(best.to)}), rather than stand and kill ~${stand}.`);
121
+ continue;
122
+ }
123
+ const t = best.to;
124
+ captured.add(t);
125
+ survivorsAt.set(t, n - straightKills(defenceAt(t), def));
126
+ captureOrder.push(t);
127
+ captureUndo.set(t, () => avail.set(x, avail.get(x) + n));
128
+ if (!targets.has(t))
129
+ targets.set(t, { id: t, cost: costAt(t) ?? n, enemy: best.enemy, sources: [x] });
130
+ if (best.deploy > 0)
131
+ caps.worstCase.set(t, defenceAt(t) + best.deploy);
132
+ moves.push({ from: x, to: t, armies: n, kind: 'attack', reason: ATTACKS, winChance: chanceOf(n, defenceAt(t)) });
133
+ rationale.push(`${head} Attack ${label(t)} with ${noSplit ? 'its whole stack' : `all ${n}`}: it holds ${defenceAt(t)}${best.deploy ? ` (+${best.deploy} if its owner deploys there first)` : ''}, so ~${n - best.losses} survive${best.enemy ? ` and ~${best.kills} of the enemy die` : ''}, against ~${stand} killed and none left by standing.`);
134
+ }
135
+ }
@@ -96,6 +96,7 @@ export function planEnemyEstimates(input) {
96
96
  turn,
97
97
  fog: ctx.fog,
98
98
  reinforcement: ctx.reinforcement,
99
+ ...(ctx.reinforcementPlays ? { plays: ctx.reinforcementPlays } : {}),
99
100
  ...(previousBoard && input.previousOrders ? { previousOrders: input.previousOrders } : {}),
100
101
  });
101
102
  const priced = applyKnown(applyArmyPrice(applySanctions(estimates, input.sanctions ?? []), input.settings?.armyCostMultiplier ?? 0), input.known ?? []);
@@ -232,7 +233,8 @@ function opponentsCtx(input) {
232
233
  ...(ctx.turn !== undefined ? { turn: ctx.turn } : {}),
233
234
  ...(ctx.picking !== undefined ? { picking: ctx.picking } : {}),
234
235
  ...(ctx.endRules ? { endRules: ctx.endRules } : {}),
235
- income: earnedIncome,
236
+ // #427: my Reinforcement card is a one-off deploy like an opponent's, so the standing reads income without it.
237
+ income: earnedIncome - Math.max(0, Math.floor(input.cardArmies ?? 0)),
236
238
  // #164 x #167: an opponent's Reinforcement card is a one-off deploy, not income: the standing
237
239
  // and the FFA ranking read each estimate less its card. PLAN-TEAMS C3: teammates' estimates go
238
240
  // too, for the team standing (the profile keeps them off the opponents' side).
@@ -427,6 +429,7 @@ function opponentsCtx(input) {
427
429
  untrustedAt,
428
430
  decidedGame,
429
431
  paybackTurns,
432
+ capturePaybackTurns: paybackTurns,
430
433
  };
431
434
  }
432
435
  /** The territories as the board shows them, and what holding them is worth (#70, #85, #125). */
@@ -0,0 +1,34 @@
1
+ import { neighborsOf } from '../graph.js';
2
+ import { noLossNeutral } from './after-leftover.js';
3
+ import { byNum } from './util.js';
4
+ export function warnIdleBesideFree(pc, ps, tgt, previousBoard) {
5
+ if (!previousBoard)
6
+ return;
7
+ const { g, territories: state, label, mineSet, me, guard, myCommanders } = pc;
8
+ const { captured, moves, warnings } = ps;
9
+ const before = new Map(previousBoard.territories.map((t) => [t.territoryId, t]));
10
+ const mineBefore = (x) => {
11
+ const t = before.get(x);
12
+ return t?.owner.kind === 'player' && t.owner.playerId === me ? t : undefined;
13
+ };
14
+ for (const x of [...mineSet].sort(byNum)) {
15
+ // Idle this turn: the plan sends nothing out of it. My commander's stack stays by rule 1k's choice.
16
+ if (myCommanders.has(x) || moves.some((m) => m.from === x))
17
+ continue;
18
+ const now = state.get(x)?.armies;
19
+ const was = mineBefore(x)?.armies;
20
+ // It had armies to move last turn and has no fewer now.
21
+ if (now == null || was == null || was - guard < 1 || now < was)
22
+ continue;
23
+ // Each neutral its own movable armies take (the guard stays), with no deploy.
24
+ const free = neighborsOf(g, x)
25
+ .filter((n) => {
26
+ const cost = tgt.targets.get(n)?.cost;
27
+ return !captured.has(n) && cost !== undefined && cost <= now - guard && noLossNeutral(pc, tgt, n) && before.get(n)?.owner.kind === 'neutral';
28
+ })
29
+ .sort(byNum);
30
+ if (!free.length)
31
+ continue;
32
+ warnings.push(`${label(x)} has stood idle two turns with ${now} armies beside ${free.map(label).join(', ')}, which ${free.length === 1 ? 'is a no-loss capture (its defenders kill none of the attackers)' : 'are no-loss captures (their defenders kill none of the attackers)'}, and this plan leaves it idle again (#426).`);
33
+ }
34
+ }
@@ -5,13 +5,13 @@
5
5
  // turn (#122). Defined once the threats are read; planPass runs them between the capture passes.
6
6
  import { carriesTeam } from '../../teams.js';
7
7
  import { bonusTerritories } from '../bonuses.js';
8
- import { bfsDistances, neighborsOf } from '../graph.js';
9
- import { chargeDeploys } from '../local-deploy.js';
8
+ import { neighborsOf } from '../graph.js';
10
9
  import { twoStepReaches } from '../lookahead.js';
11
10
  import { opensBehind } from '../opens.js';
12
11
  import { BREACH_WEIGHT, CITE_CLOSE, CITE_OPEN, CITE_SEP, CONCEDE_FACTOR, MIN_ENEMY_DEPLOY, nearMissMargin, } from './shared.js';
13
- import { capRoom, relaxedFor } from './relations.js';
12
+ import { relaxedFor } from './relations.js';
14
13
  import { byNum } from './util.js';
14
+ import { lateArrivals, reconsiderAndGarrison, withdrawals } from './withdraw.js';
15
15
  /** #235: the most territories a cut-off line names. */
16
16
  const MAX_CUT_NAMED = 4;
17
17
  /**
@@ -648,7 +648,9 @@ export function heldBonusUnits(pc, ps, book, threats, hb, prev) {
648
648
  * concedes (it does not plan to hold them, so the bonuses they break do not pay for anything).
649
649
  * R3, rule 4d and the frontier report use it.
650
650
  */
651
- 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)))));
651
+ const keptIncome = (after) => incomeAfter(keptHeld(after));
652
+ /** #433: the territories {@link keptIncome} counts (its bonuses are next turn's Local Deployment pools). */
653
+ const keptHeld = (after) => new Set([...after].filter((t) => !conceded.has(t) && !units.some((u) => (u.conceded || u.contested) && u.members.some((m) => m.id === t))));
652
654
  /** Borders a funded unit (or an individual hold) already holds. */
653
655
  const heldBorders = new Set();
654
656
  /** My commander's borders whose whole hold rule 1k deployed. */
@@ -839,7 +841,7 @@ export function heldBonusUnits(pc, ps, book, threats, hb, prev) {
839
841
  return true;
840
842
  };
841
843
  return {
842
- keptIncome, heldBorders, commanderHeld, buildUnits, unitBorders, concedeUnit, leftFor, fundUnit, fundNearMiss,
844
+ keptIncome, keptHeld, heldBorders, commanderHeld, buildUnits, unitBorders, concedeUnit, leftFor, fundUnit, fundNearMiss,
843
845
  };
844
846
  }
845
847
  /** Rule 1h's floor tier and one shared deploy (#118), the contested units, and the triage that runs them all. */
@@ -1426,307 +1428,4 @@ export function floorTier(pc, ps, book, threats, hb, prev) {
1426
1428
  };
1427
1429
  return { keptShort, floorOrConcede, settleContested, triage, mayComplete };
1428
1430
  }
1429
- /**
1430
- * #215: I am known to move first (#127) — from a source the hold sizing trusts: one the user gave,
1431
- * not the award of picks' unverified rule (`movesFirstUnverified`, #215 review) — and no opponent
1432
- * may hold an Order Priority card (`opponentsMayHoldOrderPriority`, #215 review): played, it puts
1433
- * its first order (an all-in on a border) before my first.
1434
- */
1435
- export const knownFirst = (pc) => pc.opts.movesFirst === true && pc.opts.movesFirstUnverified !== true && pc.opts.opponentsMayHoldOrderPriority !== true;
1436
- /**
1437
- * #215: the armies withdrawn into my `id` this turn (rule 1b) that a hold may count only if I move
1438
- * first. A transfer in is my own order: when the opponent moves first, its first order — an all-in
1439
- * on `id` — runs before any of mine. So unless I am known to move first (#127, {@link knownFirst})
1440
- * they are late, and a hold sized for the worse order leaves them out. 0 when I am known to move first.
1441
- */
1442
- export function lateArrivals(pc, ps, id) {
1443
- return knownFirst(pc) ? 0 : withdrawnInto(ps, id);
1444
- }
1445
- /**
1446
- * #215 review: the armies a worse-order hold on my `id` leaves out. When the opponent moves first,
1447
- * its first order runs before ALL of mine: the armies withdrawn into `id` are not there yet, and
1448
- * the armies `id` sends out by its own orders are still there. After my orders have run, the
1449
- * withdrawal is in and those armies are gone (the hold #127 sized). A move out of a territory is
1450
- * scheduled after the moves into it (schedule.ts), so the worse of the two is the withdrawal less
1451
- * what leaves: `max(0, late − sent out)`. 0 when I am known to move first.
1452
- */
1453
- export function lateNet(pc, ps, id) {
1454
- const late = lateArrivals(pc, ps, id);
1455
- return late <= 0 ? 0 : Math.max(0, late - sentOut(ps, id));
1456
- }
1457
- /** #215 review: the armies my `id` sends out by its own orders this turn (attacks and transfers). */
1458
- export function sentOut(ps, id) {
1459
- return ps.moves.reduce((n, m) => (m.from === id ? n + m.armies : n), 0);
1460
- }
1461
- /**
1462
- * #215: the armies withdrawn into my `id` this turn (rule 1b), whatever the move order. Only
1463
- * withdrawal transfers count (#215 review): `incoming` also carries a softener's survivors that come
1464
- * home and No-Split extras, which beside an idle transfer in (rule 6) would read as withdrawn.
1465
- */
1466
- export function withdrawnInto(ps, id) {
1467
- 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);
1468
- return Math.max(0, Math.min(ps.incoming.get(id) ?? 0, sent));
1469
- }
1470
- /** Rule 1b: withdraw from conceded borders (and Order Priority when a withdrawal must go first). */
1471
- export function withdrawals(pc, ps, book, threats, hb, prev) {
1472
- const { g, label, bonusName, mine, mineSet, unitsAt, toTake, noSplit } = pc;
1473
- const { warnings, rationale, avail, locked, moves, incoming } = ps;
1474
- const { coverOf, orderOf, warnSplit, pools, valueOf } = book;
1475
- const local = pools !== null && pools.bonuses.length > 0;
1476
- const { expectedAt, borders } = threats;
1477
- const { conceded, units } = hb;
1478
- const { stayAt, unitBorders } = prev;
1479
- // ---- 1b. withdraw from conceded borders ----
1480
- ps.cardAdvice = null;
1481
- /** Conceded borders of a held bonus whose garrison stays (it holds against the expected attack). */
1482
- const stood = new Set();
1483
- /** Bonuses whose Local Deployment concession warning (#103) is already given. */
1484
- const warnedLocal = new Set();
1485
- /** Local Deployment (#103): conceded borders of a held bonus that might still hold; the leftover may go there. */
1486
- const mayHold = new Set();
1487
- /** Local Deployment: the armies every pool containing `id` holds this turn. */
1488
- const poolsAt = (id) => local ? pools.bonuses.filter((p) => p.territoryIds.includes(id)).reduce((n, p) => n + p.value, 0) : 0;
1489
- /** A border no deploy this turn can hold: its hold needs more than its pools and every free army. */
1490
- const lostAnywayAt = (m) => local && m.holdCost > poolsAt(m.id) + pools.anywhere;
1491
- /** A held bonus that falls whatever this turn deploys: one of its threatened borders cannot be held. */
1492
- const lostAnyway = (u) => u.members.some(lostAnywayAt);
1493
- const withdraw = () => {
1494
- if (!conceded.size)
1495
- return;
1496
- const withdrawals = [];
1497
- const keep = (id) => mineSet.has(id) && !conceded.has(id);
1498
- // Borders that can hold: mine, not conceded, next to something not mine.
1499
- const holding = mine.filter((id) => keep(id) && neighborsOf(g, id).some((n) => !mineSet.has(n)));
1500
- for (const t of [...conceded].sort(byNum)) {
1501
- // #179: a covered exit keeps its cover; only the rest may leave.
1502
- const n = avail.get(t) - coverOf(t);
1503
- // No-Split (#124): a transfer sends the whole stack, so a covered exit sends none.
1504
- if (n <= 0 || (noSplit && coverOf(t) > 0))
1505
- continue;
1506
- // Issue #59: a held bonus's border keeps its garrison while it still holds against the
1507
- // expected attack — withdrawing it would guarantee the loss.
1508
- const held = g.map.bonuses
1509
- .filter((b) => {
1510
- const ts = bonusTerritories(g, b.id);
1511
- return b.value > 0 && ts.includes(t) && ts.every((x) => mineSet.has(x));
1512
- })
1513
- .sort((a, b) => a.id - b.id);
1514
- const stays = stayAt(t);
1515
- const take = toTake(stays) ?? Infinity;
1516
- const expected = expectedAt(t);
1517
- if (held.length && take > expected) {
1518
- locked.add(t);
1519
- stood.add(t);
1520
- 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).`);
1521
- continue;
1522
- }
1523
- // Local Deployment (#103): a conceded held bonus keeps its garrisons unless it truly
1524
- // cannot be held — some threatened border needs more than its pools and every free army
1525
- // could give it. Withdrawing turns "might lose it" into "certainly loses it".
1526
- if (local && held.length) {
1527
- const mine1 = units.filter((u) => u.conceded && u.members.some((m) => m.id === t));
1528
- const maybe = mine1.filter((u) => !lostAnyway(u));
1529
- if (maybe.length) {
1530
- locked.add(t);
1531
- stood.add(t);
1532
- mayHold.add(t);
1533
- for (const u of maybe) {
1534
- if (warnedLocal.has(u.bonusId))
1535
- continue;
1536
- warnedLocal.add(u.bonusId);
1537
- 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.`);
1538
- }
1539
- 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.`);
1540
- continue;
1541
- }
1542
- for (const u of mine1) {
1543
- if (warnedLocal.has(u.bonusId))
1544
- continue;
1545
- warnedLocal.add(u.bonusId);
1546
- const worst = u.members.find((m) => lostAnywayAt(m));
1547
- 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).`);
1548
- }
1549
- }
1550
- // B2 (T5): never onto a truce's capped border past its cap.
1551
- const options = neighborsOf(g, t)
1552
- .filter((c) => keep(c) && capRoom(pc, ps, c, withdrawals) >= n)
1553
- .map((c) => {
1554
- const dist = bfsDistances(g, [c], { passable: keep });
1555
- let best = Infinity;
1556
- let value = 0;
1557
- for (const h of holding) {
1558
- const d = dist.get(h);
1559
- if (d === undefined)
1560
- continue;
1561
- if (d < best || (d === best && valueOf(h) > value))
1562
- [best, value] = [d, valueOf(h)];
1563
- }
1564
- return { id: c, best, value };
1565
- })
1566
- .sort((a, b) => a.best - b.best || b.value - a.value || a.id - b.id);
1567
- const to = options[0];
1568
- if (!to) {
1569
- const capped = neighborsOf(g, t).some((c) => keep(c) && capRoom(pc, ps, c, withdrawals) < n);
1570
- 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.`);
1571
- continue;
1572
- }
1573
- // #118: a border of a bonus I hold in full keeps its garrison — those armies kill attackers
1574
- // where they stand — unless withdrawing them makes another valued border hold this turn.
1575
- // (Under Local Deployment rule 1b's pool test above decides instead.)
1576
- if (held.length && !local) {
1577
- const dest = borders.get(to.id);
1578
- const at = stayAt(to.id) + unitsAt(to.id);
1579
- const makesHold = dest !== undefined &&
1580
- !conceded.has(to.id) &&
1581
- valueOf(to.id) > 0 &&
1582
- (toTake(at) ?? Infinity) <= dest.threat &&
1583
- (toTake(at + n) ?? Infinity) > dest.threat;
1584
- if (!makesHold) {
1585
- locked.add(t);
1586
- stood.add(t);
1587
- 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.`);
1588
- continue;
1589
- }
1590
- }
1591
- if (orderOf(t)) {
1592
- warnSplit(t, `its ${n} remaining armies are not withdrawn to ${label(to.id)}`);
1593
- locked.add(t);
1594
- continue;
1595
- }
1596
- avail.set(t, avail.get(t) - n);
1597
- locked.add(t);
1598
- const reason = 'withdraws from a conceded border';
1599
- withdrawals.push({ from: t, to: to.id, armies: n, kind: 'transfer', reason });
1600
- incoming.set(to.id, (incoming.get(to.id) ?? 0) + n);
1601
- rationale.push(`Withdraw ${n} from ${label(t)} to ${label(to.id)}: ${reason}, toward a border that holds.`);
1602
- 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.`);
1603
- ps.cardAdvice = 'order-priority';
1604
- }
1605
- // Withdrawals go first: they only execute while the border is still mine.
1606
- moves.unshift(...withdrawals);
1607
- };
1608
- return { stood, mayHold, withdraw };
1609
- }
1610
- /** Rule 1c (R2): reconsider concessions after the capture passes; #122: garrison a bonus completed this turn. */
1611
- export function reconsiderAndGarrison(pc, ps, book, threats, hb, prev) {
1612
- const { g, guarded, reserve, paybackTurns, label, bonusName, mine, mineSet, unitsAt, toTake, myCommanders } = pc;
1613
- const { warnings, rationale, deployed, locked, captured, moves } = ps;
1614
- const { orderOf, deploy, pools, valueCache, cutCache, breachCache, opensCache, valueOf } = book;
1615
- const local = pools !== null && pools.bonuses.length > 0;
1616
- const { borders } = threats;
1617
- const { conceded, kept, garrisoned } = hb;
1618
- const { stayAt, heldBorders } = prev;
1619
- // ---- 1c. reconsider concessions after the capture passes (R2) ----
1620
- // Triage ran before captures were known, so a border in a bonus this turn's
1621
- // captures complete was valued +0 and conceded. Re-value every border against
1622
- // the holdings after the captures; a conceded border in a bonus completed this
1623
- // turn is kept (never withdrawn from) and garrisoned from the leftover.
1624
- const reconsider = () => {
1625
- if (!captured.size)
1626
- return;
1627
- ps.holdings = new Set([...mine, ...captured]);
1628
- valueCache.clear();
1629
- cutCache.clear();
1630
- breachCache.clear();
1631
- opensCache.clear();
1632
- if (!conceded.size)
1633
- return;
1634
- for (const t of [...conceded].sort(byNum)) {
1635
- // Already withdrawn from (rule 1b ran first): its armies are gone, and it stays conceded.
1636
- if (moves.some((m) => m.from === t && m.reason === 'withdraws from a conceded border'))
1637
- continue;
1638
- const completes = g.map.bonuses
1639
- .filter((b) => {
1640
- const ts = bonusTerritories(g, b.id);
1641
- return b.value > 0 && ts.includes(t) && ts.every((x) => ps.holdings.has(x)) && !ts.every((x) => mineSet.has(x));
1642
- })
1643
- .sort((a, b) => a.id - b.id);
1644
- if (!completes.length)
1645
- continue;
1646
- conceded.delete(t);
1647
- kept.add(t);
1648
- locked.add(t);
1649
- // Drop its concession warning: it is no longer conceded.
1650
- const conceding = `${label(t)} cannot be held `;
1651
- for (let i = warnings.length - 1; i >= 0; i--)
1652
- if (warnings[i].startsWith(conceding) && warnings[i].endsWith(': conceded'))
1653
- warnings.splice(i, 1);
1654
- 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)}.`);
1655
- }
1656
- };
1657
- // (Under `defend` the withdrawal runs after the capture passes, once `reconsider` has
1658
- // kept any border this turn's captures make valuable; it still goes first in the orders.)
1659
- // ---- #122: a bonus completed this turn is garrisoned like a held one (rule 1h) ----
1660
- // Its members I held at the start of the turn that face an enemy would otherwise get only the
1661
- // leftover (rule 1c), after every advance had spent the income: live, completed bonuses stood
1662
- // beside enemies on 1-army borders and never paid a turn. So once a capture completes a bonus,
1663
- // its threatened members are held whole right away — before any later capture — when the holds
1664
- // pay for themselves as a held bonus's do (cost ≤ PAYBACK_TURNS × value and ≤ CONCEDE_FACTOR ×
1665
- // its worth) and fit what may still be deployed; otherwise they are left to the leftover as
1666
- // before. Captured members are not garrisoned: next turn's deploys land before any attack.
1667
- /** Bonuses whose garrison was judged (funded or not), so each is judged once. */
1668
- const garrisonJudged = new Set();
1669
- /** Do these deploys fit together what may still be deployed (the budget, and the pools under Local Deployment)? */
1670
- const fitsTogether = (adds) => {
1671
- if (adds.reduce((n, x) => n + x.d, 0) > ps.budget)
1672
- return false;
1673
- if (!local)
1674
- return true;
1675
- const next = new Map(deployed);
1676
- for (const x of adds)
1677
- next.set(x.id, (next.get(x.id) ?? 0) + x.d);
1678
- return chargeDeploys(pools, next).anywhereUsed <= pools.anywhere;
1679
- };
1680
- const garrisonCompleted = () => {
1681
- if (!guarded || !captured.size)
1682
- return;
1683
- const after = new Set([...mine, ...captured]);
1684
- for (const b of [...g.map.bonuses].sort((x, y) => x.id - y.id)) {
1685
- if (b.value <= 0 || garrisonJudged.has(b.id))
1686
- continue;
1687
- const ts = bonusTerritories(g, b.id);
1688
- if (!ts.length || !ts.every((x) => after.has(x)) || ts.every((x) => mineSet.has(x)))
1689
- continue;
1690
- garrisonJudged.add(b.id);
1691
- const todo = [];
1692
- let have = 0;
1693
- let split = false;
1694
- for (const t of ts) {
1695
- const border = borders.get(t);
1696
- if (!mineSet.has(t) || !border || heldBorders.has(t) || myCommanders.has(t))
1697
- continue;
1698
- const stays = stayAt(t) + unitsAt(t);
1699
- let d = 0;
1700
- while ((toTake(stays + d) ?? Infinity) <= border.threat)
1701
- d++;
1702
- if (!d)
1703
- continue;
1704
- // No-Split: a deploy on a territory that already issues an order leaves with it.
1705
- if (orderOf(t))
1706
- split = true;
1707
- todo.push({ id: t, d, threat: border.threat });
1708
- have += stays;
1709
- }
1710
- if (!todo.length || split)
1711
- continue;
1712
- const cost = todo.reduce((n, x) => n + x.d, 0);
1713
- const worth = b.value + have / paybackTurns;
1714
- // #421: the strike share holds back captures only, never this garrison.
1715
- if (cost > paybackTurns * b.value || cost > CONCEDE_FACTOR * worth || cost > ps.budget - (reserve - pc.strikeShare))
1716
- continue;
1717
- // The pools are checked for the members together: each may fit the free pool on its own
1718
- // while together they overdraw it.
1719
- if (!fitsTogether(todo))
1720
- continue;
1721
- for (const x of todo) {
1722
- deploy(x.id, x.d);
1723
- garrisoned.add(x.id);
1724
- heldBorders.add(x.id);
1725
- locked.add(x.id);
1726
- const stays = stayAt(x.id) + unitsAt(x.id);
1727
- 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.`);
1728
- }
1729
- }
1730
- };
1731
- return { reconsider, garrisonCompleted };
1732
- }
1431
+ export * from './withdraw.js';
@@ -0,0 +1,42 @@
1
+ /** #432: the payback horizon, in turns, of a 1v1 whose gates are short at the start of the turn. */
2
+ export const SHORT_GATES_PAYBACK_TURNS = 5;
3
+ /**
4
+ * The start-of-turn gate budget (#297's arithmetic on my start-of-turn holdings and armies), and the shorter horizon
5
+ * when it is short: adapting only (as #201), a 1v1 only, in contact, the gates' summed shortfall over my income, and
6
+ * only when that horizon is shorter than the one the plan already counts (a decided game's may be shorter still).
7
+ * `undefined` otherwise.
8
+ */
9
+ export function shortGatesHorizon(pc, threats) {
10
+ if (!pc.auto || pc.profile.format !== '1v1' || pc.capturePaybackTurns <= SHORT_GATES_PAYBACK_TURNS)
11
+ return undefined;
12
+ const ours = (n) => pc.mineSet.has(n);
13
+ let deficit = 0;
14
+ let player;
15
+ for (const x of pc.mine) {
16
+ const th = threats.nextTurnAt(x, ours);
17
+ if (!th)
18
+ continue;
19
+ player ??= th.player;
20
+ deficit += Math.max(0, threats.holdArmies(th.threat) - pc.armiesOf(x) - pc.unitsAt(x));
21
+ }
22
+ if (player === undefined || deficit <= pc.income)
23
+ return undefined;
24
+ return { player, deficit, turns: SHORT_GATES_PAYBACK_TURNS };
25
+ }
26
+ /** The rationale line for {@link shortGatesHorizon}'s reading. */
27
+ export function shortGatesLine(pc, s) {
28
+ return `Gate budget short (#432): in this 1v1 the gates facing player ${s.player} need ${s.deficit} more than stands on them against its one floating deploy, more than my income of ${pc.income}, so every capture's payback test counts ${s.turns} turns instead of ${pc.capturePaybackTurns} (holds keep ${pc.paybackTurns}).`;
29
+ }
30
+ /**
31
+ * Apply {@link shortGatesHorizon} to the plan: its rationale line, and the shorter horizon every later phase reads
32
+ * from `pc.capturePaybackTurns` (holds keep `pc.paybackTurns`). Run right after the threats phase (nothing before it applies a payback test).
33
+ */
34
+ export function applyShortGates(pc, ps, threats) {
35
+ const sg = shortGatesHorizon(pc, threats);
36
+ if (!sg)
37
+ return undefined;
38
+ ps.rationale.push(shortGatesLine(pc, sg));
39
+ pc.capturePaybackTurns = sg.turns;
40
+ pc.shortGates = sg;
41
+ return sg;
42
+ }