@chrischall/warapp-mcp 0.6.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 (111) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +100 -7
  4. package/dist/analysis/accept-surrender.js +20 -2
  5. package/dist/analysis/calibrate.js +1 -0
  6. package/dist/analysis/card-support.js +187 -20
  7. package/dist/analysis/card-threats.js +68 -3
  8. package/dist/analysis/chat-advice.js +182 -0
  9. package/dist/analysis/chat-blocks.js +106 -0
  10. package/dist/analysis/chat-intent.js +559 -0
  11. package/dist/analysis/chat-read.js +159 -0
  12. package/dist/analysis/coalition.js +55 -0
  13. package/dist/analysis/decision-replay.js +279 -0
  14. package/dist/analysis/decision-truth.js +146 -0
  15. package/dist/analysis/finished-game.js +62 -3
  16. package/dist/analysis/game-lessons.js +12 -6
  17. package/dist/analysis/local-deploy.js +14 -0
  18. package/dist/analysis/opponent-profile.js +46 -3
  19. package/dist/analysis/opponents.js +246 -19
  20. package/dist/analysis/outlook.js +323 -17
  21. package/dist/analysis/picks.js +270 -37
  22. package/dist/analysis/plan/after-leftover.js +28 -3
  23. package/dist/analysis/plan/captures.js +80 -16
  24. package/dist/analysis/plan/completed.js +8 -1
  25. package/dist/analysis/plan/conceded-out.js +16 -11
  26. package/dist/analysis/plan/deploy-estimates.js +513 -0
  27. package/dist/analysis/plan/doomed-out.js +135 -0
  28. package/dist/analysis/plan/estimates.js +73 -7
  29. package/dist/analysis/plan/free-capture.js +34 -0
  30. package/dist/analysis/plan/guard-off.js +2 -1
  31. package/dist/analysis/plan/holds.js +85 -313
  32. package/dist/analysis/plan/horizon.js +42 -0
  33. package/dist/analysis/plan/leftover.js +188 -10
  34. package/dist/analysis/plan/observe.js +896 -0
  35. package/dist/analysis/plan/orders.js +35 -1
  36. package/dist/analysis/plan/relations.js +115 -2
  37. package/dist/analysis/plan/report.js +10 -4
  38. package/dist/analysis/plan/shared.js +7 -1189
  39. package/dist/analysis/plan/stand-still.js +7 -5
  40. package/dist/analysis/plan/state.js +12 -0
  41. package/dist/analysis/plan/stockpile.js +104 -0
  42. package/dist/analysis/plan/strike-stack.js +467 -0
  43. package/dist/analysis/plan/strike.js +8 -441
  44. package/dist/analysis/plan/targets.js +374 -72
  45. package/dist/analysis/plan/threats.js +120 -9
  46. package/dist/analysis/plan/transfers.js +35 -1
  47. package/dist/analysis/plan/two-move.js +70 -0
  48. package/dist/analysis/plan/vacated.js +124 -2
  49. package/dist/analysis/plan/withdraw.js +316 -0
  50. package/dist/analysis/planner.js +356 -53
  51. package/dist/analysis/player.js +4 -0
  52. package/dist/analysis/relations.js +8 -2
  53. package/dist/analysis/since-last.js +18 -5
  54. package/dist/analysis/stress.js +1 -1
  55. package/dist/board.js +36 -2
  56. package/dist/build-id.js +106 -0
  57. package/dist/bundle.js +15863 -10242
  58. package/dist/chat-automation.js +22 -0
  59. package/dist/client.js +14 -0
  60. package/dist/decision-log.js +1093 -0
  61. package/dist/finished-store.js +5 -1
  62. package/dist/lessons-store.js +322 -21
  63. package/dist/my-games.js +2 -0
  64. package/dist/open-games.js +122 -18
  65. package/dist/outlook-log.js +42 -1
  66. package/dist/protocol/methods.js +4 -2
  67. package/dist/review-export.js +198 -0
  68. package/dist/state-bundle.js +62 -3
  69. package/dist/state-cli.js +5 -3
  70. package/dist/strategy/notes.js +56 -0
  71. package/dist/tools/accept-surrender.js +23 -9
  72. package/dist/tools/award.js +5 -1
  73. package/dist/tools/card-advice.js +102 -33
  74. package/dist/tools/card-support-advice.js +53 -8
  75. package/dist/tools/chat-advice.js +330 -0
  76. package/dist/tools/chat-inbox.js +15 -4
  77. package/dist/tools/chat.js +41 -11
  78. package/dist/tools/check-plan.js +16 -3
  79. package/dist/tools/commander-check.js +2 -1
  80. package/dist/tools/decision-capture.js +461 -0
  81. package/dist/tools/end-of-game.js +146 -18
  82. package/dist/tools/game-kind.js +92 -0
  83. package/dist/tools/how-lost.js +7 -2
  84. package/dist/tools/index.js +3 -0
  85. package/dist/tools/join-game.js +51 -9
  86. package/dist/tools/live-context.js +6 -0
  87. package/dist/tools/live.js +43 -6
  88. package/dist/tools/map-curves.js +73 -0
  89. package/dist/tools/notifications.js +4 -3
  90. package/dist/tools/open-games.js +2 -2
  91. package/dist/tools/opponents.js +2 -0
  92. package/dist/tools/past-games.js +74 -8
  93. package/dist/tools/picks.js +169 -57
  94. package/dist/tools/profile-hook.js +62 -3
  95. package/dist/tools/profile-opponents.js +2 -0
  96. package/dist/tools/push.js +2 -2
  97. package/dist/tools/relations.js +2 -0
  98. package/dist/tools/scout.js +16 -2
  99. package/dist/tools/state.js +6 -1
  100. package/dist/tools/strategy.js +3 -3
  101. package/dist/tools/stress-opponents.js +2 -0
  102. package/dist/tools/surrender-pending.js +10 -1
  103. package/dist/tools/surrender.js +18 -3
  104. package/dist/tools/turn.js +353 -19
  105. package/dist/tools/where.js +3 -1
  106. package/dist/version.js +1 -1
  107. package/manifest.json +23 -2
  108. package/mint.yaml +23 -0
  109. package/package.json +1 -1
  110. package/server.json +20 -2
  111. package/skills/warapp-mcp/SKILL.md +42 -8
@@ -5,15 +5,59 @@
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
- import { BREACH_WEIGHT, CITE_CLOSE, CITE_OPEN, CITE_SEP, CONCEDE_FACTOR, nearMissMargin, } from './shared.js';
13
- import { capRoom, relaxedFor } from './relations.js';
11
+ import { BREACH_WEIGHT, CITE_CLOSE, CITE_OPEN, CITE_SEP, CONCEDE_FACTOR, MIN_ENEMY_DEPLOY, nearMissMargin, } from './shared.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
+ /**
18
+ * #420: `t`'s hold is sized only on the fog prior (#119) — its opponent has no usable track and its
19
+ * figure is the prior, above what the evidence gives (its base and visible bonuses, an observed deploy,
20
+ * a Reinforcement card on the clock), and `t` holds against the stacks beside it plus that evidence.
21
+ * Returns the evidence figure, else `null`. Only a plain border: one opponent beside it (every other
22
+ * neighbour mine or neutral), no chain, split, joint or worst-case sizing, no Bomb, no figure Local
23
+ * Deployment or #275 changed, no given `enemy_deploy`.
24
+ */
25
+ export function priorOnlyHold(pc, b, t) {
26
+ if (pc.custom || pc.bombOn || b.chain || b.split || b.worst !== undefined || b.alone !== undefined || b.commanderWorst)
27
+ return null;
28
+ const e = pc.estimates.get(b.player);
29
+ if (!e || e.source !== 'prior' || e.tracked !== null || b.deploy !== pc.deployOf(b.player))
30
+ return null;
31
+ for (const n of neighborsOf(pc.g, t.id)) {
32
+ const o = pc.territories.get(n)?.owner;
33
+ if (pc.mineSet.has(n) || o?.kind === 'neutral' || (o?.kind === 'player' && o.playerId === b.player))
34
+ continue;
35
+ return null;
36
+ }
37
+ const floor = Math.max(MIN_ENEMY_DEPLOY, e.base);
38
+ const evidence = Math.max(e.opening ? floor : Math.max(floor, e.base + e.bonusIncome), e.observed ?? 0) + (e.card?.armies ?? 0);
39
+ if (evidence >= b.deploy)
40
+ return null;
41
+ const take = pc.toTake(t.have + t.units);
42
+ return take !== null && take > b.movable + Math.max(evidence, b.growth) ? evidence : null;
43
+ }
44
+ /** #420: the share of my income plain holds may take when even or ahead. */
45
+ export const HOLD_CAP_EVEN = 0.5;
46
+ /** #420: the share of my income plain holds may take when behind. */
47
+ export const HOLD_CAP_BEHIND = 0.7;
48
+ /**
49
+ * #420 (owner decision of 2026-11-20, "Total hold cap"): the armies plain holds may take this turn —
50
+ * {@link HOLD_CAP_BEHIND} of my income when the profile reads me behind, else {@link HOLD_CAP_EVEN}
51
+ * (rounded down) — or `null` under a `defend` goal the caller gave (`goal` defend while not adapting) or
52
+ * with `options.holdCap: false`.
53
+ */
54
+ export function holdCapOf(pc) {
55
+ if (pc.opts.holdCap === false || (pc.goal === 'defend' && !pc.auto))
56
+ return null;
57
+ const behind = pc.profile.standing === 'behind';
58
+ const share = behind ? HOLD_CAP_BEHIND : HOLD_CAP_EVEN;
59
+ return { armies: Math.floor(share * pc.income), share, behind };
60
+ }
17
61
  /**
18
62
  * Define the holds of one pass, step by step in planPass's order. Nothing here deploys, moves or
19
63
  * says anything yet: planPass runs assessThreats, triage, withdraw, reconsider and
@@ -553,7 +597,30 @@ export function holdOrConcede(pc, ps, book, threats, hb, prev) {
553
597
  const heldStack = (t) => `${t.have + t.holdCost} armies${t.units ? ' and my commander' : ''}`;
554
598
  /** The borders a hold deployed to, by the player threatening them (for the #69 rationale). */
555
599
  const heldAgainst = new Map();
556
- const hold = (t) => {
600
+ /**
601
+ * #420 (owner decision of 2026-11-20, "Total hold cap"): plain holds take at most
602
+ * {@link HOLD_CAP_EVEN} of my income when even or ahead, {@link HOLD_CAP_BEHIND} when behind (the
603
+ * profile's standing). A held bonus's own gate (rule 1h's units, `gate`) and my commander's hold are
604
+ * funded first, outside the cap, and do not count toward it. Not under a `defend` goal the caller gave.
605
+ */
606
+ const holdCap = holdCapOf(pc);
607
+ let capSpent = 0;
608
+ /** #420: a plain hold of `t` would take the holds past the cap. */
609
+ const overCap = (t) => holdCap !== null && !t.critical && capSpent + t.holdCost > holdCap.armies;
610
+ /** #420: what a plain hold deployed outside {@link hold} (rule 4a's hold-and-break) takes of the cap. */
611
+ const chargeCap = (armies) => {
612
+ capSpent += armies;
613
+ };
614
+ /** #420: `t` is conceded for the cap (said unless `quiet`); its line reads like rule 1a's, so a revival lifts it. */
615
+ const concedeCapped = (t, quiet = false) => {
616
+ conceded.add(t.id);
617
+ if (quiet || !holdCap)
618
+ return;
619
+ warnings.push(`${label(t.id)} cannot be held within the hold cap (#420: plain holds take at most ${holdCap.armies} of my ${pc.income} income, ${holdCap.share * 100}% ${holdCap.behind ? 'when behind' : 'when even or ahead'}; ${capSpent} already go to holds, and it needs ${t.holdCost}, protects +${t.value}): conceded`);
620
+ };
621
+ const hold = (t, gate = false) => {
622
+ if (!gate && !t.critical)
623
+ capSpent += t.holdCost;
557
624
  noteRecent(t);
558
625
  deploy(t.id, t.holdCost);
559
626
  locked.add(t.id);
@@ -562,7 +629,7 @@ export function holdOrConcede(pc, ps, book, threats, hb, prev) {
562
629
  heldAgainst.set(by, (heldAgainst.get(by) ?? new Set()).add(t.id));
563
630
  rationale.push(`Deploy ${t.holdCost + (t.given ?? 0)} to ${label(t.id)} so it holds (protects +${t.value}): ${heldStack(t)} need ${toTake(t.have + t.units + t.holdCost)} to take, above the ~${t.threat} threat.`);
564
631
  };
565
- return { threatWarnings, assessThreats, acting, concedeUnaffordable, noteRecent, heldStack, heldAgainst, hold };
632
+ return { threatWarnings, assessThreats, acting, concedeUnaffordable, noteRecent, heldStack, heldAgainst, hold, overCap, chargeCap, concedeCapped };
566
633
  }
567
634
  /** Rule 1h (#51): every bonus I hold in full with a threatened border is one unit, held whole or conceded. */
568
635
  export function heldBonusUnits(pc, ps, book, threats, hb, prev) {
@@ -581,7 +648,9 @@ export function heldBonusUnits(pc, ps, book, threats, hb, prev) {
581
648
  * concedes (it does not plan to hold them, so the bonuses they break do not pay for anything).
582
649
  * R3, rule 4d and the frontier report use it.
583
650
  */
584
- 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))));
585
654
  /** Borders a funded unit (or an individual hold) already holds. */
586
655
  const heldBorders = new Set();
587
656
  /** My commander's borders whose whole hold rule 1k deployed. */
@@ -718,8 +787,9 @@ export function heldBonusUnits(pc, ps, book, threats, hb, prev) {
718
787
  let rest = cost;
719
788
  for (const m of todo) {
720
789
  rest -= m.holdCost;
790
+ // #420: a held bonus's own gate, outside the hold cap.
721
791
  if (!each?.(m, rest))
722
- hold(m);
792
+ hold(m, true);
723
793
  heldBorders.add(m.id);
724
794
  }
725
795
  return true;
@@ -771,7 +841,7 @@ export function heldBonusUnits(pc, ps, book, threats, hb, prev) {
771
841
  return true;
772
842
  };
773
843
  return {
774
- keptIncome, heldBorders, commanderHeld, buildUnits, unitBorders, concedeUnit, leftFor, fundUnit, fundNearMiss,
844
+ keptIncome, keptHeld, heldBorders, commanderHeld, buildUnits, unitBorders, concedeUnit, leftFor, fundUnit, fundNearMiss,
775
845
  };
776
846
  }
777
847
  /** Rule 1h's floor tier and one shared deploy (#118), the contested units, and the triage that runs them all. */
@@ -801,7 +871,7 @@ export function floorTier(pc, ps, book, threats, hb, prev) {
801
871
  const near = new Set(missing.flatMap(sourcesOf));
802
872
  return cost <= income + [...near].reduce((n, x) => n + avail.get(x), 0);
803
873
  });
804
- const { uneconomic, acting, concedeUnaffordable, heldStack, hold, heldBorders, commanderHeld, buildUnits, unitBorders, concedeUnit, leftFor, fundUnit, fundNearMiss, } = prev;
874
+ const { uneconomic, acting, concedeUnaffordable, heldStack, hold, heldBorders, commanderHeld, buildUnits, unitBorders, concedeUnit, leftFor, fundUnit, fundNearMiss, overCap, concedeCapped, } = prev;
805
875
  // ---- 1h. floor tier and one shared deploy (#118) ----
806
876
  // One enemy deploy lands on one target. Sizing every border of a held bonus for the whole of
807
877
  // it conceded every bonus once the deploy outgrew them, though the stacks already next to the
@@ -944,6 +1014,8 @@ export function floorTier(pc, ps, book, threats, hb, prev) {
944
1014
  concedeUnaffordable(t, room);
945
1015
  return;
946
1016
  }
1017
+ if (overCap(t))
1018
+ return concedeCapped(t, quiet);
947
1019
  hold(t);
948
1020
  heldBorders.add(t.id);
949
1021
  };
@@ -1306,6 +1378,8 @@ export function floorTier(pc, ps, book, threats, hb, prev) {
1306
1378
  concedeUnaffordable(t, left);
1307
1379
  return;
1308
1380
  }
1381
+ if (acting && overCap(t))
1382
+ return concedeCapped(t, quiet);
1309
1383
  triageBudget -= t.holdCost;
1310
1384
  if (acting) {
1311
1385
  hold(t);
@@ -1354,306 +1428,4 @@ export function floorTier(pc, ps, book, threats, hb, prev) {
1354
1428
  };
1355
1429
  return { keptShort, floorOrConcede, settleContested, triage, mayComplete };
1356
1430
  }
1357
- /**
1358
- * #215: I am known to move first (#127) — from a source the hold sizing trusts: one the user gave,
1359
- * not the award of picks' unverified rule (`movesFirstUnverified`, #215 review) — and no opponent
1360
- * may hold an Order Priority card (`opponentsMayHoldOrderPriority`, #215 review): played, it puts
1361
- * its first order (an all-in on a border) before my first.
1362
- */
1363
- export const knownFirst = (pc) => pc.opts.movesFirst === true && pc.opts.movesFirstUnverified !== true && pc.opts.opponentsMayHoldOrderPriority !== true;
1364
- /**
1365
- * #215: the armies withdrawn into my `id` this turn (rule 1b) that a hold may count only if I move
1366
- * first. A transfer in is my own order: when the opponent moves first, its first order — an all-in
1367
- * on `id` — runs before any of mine. So unless I am known to move first (#127, {@link knownFirst})
1368
- * they are late, and a hold sized for the worse order leaves them out. 0 when I am known to move first.
1369
- */
1370
- export function lateArrivals(pc, ps, id) {
1371
- return knownFirst(pc) ? 0 : withdrawnInto(ps, id);
1372
- }
1373
- /**
1374
- * #215 review: the armies a worse-order hold on my `id` leaves out. When the opponent moves first,
1375
- * its first order runs before ALL of mine: the armies withdrawn into `id` are not there yet, and
1376
- * the armies `id` sends out by its own orders are still there. After my orders have run, the
1377
- * withdrawal is in and those armies are gone (the hold #127 sized). A move out of a territory is
1378
- * scheduled after the moves into it (schedule.ts), so the worse of the two is the withdrawal less
1379
- * what leaves: `max(0, late − sent out)`. 0 when I am known to move first.
1380
- */
1381
- export function lateNet(pc, ps, id) {
1382
- const late = lateArrivals(pc, ps, id);
1383
- return late <= 0 ? 0 : Math.max(0, late - sentOut(ps, id));
1384
- }
1385
- /** #215 review: the armies my `id` sends out by its own orders this turn (attacks and transfers). */
1386
- export function sentOut(ps, id) {
1387
- return ps.moves.reduce((n, m) => (m.from === id ? n + m.armies : n), 0);
1388
- }
1389
- /**
1390
- * #215: the armies withdrawn into my `id` this turn (rule 1b), whatever the move order. Only
1391
- * withdrawal transfers count (#215 review): `incoming` also carries a softener's survivors that come
1392
- * home and No-Split extras, which beside an idle transfer in (rule 6) would read as withdrawn.
1393
- */
1394
- export function withdrawnInto(ps, id) {
1395
- 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);
1396
- return Math.max(0, Math.min(ps.incoming.get(id) ?? 0, sent));
1397
- }
1398
- /** Rule 1b: withdraw from conceded borders (and Order Priority when a withdrawal must go first). */
1399
- export function withdrawals(pc, ps, book, threats, hb, prev) {
1400
- const { g, label, bonusName, mine, mineSet, unitsAt, toTake, noSplit } = pc;
1401
- const { warnings, rationale, avail, locked, moves, incoming } = ps;
1402
- const { coverOf, orderOf, warnSplit, pools, valueOf } = book;
1403
- const local = pools !== null && pools.bonuses.length > 0;
1404
- const { expectedAt, borders } = threats;
1405
- const { conceded, units } = hb;
1406
- const { stayAt, unitBorders } = prev;
1407
- // ---- 1b. withdraw from conceded borders ----
1408
- ps.cardAdvice = null;
1409
- /** Conceded borders of a held bonus whose garrison stays (it holds against the expected attack). */
1410
- const stood = new Set();
1411
- /** Bonuses whose Local Deployment concession warning (#103) is already given. */
1412
- const warnedLocal = new Set();
1413
- /** Local Deployment (#103): conceded borders of a held bonus that might still hold; the leftover may go there. */
1414
- const mayHold = new Set();
1415
- /** Local Deployment: the armies every pool containing `id` holds this turn. */
1416
- const poolsAt = (id) => local ? pools.bonuses.filter((p) => p.territoryIds.includes(id)).reduce((n, p) => n + p.value, 0) : 0;
1417
- /** A border no deploy this turn can hold: its hold needs more than its pools and every free army. */
1418
- const lostAnywayAt = (m) => local && m.holdCost > poolsAt(m.id) + pools.anywhere;
1419
- /** A held bonus that falls whatever this turn deploys: one of its threatened borders cannot be held. */
1420
- const lostAnyway = (u) => u.members.some(lostAnywayAt);
1421
- const withdraw = () => {
1422
- if (!conceded.size)
1423
- return;
1424
- const withdrawals = [];
1425
- const keep = (id) => mineSet.has(id) && !conceded.has(id);
1426
- // Borders that can hold: mine, not conceded, next to something not mine.
1427
- const holding = mine.filter((id) => keep(id) && neighborsOf(g, id).some((n) => !mineSet.has(n)));
1428
- for (const t of [...conceded].sort(byNum)) {
1429
- // #179: a covered exit keeps its cover; only the rest may leave.
1430
- const n = avail.get(t) - coverOf(t);
1431
- // No-Split (#124): a transfer sends the whole stack, so a covered exit sends none.
1432
- if (n <= 0 || (noSplit && coverOf(t) > 0))
1433
- continue;
1434
- // Issue #59: a held bonus's border keeps its garrison while it still holds against the
1435
- // expected attack — withdrawing it would guarantee the loss.
1436
- const held = g.map.bonuses
1437
- .filter((b) => {
1438
- const ts = bonusTerritories(g, b.id);
1439
- return b.value > 0 && ts.includes(t) && ts.every((x) => mineSet.has(x));
1440
- })
1441
- .sort((a, b) => a.id - b.id);
1442
- const stays = stayAt(t);
1443
- const take = toTake(stays) ?? Infinity;
1444
- const expected = expectedAt(t);
1445
- if (held.length && take > expected) {
1446
- locked.add(t);
1447
- stood.add(t);
1448
- 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).`);
1449
- continue;
1450
- }
1451
- // Local Deployment (#103): a conceded held bonus keeps its garrisons unless it truly
1452
- // cannot be held — some threatened border needs more than its pools and every free army
1453
- // could give it. Withdrawing turns "might lose it" into "certainly loses it".
1454
- if (local && held.length) {
1455
- const mine1 = units.filter((u) => u.conceded && u.members.some((m) => m.id === t));
1456
- const maybe = mine1.filter((u) => !lostAnyway(u));
1457
- if (maybe.length) {
1458
- locked.add(t);
1459
- stood.add(t);
1460
- mayHold.add(t);
1461
- for (const u of maybe) {
1462
- if (warnedLocal.has(u.bonusId))
1463
- continue;
1464
- warnedLocal.add(u.bonusId);
1465
- 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.`);
1466
- }
1467
- 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.`);
1468
- continue;
1469
- }
1470
- for (const u of mine1) {
1471
- if (warnedLocal.has(u.bonusId))
1472
- continue;
1473
- warnedLocal.add(u.bonusId);
1474
- const worst = u.members.find((m) => lostAnywayAt(m));
1475
- 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).`);
1476
- }
1477
- }
1478
- // B2 (T5): never onto a truce's capped border past its cap.
1479
- const options = neighborsOf(g, t)
1480
- .filter((c) => keep(c) && capRoom(pc, ps, c, withdrawals) >= n)
1481
- .map((c) => {
1482
- const dist = bfsDistances(g, [c], { passable: keep });
1483
- let best = Infinity;
1484
- let value = 0;
1485
- for (const h of holding) {
1486
- const d = dist.get(h);
1487
- if (d === undefined)
1488
- continue;
1489
- if (d < best || (d === best && valueOf(h) > value))
1490
- [best, value] = [d, valueOf(h)];
1491
- }
1492
- return { id: c, best, value };
1493
- })
1494
- .sort((a, b) => a.best - b.best || b.value - a.value || a.id - b.id);
1495
- const to = options[0];
1496
- if (!to) {
1497
- const capped = neighborsOf(g, t).some((c) => keep(c) && capRoom(pc, ps, c, withdrawals) < n);
1498
- 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.`);
1499
- continue;
1500
- }
1501
- // #118: a border of a bonus I hold in full keeps its garrison — those armies kill attackers
1502
- // where they stand — unless withdrawing them makes another valued border hold this turn.
1503
- // (Under Local Deployment rule 1b's pool test above decides instead.)
1504
- if (held.length && !local) {
1505
- const dest = borders.get(to.id);
1506
- const at = stayAt(to.id) + unitsAt(to.id);
1507
- const makesHold = dest !== undefined &&
1508
- !conceded.has(to.id) &&
1509
- valueOf(to.id) > 0 &&
1510
- (toTake(at) ?? Infinity) <= dest.threat &&
1511
- (toTake(at + n) ?? Infinity) > dest.threat;
1512
- if (!makesHold) {
1513
- locked.add(t);
1514
- stood.add(t);
1515
- 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.`);
1516
- continue;
1517
- }
1518
- }
1519
- if (orderOf(t)) {
1520
- warnSplit(t, `its ${n} remaining armies are not withdrawn to ${label(to.id)}`);
1521
- locked.add(t);
1522
- continue;
1523
- }
1524
- avail.set(t, avail.get(t) - n);
1525
- locked.add(t);
1526
- const reason = 'withdraws from a conceded border';
1527
- withdrawals.push({ from: t, to: to.id, armies: n, kind: 'transfer', reason });
1528
- incoming.set(to.id, (incoming.get(to.id) ?? 0) + n);
1529
- rationale.push(`Withdraw ${n} from ${label(t)} to ${label(to.id)}: ${reason}, toward a border that holds.`);
1530
- 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.`);
1531
- ps.cardAdvice = 'order-priority';
1532
- }
1533
- // Withdrawals go first: they only execute while the border is still mine.
1534
- moves.unshift(...withdrawals);
1535
- };
1536
- return { stood, mayHold, withdraw };
1537
- }
1538
- /** Rule 1c (R2): reconsider concessions after the capture passes; #122: garrison a bonus completed this turn. */
1539
- export function reconsiderAndGarrison(pc, ps, book, threats, hb, prev) {
1540
- const { g, guarded, reserve, paybackTurns, label, bonusName, mine, mineSet, unitsAt, toTake, myCommanders } = pc;
1541
- const { warnings, rationale, deployed, locked, captured, moves } = ps;
1542
- const { orderOf, deploy, pools, valueCache, cutCache, breachCache, opensCache, valueOf } = book;
1543
- const local = pools !== null && pools.bonuses.length > 0;
1544
- const { borders } = threats;
1545
- const { conceded, kept, garrisoned } = hb;
1546
- const { stayAt, heldBorders } = prev;
1547
- // ---- 1c. reconsider concessions after the capture passes (R2) ----
1548
- // Triage ran before captures were known, so a border in a bonus this turn's
1549
- // captures complete was valued +0 and conceded. Re-value every border against
1550
- // the holdings after the captures; a conceded border in a bonus completed this
1551
- // turn is kept (never withdrawn from) and garrisoned from the leftover.
1552
- const reconsider = () => {
1553
- if (!captured.size)
1554
- return;
1555
- ps.holdings = new Set([...mine, ...captured]);
1556
- valueCache.clear();
1557
- cutCache.clear();
1558
- breachCache.clear();
1559
- opensCache.clear();
1560
- if (!conceded.size)
1561
- return;
1562
- for (const t of [...conceded].sort(byNum)) {
1563
- // Already withdrawn from (rule 1b ran first): its armies are gone, and it stays conceded.
1564
- if (moves.some((m) => m.from === t && m.reason === 'withdraws from a conceded border'))
1565
- continue;
1566
- const completes = g.map.bonuses
1567
- .filter((b) => {
1568
- const ts = bonusTerritories(g, b.id);
1569
- return b.value > 0 && ts.includes(t) && ts.every((x) => ps.holdings.has(x)) && !ts.every((x) => mineSet.has(x));
1570
- })
1571
- .sort((a, b) => a.id - b.id);
1572
- if (!completes.length)
1573
- continue;
1574
- conceded.delete(t);
1575
- kept.add(t);
1576
- locked.add(t);
1577
- // Drop its concession warning: it is no longer conceded.
1578
- const conceding = `${label(t)} cannot be held `;
1579
- for (let i = warnings.length - 1; i >= 0; i--)
1580
- if (warnings[i].startsWith(conceding) && warnings[i].endsWith(': conceded'))
1581
- warnings.splice(i, 1);
1582
- 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)}.`);
1583
- }
1584
- };
1585
- // (Under `defend` the withdrawal runs after the capture passes, once `reconsider` has
1586
- // kept any border this turn's captures make valuable; it still goes first in the orders.)
1587
- // ---- #122: a bonus completed this turn is garrisoned like a held one (rule 1h) ----
1588
- // Its members I held at the start of the turn that face an enemy would otherwise get only the
1589
- // leftover (rule 1c), after every advance had spent the income: live, completed bonuses stood
1590
- // beside enemies on 1-army borders and never paid a turn. So once a capture completes a bonus,
1591
- // its threatened members are held whole right away — before any later capture — when the holds
1592
- // pay for themselves as a held bonus's do (cost ≤ PAYBACK_TURNS × value and ≤ CONCEDE_FACTOR ×
1593
- // its worth) and fit what may still be deployed; otherwise they are left to the leftover as
1594
- // before. Captured members are not garrisoned: next turn's deploys land before any attack.
1595
- /** Bonuses whose garrison was judged (funded or not), so each is judged once. */
1596
- const garrisonJudged = new Set();
1597
- /** Do these deploys fit together what may still be deployed (the budget, and the pools under Local Deployment)? */
1598
- const fitsTogether = (adds) => {
1599
- if (adds.reduce((n, x) => n + x.d, 0) > ps.budget)
1600
- return false;
1601
- if (!local)
1602
- return true;
1603
- const next = new Map(deployed);
1604
- for (const x of adds)
1605
- next.set(x.id, (next.get(x.id) ?? 0) + x.d);
1606
- return chargeDeploys(pools, next).anywhereUsed <= pools.anywhere;
1607
- };
1608
- const garrisonCompleted = () => {
1609
- if (!guarded || !captured.size)
1610
- return;
1611
- const after = new Set([...mine, ...captured]);
1612
- for (const b of [...g.map.bonuses].sort((x, y) => x.id - y.id)) {
1613
- if (b.value <= 0 || garrisonJudged.has(b.id))
1614
- continue;
1615
- const ts = bonusTerritories(g, b.id);
1616
- if (!ts.length || !ts.every((x) => after.has(x)) || ts.every((x) => mineSet.has(x)))
1617
- continue;
1618
- garrisonJudged.add(b.id);
1619
- const todo = [];
1620
- let have = 0;
1621
- let split = false;
1622
- for (const t of ts) {
1623
- const border = borders.get(t);
1624
- if (!mineSet.has(t) || !border || heldBorders.has(t) || myCommanders.has(t))
1625
- continue;
1626
- const stays = stayAt(t) + unitsAt(t);
1627
- let d = 0;
1628
- while ((toTake(stays + d) ?? Infinity) <= border.threat)
1629
- d++;
1630
- if (!d)
1631
- continue;
1632
- // No-Split: a deploy on a territory that already issues an order leaves with it.
1633
- if (orderOf(t))
1634
- split = true;
1635
- todo.push({ id: t, d, threat: border.threat });
1636
- have += stays;
1637
- }
1638
- if (!todo.length || split)
1639
- continue;
1640
- const cost = todo.reduce((n, x) => n + x.d, 0);
1641
- const worth = b.value + have / paybackTurns;
1642
- if (cost > paybackTurns * b.value || cost > CONCEDE_FACTOR * worth || cost > ps.budget - reserve)
1643
- continue;
1644
- // The pools are checked for the members together: each may fit the free pool on its own
1645
- // while together they overdraw it.
1646
- if (!fitsTogether(todo))
1647
- continue;
1648
- for (const x of todo) {
1649
- deploy(x.id, x.d);
1650
- garrisoned.add(x.id);
1651
- heldBorders.add(x.id);
1652
- locked.add(x.id);
1653
- const stays = stayAt(x.id) + unitsAt(x.id);
1654
- 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.`);
1655
- }
1656
- }
1657
- };
1658
- return { reconsider, garrisonCompleted };
1659
- }
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
+ }