@chrischall/warapp-mcp 0.5.0 → 0.6.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 (80) hide show
  1. package/.claude-plugin/marketplace.json +3 -3
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +37 -5
  4. package/dist/analysis/card-support.js +2 -1
  5. package/dist/analysis/card-threats.js +59 -12
  6. package/dist/analysis/game-lessons.js +3 -4
  7. package/dist/analysis/hold-diff.js +3 -1
  8. package/dist/analysis/income-trend.js +38 -0
  9. package/dist/analysis/intel.js +75 -0
  10. package/dist/analysis/opens.js +64 -0
  11. package/dist/analysis/opponent-profile.js +75 -7
  12. package/dist/analysis/opponents.js +2 -2
  13. package/dist/analysis/outlook.js +39 -0
  14. package/dist/analysis/picks.js +91 -12
  15. package/dist/analysis/plan/bonus-attempts.js +105 -0
  16. package/dist/analysis/plan/capture-instead.js +116 -0
  17. package/dist/analysis/plan/captures.js +45 -4
  18. package/dist/analysis/plan/conceded-out.js +13 -2
  19. package/dist/analysis/plan/estimates.js +135 -26
  20. package/dist/analysis/plan/holds.js +31 -3
  21. package/dist/analysis/plan/jabs.js +113 -0
  22. package/dist/analysis/plan/leftover.js +249 -4
  23. package/dist/analysis/plan/orders.js +76 -4
  24. package/dist/analysis/plan/relations.js +21 -1
  25. package/dist/analysis/plan/report.js +69 -3
  26. package/dist/analysis/plan/second-sizing.js +133 -0
  27. package/dist/analysis/plan/shared.js +82 -20
  28. package/dist/analysis/plan/siege.js +303 -0
  29. package/dist/analysis/plan/stand-still.js +7 -3
  30. package/dist/analysis/plan/state.js +8 -0
  31. package/dist/analysis/plan/strike.js +10 -5
  32. package/dist/analysis/plan/targets.js +91 -60
  33. package/dist/analysis/plan/threats.js +41 -6
  34. package/dist/analysis/plan/transfers.js +46 -6
  35. package/dist/analysis/planner.js +234 -16
  36. package/dist/analysis/profile.js +13 -2
  37. package/dist/analysis/stress.js +8 -2
  38. package/dist/bonus-attempt-store.js +55 -0
  39. package/dist/bundle.js +47965 -39683
  40. package/dist/cards.js +7 -5
  41. package/dist/chat.js +35 -1
  42. package/dist/commerce.js +111 -0
  43. package/dist/index.js +9 -1
  44. package/dist/live.js +43 -0
  45. package/dist/move-order.js +64 -3
  46. package/dist/normalize.js +17 -0
  47. package/dist/profile-store.js +12 -2
  48. package/dist/protocol/methods.js +60 -5
  49. package/dist/protocol/rpc.js +8 -0
  50. package/dist/relations-store.js +38 -4
  51. package/dist/siege-store.js +49 -0
  52. package/dist/state-bundle.js +525 -0
  53. package/dist/state-cli.js +69 -0
  54. package/dist/team-cards.js +25 -0
  55. package/dist/tools/award.js +15 -1
  56. package/dist/tools/card-advice.js +16 -5
  57. package/dist/tools/card-plays.js +2 -2
  58. package/dist/tools/card-support-advice.js +2 -1
  59. package/dist/tools/chat-inbox.js +4 -0
  60. package/dist/tools/chat.js +65 -6
  61. package/dist/tools/check-plan.js +54 -10
  62. package/dist/tools/commerce-deploy.js +33 -0
  63. package/dist/tools/common.js +31 -0
  64. package/dist/tools/end-of-game.js +5 -3
  65. package/dist/tools/index.js +7 -0
  66. package/dist/tools/picks.js +12 -0
  67. package/dist/tools/profile-opponents.js +2 -0
  68. package/dist/tools/relations.js +137 -0
  69. package/dist/tools/state.js +227 -0
  70. package/dist/tools/stress-opponents.js +5 -2
  71. package/dist/tools/survival.js +11 -3
  72. package/dist/tools/team-brief.js +2 -2
  73. package/dist/tools/team.js +12 -3
  74. package/dist/tools/turn.js +332 -60
  75. package/dist/version.js +1 -1
  76. package/manifest.json +10 -2
  77. package/mint.yaml +14 -4
  78. package/package.json +4 -4
  79. package/server.json +2 -2
  80. package/skills/warapp-mcp/SKILL.md +31 -9
@@ -7,14 +7,18 @@
7
7
  // stack, the short borders' comfortable margins (#218: the rest on the step's source when it
8
8
  // defends as well; #268: else spread over the borders facing one opponent for equal headroom
9
9
  // 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
10
+ // the territory central to what I hold instead when the stack lies far from it; #288: with the
11
+ // attacks out of it when it has nothing left to attack once they land: first what each next step
12
+ // from their targets needs, then the rest offered to another capture, rule 5b's), the most fogged
11
13
  // border or the biggest stack — split against a Bomb when it concentrates for
12
14
  // nothing — and under Local Deployment each pool's rest inside its bonus. planPass runs it where
13
15
  // it ran before: after rule 1c's second reconsideration and the strike stack's choice, before the
14
16
  // strike stack is spent.
15
17
  import { bonusTerritories } from '../bonuses.js';
18
+ import { straightKills } from '../combat.js';
16
19
  import { bfsDistances, neighborsOf } from '../graph.js';
17
20
  import { chargeDeploys } from '../local-deploy.js';
21
+ import { plainEconomy, plainEligible } from './after-leftover.js';
18
22
  import { completedMembers } from './completed.js';
19
23
  import { COMFORT_MARGIN } from './shared.js';
20
24
  /** #218 (comment): hops the expansion stack may lie farther from my farthest border than the centre before the leftover stays central. */
@@ -39,6 +43,11 @@ export function leftoverDeploy(pc, ps, book, threats, hd, tgt, saveStep, stack,
39
43
  let strikeStack;
40
44
  /** Armies a Local Deployment pool put on each border this turn (#103): never moved out. */
41
45
  const poolDeployed = new Map();
46
+ /**
47
+ * #288: the rest of the leftover offered to another capture this turn (its territory), and how to send
48
+ * it with the attacks after all when rule 5b takes nothing from there (planPass calls `revert`).
49
+ */
50
+ let offered;
42
51
  /**
43
52
  * #125: the capture to save toward — rule 4e's top step it could not afford, else (rule 4f
44
53
  * committing) the closest bonus's cheapest missing member in reach when this turn made no capture
@@ -451,6 +460,31 @@ export function leftoverDeploy(pc, ps, book, threats, hd, tgt, saveStep, stack,
451
460
  };
452
461
  const fogged = [...mine].filter((x) => open(x) && notSoftening(x)).sort((a, b) => foggedNext(b) - foggedNext(a) || a - b).find((id) => foggedNext(id) > 0);
453
462
  const saving = stepSource(open, notSoftening);
463
+ /**
464
+ * #303: my income flat (#312's rule) and the step saved toward is in a positive bonus whose every
465
+ * member not mine is a visible neutral or held by an opponent earning less than I do: no comfort
466
+ * margin above the exact holds goes ahead of that completion — the leftover saves toward it.
467
+ */
468
+ const flatSave = (() => {
469
+ const tr = pc.incomeTrend;
470
+ if (!tr?.flat || !saving)
471
+ return null;
472
+ const value = g.map.bonuses.find((b) => b.id === saving.bonusId)?.value ?? 0;
473
+ if (value <= 0)
474
+ return null;
475
+ const every = tr.turns[tr.turns.length - 1].income;
476
+ const missing = bonusTerritories(g, saving.bonusId).filter((x) => !mineSet.has(x));
477
+ const weak = (x) => {
478
+ const o = state.get(x)?.owner;
479
+ if (o?.kind === 'neutral')
480
+ return true;
481
+ return o?.kind === 'player' && pc.foe(o.playerId) && pc.incomeOfPlayer(o.playerId) < every;
482
+ };
483
+ if (!missing.length || !missing.every(weak))
484
+ return null;
485
+ const first = tr.turns[0];
486
+ 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
+ })();
454
488
  const biggest = (ids) => [...ids].sort((a, b) => armiesOf(b) + (deployed.get(b) ?? 0) - (armiesOf(a) + (deployed.get(a) ?? 0)) || a - b)[0];
455
489
  const takenBack = reviving ? holdAfterAll() : undefined;
456
490
  if (reviving) {
@@ -565,6 +599,47 @@ export function leftoverDeploy(pc, ps, book, threats, hd, tgt, saveStep, stack,
565
599
  }
566
600
  return got;
567
601
  };
602
+ /**
603
+ * #290 (owner decision 2026-11-19): before the even spread, a border whose enemy stack beside it grew
604
+ * this turn (as the two boards show it) is topped up to hold against that stack plus its owner's whole
605
+ * observed deploy — the estimate, the observed figure before its cap, this turn's high reading (growth
606
+ * beside the fog read as deploy), or the reading #123's bound cut on the track (`newestCut`): a jump
607
+ * kept as a lower bound counts in full — highest protected value first, as far as the leftover goes.
608
+ * The spread itself is unchanged.
609
+ */
610
+ const fundGrown = () => {
611
+ const whole = (b) => {
612
+ const e = pc.estimates.get(b.player);
613
+ return Math.max(b.deploy, grewBy(b), e?.observedRaw ?? 0, e?.observation?.high ?? 0, e?.newestCut?.reading ?? 0);
614
+ };
615
+ /** The most any stack of the border's opponent beside it grew since the previous board, as the boards show it. */
616
+ const grewBy = (b) => Math.max(0, ...neighborsOf(g, b.id).map((n) => {
617
+ const st = state.get(n);
618
+ const was = threats.previousBoard?.territories.find((t) => t.territoryId === n);
619
+ const same = (t) => t?.owner.kind === 'player' && t.owner.playerId === b.player && typeof t.armies === 'number';
620
+ return same(st) && same(was) ? st.armies - was.armies : 0;
621
+ }));
622
+ const grown = [...borders.values()]
623
+ .filter((b) => grewBy(b) > 0 && open(b.id) && !orderOf(b.id) && !moves.some((m) => m.from === b.id && m.kind === 'attack'))
624
+ .sort((a, b) => valueOf(b.id) - valueOf(a.id) || a.id - b.id);
625
+ for (const b of grown) {
626
+ const bar = b.movable + whole(b);
627
+ let d = 0;
628
+ const room = roomAt(b.id);
629
+ while (d < room && d < ps.budget) {
630
+ const take = toTake(stays(b.id) + d + unitsAt(b.id));
631
+ if (take === null || take > bar)
632
+ break;
633
+ d++;
634
+ }
635
+ if (d <= 0)
636
+ continue;
637
+ deploy(b.id, d);
638
+ locked.add(b.id);
639
+ keepFromMargin(b.id);
640
+ 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
+ }
642
+ };
568
643
  /** #268: the rest spread by {@link headroomSpread}, already deployed: nothing is left for `where`. */
569
644
  let spreadRest;
570
645
  let where;
@@ -576,11 +651,102 @@ export function leftoverDeploy(pc, ps, book, threats, hd, tgt, saveStep, stack,
576
651
  let central = false;
577
652
  /** #226 review: the leftover defends `where` or saves there: the #226 margin leaves it. */
578
653
  let defends = false;
654
+ /** #288: the attacks out of the expansion stack the leftover goes with (it has nothing else left to attack). */
655
+ let joins;
656
+ /** Territories beside `t` that are neither mine nor captured this turn: what is left to attack from it. */
657
+ const leftToAttack = (t) => neighborsOf(g, t).filter((n) => !mineSet.has(n) && !captured.has(n));
658
+ /**
659
+ * #288: a source facing no threat whose every neighbour is mine or captured this turn has nothing
660
+ * left to attack once the captures land, so a leftover there idles: it goes with its attacks whose
661
+ * targets still have a step onward (most steps onward first, then id). Never under No-Split (an
662
+ * order already carries the whole stack), nor with a combined capture or a softener.
663
+ */
664
+ const joinsOf = (src) => {
665
+ if (noSplit || borders.has(src) || pc.myCommanders.has(src) || leftToAttack(src).length)
666
+ return undefined;
667
+ const onward = (t) => leftToAttack(t).filter((n) => n !== src).length;
668
+ const out = moves
669
+ .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)
670
+ .sort((a, b) => onward(b.to) - onward(a.to) || a.to - b.to);
671
+ return out.length ? out : undefined;
672
+ };
673
+ /**
674
+ * #288 (second half): the next step from the target of `m`, an attack out of `src` the leftover may
675
+ * join: the cheapest visible neutral beside it that is neither mine nor captured this turn, and the
676
+ * armies its capture next turn needs beyond those that land movable (0 with no such neutral).
677
+ */
678
+ const nextStep = (m, src) => {
679
+ const lands = ps.survivorsAt.get(m.to) ?? m.armies - straightKills(pc.defenceAt(m.to), pc.rates.defensiveKillRate);
680
+ const movable = Math.max(0, lands - pc.guard);
681
+ const best = leftToAttack(m.to)
682
+ .filter((x) => x !== src && state.get(x)?.owner.kind === 'neutral' && typeof state.get(x)?.armies === 'number')
683
+ .map((x) => ({ x, c: pc.costAt(x) }))
684
+ .filter((o) => o.c !== null)
685
+ .sort((a, b) => a.c - b.c || a.x - b.x)[0];
686
+ return best ? { m, need: Math.max(0, best.c - movable), step: best.x, cost: best.c, movable } : { m, need: 0, movable };
687
+ };
688
+ /**
689
+ * #288: another capture this turn the rest of the leftover (`left`) can pay for, rule 5b's way: a
690
+ * neutral not captured that passes pass 3's eligibility and economy tests, beside an open territory
691
+ * of mine other than `src` that issues no order, holds no commander of mine and attacks no player,
692
+ * whose armies fall short of its cost by no more than `left` (fewest short first, then cost, id).
693
+ * Not under Local Deployment (the pools decide where the rest may land). Rule 5b judges the hold.
694
+ */
695
+ const otherCapture = (left, src) => {
696
+ // As rule 5b: never under `complete-bonus` (No-Split never gets here: no join).
697
+ if (local || pc.goal === 'complete-bonus')
698
+ return undefined;
699
+ const c = [...targets.values()]
700
+ .filter((tg) => state.get(tg.id)?.owner.kind === 'neutral' && !captured.has(tg.id) && !repulsed.has(tg.id) && !pc.truce.noTarget(tg.id))
701
+ .filter((tg) => {
702
+ const gain = book.gainWith([tg.id]);
703
+ return gain >= 0 && plainEligible(pc, tgt, tg.id, false) && !plainEconomy(pc, tgt, tg.id, gain);
704
+ })
705
+ .flatMap((tg) => tg.sources
706
+ .filter((x) => x !== src &&
707
+ mineSet.has(x) &&
708
+ open(x) &&
709
+ !conceded.has(x) &&
710
+ !pc.myCommanders.has(x) &&
711
+ !orderOf(x) &&
712
+ !moves.some((m) => m.from === x && m.kind === 'attack' && state.get(m.to)?.owner.kind === 'player'))
713
+ .map((x) => ({ t: tg.id, at: x, cost: tg.cost, short: tg.cost - avail.get(x) })))
714
+ .filter((o) => o.short > 0 && o.short <= left)
715
+ .sort((a, b) => a.short - b.short || a.cost - b.cost || a.t - b.t || a.at - b.at)[0];
716
+ return c ? { ...c, n: left } : undefined;
717
+ };
718
+ /** Sends `k` more of `src`'s armies with the attack `m`. */
719
+ const applyTo = (src, m, k) => {
720
+ m.armies += k;
721
+ m.winChance = pc.chanceOf(m.armies, pc.defenceAt(m.to));
722
+ avail.set(src, avail.get(src) - k);
723
+ if (ps.survivorsAt.has(m.to))
724
+ ps.survivorsAt.set(m.to, ps.survivorsAt.get(m.to) + k);
725
+ };
726
+ /** The rationale line of the leftover `k` deployed on `src` and sent with the attacks (`add` more each). */
727
+ const joinLine = (src, k, steps, add) => {
728
+ const parts = steps
729
+ .filter((s) => (add.get(s.m) ?? 0) > 0)
730
+ .map((s) => `the attack on ${label(s.m.to)} (${s.m.armies - add.get(s.m)} → ${s.m.armies})`);
731
+ const needs = steps
732
+ .filter((s) => s.funded)
733
+ .map((s) => `${label(s.step)} beside ${label(s.m.to)} takes ${s.cost}, ${s.need} more than the ${s.movable} that would land movable`);
734
+ 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('; ')})` : ''}.`;
735
+ };
579
736
  if (stack) {
580
737
  lock = true;
581
738
  concentrating = true;
582
739
  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`;
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`;
741
+ }
742
+ else if (short[0] && flatSave && saving && open(saving.from) && roomAt(saving.from) > 0) {
743
+ // (Under Local Deployment the leftover may not land there: then the margins stand.)
744
+ // #303: the holds already have their exact armies; the margin over them waits behind the completion.
745
+ where = saving.from;
746
+ why = `save toward ${label(saving.t)} (${saving.cost} to take), the next step of bonus ${bonusName(saving.bonusId)}, ${cannotAfford(saving)}: ${flatSave}`;
747
+ defends = true;
748
+ lock = true;
749
+ concentrating = true;
584
750
  }
585
751
  else if (short[0]) {
586
752
  defends = true;
@@ -623,6 +789,7 @@ export function leftoverDeploy(pc, ps, book, threats, hd, tgt, saveStep, stack,
623
789
  }
624
790
  else {
625
791
  where = short[0].id;
792
+ fundGrown();
626
793
  spreadRest = headroomSpread(short[0], !spread);
627
794
  why = spread
628
795
  ? `the rest, once every short border has its comfortable margin, to the one with the most at stake (protects +${valueOf(where)})`
@@ -655,6 +822,7 @@ export function leftoverDeploy(pc, ps, book, threats, hd, tgt, saveStep, stack,
655
822
  why = 'the stack working on the top expansion';
656
823
  lock = true;
657
824
  concentrating = true;
825
+ joins = joinsOf(expansion);
658
826
  }
659
827
  }
660
828
  else if (fogged !== undefined) {
@@ -698,7 +866,84 @@ export function leftoverDeploy(pc, ps, book, threats, hd, tgt, saveStep, stack,
698
866
  n = roomAt(where);
699
867
  }
700
868
  }
701
- if (n > 0 && !spreadRest) {
869
+ if (n > 0 && !spreadRest && joins) {
870
+ // #288 (second half, the rule chosen for the owner): extra armies go with an attack only as far as
871
+ // the next step from its target needs them; what is left is offered to another capture this turn
872
+ // (rule 5b takes it, else planPass hands it back here); only the rest still rides the attacks.
873
+ const js = joins;
874
+ const src = where;
875
+ const steps = js.map((m) => nextStep(m, src));
876
+ const add = new Map();
877
+ let left = n;
878
+ // First each need the leftover covers whole, in the joins' order (most steps onward first), one
879
+ // attack per next step: a share that leaves the step short still costs a deploy next turn.
880
+ const funded = new Set();
881
+ for (const s of steps) {
882
+ if (s.need > 0 && s.need <= left && !funded.has(s.step)) {
883
+ add.set(s.m, s.need);
884
+ left -= s.need;
885
+ funded.add(s.step);
886
+ s.funded = true;
887
+ }
888
+ }
889
+ const offer = left > 0 ? otherCapture(left, src) : undefined;
890
+ if (offer)
891
+ left -= offer.n;
892
+ // The rest rides the attacks as before (#288's first half), an army at a time to the one with the
893
+ // least extra so far (the first among equals): the even split #402 made whenever no need exceeds
894
+ // its share, so a landing that also faces an enemy next turn keeps what it had.
895
+ const spread = (k, out) => {
896
+ for (let a = 0; a < k; a++) {
897
+ const m = js.reduce((best, x) => ((out.get(x) ?? 0) < (out.get(best) ?? 0) ? x : best));
898
+ out.set(m, (out.get(m) ?? 0) + 1);
899
+ }
900
+ };
901
+ spread(left, add);
902
+ const sent = n - (offer?.n ?? 0);
903
+ let firstLine;
904
+ if (sent > 0) {
905
+ deploy(src, sent);
906
+ for (const [m, k] of add)
907
+ applyTo(src, m, k);
908
+ firstLine = joinLine(src, sent, steps, add);
909
+ rationale.push(firstLine);
910
+ locked.add(src);
911
+ }
912
+ if (offer) {
913
+ deploy(offer.at, offer.n);
914
+ 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.`;
915
+ rationale.push(offerLine);
916
+ offered = {
917
+ at: offer.at,
918
+ revert: () => {
919
+ // No capture took it (rule 5b refused it): it rides the attacks out of the stack after all,
920
+ // unless an order since sent some of it.
921
+ if (avail.get(offer.at) < offer.n)
922
+ return;
923
+ undeploy(offer.at, offer.n);
924
+ const i = rationale.indexOf(offerLine);
925
+ if (i >= 0)
926
+ rationale.splice(i, 1);
927
+ const total = new Map(add);
928
+ spread(offer.n, total);
929
+ deploy(src, offer.n);
930
+ for (const m of js) {
931
+ const k = (total.get(m) ?? 0) - (add.get(m) ?? 0);
932
+ if (k > 0)
933
+ applyTo(src, m, k);
934
+ }
935
+ const again = joinLine(src, n, steps, total);
936
+ const was = firstLine === undefined ? -1 : rationale.indexOf(firstLine);
937
+ if (was >= 0)
938
+ rationale[was] = again;
939
+ else
940
+ rationale.push(again);
941
+ locked.add(src);
942
+ },
943
+ };
944
+ }
945
+ }
946
+ else if (n > 0 && !spreadRest) {
702
947
  rationale.push(`Deploy the leftover ${n} to ${label(where)}: ${why}.`);
703
948
  deploy(where, n);
704
949
  // Keep a strike or expansion stack there: the transfer step must not walk it back as "idle
@@ -756,5 +1001,5 @@ export function leftoverDeploy(pc, ps, book, threats, hd, tgt, saveStep, stack,
756
1001
  deploy(where, ps.budget);
757
1002
  }
758
1003
  }
759
- return { strikeStack, poolDeployed, staging };
1004
+ return { strikeStack, poolDeployed, staging, offered };
760
1005
  }
@@ -8,11 +8,12 @@ import { breachBehind } from '../breach.js';
8
8
  import { neighborsOf } from '../graph.js';
9
9
  import { chargeDeploys, deployPools } from '../local-deploy.js';
10
10
  import { territoryIncome } from '../player.js';
11
- import { BREACH_WEIGHT, WASTELAND_FACTOR } from './shared.js';
11
+ import { opensBehind } from '../opens.js';
12
+ import { BREACH_WEIGHT, OPENS_WEIGHT, WASTELAND_FACTOR, visibleState } from './shared.js';
12
13
  import { byNum } from './util.js';
13
14
  import { secondLineOf } from './guard-off.js';
14
15
  /** Open the deploy book of one pass: sets `ps.budget`, `ps.holdings` and the starting `avail`. */
15
- export function deployBook(ctx, ps) {
16
+ export function deployBook(ctx, ps, previousBoard) {
16
17
  const { g, territories: state, s, mine, mineSet, myCommanders, foe, guard, noSplit, armiesOf, incomeGain, label, income, reserve, econCostAt, paybackTurns, baseIncome, unitsAt, deployOf, untrustedAt, } = ctx;
17
18
  const { warnings, rationale, deployed, avail, coverKeep, captured, moves } = ps;
18
19
  // ---- mutable plan state ----
@@ -139,6 +140,53 @@ export function deployBook(ctx, ps) {
139
140
  }
140
141
  return cost <= paybackTurns * value && worst <= WASTELAND_FACTOR * value;
141
142
  };
143
+ /**
144
+ * #298: a foe's stack arrived on `x` since `previousBoard`: it took `x` from me, or its armies there
145
+ * grew, both read only where that board showed `x` (owner and armies). No previous board: none.
146
+ */
147
+ const before = new Map(previousBoard?.territories.map((t) => [t.territoryId, t]));
148
+ const arrived = (x, armiesNow) => {
149
+ const was = visibleState(before.get(x));
150
+ if (!was)
151
+ return false;
152
+ if (was.owner.kind !== 'player')
153
+ return false;
154
+ return was.owner.playerId === ctx.me || (foe(was.owner.playerId) && armiesNow > (was.armies ?? 0));
155
+ };
156
+ /**
157
+ * #298: an enemy stack roams inside bonus `ts`, beside my member `t`. Every missing member is a
158
+ * visible neutral or a visible foe's territory, at least one of them a foe's beside `t` whose stack
159
+ * arrived since the previous board (it took the member from me, or grew there: {@link arrived}), and
160
+ * finishing it passes #122's economy tests on what stands there now. My members within that stack's
161
+ * reach are garrisoned like those of a bonus I am building, so the bonus is not lost one member at a
162
+ * time while I retake the one it left.
163
+ */
164
+ const roamedBy = (t, ts, value) => {
165
+ let cost = 0;
166
+ let worst = 0;
167
+ let reach = false;
168
+ for (const x of ts) {
169
+ if (ps.holdings.has(x))
170
+ continue;
171
+ const st = state.get(x);
172
+ if (st === undefined || st.armies === null)
173
+ return false;
174
+ const o = st.owner;
175
+ if (o.kind === 'player') {
176
+ if (!foe(o.playerId))
177
+ return false;
178
+ // A stack: armies that can move (an empty or guard-only member roams nowhere).
179
+ if (st.armies > (guard ? 1 : 0) && neighborsOf(g, t).includes(x) && arrived(x, st.armies))
180
+ reach = true;
181
+ }
182
+ else if (o.kind !== 'neutral')
183
+ return false;
184
+ const c = econCostAt(x);
185
+ cost += c;
186
+ worst = Math.max(worst, c);
187
+ }
188
+ return reach && cost <= paybackTurns * value && worst <= WASTELAND_FACTOR * value;
189
+ };
142
190
  /**
143
191
  * #235: what losing my `t` cuts off from the rest of my holdings (`ps.holdings` without `t`): when
144
192
  * its neighbours of mine fall into two or more parts, every part but the largest (most territories,
@@ -233,11 +281,32 @@ export function deployBook(ctx, ps) {
233
281
  return out;
234
282
  };
235
283
  const breachCache = new Map();
284
+ /** #291: an enemy's territory or a hidden one: where a route into my land can start. */
285
+ const source = (x) => {
286
+ const o = state.get(x)?.owner;
287
+ return o === undefined || o.kind === 'unknown' || (o.kind === 'player' && foe(o.playerId));
288
+ };
289
+ /**
290
+ * #291: what losing my `t` opens to the enemy ({@link opensBehind}): the held bonuses every route from an enemy
291
+ * or the fog reaches only through it, less what its cut (#235) and its breach (#275) already count, with
292
+ * `worth` = {@link OPENS_WEIGHT} of their income. `null` when it opens nothing that earns.
293
+ */
294
+ const opensAt = (t) => {
295
+ if (opensCache.has(t))
296
+ return opensCache.get(t);
297
+ const skip = new Set([...(cutOff(t)?.ids ?? []), ...(breachAt(t)?.ids ?? [])]);
298
+ const o = opensBehind(g, ps.holdings, source, t, skip);
299
+ const out = o.income > 0 ? { ...o, worth: Math.round(OPENS_WEIGHT * o.income * 10) / 10 } : null;
300
+ opensCache.set(t, out);
301
+ return out;
302
+ };
303
+ const opensCache = new Map();
236
304
  const protectedValue = (t) => {
237
305
  // Each bonus is visited once, so it counts once however many of its borders are threatened.
238
306
  // #235: plus the income of what losing it cuts off from the rest of my holdings.
239
307
  // #275: plus, with the guard off, BREACH_WEIGHT × what a breach of it opens behind it.
240
- let v = (cutOff(t)?.income ?? 0) + (breachAt(t)?.worth ?? 0);
308
+ // #291: plus OPENS_WEIGHT × what its loss opens to the enemy (a gate cuts nothing off yet shields it all).
309
+ let v = (cutOff(t)?.income ?? 0) + (breachAt(t)?.worth ?? 0) + (opensAt(t)?.worth ?? 0);
241
310
  const mineWithout = (x) => x !== t && ps.holdings.has(x);
242
311
  for (const b of g.map.bonuses) {
243
312
  const ts = bonusTerritories(g, b.id);
@@ -266,7 +335,8 @@ export function deployBook(ctx, ps) {
266
335
  // foothold) was worth the whole bonus. Being built: every missing member is a visible
267
336
  // neutral, and finishing it passes rule 4's economy tests (a bonus behind an enemy, the
268
337
  // fog or a wasteland is not being built).
269
- if (building(ts, b.value)) {
338
+ // #298: so does a member an enemy stack roaming inside the bonus can reach (`roamedBy`).
339
+ if (building(ts, b.value) || roamedBy(t, ts, b.value)) {
270
340
  const held = ts.filter((x) => ps.holdings.has(x) || x === t).length;
271
341
  v += Math.round(((b.value * held) / ts.length) * 10) / 10;
272
342
  }
@@ -312,6 +382,8 @@ export function deployBook(ctx, ps) {
312
382
  cutCache,
313
383
  breachAt,
314
384
  breachCache,
385
+ opensAt,
386
+ opensCache,
315
387
  stakeAt,
316
388
  };
317
389
  }
@@ -52,6 +52,7 @@ const NONE = {
52
52
  enforced: new Set(),
53
53
  lookAheadFoes: new Set(),
54
54
  noTarget: () => false,
55
+ avoided: () => false,
55
56
  noFront: () => false,
56
57
  format: 'ffa',
57
58
  };
@@ -60,6 +61,25 @@ const NONE = {
60
61
  * and the territories none of my passes may attack. `notFoe` says who is me or a teammate.
61
62
  */
62
63
  export function truceOf(input, o) {
64
+ return withAvoid(truceFrom(input, o), input);
65
+ }
66
+ /** #375: a territory the caller asked to avoid, or one an avoided player holds, is never a target either. */
67
+ export function avoidedBy(input) {
68
+ const territories = new Set(input.options?.avoid?.territories ?? []);
69
+ const players = new Set(input.options?.avoid?.players ?? []);
70
+ if (!territories.size && !players.size)
71
+ return () => false;
72
+ const owner = new Map();
73
+ for (const t of input.board.territories)
74
+ if (t.owner.kind === 'player')
75
+ owner.set(t.territoryId, t.owner.playerId);
76
+ return (t) => territories.has(t) || players.has(owner.get(t) ?? Number.NaN);
77
+ }
78
+ function withAvoid(truce, input) {
79
+ const avoided = avoidedBy(input);
80
+ return { ...truce, avoided, noTarget: (t) => avoided(t) || truce.noTarget(t) };
81
+ }
82
+ function truceFrom(input, o) {
63
83
  const given = input.relations ?? [];
64
84
  if (!given.length)
65
85
  return NONE;
@@ -133,7 +153,7 @@ export function truceOf(input, o) {
133
153
  if (binds[i] && enforcedNow[i] && (r.enforcedUntil === undefined || (o.turnNow !== null && r.enforcedUntil > o.turnNow + 1)))
134
154
  lookAheadFoes.delete(r.player);
135
155
  });
136
- return { given, status, binds, partners, enforced, lookAheadFoes, noTarget, noFront, format: o.format };
156
+ return { given, status, binds, partners, enforced, lookAheadFoes, noTarget, avoided: () => false, noFront, format: o.format };
137
157
  }
138
158
  /**
139
159
  * T4 for rule 0p.2: the binding partners the game profile counts among my opponents — on the
@@ -7,7 +7,9 @@
7
7
  // (#167) and the turns to eliminate each opponent (#179). planPass runs them where they ran before:
8
8
  // the expected outcome and the offence report after Order Priority for a strike, the plan last,
9
9
  // after the move order (plan/move-order.ts).
10
+ import { siegeFitLine, siegeLines, siegeReport } from './siege.js';
10
11
  import { bonusTerritories } from '../bonuses.js';
12
+ import { DEFAULT_DEFENSIVE_KILL_RATE, DEFAULT_OFFENSIVE_KILL_RATE, straightKills } from '../combat.js';
11
13
  import { classifyExchange } from '../exchange.js';
12
14
  import { neighborsOf } from '../graph.js';
13
15
  import { bonusesAtRisk, captureCost, CITE_OPEN, CITE_RE, ETA_HORIZON, NOT_ATTACKING_REASONS, SECOND_FRONT_LEAD, SLOT_NAMES, } from './shared.js';
@@ -67,6 +69,31 @@ export function reportExpected(pc, ps, book, threats, hd, tgt, caps) {
67
69
  ...frontierOf(after, (x) => (mineSet.has(x) ? stayAt(x) : (survivorsAt.get(x) ?? 0))),
68
70
  income: keptIncome(after),
69
71
  };
72
+ // #297: in a 1v1, the gates — every border of mine facing the opponent — against its one floating deploy.
73
+ const gates = (() => {
74
+ if (pc.profile.format !== '1v1')
75
+ return undefined;
76
+ const have = (x) => (mineSet.has(x) ? stayAt(x) : (survivorsAt.get(x) ?? 0)) + (mineSet.has(x) ? unitsAt(x) : 0);
77
+ const list = [];
78
+ let player;
79
+ for (const x of [...after].sort(byNum)) {
80
+ const th = threats.nextTurnAt(x, (n) => after.has(n));
81
+ if (!th)
82
+ continue;
83
+ player ??= th.player;
84
+ list.push({ id: x, needs: threats.holdArmies(th.threat), armies: have(x), ...(conceded.has(x) ? { conceded: true } : {}) });
85
+ }
86
+ if (player === undefined || !list.length)
87
+ return undefined;
88
+ const need = list.reduce((n, g) => n + g.needs, 0);
89
+ const onGates = list.reduce((n, g) => n + g.armies, 0);
90
+ const deficit = list.reduce((n, g) => n + Math.max(0, g.needs - g.armies), 0);
91
+ return { player, gates: list, need, onGates, deficit, income: frontier.income, short: Math.max(0, deficit - frontier.income) };
92
+ })();
93
+ // Warned only when this plan's own captures open a gate the budget cannot pay for (the shortfall alone is in the report).
94
+ const opened = gates ? gates.gates.filter((x) => captured.has(x.id)).map((x) => x.id) : [];
95
+ if (gates && gates.short > 0 && opened.length)
96
+ warnings.push(`Gate budget (#297): this plan's capture of ${opened.map(label).join(', ')} opens ${opened.length === 1 ? 'a gate' : 'gates'} the income cannot hold — ${gates.gates.length} gates facing player ${gates.player}${gates.gates.some((x) => x.conceded) ? ` (${gates.gates.filter((x) => x.conceded).length} conceded)` : ''} need ${gates.need} against its one floating deploy; ${gates.onGates} stand on them, ${gates.deficit} short across them, and the next income is ${gates.income}: ${gates.short} short.`);
70
97
  const startCost = startHold();
71
98
  const outgrown = frontier.holdCost > frontier.income && frontier.holdCost > startCost;
72
99
  // A capture stopped by one pass but taken by a later one (the next income grew in between) is
@@ -230,7 +257,7 @@ export function reportExpected(pc, ps, book, threats, hd, tgt, caps) {
230
257
  }
231
258
  if (noSplit && moves.length && guard)
232
259
  warnings.push('No-Split is on: each order sends its territory\'s whole stack less the one army that stands guard; whether war.app leaves that army behind under No-Split is unverified (a live turn with the guard off left every source at 0).');
233
- return { completed, nextIncome, atRisk, ifFall, reportRisk, frontier };
260
+ return { completed, nextIncome, atRisk, ifFall, reportRisk, frontier, ...(gates ? { gates } : {}) };
234
261
  }
235
262
  /** The offence report (#72), the warnings that follow the deploys, and the "Not attacking" line (#167). */
236
263
  export function reportOffence(pc, ps, book, threats, hd, tgt, holdLocked, leadSpareFor) {
@@ -424,6 +451,10 @@ export function reportOffence(pc, ps, book, threats, hd, tgt, holdLocked, leadSp
424
451
  const p = st.owner.playerId;
425
452
  if (uncounted(n))
426
453
  return `it holds ${uncountedKind(n)}, whose strength the board does not carry`;
454
+ if (pc.truce.avoided(n))
455
+ return 'the plan was told to avoid it (#375)';
456
+ if (pc.truce.siegeHeld?.(n))
457
+ return `the siege holds the assault on player ${p} until its trigger fires: only its bonus members are attacked (#382)`;
427
458
  // B2 (T1): the truce covers it.
428
459
  if (pc.truce.noTarget(n))
429
460
  return `my truce with player ${p} covers it (T1)`;
@@ -524,7 +555,7 @@ export function finishPlan(pc, ps, pass, threats, hd, tgt, expected, sentAt, slo
524
555
  const { reinforcementAt, borders, ownedBy, ownerOf, fogEdge } = threats;
525
556
  const { conceded, stayAt } = hd;
526
557
  const { offence, offenceSkip } = tgt;
527
- const { completed, nextIncome, atRisk, ifFall, reportRisk, frontier } = expected;
558
+ const { completed, nextIncome, atRisk, ifFall, reportRisk, frontier, gates } = expected;
528
559
  const offenceList = [...offence.values()].map(({ bonusId, ...o }) => {
529
560
  // A strike attack's cost is what the final orders send (a top-up can raise it).
530
561
  // The strike stack's own entry is final as built.
@@ -612,6 +643,29 @@ export function finishPlan(pc, ps, pass, threats, hd, tgt, expected, sentAt, slo
612
643
  return `${label(e.to)} from ${label(e.from)} with ${e.armies}: ${e.label} (${at(now)}, ${at(est)} after the estimated deploy, ${at(whole)} after the whole income)`;
613
644
  })
614
645
  .join('; ')}.`);
646
+ // ---- #314: a hold that survives by a handful ----
647
+ // What stays on a held border against its threat (the stack beside it plus its owner's deploy, one
648
+ // attack), luck-free: when that attack fails but leaves so little of mine that its own survivors
649
+ // take it next turn with nothing more deployed, the border is lost anyway. Only a contested big stack
650
+ // (mine at least a turn's income, facing a stack): a small border is re-sized every turn. Report only.
651
+ for (const b of [...borders.values()].sort((a, c) => a.id - c.id)) {
652
+ if (conceded.has(b.id) || b.movable <= 0)
653
+ continue;
654
+ const have = stayAt(b.id) + unitsAt(b.id);
655
+ if (have < income)
656
+ continue;
657
+ const take = toTake(have);
658
+ if (take === null || take <= b.threat)
659
+ continue;
660
+ const mineAfter = Math.max(0, have - straightKills(b.threat, rates.offensiveKillRate ?? DEFAULT_OFFENSIVE_KILL_RATE));
661
+ const hisAfter = Math.max(0, b.threat - straightKills(have, rates.defensiveKillRate ?? DEFAULT_DEFENSIVE_KILL_RATE));
662
+ const next = toTake(mineAfter);
663
+ if (next === null || next > hisAfter)
664
+ continue;
665
+ warnings.push(`${label(b.id)} holds by a handful (#314): an attack of ${b.threat} (its stacks beside it plus player ${b.player}'s deploy) ` +
666
+ `leaves ${mineAfter} of mine against ${hisAfter} of player ${b.player}'s, which take it next turn with nothing more there: ` +
667
+ 'it holds this turn only, so add to it or plan for losing the stack.');
668
+ }
615
669
  // ---- #179: turns to eliminate each visible opponent ----
616
670
  const eliminateEta = {};
617
671
  {
@@ -640,8 +694,19 @@ export function finishPlan(pc, ps, pass, threats, hd, tgt, expected, sentAt, slo
640
694
  eliminateEta[p] = { turns, atLeast: fogEdge(p).length > 0, distance, armies: Number.isFinite(armies) ? armies : null };
641
695
  }
642
696
  }
697
+ // #382: the siege's state and rationale, first.
698
+ if (pc.siegeWarning)
699
+ warnings.push(pc.siegeWarning);
700
+ if (pc.siege)
701
+ rationale.unshift(...siegeLines(pc.siege, label, pc.bonusName));
702
+ const chose = pc.siege ? siegeFitLine(pc.siege, pc.bonusName) : undefined;
703
+ if (chose)
704
+ rationale.unshift(chose);
705
+ if (pc.siegeHandBack)
706
+ rationale.push(pc.siegeHandBack);
643
707
  return {
644
- goal,
708
+ goal: pc.opts.goal === 'siege' || pc.siege ? 'siege' : goal,
709
+ ...(pc.siege ? { siege: siegeReport(pc.siege, g, captured, pc.bonusName) } : {}),
645
710
  profile,
646
711
  // Deploys interleave like moves, and the order they land in shows the opponent my income and
647
712
  // the move order: next to a visible enemy first, in the back after (ascending id within each).
@@ -663,6 +728,7 @@ export function finishPlan(pc, ps, pass, threats, hd, tgt, expected, sentAt, slo
663
728
  cardAdvice: ps.cardAdvice,
664
729
  multiSourceCaptures: [...combined].sort(byNum),
665
730
  frontier,
731
+ ...(gates ? { gates } : {}),
666
732
  offence: offenceList,
667
733
  moveSlots: moves.map((m) => SLOT_NAMES[slotOf(m)]),
668
734
  ...(exchanges.length ? { exchanges } : {}),