@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
@@ -232,7 +232,8 @@ function opponentsCtx(input) {
232
232
  ...(ctx.turn !== undefined ? { turn: ctx.turn } : {}),
233
233
  ...(ctx.picking !== undefined ? { picking: ctx.picking } : {}),
234
234
  ...(ctx.endRules ? { endRules: ctx.endRules } : {}),
235
- income: earnedIncome,
235
+ // #427: my Reinforcement card is a one-off deploy like an opponent's, so the standing reads income without it.
236
+ income: earnedIncome - Math.max(0, Math.floor(input.cardArmies ?? 0)),
236
237
  // #164 x #167: an opponent's Reinforcement card is a one-off deploy, not income: the standing
237
238
  // and the FFA ranking read each estimate less its card. PLAN-TEAMS C3: teammates' estimates go
238
239
  // too, for the team standing (the profile keeps them off the opponents' side).
@@ -427,6 +428,7 @@ function opponentsCtx(input) {
427
428
  untrustedAt,
428
429
  decidedGame,
429
430
  paybackTurns,
431
+ capturePaybackTurns: paybackTurns,
430
432
  };
431
433
  }
432
434
  /** 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
+ }
@@ -29,6 +29,8 @@ export const DETERRENT_MIN_VALUE = 5;
29
29
  /** #440: how many times the most any border being topped up protects that territory must protect. */
30
30
  export const DETERRENT_VALUE_RATIO = 2;
31
31
  import { knownFirst, lateArrivals, lateNet } from './holds.js';
32
+ import { isDoomedOut } from './doomed-out.js';
33
+ import { paybackLive } from './state.js';
32
34
  import { stackFacing } from './strike.js';
33
35
  /**
34
36
  * The leftover deploy (rule 5). `stack` is the strike stack rule 0p.3c chose (plan/strike.ts),
@@ -39,7 +41,7 @@ import { stackFacing } from './strike.js';
39
41
  export function leftoverDeploy(pc, ps, book, threats, hd, tgt, saveStep, stack, open, stays) {
40
42
  const { g, territories: state, label, bonusName, mine, mineSet, armiesOf, unitsAt, toTake, noSplit, bombOn } = pc;
41
43
  const { warnings, rationale, deployed, avail, locked, captured, moves, incoming } = ps;
42
- const { orderOf, deploy, undeploy, pools, roomAt, valueOf } = book;
44
+ const { orderOf, deploy, undeploy, pools, roomAt, valueOf, coverOf } = book;
43
45
  const { borders } = threats;
44
46
  const { conceded, kept, garrisoned, stood, threatened, stayAt } = hd;
45
47
  const { committing, byCloseness, bonusTarget, targets, repulsed } = tgt;
@@ -776,6 +778,8 @@ export function leftoverDeploy(pc, ps, book, threats, hd, tgt, saveStep, stack,
776
778
  let spreadRest;
777
779
  let where;
778
780
  let why;
781
+ /** #431: the move out of a doomed stack's border the leftover goes with (every territory of mine left). */
782
+ let ridesOut;
779
783
  let lock = false;
780
784
  /** #163: the leftover concentrates for one attack (strike, saving, expansion): no Bomb split. */
781
785
  let concentrating = false;
@@ -793,14 +797,22 @@ export function leftoverDeploy(pc, ps, book, threats, hd, tgt, saveStep, stack,
793
797
  * #288: a source facing no threat whose every neighbour is mine or captured this turn has nothing
794
798
  * left to attack once the captures land, so a leftover there idles: it goes with its attacks whose
795
799
  * targets still have a step onward (most steps onward first, then id). Never under No-Split (an
796
- * order already carries the whole stack), nor with a combined capture or a softener.
800
+ * order already carries the whole stack), nor with a combined capture or a softener, nor onto a
801
+ * member a #422 payback completion may lose next turn.
797
802
  */
798
803
  const joinsOf = (src) => {
799
804
  if (noSplit || borders.has(src) || pc.myCommanders.has(src) || leftToAttack(src).length)
800
805
  return undefined;
801
806
  const onward = (t) => leftToAttack(t).filter((n) => n !== src).length;
802
807
  const out = moves
803
- .filter((m) => m.kind === 'attack' && m.from === src && captured.has(m.to) && !ps.combined.has(m.to) && state.get(m.to)?.owner.kind === 'neutral' && onward(m.to) > 0)
808
+ .filter((m) => m.kind === 'attack' &&
809
+ m.from === src &&
810
+ captured.has(m.to) &&
811
+ !ps.combined.has(m.to) &&
812
+ // #422: never onto a member a payback completion expects to lose next turn.
813
+ !paybackLive(ps, ps.paybackFalls, m.to) &&
814
+ state.get(m.to)?.owner.kind === 'neutral' &&
815
+ onward(m.to) > 0)
804
816
  .sort((a, b) => onward(b.to) - onward(a.to) || a.to - b.to);
805
817
  return out.length ? out : undefined;
806
818
  };
@@ -976,9 +988,15 @@ export function leftoverDeploy(pc, ps, book, threats, hd, tgt, saveStep, stack,
976
988
  why = 'my biggest stack';
977
989
  }
978
990
  else {
979
- where = biggest(mine);
991
+ // #431: never the border a doomed stack just left, while another territory of mine remains;
992
+ // when none does, the leftover leaves with that stack's move out (deploys land before moves).
993
+ const others = mine.filter((x) => !ps.doomedOut.has(x));
994
+ where = biggest(others.length ? others : mine);
980
995
  why = 'my biggest stack';
981
- warnings.push(`Every territory I hold is conceded; the leftover ${ps.budget} goes to ${label(where)} anyway.`);
996
+ ridesOut = ps.doomedOut.has(where) ? moves.find((m) => m.from === where && isDoomedOut(m)) : undefined;
997
+ warnings.push(ridesOut
998
+ ? `Every territory I hold is conceded; the leftover ${ps.budget} goes to ${label(where)} and leaves with its move out (#431).`
999
+ : `Every territory I hold is conceded; the leftover ${ps.budget} goes to ${label(where)} anyway.`);
982
1000
  }
983
1001
  }
984
1002
  let n = roomAt(where);
@@ -1086,6 +1104,23 @@ export function leftoverDeploy(pc, ps, book, threats, hd, tgt, saveStep, stack,
1086
1104
  else if (n > 0 && !spreadRest) {
1087
1105
  rationale.push(`Deploy the leftover ${n} to ${label(where)}: ${why}.`);
1088
1106
  deploy(where, n);
1107
+ // #431: the border its doomed stack left is lost for sure: the deploy goes with that stack.
1108
+ if (ridesOut) {
1109
+ const m = ridesOut;
1110
+ const add = Math.min(n, avail.get(where) - (pc.noSplit ? 0 : coverOf(where)));
1111
+ if (add > 0) {
1112
+ avail.set(where, avail.get(where) - add);
1113
+ m.armies += add;
1114
+ if (m.kind === 'transfer')
1115
+ incoming.set(m.to, (incoming.get(m.to) ?? 0) + add);
1116
+ else {
1117
+ if (ps.survivorsAt.has(m.to))
1118
+ ps.survivorsAt.set(m.to, ps.survivorsAt.get(m.to) + add);
1119
+ m.winChance = pc.chanceOf(m.armies, pc.defenceAt(m.to));
1120
+ }
1121
+ rationale.push(`The ${add} deployed on ${label(where)} leave with its move out to ${label(m.to)} (#431): ${m.armies} go.`);
1122
+ }
1123
+ }
1089
1124
  // Keep a strike or expansion stack there: the transfer step must not walk it back as "idle
1090
1125
  // interior" armies. Only when it got deploys (under Local Deployment it may get none).
1091
1126
  if (lock)
@@ -1120,6 +1155,9 @@ export function leftoverDeploy(pc, ps, book, threats, hd, tgt, saveStep, stack,
1120
1155
  const m = [...p.territoryIds].sort((a, b) =>
1121
1156
  // No-Split (#124): a member that issues an order would send the pool away with it.
1122
1157
  Number(orderOf(a) !== undefined) - Number(orderOf(b) !== undefined) ||
1158
+ // #431: a border a doomed stack left (merged or attacked out of) is lost for sure: the pool
1159
+ // goes to any other member first, even an interior one.
1160
+ Number(ps.doomedOut.has(a)) - Number(ps.doomedOut.has(b)) ||
1123
1161
  Number(borders.has(b)) - Number(borders.has(a)) ||
1124
1162
  Number(lost(a)) - Number(lost(b)) ||
1125
1163
  danger(b) - danger(a) ||