@chrischall/warapp-mcp 0.5.0 → 0.7.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 (125) hide show
  1. package/.claude-plugin/marketplace.json +3 -3
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +133 -8
  4. package/dist/analysis/accept-surrender.js +20 -2
  5. package/dist/analysis/calibrate.js +1 -0
  6. package/dist/analysis/card-support.js +177 -17
  7. package/dist/analysis/card-threats.js +126 -14
  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/decision-replay.js +279 -0
  13. package/dist/analysis/decision-truth.js +146 -0
  14. package/dist/analysis/finished-game.js +62 -3
  15. package/dist/analysis/game-lessons.js +15 -10
  16. package/dist/analysis/hold-diff.js +3 -1
  17. package/dist/analysis/income-trend.js +38 -0
  18. package/dist/analysis/intel.js +75 -0
  19. package/dist/analysis/opens.js +64 -0
  20. package/dist/analysis/opponent-profile.js +121 -10
  21. package/dist/analysis/opponents.js +246 -20
  22. package/dist/analysis/outlook.js +360 -15
  23. package/dist/analysis/picks.js +91 -12
  24. package/dist/analysis/plan/after-leftover.js +4 -1
  25. package/dist/analysis/plan/bonus-attempts.js +105 -0
  26. package/dist/analysis/plan/capture-instead.js +116 -0
  27. package/dist/analysis/plan/captures.js +49 -7
  28. package/dist/analysis/plan/conceded-out.js +13 -2
  29. package/dist/analysis/plan/estimates.js +203 -30
  30. package/dist/analysis/plan/guard-off.js +2 -1
  31. package/dist/analysis/plan/holds.js +110 -9
  32. package/dist/analysis/plan/jabs.js +113 -0
  33. package/dist/analysis/plan/leftover.js +393 -8
  34. package/dist/analysis/plan/orders.js +76 -4
  35. package/dist/analysis/plan/relations.js +135 -2
  36. package/dist/analysis/plan/report.js +69 -3
  37. package/dist/analysis/plan/second-sizing.js +133 -0
  38. package/dist/analysis/plan/shared.js +279 -27
  39. package/dist/analysis/plan/siege.js +303 -0
  40. package/dist/analysis/plan/stand-still.js +9 -5
  41. package/dist/analysis/plan/state.js +8 -0
  42. package/dist/analysis/plan/stockpile.js +104 -0
  43. package/dist/analysis/plan/strike.js +39 -7
  44. package/dist/analysis/plan/targets.js +256 -110
  45. package/dist/analysis/plan/threats.js +148 -10
  46. package/dist/analysis/plan/transfers.js +57 -6
  47. package/dist/analysis/plan/two-move.js +70 -0
  48. package/dist/analysis/plan/vacated.js +124 -2
  49. package/dist/analysis/planner.js +527 -49
  50. package/dist/analysis/profile.js +13 -2
  51. package/dist/analysis/since-last.js +18 -5
  52. package/dist/analysis/stress.js +8 -2
  53. package/dist/board.js +36 -2
  54. package/dist/bonus-attempt-store.js +55 -0
  55. package/dist/build-id.js +106 -0
  56. package/dist/bundle.js +54138 -41059
  57. package/dist/cards.js +7 -5
  58. package/dist/chat-automation.js +22 -0
  59. package/dist/chat.js +35 -1
  60. package/dist/client.js +14 -0
  61. package/dist/commerce.js +111 -0
  62. package/dist/decision-log.js +1093 -0
  63. package/dist/finished-store.js +5 -1
  64. package/dist/index.js +9 -1
  65. package/dist/lessons-store.js +322 -21
  66. package/dist/live.js +43 -0
  67. package/dist/move-order.js +64 -3
  68. package/dist/normalize.js +17 -0
  69. package/dist/open-games.js +36 -16
  70. package/dist/outlook-log.js +42 -1
  71. package/dist/profile-store.js +12 -2
  72. package/dist/protocol/methods.js +62 -5
  73. package/dist/protocol/rpc.js +8 -0
  74. package/dist/relations-store.js +38 -4
  75. package/dist/review-export.js +198 -0
  76. package/dist/siege-store.js +49 -0
  77. package/dist/state-bundle.js +584 -0
  78. package/dist/state-cli.js +71 -0
  79. package/dist/strategy/notes.js +56 -0
  80. package/dist/team-cards.js +25 -0
  81. package/dist/tools/accept-surrender.js +23 -9
  82. package/dist/tools/award.js +20 -2
  83. package/dist/tools/card-advice.js +93 -28
  84. package/dist/tools/card-plays.js +2 -2
  85. package/dist/tools/card-support-advice.js +37 -7
  86. package/dist/tools/chat-advice.js +330 -0
  87. package/dist/tools/chat-inbox.js +19 -4
  88. package/dist/tools/chat.js +106 -17
  89. package/dist/tools/check-plan.js +68 -12
  90. package/dist/tools/commerce-deploy.js +33 -0
  91. package/dist/tools/common.js +31 -0
  92. package/dist/tools/decision-capture.js +459 -0
  93. package/dist/tools/end-of-game.js +151 -21
  94. package/dist/tools/game-kind.js +92 -0
  95. package/dist/tools/how-lost.js +7 -2
  96. package/dist/tools/index.js +10 -0
  97. package/dist/tools/join-game.js +10 -4
  98. package/dist/tools/live-context.js +6 -0
  99. package/dist/tools/live.js +10 -1
  100. package/dist/tools/map-curves.js +73 -0
  101. package/dist/tools/notifications.js +4 -3
  102. package/dist/tools/opponents.js +2 -0
  103. package/dist/tools/past-games.js +74 -8
  104. package/dist/tools/picks.js +61 -10
  105. package/dist/tools/profile-hook.js +62 -3
  106. package/dist/tools/profile-opponents.js +4 -0
  107. package/dist/tools/push.js +2 -2
  108. package/dist/tools/relations.js +139 -0
  109. package/dist/tools/scout.js +16 -2
  110. package/dist/tools/state.js +232 -0
  111. package/dist/tools/strategy.js +3 -3
  112. package/dist/tools/stress-opponents.js +7 -2
  113. package/dist/tools/surrender-pending.js +10 -1
  114. package/dist/tools/surrender.js +18 -3
  115. package/dist/tools/survival.js +11 -3
  116. package/dist/tools/team-brief.js +2 -2
  117. package/dist/tools/team.js +12 -3
  118. package/dist/tools/turn.js +643 -76
  119. package/dist/tools/where.js +3 -1
  120. package/dist/version.js +1 -1
  121. package/manifest.json +32 -3
  122. package/mint.yaml +37 -4
  123. package/package.json +4 -4
  124. package/server.json +20 -2
  125. package/skills/warapp-mcp/SKILL.md +73 -17
@@ -0,0 +1,113 @@
1
+ // Single-army jabs (#361). At 0% luck under straight rounding one attacking army kills
2
+ // round(1 × the offensive kill rate) defenders: at a 60% rate that is 1 (seen live: 75 → 74, 19 → 18),
3
+ // and the defenders kill it back. A one-for-one trade, the best rate an attack gets under these rules
4
+ // (10 attackers kill only 6). It captures nothing and earns no card piece, so its only use is
5
+ // attrition, and attrition pays only against an opponent I out-earn or out-army.
6
+ //
7
+ // Once every other order is sized (after the #226 margin), the armies still idle on a territory of
8
+ // mine beyond what holds it (`spareBeyondHold`: never a hold's own armies, a conceded border's or my
9
+ // commander's; never a step's saving source, where rule 5's leftover went to stay, or the strike stack
10
+ // but for a siege's break member) jab enemy stacks beside it, one army each, at most one jab per enemy stack, filler orders:
11
+ // 1. the siege target's breakable bonus members (#382), its cheapest break first: each jab is one
12
+ // defender fewer for next turn's break;
13
+ // 2. a member of a bonus an opponent holds in full in view (wearing down a bonus edge);
14
+ // 3. any other stack of an opponent I out-earn or out-army.
15
+ // On under `goal: 'siege'`, opt-in otherwise (`PlanOptions.jabs`), until measured further (#361).
16
+ // Never a territory another order of this plan attacks, a truce's or the held siege's (`noTarget`), a
17
+ // #240 repulsed one, a
18
+ // territory with a special unit, or a stack of fewer than 2 (a lone defender and the jab destroy
19
+ // each other and the territory keeps one: nothing traded).
20
+ import { straightKills } from '../combat.js';
21
+ import { neighborsOf } from '../graph.js';
22
+ import { breakableBonuses } from './siege.js';
23
+ /** Whether jabs trade one for one in this game: 0% luck, straight rounding, a lone army kills one. */
24
+ export function jabsTrade(pc) {
25
+ return pc.luck === 0 && !pc.weightedRounding && straightKills(1, pc.rates.offensiveKillRate) >= 1;
26
+ }
27
+ /**
28
+ * Plans the jabs and adds them to `ps.moves` (1 army, `winChance` 0), spending `spare` (the armies a
29
+ * source has beyond its hold; read once per source, then counted down here). `skip`: sources kept
30
+ * whole (the strike stack, a step's saving source); `strike`, the strike stack, jabs only the siege
31
+ * target's break members (a siege's stack grows or breaks, #382). `refused`: targets no jab goes to (#240's repulsed
32
+ * ones, attacked only at their sure size).
33
+ */
34
+ export function planJabs(pc, ps, spare, skip, refused = () => false, strike) {
35
+ const { g, territories: state, label, mineSet, foe, noSplit, unitsAt, defenceAt } = pc;
36
+ const { moves, avail, captured, rationale } = ps;
37
+ if (noSplit || !jabsTrade(pc))
38
+ return [];
39
+ const kills = straightKills(1, pc.rates.offensiveKillRate);
40
+ // Who the trade favours: an opponent I out-earn, or whose armies in view are fewer than mine.
41
+ const armiesOf = new Map();
42
+ let myArmies = 0;
43
+ for (const st of state.values()) {
44
+ if (st.owner.kind !== 'player' || st.armies === null)
45
+ continue;
46
+ if (mineSet.has(st.territoryId))
47
+ myArmies += st.armies;
48
+ else
49
+ armiesOf.set(st.owner.playerId, (armiesOf.get(st.owner.playerId) ?? 0) + st.armies);
50
+ }
51
+ const favours = (p) => pc.income > pc.incomeOfPlayer(p) || myArmies > (armiesOf.get(p) ?? 0);
52
+ const siegeRank = new Map();
53
+ if (pc.siege)
54
+ pc.siege.breaks.forEach((b, i) => {
55
+ for (const t of pc.bonusTs.get(b.bonusId) ?? [])
56
+ if (!siegeRank.has(t))
57
+ siegeRank.set(t, i);
58
+ });
59
+ const edge = new Set(breakableBonuses(g, state, foe, undefined)
60
+ .filter((b) => !b.probable)
61
+ .flatMap((b) => pc.bonusTs.get(b.bonusId) ?? []));
62
+ const attacked = new Set(moves.filter((m) => m.kind === 'attack').map((m) => m.to));
63
+ const left = new Map();
64
+ const spareAt = (x) => {
65
+ if (!left.has(x))
66
+ left.set(x, (skip.has(x) && x !== strike) || ps.leftoverKept.has(x) ? 0 : Math.max(0, spare(x)));
67
+ return left.get(x);
68
+ };
69
+ const cands = [];
70
+ for (const [t, st] of state) {
71
+ if (st.owner.kind !== 'player' || st.armies === null || mineSet.has(t))
72
+ continue;
73
+ const p = st.owner.playerId;
74
+ if (!foe(p) || attacked.has(t) || captured.has(t) || refused(t) || pc.truce.noTarget(t) || unitsAt(t) > 0)
75
+ continue;
76
+ const d = defenceAt(t);
77
+ if (d < 2 || !neighborsOf(g, t).some((n) => mineSet.has(n)))
78
+ continue;
79
+ const why = siegeRank.has(t) && pc.siege?.target === p ? 'siege-break' : edge.has(t) ? 'bonus-edge' : 'attrition';
80
+ if (why !== 'siege-break' && !favours(p))
81
+ continue;
82
+ // Before its trigger a siege attacks nothing of its target but the break members (noTarget says so).
83
+ cands.push({ t, player: p, d, why, rank: why === 'siege-break' ? siegeRank.get(t) : why === 'bonus-edge' ? 1000 : 2000 });
84
+ }
85
+ cands.sort((a, b) => a.rank - b.rank || a.d - b.d || a.t - b.t);
86
+ const jabs = [];
87
+ for (const c of cands) {
88
+ const from = neighborsOf(g, c.t)
89
+ .filter((x) => mineSet.has(x) && (x !== strike || (c.why === 'siege-break' && skip.has(x))) && spareAt(x) >= 1)
90
+ .sort((a, b) => spareAt(b) - spareAt(a) || a - b)[0];
91
+ if (from === undefined)
92
+ continue;
93
+ left.set(from, spareAt(from) - 1);
94
+ avail.set(from, avail.get(from) - 1);
95
+ const what = c.why === 'siege-break'
96
+ ? `one defender fewer on player ${c.player}'s bonus member for the siege's break (#382)`
97
+ : c.why === 'bonus-edge'
98
+ ? `wearing down an edge of a bonus player ${c.player} holds`
99
+ : `attrition against player ${c.player}, whom I out-earn or out-army`;
100
+ moves.push({
101
+ from,
102
+ to: c.t,
103
+ armies: 1,
104
+ kind: 'attack',
105
+ reason: `jab (#361): 1 army kills ${kills} of the ${c.d} at 0% luck and straight rounding, a one-for-one trade — ${what}; it takes nothing`,
106
+ winChance: 0,
107
+ });
108
+ jabs.push({ from, to: c.t, player: c.player, defenders: c.d, kills, loses: 1, why: c.why });
109
+ }
110
+ if (jabs.length)
111
+ rationale.push(`Jab (#361): ${jabs.map((j) => `1 from ${label(j.from)} into ${label(j.to)} (${j.defenders})`).join(', ')} — each lone army kills ${kills} and dies (0% luck, straight rounding), from armies beyond what holds their source: attrition, never a capture.`);
112
+ return jabs;
113
+ }
@@ -4,22 +4,32 @@
4
4
  // each member of a bonus this turn's captures complete that falls to the enemy beside it (#265), to
5
5
  // the borders that fall without the armies withdrawn into them unless I am known to move first
6
6
  // (#215), to the borders short of their hold before the strike stack, then to the strike
7
- // stack, the short borders' comfortable margins (#218: the rest on the step's source when it
7
+ // stack, the territory with the most income at stake as a deterrent guard (#440), the short borders'
8
+ // comfortable margins (#218: the rest on the step's source when it
8
9
  // defends as well; #268: else spread over the borders facing one opponent for equal headroom
9
10
  // over its deploy), the step it saves toward, the expansion stack (#218: with no front in view,
10
- // the territory central to what I hold instead when the stack lies far from it), the most fogged
11
+ // the territory central to what I hold instead when the stack lies far from it; #288: with the
12
+ // attacks out of it when it has nothing left to attack once they land: first what each next step
13
+ // from their targets needs, then the rest offered to another capture, rule 5b's), the most fogged
11
14
  // border or the biggest stack — split against a Bomb when it concentrates for
12
15
  // nothing — and under Local Deployment each pool's rest inside its bonus. planPass runs it where
13
16
  // it ran before: after rule 1c's second reconsideration and the strike stack's choice, before the
14
17
  // strike stack is spent.
15
18
  import { bonusTerritories } from '../bonuses.js';
19
+ import { straightKills } from '../combat.js';
16
20
  import { bfsDistances, neighborsOf } from '../graph.js';
17
21
  import { chargeDeploys } from '../local-deploy.js';
22
+ import { plainEconomy, plainEligible } from './after-leftover.js';
18
23
  import { completedMembers } from './completed.js';
19
24
  import { COMFORT_MARGIN } from './shared.js';
20
25
  /** #218 (comment): hops the expansion stack may lie farther from my farthest border than the centre before the leftover stays central. */
21
26
  export const CENTRE_SLACK = 1;
27
+ /** #440: the least protected value of the territory a deterrent guard goes to. */
28
+ export const DETERRENT_MIN_VALUE = 5;
29
+ /** #440: how many times the most any border being topped up protects that territory must protect. */
30
+ export const DETERRENT_VALUE_RATIO = 2;
22
31
  import { knownFirst, lateArrivals, lateNet } from './holds.js';
32
+ import { stackFacing } from './strike.js';
23
33
  /**
24
34
  * The leftover deploy (rule 5). `stack` is the strike stack rule 0p.3c chose (plan/strike.ts),
25
35
  * `open` and `stays` planPass's views of a border; it returns the strike stack with the leftover
@@ -39,6 +49,11 @@ export function leftoverDeploy(pc, ps, book, threats, hd, tgt, saveStep, stack,
39
49
  let strikeStack;
40
50
  /** Armies a Local Deployment pool put on each border this turn (#103): never moved out. */
41
51
  const poolDeployed = new Map();
52
+ /**
53
+ * #288: the rest of the leftover offered to another capture this turn (its territory), and how to send
54
+ * it with the attacks after all when rule 5b takes nothing from there (planPass calls `revert`).
55
+ */
56
+ let offered;
42
57
  /**
43
58
  * #125: the capture to save toward — rule 4e's top step it could not afford, else (rule 4f
44
59
  * committing) the closest bonus's cheapest missing member in reach when this turn made no capture
@@ -224,6 +239,7 @@ export function leftoverDeploy(pc, ps, book, threats, hd, tgt, saveStep, stack,
224
239
  };
225
240
  const revivable = threatened
226
241
  .filter((t) => conceded.has(t.id) &&
242
+ revivableHere(t.id) &&
227
243
  !stood.has(t.id) &&
228
244
  !moves.some((m) => m.from === t.id && m.reason !== 'withdraws from a conceded border'))
229
245
  .map((t) => {
@@ -431,7 +447,22 @@ export function leftoverDeploy(pc, ps, book, threats, hd, tgt, saveStep, stack,
431
447
  // stack, a border short of its margin), and then before the worse-order holds; otherwise the
432
448
  // worse-order holds go first, as before.
433
449
  // #240 review: judged as the plain plan judged it, so a repulsed attack's sure size revives nothing.
434
- const reviving = !stack && ps.budget > 0 && shortOf(comfortPool, new Map(), true).length > 0;
450
+ // #420: an opponent's most valuable border keeps its full deploy. When it was conceded while the borders
451
+ // its top-up sizes read comfortable (a 0 top-up leaves a guard-only stack no threat), no border is short
452
+ // and the revival would not run, so the leftover went to a stack nothing threatens: the full-deploy border
453
+ // is revived then too (alone), as it was when its other borders were sized for the full deploy.
454
+ const fullConceded = (() => {
455
+ const { primary, capAt } = threats.oneBorder();
456
+ const out = new Set();
457
+ for (const [player, t] of primary)
458
+ if (conceded.has(t) && [...capAt.values()].some((m) => m.has(player)))
459
+ out.add(t);
460
+ return out;
461
+ })();
462
+ const shortNow = shortOf(comfortPool, new Map(), true).length > 0;
463
+ const reviving = !stack && ps.budget > 0 && (shortNow || fullConceded.size > 0);
464
+ /** The conceded borders the revival may hold: every one when a border is short, else the #420 full-deploy ones. */
465
+ const revivableHere = (id) => shortNow || fullConceded.has(id);
435
466
  if (!reviving) {
436
467
  holdCompletedMembers();
437
468
  worseOrderHolds();
@@ -451,6 +482,68 @@ export function leftoverDeploy(pc, ps, book, threats, hd, tgt, saveStep, stack,
451
482
  };
452
483
  const fogged = [...mine].filter((x) => open(x) && notSoftening(x)).sort((a, b) => foggedNext(b) - foggedNext(a) || a - b).find((id) => foggedNext(id) > 0);
453
484
  const saving = stepSource(open, notSoftening);
485
+ /**
486
+ * #303: my income flat (#312's rule) and the step saved toward is in a positive bonus whose every
487
+ * member not mine is a visible neutral or held by an opponent earning less than I do: no comfort
488
+ * margin above the exact holds goes ahead of that completion — the leftover saves toward it.
489
+ */
490
+ const flatSave = (() => {
491
+ const tr = pc.incomeTrend;
492
+ if (!tr?.flat || !saving)
493
+ return null;
494
+ const value = g.map.bonuses.find((b) => b.id === saving.bonusId)?.value ?? 0;
495
+ if (value <= 0)
496
+ return null;
497
+ const every = tr.turns[tr.turns.length - 1].income;
498
+ const missing = bonusTerritories(g, saving.bonusId).filter((x) => !mineSet.has(x));
499
+ const weak = (x) => {
500
+ const o = state.get(x)?.owner;
501
+ if (o?.kind === 'neutral')
502
+ return true;
503
+ return o?.kind === 'player' && pc.foe(o.playerId) && pc.incomeOfPlayer(o.playerId) < every;
504
+ };
505
+ if (!missing.length || !missing.every(weak))
506
+ return null;
507
+ const first = tr.turns[0];
508
+ return `my income is flat (${tr.turns.map((t) => t.income).join(', ')} over turns ${first.turn}–${tr.turns[tr.turns.length - 1].turn}, slope ${tr.slope}/turn), so no comfort margin above the exact holds goes ahead of completing bonus ${bonusName(saving.bonusId)} (+${value}) from ${missing.some((x) => state.get(x)?.owner.kind === 'player') ? 'neutrals and weaker opponents' : 'neutrals'} (#303)`;
509
+ })();
510
+ /** #218 (comment): the expansion stack's attacks land for sure without the leftover (under luck it raises their odds). */
511
+ const expansionSure = () => moves.every((m) => m.from !== expansion || m.kind !== 'attack' || (m.winChance ?? 1) >= 1);
512
+ /**
513
+ * #424: with no foe in view because a Diplomacy card in force makes the only one beside me no foe
514
+ * this turn, its border is still the front the card's end reopens: the leftover goes there rather
515
+ * than central or onto the expansion stack (live, it went to an ocean tile while the partner's
516
+ * stacks stood beside me). An open border of mine issuing no order beside a visible stack of an
517
+ * enforced partner, most at stake first, then the biggest partner stack beside it, then id. Only
518
+ * once the expansion stack's attacks land for sure without it, as the centre's rule.
519
+ */
520
+ const partnerFront = () => {
521
+ if (!noFront || !pc.truce.enforced.size || (expansion !== undefined && !expansionSure()))
522
+ return undefined;
523
+ const facing = (x) => {
524
+ let best;
525
+ for (const n of neighborsOf(g, x)) {
526
+ const st = state.get(n);
527
+ if (captured.has(n) || st?.owner.kind !== 'player' || !pc.truce.enforced.has(st.owner.playerId))
528
+ continue;
529
+ const armies = st.armies ?? 0;
530
+ if (!best || armies > best.armies || (armies === best.armies && st.owner.playerId < best.player))
531
+ best = { player: st.owner.playerId, armies };
532
+ }
533
+ return best;
534
+ };
535
+ const pick = [...mine]
536
+ .filter((x) => open(x) && !orderOf(x) && roomAt(x) > 0)
537
+ .flatMap((x) => {
538
+ const f = facing(x);
539
+ return f ? [{ id: x, ...f }] : [];
540
+ })
541
+ .sort((a, b) => valueOf(b.id) - valueOf(a.id) || b.armies - a.armies || a.id - b.id)[0];
542
+ if (!pick)
543
+ return undefined;
544
+ const until = pc.truce.given.find((r) => r.player === pick.player && r.enforced)?.enforcedUntil;
545
+ return { id: pick.id, player: pick.player, ...(until !== undefined ? { until } : {}) };
546
+ };
454
547
  const biggest = (ids) => [...ids].sort((a, b) => armiesOf(b) + (deployed.get(b) ?? 0) - (armiesOf(a) + (deployed.get(a) ?? 0)) || a - b)[0];
455
548
  const takenBack = reviving ? holdAfterAll() : undefined;
456
549
  if (reviving) {
@@ -565,6 +658,120 @@ export function leftoverDeploy(pc, ps, book, threats, hd, tgt, saveStep, stack,
565
658
  }
566
659
  return got;
567
660
  };
661
+ /**
662
+ * #290 (owner decision 2026-11-19): before the even spread, a border whose enemy stack beside it grew
663
+ * this turn (as the two boards show it) is topped up to hold against that stack plus its owner's whole
664
+ * observed deploy — the estimate, the observed figure before its cap, this turn's high reading (growth
665
+ * beside the fog read as deploy), or the reading #123's bound cut on the track (`newestCut`): a jump
666
+ * kept as a lower bound counts in full — highest protected value first, as far as the leftover goes.
667
+ * The spread itself is unchanged.
668
+ */
669
+ const fundGrown = () => {
670
+ const whole = (b) => {
671
+ const e = pc.estimates.get(b.player);
672
+ return Math.max(b.deploy, grewBy(b), e?.observedRaw ?? 0, e?.observation?.high ?? 0, e?.newestCut?.reading ?? 0);
673
+ };
674
+ /** The most any stack of the border's opponent beside it grew since the previous board, as the boards show it. */
675
+ const grewBy = (b) => Math.max(0, ...neighborsOf(g, b.id).map((n) => {
676
+ const st = state.get(n);
677
+ const was = threats.previousBoard?.territories.find((t) => t.territoryId === n);
678
+ const same = (t) => t?.owner.kind === 'player' && t.owner.playerId === b.player && typeof t.armies === 'number';
679
+ return same(st) && same(was) ? st.armies - was.armies : 0;
680
+ }));
681
+ const grown = [...borders.values()]
682
+ .filter((b) => grewBy(b) > 0 && open(b.id) && !orderOf(b.id) && !moves.some((m) => m.from === b.id && m.kind === 'attack'))
683
+ .sort((a, b) => valueOf(b.id) - valueOf(a.id) || a.id - b.id);
684
+ for (const b of grown) {
685
+ const bar = b.movable + whole(b);
686
+ let d = 0;
687
+ const room = roomAt(b.id);
688
+ while (d < room && d < ps.budget) {
689
+ const take = toTake(stays(b.id) + d + unitsAt(b.id));
690
+ if (take === null || take > bar)
691
+ break;
692
+ d++;
693
+ }
694
+ if (d <= 0)
695
+ continue;
696
+ deploy(b.id, d);
697
+ locked.add(b.id);
698
+ keepFromMargin(b.id);
699
+ rationale.push(`Deploy ${d} of the leftover to ${label(b.id)} before the spread (#290): player ${b.player}'s stack beside it grew this turn (+${grewBy(b)}), so it is topped up toward its ${b.movable} movable armies plus its whole observed deploy (~${whole(b)}) (protects +${valueOf(b.id)}).`);
700
+ }
701
+ };
702
+ /**
703
+ * #440: before the leftover tops up a border that already holds, or one a recorded truce covers (T2),
704
+ * the territory with the most income at stake that carries a single-territory bonus of at least
705
+ * DETERRENT_MIN_VALUE gets a deterrent guard. Live (a large FFA), the +8
706
+ * territory that was the hub of nine pair bonuses ended on 3 while 15 armies topped up two low-value
707
+ * borders. That territory (open, issuing no order, not itself a border being topped up) must protect
708
+ * at least DETERRENT_MIN_VALUE and DETERRENT_VALUE_RATIO × the most any border being topped up
709
+ * protects, with an opponent within two steps; it gets armies until taking it needs more than
710
+ * COMFORT_MARGIN × a casual attack (the largest deploy estimate of those opponents, or its own
711
+ * threat when it is a border). The borders that would fall keep what makes them hold (a truce-covered
712
+ * one excepted: the truce covers it). Its armies then stay (`locked`: rule 6 moves none out), and so do
713
+ * they when it already needs more than that to take and gets no deploy.
714
+ */
715
+ const deterrentGuard = (bs) => {
716
+ const relaxed = (id) => ps.truce?.relaxed.has(id) ?? false;
717
+ const holdNeed = (b) => {
718
+ let d = 0;
719
+ while (d < ps.budget) {
720
+ const take = toTake(stays(b.id) + d + unitsAt(b.id));
721
+ if (take === null || take > b.threat)
722
+ break;
723
+ d++;
724
+ }
725
+ return d;
726
+ };
727
+ const reserve = bs.filter((b) => !relaxed(b.id)).reduce((sum, b) => sum + holdNeed(b), 0);
728
+ // A territory that carries a large single-territory bonus of its own (a city, a capital), not
729
+ // any member of a held bonus: the issue's case, and the golden corpus's churn stays small.
730
+ const carries = (x) => [...g.bonusById.values()].some((b) => b.value >= DETERRENT_MIN_VALUE && bonusTerritories(g, b.id).length === 1 && bonusTerritories(g, b.id)[0] === x);
731
+ const hub = [...mine]
732
+ .filter((x) => open(x) && !orderOf(x) && carries(x))
733
+ .sort((a, b) => valueOf(b) - valueOf(a) || a - b)[0];
734
+ if (hub === undefined || bs.some((b) => b.id === hub))
735
+ return;
736
+ const value = valueOf(hub);
737
+ const top = Math.max(0, ...bs.map((b) => valueOf(b.id)));
738
+ if (value < DETERRENT_MIN_VALUE || value < DETERRENT_VALUE_RATIO * top)
739
+ return;
740
+ const near = new Set([hub, ...neighborsOf(g, hub)].flatMap((x) => [x, ...neighborsOf(g, x)]));
741
+ const foes = [...new Set([...near].flatMap((x) => {
742
+ const st = state.get(x);
743
+ return !captured.has(x) && st?.owner.kind === 'player' && pc.foe(st.owner.playerId) ? [st.owner.playerId] : [];
744
+ }))].sort((a, b) => a - b);
745
+ if (!foes.length)
746
+ return;
747
+ const casual = Math.max(...foes.map((p) => pc.deployOf(p)), borders.get(hub)?.threat ?? 0);
748
+ const bar = COMFORT_MARGIN * casual;
749
+ const most = Math.min(roomAt(hub), ps.budget - reserve);
750
+ let d = 0;
751
+ while (d < most) {
752
+ const take = toTake(stays(hub) + d + unitsAt(hub));
753
+ if (take === null || take > bar)
754
+ break;
755
+ d++;
756
+ }
757
+ const against = `${COMFORT_MARGIN} × the ~${casual} ${borders.has(hub) && casual === borders.get(hub).threat ? 'threat beside it' : `deploy of player ${foes.length === 1 ? foes[0] : foes.join(' or ')} within two steps`}`;
758
+ if (d <= 0) {
759
+ // Already at its bar: it needs no deploy, but its armies still stay (rule 6 would otherwise
760
+ // walk them to the front and leave a stronger capital weaker than a topped-up one).
761
+ const at = stays(hub) + unitsAt(hub);
762
+ const take = toTake(at);
763
+ if (take !== null && take <= bar)
764
+ return;
765
+ locked.add(hub);
766
+ rationale.push(`${label(hub)} keeps its ${at} armies as a deterrent guard (#440): it has the most income at stake (protects +${value}, the borders being topped up at most +${top}), and they ${take === null ? 'cannot be taken' : `need ${take} to take`}, more than ${against}, so none move to the front.`);
767
+ return;
768
+ }
769
+ deploy(hub, d);
770
+ locked.add(hub);
771
+ keepFromMargin(hub);
772
+ const at = stays(hub) + unitsAt(hub);
773
+ rationale.push(`Deploy ${d} of the leftover to ${label(hub)} as a deterrent guard (#440): it has the most income at stake (protects +${value}, the borders being topped up at most +${top}), and its ${at} armies now need ${toTake(at)} to take, more than ${against}, before any border that already holds is topped up.`);
774
+ };
568
775
  /** #268: the rest spread by {@link headroomSpread}, already deployed: nothing is left for `where`. */
569
776
  let spreadRest;
570
777
  let where;
@@ -574,16 +781,110 @@ export function leftoverDeploy(pc, ps, book, threats, hd, tgt, saveStep, stack,
574
781
  let concentrating = false;
575
782
  /** #218 (comment): the leftover stays central: rule 6 keeps it there, not the armies already there. */
576
783
  let central = false;
784
+ /** #424: the Diplomacy partner's border the leftover keeps as the front. */
785
+ let peace;
577
786
  /** #226 review: the leftover defends `where` or saves there: the #226 margin leaves it. */
578
787
  let defends = false;
788
+ /** #288: the attacks out of the expansion stack the leftover goes with (it has nothing else left to attack). */
789
+ let joins;
790
+ /** Territories beside `t` that are neither mine nor captured this turn: what is left to attack from it. */
791
+ const leftToAttack = (t) => neighborsOf(g, t).filter((n) => !mineSet.has(n) && !captured.has(n));
792
+ /**
793
+ * #288: a source facing no threat whose every neighbour is mine or captured this turn has nothing
794
+ * left to attack once the captures land, so a leftover there idles: it goes with its attacks whose
795
+ * 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.
797
+ */
798
+ const joinsOf = (src) => {
799
+ if (noSplit || borders.has(src) || pc.myCommanders.has(src) || leftToAttack(src).length)
800
+ return undefined;
801
+ const onward = (t) => leftToAttack(t).filter((n) => n !== src).length;
802
+ 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)
804
+ .sort((a, b) => onward(b.to) - onward(a.to) || a.to - b.to);
805
+ return out.length ? out : undefined;
806
+ };
807
+ /**
808
+ * #288 (second half): the next step from the target of `m`, an attack out of `src` the leftover may
809
+ * join: the cheapest visible neutral beside it that is neither mine nor captured this turn, and the
810
+ * armies its capture next turn needs beyond those that land movable (0 with no such neutral).
811
+ */
812
+ const nextStep = (m, src) => {
813
+ const lands = ps.survivorsAt.get(m.to) ?? m.armies - straightKills(pc.defenceAt(m.to), pc.rates.defensiveKillRate);
814
+ const movable = Math.max(0, lands - pc.guard);
815
+ const best = leftToAttack(m.to)
816
+ .filter((x) => x !== src && state.get(x)?.owner.kind === 'neutral' && typeof state.get(x)?.armies === 'number')
817
+ .map((x) => ({ x, c: pc.costAt(x) }))
818
+ .filter((o) => o.c !== null)
819
+ .sort((a, b) => a.c - b.c || a.x - b.x)[0];
820
+ return best ? { m, need: Math.max(0, best.c - movable), step: best.x, cost: best.c, movable } : { m, need: 0, movable };
821
+ };
822
+ /**
823
+ * #288: another capture this turn the rest of the leftover (`left`) can pay for, rule 5b's way: a
824
+ * neutral not captured that passes pass 3's eligibility and economy tests, beside an open territory
825
+ * of mine other than `src` that issues no order, holds no commander of mine and attacks no player,
826
+ * whose armies fall short of its cost by no more than `left` (fewest short first, then cost, id).
827
+ * Not under Local Deployment (the pools decide where the rest may land). Rule 5b judges the hold.
828
+ */
829
+ const otherCapture = (left, src) => {
830
+ // As rule 5b: never under `complete-bonus` (No-Split never gets here: no join).
831
+ if (local || pc.goal === 'complete-bonus')
832
+ return undefined;
833
+ const c = [...targets.values()]
834
+ .filter((tg) => state.get(tg.id)?.owner.kind === 'neutral' && !captured.has(tg.id) && !repulsed.has(tg.id) && !pc.truce.noTarget(tg.id))
835
+ .filter((tg) => {
836
+ const gain = book.gainWith([tg.id]);
837
+ return gain >= 0 && plainEligible(pc, tgt, tg.id, false) && !plainEconomy(pc, tgt, tg.id, gain);
838
+ })
839
+ .flatMap((tg) => tg.sources
840
+ .filter((x) => x !== src &&
841
+ mineSet.has(x) &&
842
+ open(x) &&
843
+ !conceded.has(x) &&
844
+ !pc.myCommanders.has(x) &&
845
+ !orderOf(x) &&
846
+ !moves.some((m) => m.from === x && m.kind === 'attack' && state.get(m.to)?.owner.kind === 'player'))
847
+ .map((x) => ({ t: tg.id, at: x, cost: tg.cost, short: tg.cost - avail.get(x) })))
848
+ .filter((o) => o.short > 0 && o.short <= left)
849
+ .sort((a, b) => a.short - b.short || a.cost - b.cost || a.t - b.t || a.at - b.at)[0];
850
+ return c ? { ...c, n: left } : undefined;
851
+ };
852
+ /** Sends `k` more of `src`'s armies with the attack `m`. */
853
+ const applyTo = (src, m, k) => {
854
+ m.armies += k;
855
+ m.winChance = pc.chanceOf(m.armies, pc.defenceAt(m.to));
856
+ avail.set(src, avail.get(src) - k);
857
+ if (ps.survivorsAt.has(m.to))
858
+ ps.survivorsAt.set(m.to, ps.survivorsAt.get(m.to) + k);
859
+ };
860
+ /** The rationale line of the leftover `k` deployed on `src` and sent with the attacks (`add` more each). */
861
+ const joinLine = (src, k, steps, add) => {
862
+ const parts = steps
863
+ .filter((s) => (add.get(s.m) ?? 0) > 0)
864
+ .map((s) => `the attack on ${label(s.m.to)} (${s.m.armies - add.get(s.m)} → ${s.m.armies})`);
865
+ const needs = steps
866
+ .filter((s) => s.funded)
867
+ .map((s) => `${label(s.step)} beside ${label(s.m.to)} takes ${s.cost}, ${s.need} more than the ${s.movable} that would land movable`);
868
+ return `Deploy the leftover ${k} to ${label(src)} and send it with ${parts.join(' and ')} (#288): once this turn's captures land ${label(src)} has nothing left to attack, so a leftover there would idle, while the armies that land fund the next step from there without a deploy${needs.length ? ` (${needs.join('; ')})` : ''}.`;
869
+ };
579
870
  if (stack) {
580
871
  lock = true;
581
872
  concentrating = true;
582
873
  where = stack.id;
583
- why = `one strike stack on the border facing player ${stack.player}, the strongest opponent (~${stack.income} income, ${stack.source}), not spread`;
874
+ why = `one strike stack on the border facing player ${stack.player}, ${stackFacing(pc, stack)} (~${stack.income} income, ${stack.source}), not spread`;
875
+ }
876
+ else if (short[0] && flatSave && saving && open(saving.from) && roomAt(saving.from) > 0) {
877
+ // (Under Local Deployment the leftover may not land there: then the margins stand.)
878
+ // #303: the holds already have their exact armies; the margin over them waits behind the completion.
879
+ where = saving.from;
880
+ why = `save toward ${label(saving.t)} (${saving.cost} to take), the next step of bonus ${bonusName(saving.bonusId)}, ${cannotAfford(saving)}: ${flatSave}`;
881
+ defends = true;
882
+ lock = true;
883
+ concentrating = true;
584
884
  }
585
885
  else if (short[0]) {
586
886
  defends = true;
887
+ deterrentGuard(short);
587
888
  // #218: the source of the step the leftover would save toward, when it is an open border:
588
889
  // once every short border has its comfortable margin, the rest goes there when it defends
589
890
  // as well as the border the rest would go to, and counts toward the step. A margin itself
@@ -623,6 +924,7 @@ export function leftoverDeploy(pc, ps, book, threats, hd, tgt, saveStep, stack,
623
924
  }
624
925
  else {
625
926
  where = short[0].id;
927
+ fundGrown();
626
928
  spreadRest = headroomSpread(short[0], !spread);
627
929
  why = spread
628
930
  ? `the rest, once every short border has its comfortable margin, to the one with the most at stake (protects +${valueOf(where)})`
@@ -636,6 +938,12 @@ export function leftoverDeploy(pc, ps, book, threats, hd, tgt, saveStep, stack,
636
938
  lock = true;
637
939
  concentrating = true;
638
940
  }
941
+ else if ((peace = partnerFront()) !== undefined) {
942
+ where = peace.id;
943
+ why = `the border facing player ${peace.player}, at peace by a Diplomacy card in force${peace.until !== undefined ? ` until turn ${peace.until}` : ''} — no other enemy is in view, and its border is the front again once the card ends (#424)`;
944
+ defends = true;
945
+ lock = true;
946
+ }
639
947
  else if (expansion !== undefined && open(expansion)) {
640
948
  // #218 (comment): with no enemy in view there is no front to go to, and a leftover riding
641
949
  // the top expansion walks deeper into one region every turn (live: 14 hops from the nearest
@@ -643,8 +951,7 @@ export function leftoverDeploy(pc, ps, book, threats, hd, tgt, saveStep, stack,
643
951
  // from my farthest border than the territory central to what I hold, and its attacks land
644
952
  // for sure without the leftover, the leftover stays there.
645
953
  // Only once its attacks land for sure: under luck the leftover there raises their odds.
646
- const sure = moves.every((m) => m.from !== expansion || m.kind !== 'attack' || (m.winChance ?? 1) >= 1);
647
- const c = noFront && sure ? centre() : undefined;
954
+ const c = noFront && expansionSure() ? centre() : undefined;
648
955
  if (c && c.id !== expansion && (c.ecc.get(expansion) ?? Infinity) > c.ecc.get(c.id) + CENTRE_SLACK) {
649
956
  where = c.id;
650
957
  why = `no enemy is in view, so there is no front to go to: it stays central to what I hold (at most ${c.ecc.get(c.id)} hops from each of my borders, where the stack working on the top expansion, ${label(expansion)}, is ${c.ecc.get(expansion)} from its farthest), ready for wherever a front opens`;
@@ -655,6 +962,7 @@ export function leftoverDeploy(pc, ps, book, threats, hd, tgt, saveStep, stack,
655
962
  why = 'the stack working on the top expansion';
656
963
  lock = true;
657
964
  concentrating = true;
965
+ joins = joinsOf(expansion);
658
966
  }
659
967
  }
660
968
  else if (fogged !== undefined) {
@@ -698,7 +1006,84 @@ export function leftoverDeploy(pc, ps, book, threats, hd, tgt, saveStep, stack,
698
1006
  n = roomAt(where);
699
1007
  }
700
1008
  }
701
- if (n > 0 && !spreadRest) {
1009
+ if (n > 0 && !spreadRest && joins) {
1010
+ // #288 (second half, the rule chosen for the owner): extra armies go with an attack only as far as
1011
+ // the next step from its target needs them; what is left is offered to another capture this turn
1012
+ // (rule 5b takes it, else planPass hands it back here); only the rest still rides the attacks.
1013
+ const js = joins;
1014
+ const src = where;
1015
+ const steps = js.map((m) => nextStep(m, src));
1016
+ const add = new Map();
1017
+ let left = n;
1018
+ // First each need the leftover covers whole, in the joins' order (most steps onward first), one
1019
+ // attack per next step: a share that leaves the step short still costs a deploy next turn.
1020
+ const funded = new Set();
1021
+ for (const s of steps) {
1022
+ if (s.need > 0 && s.need <= left && !funded.has(s.step)) {
1023
+ add.set(s.m, s.need);
1024
+ left -= s.need;
1025
+ funded.add(s.step);
1026
+ s.funded = true;
1027
+ }
1028
+ }
1029
+ const offer = left > 0 ? otherCapture(left, src) : undefined;
1030
+ if (offer)
1031
+ left -= offer.n;
1032
+ // The rest rides the attacks as before (#288's first half), an army at a time to the one with the
1033
+ // least extra so far (the first among equals): the even split #402 made whenever no need exceeds
1034
+ // its share, so a landing that also faces an enemy next turn keeps what it had.
1035
+ const spread = (k, out) => {
1036
+ for (let a = 0; a < k; a++) {
1037
+ const m = js.reduce((best, x) => ((out.get(x) ?? 0) < (out.get(best) ?? 0) ? x : best));
1038
+ out.set(m, (out.get(m) ?? 0) + 1);
1039
+ }
1040
+ };
1041
+ spread(left, add);
1042
+ const sent = n - (offer?.n ?? 0);
1043
+ let firstLine;
1044
+ if (sent > 0) {
1045
+ deploy(src, sent);
1046
+ for (const [m, k] of add)
1047
+ applyTo(src, m, k);
1048
+ firstLine = joinLine(src, sent, steps, add);
1049
+ rationale.push(firstLine);
1050
+ locked.add(src);
1051
+ }
1052
+ if (offer) {
1053
+ deploy(offer.at, offer.n);
1054
+ const offerLine = `Deploy ${offer.n} of the leftover to ${label(offer.at)} for another capture this turn (#288): the attacks out of ${label(src)} already carry what the next steps from their targets need, so the rest is offered to a capture (${label(offer.t)}, ${offer.cost} to take) before it rides them.`;
1055
+ rationale.push(offerLine);
1056
+ offered = {
1057
+ at: offer.at,
1058
+ revert: () => {
1059
+ // No capture took it (rule 5b refused it): it rides the attacks out of the stack after all,
1060
+ // unless an order since sent some of it.
1061
+ if (avail.get(offer.at) < offer.n)
1062
+ return;
1063
+ undeploy(offer.at, offer.n);
1064
+ const i = rationale.indexOf(offerLine);
1065
+ if (i >= 0)
1066
+ rationale.splice(i, 1);
1067
+ const total = new Map(add);
1068
+ spread(offer.n, total);
1069
+ deploy(src, offer.n);
1070
+ for (const m of js) {
1071
+ const k = (total.get(m) ?? 0) - (add.get(m) ?? 0);
1072
+ if (k > 0)
1073
+ applyTo(src, m, k);
1074
+ }
1075
+ const again = joinLine(src, n, steps, total);
1076
+ const was = firstLine === undefined ? -1 : rationale.indexOf(firstLine);
1077
+ if (was >= 0)
1078
+ rationale[was] = again;
1079
+ else
1080
+ rationale.push(again);
1081
+ locked.add(src);
1082
+ },
1083
+ };
1084
+ }
1085
+ }
1086
+ else if (n > 0 && !spreadRest) {
702
1087
  rationale.push(`Deploy the leftover ${n} to ${label(where)}: ${why}.`);
703
1088
  deploy(where, n);
704
1089
  // Keep a strike or expansion stack there: the transfer step must not walk it back as "idle
@@ -756,5 +1141,5 @@ export function leftoverDeploy(pc, ps, book, threats, hd, tgt, saveStep, stack,
756
1141
  deploy(where, ps.budget);
757
1142
  }
758
1143
  }
759
- return { strikeStack, poolDeployed, staging };
1144
+ return { strikeStack, poolDeployed, staging, offered };
760
1145
  }