@chrischall/warapp-mcp 0.6.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 (90) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +99 -6
  4. package/dist/analysis/accept-surrender.js +20 -2
  5. package/dist/analysis/calibrate.js +1 -0
  6. package/dist/analysis/card-support.js +175 -16
  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/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 +12 -6
  16. package/dist/analysis/opponent-profile.js +46 -3
  17. package/dist/analysis/opponents.js +245 -19
  18. package/dist/analysis/outlook.js +323 -17
  19. package/dist/analysis/plan/after-leftover.js +4 -1
  20. package/dist/analysis/plan/captures.js +4 -3
  21. package/dist/analysis/plan/estimates.js +70 -6
  22. package/dist/analysis/plan/guard-off.js +2 -1
  23. package/dist/analysis/plan/holds.js +79 -6
  24. package/dist/analysis/plan/leftover.js +145 -5
  25. package/dist/analysis/plan/relations.js +115 -2
  26. package/dist/analysis/plan/shared.js +201 -11
  27. package/dist/analysis/plan/stand-still.js +2 -2
  28. package/dist/analysis/plan/stockpile.js +104 -0
  29. package/dist/analysis/plan/strike.js +34 -7
  30. package/dist/analysis/plan/targets.js +168 -53
  31. package/dist/analysis/plan/threats.js +108 -5
  32. package/dist/analysis/plan/transfers.js +11 -0
  33. package/dist/analysis/plan/two-move.js +70 -0
  34. package/dist/analysis/plan/vacated.js +124 -2
  35. package/dist/analysis/planner.js +302 -42
  36. package/dist/analysis/since-last.js +18 -5
  37. package/dist/board.js +36 -2
  38. package/dist/build-id.js +106 -0
  39. package/dist/bundle.js +14943 -10146
  40. package/dist/chat-automation.js +22 -0
  41. package/dist/client.js +14 -0
  42. package/dist/decision-log.js +1093 -0
  43. package/dist/finished-store.js +5 -1
  44. package/dist/lessons-store.js +322 -21
  45. package/dist/open-games.js +36 -16
  46. package/dist/outlook-log.js +42 -1
  47. package/dist/protocol/methods.js +4 -2
  48. package/dist/review-export.js +198 -0
  49. package/dist/state-bundle.js +62 -3
  50. package/dist/state-cli.js +5 -3
  51. package/dist/strategy/notes.js +56 -0
  52. package/dist/tools/accept-surrender.js +23 -9
  53. package/dist/tools/award.js +5 -1
  54. package/dist/tools/card-advice.js +77 -23
  55. package/dist/tools/card-support-advice.js +36 -7
  56. package/dist/tools/chat-advice.js +330 -0
  57. package/dist/tools/chat-inbox.js +15 -4
  58. package/dist/tools/chat.js +41 -11
  59. package/dist/tools/check-plan.js +14 -2
  60. package/dist/tools/decision-capture.js +459 -0
  61. package/dist/tools/end-of-game.js +146 -18
  62. package/dist/tools/game-kind.js +92 -0
  63. package/dist/tools/how-lost.js +7 -2
  64. package/dist/tools/index.js +3 -0
  65. package/dist/tools/join-game.js +10 -4
  66. package/dist/tools/live-context.js +6 -0
  67. package/dist/tools/live.js +10 -1
  68. package/dist/tools/map-curves.js +73 -0
  69. package/dist/tools/notifications.js +4 -3
  70. package/dist/tools/opponents.js +2 -0
  71. package/dist/tools/past-games.js +74 -8
  72. package/dist/tools/picks.js +49 -10
  73. package/dist/tools/profile-hook.js +62 -3
  74. package/dist/tools/profile-opponents.js +2 -0
  75. package/dist/tools/push.js +2 -2
  76. package/dist/tools/relations.js +2 -0
  77. package/dist/tools/scout.js +16 -2
  78. package/dist/tools/state.js +6 -1
  79. package/dist/tools/strategy.js +3 -3
  80. package/dist/tools/stress-opponents.js +2 -0
  81. package/dist/tools/surrender-pending.js +10 -1
  82. package/dist/tools/surrender.js +18 -3
  83. package/dist/tools/turn.js +313 -18
  84. package/dist/tools/where.js +3 -1
  85. package/dist/version.js +1 -1
  86. package/manifest.json +23 -2
  87. package/mint.yaml +23 -0
  88. package/package.json +1 -1
  89. package/server.json +20 -2
  90. package/skills/warapp-mcp/SKILL.md +42 -8
@@ -82,7 +82,8 @@ export function fillSecondLine(pc, ps, book) {
82
82
  const owed = e.size - secondLineKept.get(id);
83
83
  if (owed <= 0)
84
84
  continue;
85
- const k = Math.min(owed, Math.max(0, ps.budget - reserve), roomAt(id));
85
+ // #421: the strike share holds back captures only, never the second line's exact need.
86
+ const k = Math.min(owed, Math.max(0, ps.budget - (reserve - pc.strikeShare)), roomAt(id));
86
87
  if (k > 0) {
87
88
  deploy(id, k);
88
89
  // The deployed armies join the garrison: they stay, as the guard would.
@@ -9,11 +9,55 @@ import { bfsDistances, neighborsOf } from '../graph.js';
9
9
  import { chargeDeploys } from '../local-deploy.js';
10
10
  import { twoStepReaches } from '../lookahead.js';
11
11
  import { opensBehind } from '../opens.js';
12
- import { BREACH_WEIGHT, CITE_CLOSE, CITE_OPEN, CITE_SEP, CONCEDE_FACTOR, nearMissMargin, } from './shared.js';
12
+ import { BREACH_WEIGHT, CITE_CLOSE, CITE_OPEN, CITE_SEP, CONCEDE_FACTOR, MIN_ENEMY_DEPLOY, nearMissMargin, } from './shared.js';
13
13
  import { capRoom, relaxedFor } from './relations.js';
14
14
  import { byNum } from './util.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) {
@@ -718,8 +785,9 @@ export function heldBonusUnits(pc, ps, book, threats, hb, prev) {
718
785
  let rest = cost;
719
786
  for (const m of todo) {
720
787
  rest -= m.holdCost;
788
+ // #420: a held bonus's own gate, outside the hold cap.
721
789
  if (!each?.(m, rest))
722
- hold(m);
790
+ hold(m, true);
723
791
  heldBorders.add(m.id);
724
792
  }
725
793
  return true;
@@ -801,7 +869,7 @@ export function floorTier(pc, ps, book, threats, hb, prev) {
801
869
  const near = new Set(missing.flatMap(sourcesOf));
802
870
  return cost <= income + [...near].reduce((n, x) => n + avail.get(x), 0);
803
871
  });
804
- const { uneconomic, acting, concedeUnaffordable, heldStack, hold, heldBorders, commanderHeld, buildUnits, unitBorders, concedeUnit, leftFor, fundUnit, fundNearMiss, } = prev;
872
+ const { uneconomic, acting, concedeUnaffordable, heldStack, hold, heldBorders, commanderHeld, buildUnits, unitBorders, concedeUnit, leftFor, fundUnit, fundNearMiss, overCap, concedeCapped, } = prev;
805
873
  // ---- 1h. floor tier and one shared deploy (#118) ----
806
874
  // One enemy deploy lands on one target. Sizing every border of a held bonus for the whole of
807
875
  // it conceded every bonus once the deploy outgrew them, though the stacks already next to the
@@ -944,6 +1012,8 @@ export function floorTier(pc, ps, book, threats, hb, prev) {
944
1012
  concedeUnaffordable(t, room);
945
1013
  return;
946
1014
  }
1015
+ if (overCap(t))
1016
+ return concedeCapped(t, quiet);
947
1017
  hold(t);
948
1018
  heldBorders.add(t.id);
949
1019
  };
@@ -1306,6 +1376,8 @@ export function floorTier(pc, ps, book, threats, hb, prev) {
1306
1376
  concedeUnaffordable(t, left);
1307
1377
  return;
1308
1378
  }
1379
+ if (acting && overCap(t))
1380
+ return concedeCapped(t, quiet);
1309
1381
  triageBudget -= t.holdCost;
1310
1382
  if (acting) {
1311
1383
  hold(t);
@@ -1639,7 +1711,8 @@ export function reconsiderAndGarrison(pc, ps, book, threats, hb, prev) {
1639
1711
  continue;
1640
1712
  const cost = todo.reduce((n, x) => n + x.d, 0);
1641
1713
  const worth = b.value + have / paybackTurns;
1642
- if (cost > paybackTurns * b.value || cost > CONCEDE_FACTOR * worth || cost > ps.budget - reserve)
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))
1643
1716
  continue;
1644
1717
  // The pools are checked for the members together: each may fit the free pool on its own
1645
1718
  // while together they overdraw it.
@@ -4,7 +4,8 @@
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
11
  // the territory central to what I hold instead when the stack lies far from it; #288: with the
@@ -23,7 +24,12 @@ import { completedMembers } from './completed.js';
23
24
  import { COMFORT_MARGIN } from './shared.js';
24
25
  /** #218 (comment): hops the expansion stack may lie farther from my farthest border than the centre before the leftover stays central. */
25
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;
26
31
  import { knownFirst, lateArrivals, lateNet } from './holds.js';
32
+ import { stackFacing } from './strike.js';
27
33
  /**
28
34
  * The leftover deploy (rule 5). `stack` is the strike stack rule 0p.3c chose (plan/strike.ts),
29
35
  * `open` and `stays` planPass's views of a border; it returns the strike stack with the leftover
@@ -233,6 +239,7 @@ export function leftoverDeploy(pc, ps, book, threats, hd, tgt, saveStep, stack,
233
239
  };
234
240
  const revivable = threatened
235
241
  .filter((t) => conceded.has(t.id) &&
242
+ revivableHere(t.id) &&
236
243
  !stood.has(t.id) &&
237
244
  !moves.some((m) => m.from === t.id && m.reason !== 'withdraws from a conceded border'))
238
245
  .map((t) => {
@@ -440,7 +447,22 @@ export function leftoverDeploy(pc, ps, book, threats, hd, tgt, saveStep, stack,
440
447
  // stack, a border short of its margin), and then before the worse-order holds; otherwise the
441
448
  // worse-order holds go first, as before.
442
449
  // #240 review: judged as the plain plan judged it, so a repulsed attack's sure size revives nothing.
443
- 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);
444
466
  if (!reviving) {
445
467
  holdCompletedMembers();
446
468
  worseOrderHolds();
@@ -485,6 +507,43 @@ export function leftoverDeploy(pc, ps, book, threats, hd, tgt, saveStep, stack,
485
507
  const first = tr.turns[0];
486
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)`;
487
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
+ };
488
547
  const biggest = (ids) => [...ids].sort((a, b) => armiesOf(b) + (deployed.get(b) ?? 0) - (armiesOf(a) + (deployed.get(a) ?? 0)) || a - b)[0];
489
548
  const takenBack = reviving ? holdAfterAll() : undefined;
490
549
  if (reviving) {
@@ -640,6 +699,79 @@ export function leftoverDeploy(pc, ps, book, threats, hd, tgt, saveStep, stack,
640
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)}).`);
641
700
  }
642
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
+ };
643
775
  /** #268: the rest spread by {@link headroomSpread}, already deployed: nothing is left for `where`. */
644
776
  let spreadRest;
645
777
  let where;
@@ -649,6 +781,8 @@ export function leftoverDeploy(pc, ps, book, threats, hd, tgt, saveStep, stack,
649
781
  let concentrating = false;
650
782
  /** #218 (comment): the leftover stays central: rule 6 keeps it there, not the armies already there. */
651
783
  let central = false;
784
+ /** #424: the Diplomacy partner's border the leftover keeps as the front. */
785
+ let peace;
652
786
  /** #226 review: the leftover defends `where` or saves there: the #226 margin leaves it. */
653
787
  let defends = false;
654
788
  /** #288: the attacks out of the expansion stack the leftover goes with (it has nothing else left to attack). */
@@ -737,7 +871,7 @@ export function leftoverDeploy(pc, ps, book, threats, hd, tgt, saveStep, stack,
737
871
  lock = true;
738
872
  concentrating = true;
739
873
  where = stack.id;
740
- why = `one strike stack on the border facing player ${stack.player}, ${pc.siege?.target === stack.player ? 'the siege target' : '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`;
741
875
  }
742
876
  else if (short[0] && flatSave && saving && open(saving.from) && roomAt(saving.from) > 0) {
743
877
  // (Under Local Deployment the leftover may not land there: then the margins stand.)
@@ -750,6 +884,7 @@ export function leftoverDeploy(pc, ps, book, threats, hd, tgt, saveStep, stack,
750
884
  }
751
885
  else if (short[0]) {
752
886
  defends = true;
887
+ deterrentGuard(short);
753
888
  // #218: the source of the step the leftover would save toward, when it is an open border:
754
889
  // once every short border has its comfortable margin, the rest goes there when it defends
755
890
  // as well as the border the rest would go to, and counts toward the step. A margin itself
@@ -803,6 +938,12 @@ export function leftoverDeploy(pc, ps, book, threats, hd, tgt, saveStep, stack,
803
938
  lock = true;
804
939
  concentrating = true;
805
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
+ }
806
947
  else if (expansion !== undefined && open(expansion)) {
807
948
  // #218 (comment): with no enemy in view there is no front to go to, and a leftover riding
808
949
  // the top expansion walks deeper into one region every turn (live: 14 hops from the nearest
@@ -810,8 +951,7 @@ export function leftoverDeploy(pc, ps, book, threats, hd, tgt, saveStep, stack,
810
951
  // from my farthest border than the territory central to what I hold, and its attacks land
811
952
  // for sure without the leftover, the leftover stays there.
812
953
  // Only once its attacks land for sure: under luck the leftover there raises their odds.
813
- const sure = moves.every((m) => m.from !== expansion || m.kind !== 'attack' || (m.winChance ?? 1) >= 1);
814
- const c = noFront && sure ? centre() : undefined;
954
+ const c = noFront && expansionSure() ? centre() : undefined;
815
955
  if (c && c.id !== expansion && (c.ecc.get(expansion) ?? Infinity) > c.ecc.get(c.id) + CENTRE_SLACK) {
816
956
  where = c.id;
817
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`;
@@ -39,7 +39,8 @@
39
39
  import { bonusTerritories } from '../bonuses.js';
40
40
  import { bfsDistances, neighborsOf } from '../graph.js';
41
41
  import { simTerritories, simulateTurn } from '../turn-sim.js';
42
- import { CONCEDE_FACTOR, } from './shared.js';
42
+ import { armiesToTake, DEFAULT_DEFENSIVE_KILL_RATE, straightKills } from '../combat.js';
43
+ import { captureCost, CONCEDE_FACTOR, } from './shared.js';
43
44
  import { byNum } from './util.js';
44
45
  /** T3: a covered border protecting more than this share of my income keeps its full hold. */
45
46
  export const TRUCE_RELAX_VALUE = 0.25;
@@ -75,6 +76,75 @@ export function avoidedBy(input) {
75
76
  owner.set(t.territoryId, t.owner.playerId);
76
77
  return (t) => territories.has(t) || players.has(owner.get(t) ?? Number.NaN);
77
78
  }
79
+ /**
80
+ * #441: the neutrals an avoided player is visibly collecting — its only enemy neighbour is that player, or it
81
+ * sits in a bonus whose members that player visibly holds more than half of — which the plan skips like the
82
+ * player's own territories: taking one beside its stack reads as a provocation and is conceded next turn.
83
+ * Not skipped: a neutral whose capture completes a bonus of mine on its own (every other member mine at the
84
+ * start), or one the capture would hold next turn with what it leaves there alone (the fewest attackers that
85
+ * take it, less the defenders' kills) against every enemy stack beside it plus its owner's deploy.
86
+ * #457: a truce partner's (`truce`, `Truce.keptWith`) the same way — its enemy neighbours counting the partner
87
+ * even when a card makes it no foe — except that holding is no reason to take one: to the partner it reads as a
88
+ * breach either way; only completing a bonus of mine is (`truce: true` on the skirt). Empty with no avoided
89
+ * player and no truce partner, so every other plan is unchanged.
90
+ */
91
+ export function skirtedNeutrals(input, o) {
92
+ const out = new Map();
93
+ const avoid = new Set(input.options?.avoid?.players ?? []);
94
+ const partners = o.truce ?? new Set();
95
+ if (!avoid.size && !partners.size)
96
+ return out;
97
+ const watched = [...new Set([...avoid, ...partners])].sort(byNum);
98
+ const { graph: g, board, me } = input;
99
+ const state = new Map(board.territories.map((t) => [t.territoryId, t]));
100
+ const ownerOf = (t) => {
101
+ const st = state.get(t);
102
+ return st?.owner.kind === 'player' ? st.owner.playerId : undefined;
103
+ };
104
+ const rates = o.settings;
105
+ for (const st of [...board.territories].sort((a, b) => a.territoryId - b.territoryId)) {
106
+ const n = st.territoryId;
107
+ if (st.owner.kind !== 'neutral' || !g.territoryById.has(n))
108
+ continue;
109
+ const bonuses = g.map.bonuses.filter((b) => bonusTerritories(g, b.id).includes(n));
110
+ // It completes a bonus of mine: always worth taking.
111
+ if (bonuses.some((b) => b.value > 0 && bonusTerritories(g, b.id).every((x) => x === n || ownerOf(x) === me)))
112
+ continue;
113
+ const foes = [...new Set(neighborsOf(g, n).flatMap((x) => {
114
+ const p = ownerOf(x);
115
+ return p !== undefined && (o.foe(p) || partners.has(p)) ? [p] : [];
116
+ }))];
117
+ const of = (player, why) => ({ player, why, ...(partners.has(player) ? { truce: true } : {}) });
118
+ let skirt;
119
+ if (foes.length === 1 && (avoid.has(foes[0]) || partners.has(foes[0])))
120
+ skirt = of(foes[0], 'stack');
121
+ else
122
+ for (const b of [...bonuses].sort((x, y) => x.id - y.id)) {
123
+ const ts = bonusTerritories(g, b.id);
124
+ const p = watched.find((a) => ts.filter((x) => ownerOf(x) === a).length * 2 > ts.length);
125
+ if (p !== undefined) {
126
+ skirt = of(p, 'bonus');
127
+ break;
128
+ }
129
+ }
130
+ if (!skirt)
131
+ continue;
132
+ // #457: a truce partner's is skipped whether or not the capture would hold.
133
+ if (skirt.truce) {
134
+ out.set(n, skirt);
135
+ continue;
136
+ }
137
+ // It holds next turn with its survivors alone: no provocation that costs it.
138
+ const defenders = st.armies ?? 0;
139
+ const sent = captureCost(defenders, o.settings);
140
+ const survivors = sent === null ? 0 : sent - straightKills(defenders, rates.defensiveKillRate ?? DEFAULT_DEFENSIVE_KILL_RATE);
141
+ const threat = Math.max(0, ...foes.map((p) => neighborsOf(g, n).reduce((sum, x) => sum + (ownerOf(x) === p ? Math.max(0, (state.get(x).armies ?? 0) - 1) : 0), 0) + o.deployOf(p)));
142
+ if (survivors > 0 && (armiesToTake(survivors, rates) ?? Number.POSITIVE_INFINITY) > threat)
143
+ continue;
144
+ out.set(n, skirt);
145
+ }
146
+ return out;
147
+ }
78
148
  function withAvoid(truce, input) {
79
149
  const avoided = avoidedBy(input);
80
150
  return { ...truce, avoided, noTarget: (t) => avoided(t) || truce.noTarget(t) };
@@ -116,11 +186,15 @@ function truceFrom(input, o) {
116
186
  const partners = new Set();
117
187
  const enforced = new Set();
118
188
  const lookAheadFoes = new Set();
189
+ /** #457: the players an agreement (not only a card) binds this turn, in any format. */
190
+ const keptWith = new Set();
119
191
  /** Per partner whose agreement binds (in any format), the territories of theirs covered. */
120
192
  const theirs = new Map();
121
193
  given.forEach((r, i) => {
122
194
  if (!kept[i])
123
195
  return;
196
+ if (!r.card)
197
+ keptWith.add(r.player);
124
198
  // T2–T5 and T9 only in a free-for-all; T1 (never a surprise break, D3) wherever the agreement binds.
125
199
  if (binds[i]) {
126
200
  partners.add(r.player);
@@ -153,7 +227,19 @@ function truceFrom(input, o) {
153
227
  if (binds[i] && enforcedNow[i] && (r.enforcedUntil === undefined || (o.turnNow !== null && r.enforcedUntil > o.turnNow + 1)))
154
228
  lookAheadFoes.delete(r.player);
155
229
  });
156
- return { given, status, binds, partners, enforced, lookAheadFoes, noTarget, avoided: () => false, noFront, format: o.format };
230
+ return {
231
+ given,
232
+ status,
233
+ binds,
234
+ partners,
235
+ ...(keptWith.size ? { keptWith } : {}),
236
+ enforced,
237
+ lookAheadFoes,
238
+ noTarget,
239
+ avoided: () => false,
240
+ noFront,
241
+ format: o.format,
242
+ };
157
243
  }
158
244
  /**
159
245
  * T4 for rule 0p.2: the binding partners the game profile counts among my opponents — on the
@@ -698,6 +784,33 @@ export function truceBreakLosses(pc, plan) {
698
784
  return best;
699
785
  });
700
786
  }
787
+ /**
788
+ * #457: a neutral the plan's final orders attack beside a territory (at the start) of a player an agreement binds
789
+ * (`Truce.keptWith`): a warning per neutral that it may read as a breach to that player, so the owner can tell it
790
+ * first. Ascending territory id; nothing with no such agreement.
791
+ */
792
+ export function warnTruceNeutrals(pc, plan) {
793
+ const kept = pc.truce.keptWith;
794
+ if (!kept?.size)
795
+ return;
796
+ const ownerOf = (t) => {
797
+ const o = pc.territories.get(t)?.owner;
798
+ return o?.kind === 'player' ? o.playerId : undefined;
799
+ };
800
+ const taken = [...new Set(plan.moves.filter((m) => m.kind === 'attack').map((m) => m.to))].sort(byNum);
801
+ for (const t of taken) {
802
+ if (pc.territories.get(t)?.owner.kind !== 'neutral')
803
+ continue;
804
+ const beside = [...new Set(neighborsOf(pc.g, t).flatMap((x) => {
805
+ const p = ownerOf(x);
806
+ return p !== undefined && kept.has(p) ? [p] : [];
807
+ }))].sort(byNum);
808
+ if (!beside.length)
809
+ continue;
810
+ const who = beside.map((p) => `player ${p}`).join(' and ');
811
+ plan.warnings.push(`Taking ${pc.label(t)}, a neutral beside ${beside.map((p) => `player ${p}'s`).join(' and ')} land, may read as a breach to ${who} (a truce binds you): tell ${who} first (#457).`);
812
+ }
813
+ }
701
814
  /**
702
815
  * T6's report: each binding truce's {@link truceBreakLosses} on its view, and a rationale line that
703
816
  * says what a break would take. Nothing with no relations.