@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
@@ -18,6 +18,7 @@
18
18
  // 5. the leftover deploy, 3b's short borders (#121) ........... plan/leftover.ts
19
19
  // 5b. a neutral the leftover pays for (#218) ................. plan/after-leftover.ts
20
20
  // 6. transfers, #125 staging ................................. plan/transfers.ts
21
+ // #277: a held bonus funded from a second sure sizing ......... plan/second-sizing.ts
21
22
  // 7. move order, rule 1s's Order Priority ..................... plan/move-order.ts
22
23
  // 1w. my commander walks, its transit hold (#274) ............. plan/commander.ts
23
24
  // 7r. reports, the offence report, 1i (#109), the final plan .. plan/report.ts
@@ -61,7 +62,8 @@
61
62
  // returned as `profile`: format (1v1 / ffa / teams), phase (opening / expansion /
62
63
  // contact / late; in an FFA, contact only when an enemy stack as it stands can take a
63
64
  // territory of mine or most of my borders face enemies, #132), standing (my income against the strongest opponent's estimate:
64
- // ahead ≥ AHEAD_RATIO×, behind ≤ BEHIND_RATIO×, unknown when fog hides most of the
65
+ // ahead ≥ AHEAD_RATIO×, behind ≤ BEHIND_RATIO× (#287: in a 1v1 also when the opponent's armies in
66
+ // view are ≥ OUTNUMBERED_RATIO× mine), unknown when fog hides most of the
65
67
  // board) and the settings that shape strategy. #276: with One Army Must Stand Guard off it
66
68
  // names that case first (`guard`, `guardCase`: what it means for interior defence) and its note
67
69
  // leads `notes`; with the guard on it is absent, so a guard-on plan is unchanged
@@ -336,9 +338,11 @@
336
338
  // + the sum of each turn's frontier coverage (#294, `frontierCoverage`) over its consecutive observed
337
339
  // turns up to the newest board, none when the run stopped earlier) of its lead over the larger of
338
340
  // its tracked income and its visible income (`priorBlend`), and the warning names both.
339
- // #294: while the tracked figure, above its visible income, was read from under LOW_COVERAGE (0.5)
340
- // of its frontier, the estimate is at least tracked × LOW_COVERAGE_FACTOR (1.5), at most what it
341
- // could earn (`coverageFloor`); the warning says what it was read from. Both unmeasured.
341
+ // #368 (owner decision of 2026-11-19, replacing #294's floor of tracked × 1.5): while the tracked
342
+ // figure was read from under LOW_COVERAGE (0.5) of its frontier, the estimate is the midpoint between
343
+ // its lower bound (visible, tracked, a rising trend's next step) and its upper bound (the fog prior,
344
+ // else what it could earn), moved toward the lower bound as the coverage nears LOW_COVERAGE
345
+ // (`thinEvidence`); the warning names both bounds. Unmeasured.
342
346
  // In a 1v1 too, so it trades #119's prior back toward tracked figures #119 found 2-3x low:
343
347
  // PRIOR_EVIDENCE_TURNS (4) is unmeasured against a finished 1v1.
344
348
  // #164, exact income: under a fog setting that shows every owner (`OWNERS_SHOWN_FOG`: No, Light
@@ -466,7 +470,12 @@
466
470
  // that I would lose all access to without it, plus (#122) its share of every other
467
471
  // incomplete bonus containing it that I am building — value × the members I hold ÷ its
468
472
  // size, one decimal, when every missing member is a visible neutral and finishing it passes
469
- // rule 4's economy tests (PAYBACK_TURNS, WASTELAND_FACTOR) — plus the per-territory
473
+ // rule 4's economy tests (PAYBACK_TURNS, WASTELAND_FACTOR); #298: or when the missing members
474
+ // are visible neutrals and visible foe territories, one of them a foe's movable stack beside the
475
+ // border that arrived since `previousBoard` (taken from me, or grown there, read only where that
476
+ // board showed it): an enemy stack roaming inside the bonus that can reach the border. On the
477
+ // same economy tests over what
478
+ // stands there now, so the members it can reach are garrisoned — plus the per-territory
470
479
  // income it carries (each bonus counted once). Its worth adds the armies a
471
480
  // hold saves, in income terms (armies / PAYBACK_TURNS): a top-up that keeps a
472
481
  // big stack is worth paying even for a small bonus (live, a 60-army border
@@ -484,7 +493,13 @@
484
493
  // fog, that no other front reaches within two steps, and that are hollow (none of mine beside
485
494
  // them, themselves included, holds the largest visible foe stack beside the border plus its
486
495
  // owner's deploy), plus their per-territory income; what #235 cuts off is not counted twice. A
487
- // rationale line names it ("… alone shields … (#275)"). Its hold cost is the fewest
496
+ // rationale line names it ("… alone shields … (#275)"). #291, guard on or off: a gate — a border
497
+ // every route from an enemy or the fog takes to reach territories of mine behind it
498
+ // (src/analysis/opens.ts `opensBehind`) — also protects OPENS_WEIGHT (0.5) of the held bonuses its
499
+ // loss opens (none containing it, none its cut or breach counts), with a line ("… is the only way in
500
+ // to …"); and a territory whose loss opens held bonuses guards against a stack two steps away
501
+ // (#172) like a bonus member, so the gate behind a conceded border keeps a hold — save when a stack
502
+ // steps into that conceded border and makes it hold (#257), which cuts the reach. Its hold cost is the fewest
488
503
  // deploys making `armiesToTake(armies + d) > threat`. Every border facing one
489
504
  // opponent is sized for that opponent's whole deploy (#69): it picks where to land
490
505
  // after I commit, so that is each border's worst case, and a sure hold of several
@@ -556,7 +571,12 @@
556
571
  // better use. It is floored (below) and waits for the captures; once they are planned
557
572
  // (before rule 1c, and under `defend` after passes 1–2), it is held whole if what is left
558
573
  // covers it (rationale "… (more than …), and nothing else this turn uses those armies"),
559
- // else spread (below) when floored, else conceded whole as before. Under Local Deployment (#103) those tests (and its score)
574
+ // else spread (below) when floored, else conceded whole as before. #285 (plan/capture-instead.ts): just before
575
+ // that, an enemy territory whose fall leaves contested members bordering no enemy, fog or hidden territory
576
+ // is captured from the one of them needing the least deploy, sized for its owner's deploy there (the
577
+ // estimate the holds use, #368's middle figure; #120), when that deploy is at most HOLD_CREDIT_TURNS (3)
578
+ // × the hold costs it saves (owner decisions of 2026-11-19); those members are then held ("Take …
579
+ // rather than hold …"). Under Local Deployment (#103) those tests (and its score)
560
580
  // use the cost net of the bonus's own pool, max(0, cost − pool): the pool can be
561
581
  // deployed nowhere else. A unit that pays is funded before any capture that
562
582
  // completes no bonus (advances, breaks, other expansion, unless focused): under `defend` with the
@@ -730,7 +750,10 @@
730
750
  // while one capture makes another complete. R3 does not refuse it (the armies would otherwise
731
751
  // leave a border the plan gives up), and a completed bonus keeps the border (rule 1c). Live, the
732
752
  // last empty members of a bonus stood beside a conceded border: one was taken, the other refused
733
- // ("a conceded border never attacks out for a capture that only costs nothing").
753
+ // ("a conceded border never attacks out for a capture that only costs nothing"). #286: a border
754
+ // rule 1c will keep (a positive bonus containing it already completed by this turn's captures)
755
+ // is no source: its armies would not withdraw (live, a kept +2 member sent 3 into an uneconomic
756
+ // bonus and ended 1 army short of its hold).
734
757
  // 1i. Income at risk (#109). `expected.nextIncome` is next turn's income if every territory
735
758
  // the plan keeps and captures is held — the borders it concedes included, withdrawn from
736
759
  // or not. A conceded border is not kept, so the plan also reports
@@ -806,6 +829,17 @@
806
829
  // without it would (`repulsedSurplus`: the sure size's surplus over the plain one still on the
807
830
  // source; one that would fall without it stays short), and the leftover put there is not kept
808
831
  // from the #226 margin; the strike stack reports such an attack as sized for the deploy.
832
+ // #298, all-in or drop (plan/bonus-attempts.ts; owner defaults of 2026-11-20): with
833
+ // `input.bonusAttempts` (the attempt memory, src/bonus-attempt-store.ts) a contested bonus whose
834
+ // expected completion failed on FAILED_ATTEMPTS (2) consecutive turns is pushed all-in once
835
+ // (`planPushed`: focused, every missing member in view and beside mine, each one a player holds
836
+ // sized for its defenders plus its owner's deploy, #368's middle figure, taken at that size or not
837
+ // at all, as #240's sure size; the whole at most ALL_IN_VALUE_TURNS (2) × its value and my income)
838
+ // when that plan takes every missing member; otherwise it is planned again with the bonus dropped
839
+ // for DROP_TURNS (3) turns, this one included, as it is after an all-in that failed: no bonus
840
+ // scoring, and rule 4e's contact fallback, #203's lead steps and #272's attack out of a conceded
841
+ // border never go into its missing members. `bonusPush` and a rationale line say which. No memory,
842
+ // or no verdict: the plan is byte-identical.
809
843
  // #226, a margin: once the transfers (rule 6) have moved what they move, an attack on a
810
844
  // player's territory whose owner may deploy there (not a combined capture; not under No-Split,
811
845
  // which sends the whole stack already) takes the armies still on its source beyond what holds
@@ -898,7 +932,10 @@
898
932
  // income may lose at most PLAIN_EXPANSION_LOSS (a rationale line "Do not expand into …"
899
933
  // names an affordable one refused). The leftover's expansion stack (rule 5) is a capture's
900
934
  // finisher, never a combined capture's softener.
901
- // 4a. Balanced (the default goal). Instead of passes 1–2, every candidate is
935
+ // 4a. Balanced (the default goal; `siege` too, #382: the siege target's breaks weigh
936
+ // SIEGE_BREAK_WEIGHT × a 1v1 break and are never a second front, its other territories are
937
+ // no target until the trigger fires, and rule 0p.3c's strike stack faces it — plan/siege.ts).
938
+ // Instead of passes 1–2, every candidate is
902
939
  // scored as income per army and taken greedily (focus first, then score, then
903
940
  // cheaper, fewer bonus borders, id): a hold (protected value / hold cost),
904
941
  // completing or advancing a bonus (value / remaining cost), breaking an enemy
@@ -980,6 +1017,13 @@
980
1017
  // territory my commander walks from — all that stands there is its transit hold (rule 1w,
981
1018
  // `commanderTransit` sizes it on the whole stack); a commander that stays keeps its worst-case
982
1019
  // hold through `keepOf`, as from any capture.
1020
+ // #297, a 1v1 only: every border of mine facing the opponent is a gate, each sized for its stack plus the
1021
+ // opponent's whole deploy, since that one deploy floats to whichever it picks. A capture that adds a gate is
1022
+ // stopped when the frontier would then need more next turn than the next income and more than without it
1023
+ // (`gateStop`, src/analysis/plan/captures.ts) — rule 4d's start-of-turn escape does not apply in a 1v1, and
1024
+ // rule 4e's contact fallback, where 4d is only a cost (#114), runs it too. The plan reports `gates` (each gate's
1025
+ // need and armies, conceded ones marked, the summed need, what stands on them, the per-gate deficit, the next
1026
+ // income and the shortfall) and warns when its own captures open a gate the income cannot hold.
983
1027
  // 4e. Never stand still (#104, #107; every goal but `complete-bonus`, after pass 3). A plan that
984
1028
  // makes no capture at all (no expansion, break, finishing off or strike) in the opening or
985
1029
  // expansion phase takes one neutral capture toward a positive bonus (net > 0, never a negative
@@ -1183,8 +1227,24 @@
1183
1227
  // territory central to what I hold (open, issuing no order; my largest connected holding,
1184
1228
  // then the fewest hops through my land to its farthest border, then the least sum, then id),
1185
1229
  // the leftover stays on that centre ("no front to go to: it stays central …"; rule 6 moves
1186
- // the armies already there, never the leftover) — else the
1230
+ // the armies already there, never the leftover); #288: when that source faces no threat, holds
1231
+ // no commander of mine and has nothing left to attack once this turn's captures land (every
1232
+ // neighbour mine or captured), the leftover goes with its attacks on neutrals whose targets have
1233
+ // a step onward (most steps onward first; not under No-Split, not a combined capture: "and send
1234
+ // it with the attack on …"): each attack first gets what the next step from its target (its
1235
+ // cheapest visible neutral onward) needs beyond the armies that land movable, when the leftover
1236
+ // covers that whole; the rest is offered to another capture this turn (a neutral beside another
1237
+ // open territory of mine that issues no order, holds no commander and attacks no player, short
1238
+ // of its cost by no more than the rest: "for another capture this turn"), which rule 5b takes or
1239
+ // planPass sends back with the attacks (`revert`); what is left rides them in equal shares — else the
1187
1240
  // border with the most fogged neighbours, else my biggest stack.
1241
+ // #303 (plan/leftover.ts `flatSave`): when my income is flat (`PlanInput.incomeHistory` → `PlanCtx.incomeTrend`,
1242
+ // #312's rule: the last FLAT_TURNS + 1 turns consecutive and within FLAT_TOLERANCE of the first) and the step
1243
+ // the leftover would save toward is in a positive bonus whose every member not mine is a visible neutral or
1244
+ // held by an opponent earning less than I do, the leftover saves toward it before any comfort margin: the
1245
+ // holds keep their exact armies, and the idle stacks stage toward the step rather than the front (rule 6).
1246
+ // Only where the leftover can land on the step's source (Local Deployment); otherwise unchanged. The plan
1247
+ // reports `incomeTrend` (the last five turns, a least-squares slope, `flat`).
1188
1248
  // 5b. A neutral the leftover pays for (#218; live: a capture ruled out because its source "stays
1189
1249
  // to hold its border", then the leftover put 8 on that source as its comfortable margin, and
1190
1250
  // nothing took the 1-army neutral beside it). After the leftover, the strike stack's orders and
@@ -1230,7 +1290,14 @@
1230
1290
  // into it from Y, Z make it hold together …"), never left reported conceded. Only a stack
1231
1291
  // no enemy can be reached from heads for the nearest territory
1232
1292
  // not mine (neutral or fog; never a teammate's, PLAN-TEAMS C3) instead (#121: idle armies walked toward a worthless neutral
1233
- // while the enemy front was short, and a stack beside one never moved). This turn's
1293
+ // while the enemy front was short, and a stack beside one never moved). Heading for an enemy
1294
+ // front (not by a #260 step, not to a neutral edge), a step must also bring the stack strictly
1295
+ // nearer the enemy front measured through every territory held, conceded borders included (#367):
1296
+ // a conceded border falls to the stack beside it and the front is then right there, so a stack
1297
+ // behind one waits ("Keep the N idle armies on X: the enemy front nearest them, Y, lies past Z, a
1298
+ // border the plan concedes (#367) …"). Measured only around it, the front jumped to a farther
1299
+ // one; live, a 649 stack walked away from a conceded border and straight back the next turn, once
1300
+ // it had fallen. Judged on the one board, no memory of last turn. This turn's
1234
1301
  // captures count as mine only when they land for sure — a neutral, or an attack on a player
1235
1302
  // sized for its owner's whole deploy (rule 1e, 1s, or rule 3's #120 sizing): an exact-sized attack on a player fails
1236
1303
  // if the owner reinforces, and the garrison beside it is not idle. Even a sure one may fail
@@ -1503,6 +1570,9 @@ import { guaranteedKills, nextBreakpoint, straightKills, } from './combat.js';
1503
1570
  import { neighborsOf } from './graph.js';
1504
1571
  import { forecastBorder, mainFront } from './exchange.js';
1505
1572
  import { byNum, pct } from './plan/util.js';
1573
+ import { SIEGE_BREAK_WEIGHT } from './plan/siege.js';
1574
+ import { ALL_IN_VALUE_TURNS, bonusVerdicts, DROP_TURNS, judgeAttempts } from './plan/bonus-attempts.js';
1575
+ import { planJabs } from './plan/jabs.js';
1506
1576
  import { BREAK_WEIGHT, MIN_EXPANSION_SHARE, PLAIN_EXPANSION_LOSS, SECOND_FRONT_LEAD, SECOND_FRONT_SIMILAR, captureCost, } from './plan/shared.js';
1507
1577
  import { emptyPlan, noteEstimates, planContext } from './plan/estimates.js';
1508
1578
  import { neutralizeSeats, seatTerritories, staticSeats } from './static-seats.js';
@@ -1514,12 +1584,14 @@ import { capturesPhase } from './plan/captures.js';
1514
1584
  import { completedMembers } from './plan/completed.js';
1515
1585
  import { chooseStrikeStack, leadStrikes, spendStrikeStack, strikesPhase } from './plan/strike.js';
1516
1586
  import { afterLeftoverCaptures, plainEconomy, plainEligible } from './plan/after-leftover.js';
1587
+ import { fundFromSecondSizing } from './plan/second-sizing.js';
1517
1588
  import { leftoverDeploy } from './plan/leftover.js';
1518
1589
  import { fillSecondLine, guardOffRaids } from './plan/guard-off.js';
1519
1590
  import { neverStandStill } from './plan/stand-still.js';
1520
1591
  import { addEmptyEnemyTargets, dropEmptyEnemyTargets, plainOrderCosts, tryEmptyEnemy, withoutTransit } from './plan/vacated.js';
1521
1592
  import { spendUnderCap } from './plan/cap-spend.js';
1522
1593
  import { attackOutOfConceded } from './plan/conceded-out.js';
1594
+ import { captureInsteadOfHold } from './plan/capture-instead.js';
1523
1595
  import { transfers } from './plan/transfers.js';
1524
1596
  import { scheduleOrders, strikeOrderPriority } from './plan/move-order.js';
1525
1597
  import { commanderMoveWarning, placeCommanderMove, reserveCommanderMove } from './plan/commander.js';
@@ -1530,6 +1602,7 @@ import { applyBorderCaps, armiesFreed, partnerFronts, reportBreakLosses, reportT
1530
1602
  export * from './plan/shared.js';
1531
1603
  export { alliesOf, planEnemyEstimates } from './plan/estimates.js';
1532
1604
  export { TRUCE_RELAX_VALUE } from './plan/relations.js';
1605
+ export { SPREAD_INCOME_SLACK, SPREAD_LAST_TURN, SPREAD_TERRITORIES } from './plan/targets.js';
1533
1606
  /** Passes that refine the cut set (#172) before falling back to the plan that cuts nothing. */
1534
1607
  const TWO_STEP_PASSES = 3;
1535
1608
  /** Passes that learn which territories in between end held (#172) before none is counted held. */
@@ -1567,7 +1640,7 @@ export function planTurn(input) {
1567
1640
  // territories are planned as neutrals (static armies), and it is no opponent anywhere below.
1568
1641
  const seats = staticSeats(input.game?.players, input.game?.endRules, input.me);
1569
1642
  const held = seatTerritories(input.board, seats);
1570
- const plan = planSettled(withoutStaticSeats(input, seats));
1643
+ const plan = planPushed(withoutStaticSeats(input, seats));
1571
1644
  for (const [p, n] of [...held].sort((a, b) => a[0] - b[0]))
1572
1645
  plan.rationale.push(`Player ${p} is out (${seats.get(p)}) and no AI plays its seat: it deploys and attacks nothing, so its ${n} territor${n === 1 ? 'y is' : 'ies are'} planned as neutrals — static armies to take, no hold needed beside them (#270).`);
1573
1646
  return plan;
@@ -1600,6 +1673,102 @@ function withoutStaticSeats(input, seats) {
1600
1673
  ...(input.game && opening ? { game: { ...input.game, opening: new Map([...opening].filter(([p]) => !seats.has(p))) } } : {}),
1601
1674
  };
1602
1675
  }
1676
+ /** #298: per plan, the all-in pushes its pass sized (plan/targets.ts), by bonus id. */
1677
+ const allInOutcome = new WeakMap();
1678
+ /**
1679
+ * #298: the plan with the attempt memory's verdicts (plan/bonus-attempts.ts). A bonus whose completion
1680
+ * failed on two consecutive turns is pushed all-in (focused, every missing member sized for its owner's
1681
+ * deploy or not taken); when the push does not fit the cap, or the plan does not take every missing
1682
+ * member, it is planned again with that bonus dropped for DROP_TURNS turns. With no verdict, the plan
1683
+ * is exactly what it was without the memory.
1684
+ */
1685
+ function planPushed(input) {
1686
+ const turn = input.turn;
1687
+ if (!input.bonusAttempts || turn === undefined)
1688
+ return planSettled(input);
1689
+ const judged = judgeAttempts(input.bonusAttempts, turn, input.graph, input.board, input.me);
1690
+ const verdicts = bonusVerdicts(judged, turn).filter((v) => input.graph.bonusById.has(v.bonusId));
1691
+ if (!verdicts.length)
1692
+ return planSettled(input);
1693
+ const entries = new Map();
1694
+ for (const v of verdicts)
1695
+ if (v.kind === 'dropped')
1696
+ entries.set(v.bonusId, { ...v });
1697
+ let allIn = verdicts.filter((v) => v.kind === 'all-in');
1698
+ const missingOf = (bonusId) => {
1699
+ const at = new Map(input.board.territories.map((t) => [t.territoryId, t]));
1700
+ return bonusTerritories(input.graph, bonusId).filter((t) => {
1701
+ const o = at.get(t)?.owner;
1702
+ return !(o?.kind === 'player' && o.playerId === input.me);
1703
+ });
1704
+ };
1705
+ // A bonus already complete, or no longer contested, needs no push (#406): an all-in verdict needs a
1706
+ // missing member another player still holds; with only neutrals left it is planned as any other bonus,
1707
+ // neither pushed nor dropped.
1708
+ const owners = new Map(input.board.territories.map((t) => [t.territoryId, t.owner]));
1709
+ const contested = (bonusId) => missingOf(bonusId).some((t) => {
1710
+ const o = owners.get(t);
1711
+ return o?.kind === 'player' && o.playerId !== input.me;
1712
+ });
1713
+ allIn = allIn.filter((v) => missingOf(v.bonusId).length > 0 && contested(v.bonusId));
1714
+ let plan;
1715
+ for (;;) {
1716
+ const ids = new Set(allIn.map((v) => v.bonusId));
1717
+ const focus = [...new Set([...(input.options?.focusBonusIds ?? []), ...ids])];
1718
+ plan = planSettled({
1719
+ ...input,
1720
+ bonusPush: { allIn: ids, dropped: new Set([...entries.keys()]) },
1721
+ options: { ...input.options, ...(ids.size ? { focusBonusIds: focus } : {}) },
1722
+ });
1723
+ const tries = allInOutcome.get(plan);
1724
+ const taken = new Set(plan.expected.captures);
1725
+ const failing = allIn.flatMap((v) => {
1726
+ const t = tries?.get(v.bonusId);
1727
+ if (!t)
1728
+ return [{ v, detail: 'it could not be sized' }];
1729
+ if (!t.feasible)
1730
+ return [{ v, detail: t.detail ?? 'it could not be sized', cost: t.cost, cap: t.cap }];
1731
+ const left = missingOf(v.bonusId).filter((x) => !taken.has(x));
1732
+ return left.length ? [{ v, detail: `this turn's plan cannot take ${left.map((x) => `#${x}`).join(', ')} at that size` }] : [];
1733
+ });
1734
+ if (!failing.length) {
1735
+ for (const v of allIn) {
1736
+ const t = tries.get(v.bonusId);
1737
+ entries.set(v.bonusId, { bonusId: v.bonusId, kind: 'all-in', failedTurns: v.failedTurns, cost: t.cost, cap: t.cap });
1738
+ }
1739
+ break;
1740
+ }
1741
+ for (const f of failing)
1742
+ entries.set(f.v.bonusId, {
1743
+ bonusId: f.v.bonusId,
1744
+ kind: 'dropped',
1745
+ why: 'no-all-in',
1746
+ from: turn,
1747
+ until: turn + DROP_TURNS - 1,
1748
+ failedTurns: f.v.failedTurns,
1749
+ detail: f.detail,
1750
+ });
1751
+ const out = new Set(failing.map((f) => f.v.bonusId));
1752
+ allIn = allIn.filter((v) => !out.has(v.bonusId));
1753
+ }
1754
+ const name = (id) => `${input.graph.bonusById.get(id).name} (#${id})`;
1755
+ const turnsText = (ts) => (ts.length > 1 ? `${ts.slice(0, -1).join(', ')} and ${ts[ts.length - 1]}` : `${ts[0]}`);
1756
+ const push = [...entries.values()].sort((a, b) => a.bonusId - b.bonusId);
1757
+ for (const e of push) {
1758
+ if (e.kind === 'all-in')
1759
+ plan.rationale.push(`Bonus ${name(e.bonusId)}: my attempts to complete it failed on turns ${turnsText(e.failedTurns)}: all-in this turn, every missing member taken, each one another player holds sized for its owner's deploy (#368's middle figure): ${e.cost} armies, within the cap of ${e.cap} (${ALL_IN_VALUE_TURNS} turns of its value, at most my income) (#298).`);
1760
+ else {
1761
+ const why = e.why === 'still-dropped'
1762
+ ? `dropped on turn ${e.from} after repeated failed attempts`
1763
+ : e.why === 'all-in-failed'
1764
+ ? `my attempts to complete it failed on turns ${turnsText(e.failedTurns)}, the last of them all-in`
1765
+ : `my attempts to complete it failed on turns ${turnsText(e.failedTurns)}, and no single all-in push this turn completes it: ${e.detail}`;
1766
+ plan.rationale.push(`Bonus ${name(e.bonusId)} is dropped as a target on turns ${e.from} to ${e.until} (#298): ${why}. No armies go into it piecemeal.`);
1767
+ }
1768
+ }
1769
+ plan.bonusPush = push;
1770
+ return plan;
1771
+ }
1603
1772
  function planSettled(input) {
1604
1773
  const plan = planRun(input, false);
1605
1774
  const bare = runOutcome.get(plan);
@@ -1668,7 +1837,7 @@ function planPass(input, pass) {
1668
1837
  return empty;
1669
1838
  }
1670
1839
  // ---- the deploy book (plan/orders.ts): budget, guard, deploys, pools, protected value ----
1671
- const book = deployBook(pc, ps);
1840
+ const book = deployBook(pc, ps, input.previousBoard);
1672
1841
  // #274: under No-Split my commander's walk is its territory's one order, entered before any pass plans.
1673
1842
  reserveCommanderMove(pc, ps);
1674
1843
  const { guardAt, coverOf, heldNow, gainWith, orderOf, deploy, pools, roomAt, spareAt, } = book;
@@ -1745,7 +1914,10 @@ function planPass(input, pass) {
1745
1914
  const secondFrontSaid = new Set();
1746
1915
  /** #167: the neutral's share of a break's score that skips it, scaled by my army lead (at least 1×). */
1747
1916
  const similar = SECOND_FRONT_SIMILAR * Math.max(1, Math.min(SECOND_FRONT_LEAD, armyLead.ratio));
1917
+ /** #382: a break of the siege target's bonus (scored {@link SIEGE_BREAK_WEIGHT} × a 1v1 break, never a second front). */
1918
+ const besieged = (b) => pc.siege?.target === b.player;
1748
1919
  const opensSecondFront = (b, score) => ffa &&
1920
+ !besieged(b) &&
1749
1921
  !leadLever &&
1750
1922
  b.player !== clearLeader &&
1751
1923
  !threatensMyBonus(b.player) &&
@@ -1925,7 +2097,7 @@ function planPass(input, pass) {
1925
2097
  const o = options[0];
1926
2098
  if (!o)
1927
2099
  continue;
1928
- const worth = strikeWorth(b.value, o);
2100
+ const worth = besieged(b) ? (strikeWorth(b.value, o) * SIEGE_BREAK_WEIGHT) / weight : strikeWorth(b.value, o);
1929
2101
  const score = worth / Math.max(1, o.scoreCost);
1930
2102
  offence.set(`break:${b.bonusId}`, {
1931
2103
  bonusId: b.bonusId,
@@ -2341,6 +2513,8 @@ function planPass(input, pass) {
2341
2513
  for (const c of candidates)
2342
2514
  if (c.target !== undefined && !captured.has(c.target) && targets.get(c.target)?.sources.some((x) => unlocked.has(x)))
2343
2515
  c.run();
2516
+ // #285: a contested held bonus's borders facing one enemy stack take it when that costs less.
2517
+ captureInsteadOfHold(pc, ps, book, threats, hd, tgt, caps);
2344
2518
  settleContested();
2345
2519
  // #272: a conceded border attacks out for a free step into a bonus before it withdraws (and
2346
2520
  // before rule 1c re-values the borders, so one whose bonus this completes is kept).
@@ -2359,6 +2533,8 @@ function planPass(input, pass) {
2359
2533
  advance(p);
2360
2534
  garrisonCompleted();
2361
2535
  }
2536
+ // #285: as under `balanced`.
2537
+ captureInsteadOfHold(pc, ps, book, threats, hd, tgt, caps);
2362
2538
  settleContested();
2363
2539
  // #272: a conceded border attacks out for a free step into a bonus before it withdraws (and
2364
2540
  // before rule 1c re-values the borders, so one whose bonus this completes is kept).
@@ -2528,7 +2704,7 @@ function planPass(input, pass) {
2528
2704
  const beforeLeftover = new Map(ps.deployed);
2529
2705
  const leftover = leftoverDeploy(pc, ps, book, threats, hd, tgt, saveStep, stack, open, stays);
2530
2706
  let { strikeStack } = leftover;
2531
- const { poolDeployed, staging } = leftover;
2707
+ const { poolDeployed, staging, offered } = leftover;
2532
2708
  // #235: the Standing-still warning names the source the leftover actually stages on.
2533
2709
  // Found by its text: earlier warnings may have been spliced out since (a revival, a dropped capture).
2534
2710
  if (staging && standStill && staging.t === standStill.t && staging.from !== standStill.named) {
@@ -2597,7 +2773,11 @@ function planPass(input, pass) {
2597
2773
  // ---- 5b. a neutral the leftover pays for (#218) (plan/after-leftover.ts) ----
2598
2774
  // The strike stack concentrates for its strike, and a step's source saves toward it: neither spends.
2599
2775
  const keepWhole = new Set([...(strikeStack ? [strikeStack.id] : []), ...(staging ? [staging.from] : [])]);
2600
- afterLeftoverCaptures(pc, ps, book, threats, hd, tgt, caps, beforeLeftover, keepWhole, poolDeployed);
2776
+ const takenAfter = afterLeftoverCaptures(pc, ps, book, threats, hd, tgt, caps, beforeLeftover, keepWhole, poolDeployed);
2777
+ // #288: the rest of the leftover offered to another capture rides the expansion stack's attacks
2778
+ // after all when rule 5b took nothing from where it was offered.
2779
+ if (offered && !moves.some((m) => m.kind === 'attack' && m.from === offered.at && takenAfter.includes(m.to)))
2780
+ offered.revert();
2601
2781
  // ---- efficient sizes (S2) ----
2602
2782
  // An attack below its next kill breakpoint is topped up to it from armies that would sit
2603
2783
  // idle on its source — never from a hold, a conceded border, my commander's territory, or
@@ -2848,6 +3028,8 @@ function planPass(input, pass) {
2848
3028
  warnings.splice(i, 1);
2849
3029
  rationale.push(`Drop the attack on ${label(t)}: it could send only ${sent} by the end of the turn, short of the ${rep.cost} that take it ${rep.sure ? `even if player ${rep.player} deploys its ~${rep.extra} there first` : `against the ~${rep.extra} player ${rep.player} put there on those turns`}, and my attacks on it failed before, its owner reinforcing it (#240); its armies stay where they are.`);
2850
3030
  }
3031
+ // ---- #277: a held bonus funded before a second attack sized for the same deploy (plan/second-sizing.ts) ----
3032
+ fundFromSecondSizing(pc, ps, book, threats, hd, caps);
2851
3033
  // #120: an attack on a player's territory still sized below its owner's deploy says what it
2852
3034
  // faces if that deploy lands there first.
2853
3035
  for (const m of moves) {
@@ -2865,6 +3047,35 @@ function planPass(input, pass) {
2865
3047
  const aim = chanceAt(m.to);
2866
3048
  warnings[w] = `Attack on enemy ${label(m.to)} assumes its owner does not reinforce it first: if player ${st.owner.playerId} deploys its ~${extra} there, ${m.armies} attack ${d + extra} (win chance ${pct(chanceOf(m.armies, d + extra))})${full !== null ? `; ${full} would ${aim >= 1 ? 'be sure' : `reach ${pct(aim)}`}` : ''}.`;
2867
3049
  }
3050
+ // ---- #361: single-army jabs from the armies still idle beyond each hold (plan/jabs.ts) ----
3051
+ const jabsOn = pc.opts.jabs ?? pc.siege !== undefined;
3052
+ // A jab never brings on #128's or #314's warning: a border that holds against two opponents
3053
+ // attacking it together keeps what holds it so, and one whose hold leaves enough that the attack's
3054
+ // survivors cannot take it next turn keeps that too (report.ts's #314 test).
3055
+ const thin = (x, have) => {
3056
+ const b = borders.get(x);
3057
+ if (!b || conceded.has(x) || b.movable <= 0)
3058
+ return false;
3059
+ const take = toTake(have);
3060
+ if (take === null || take <= b.threat)
3061
+ return false;
3062
+ const mineAfter = Math.max(0, have - straightKills(b.threat, rates.offensiveKillRate));
3063
+ const hisAfter = Math.max(0, b.threat - straightKills(have, rates.defensiveKillRate));
3064
+ const next = toTake(mineAfter);
3065
+ return next !== null && next <= hisAfter;
3066
+ };
3067
+ const jabSpare = (x) => {
3068
+ let spare = spareBeyondHold(x);
3069
+ const now = hd.stayAt(x) + unitsAt(x);
3070
+ if (!thin(x, now))
3071
+ while (spare > 0 && thin(x, now - spare))
3072
+ spare--;
3073
+ const pile = threats.forceAt(x, (n) => captured.has(n), { trend: true, allPlayers: true, pileOn: true });
3074
+ if (!pile?.split || pile.split.players.length < 2)
3075
+ return spare;
3076
+ return now > pile.split.takes ? Math.min(spare, now - pile.split.takes - 1) : spare;
3077
+ };
3078
+ const jabs = jabsOn ? planJabs(pc, ps, jabSpare, keepWhole, (t) => tgt.repulsed.has(t), pc.siege ? strikeStack?.id : undefined) : [];
2868
3079
  // ---- Order Priority for a strike (rule 1s) (plan/move-order.ts) ----
2869
3080
  const { strikeCard, strikeWho } = strikeOrderPriority(pc, ps, threats, hd, struck);
2870
3081
  // #274: my commander's step toward safety, once every other order is planned (plan/commander.ts).
@@ -2882,6 +3093,11 @@ function planPass(input, pass) {
2882
3093
  // #218: the main front's forecast at my whole income, for the game outlook to share.
2883
3094
  if (ps.front)
2884
3095
  plan.front = ps.front;
3096
+ if (jabs.length)
3097
+ plan.jabs = jabs;
3098
+ // #303: my income over the last turns, as rule 5's flat-income saving (plan/leftover.ts) read it.
3099
+ if (pc.incomeTrend)
3100
+ plan.incomeTrend = pc.incomeTrend;
2885
3101
  // PLAN-TEAMS C3.3: the bonuses I share with a teammate (plan/team.ts).
2886
3102
  const team = teamReport(pc, { ps, threats, hd, deploys: plan.deploys });
2887
3103
  if (team)
@@ -2920,6 +3136,8 @@ function planPass(input, pass) {
2920
3136
  if (!heldBorders.has(m.id))
2921
3137
  unheld.add(m.id);
2922
3138
  runOutcome.set(plan, { bareSteps: [...caps.bareTaken].filter(gone).sort(byNum), held, unheld });
3139
+ if (tgt.allInTries.size)
3140
+ allInOutcome.set(plan, tgt.allInTries);
2923
3141
  // #274: a plan that walks my commander says so first.
2924
3142
  if (pc.commanderAt?.retreat)
2925
3143
  plan.warnings.unshift(commanderMoveWarning(pc.commanderAt.retreat, label));
@@ -13,6 +13,11 @@ import { neighborsOf } from './graph.js';
13
13
  export const AHEAD_RATIO = 1.25;
14
14
  /** Behind when my income is at most this many times the strongest opponent's estimated income. */
15
15
  export const BEHIND_RATIO = 0.8;
16
+ /**
17
+ * #287 (1v1 only, the owner's choice): behind, not ahead or even, when the opponent's armies in view are at
18
+ * least this many times mine (what it shows is the least it has). The reciprocal of {@link BEHIND_RATIO}.
19
+ */
20
+ export const OUTNUMBERED_RATIO = 1.25;
16
21
  /**
17
22
  * A player's strength in a free-for-all ranking (#167): its visible armies plus this many turns of
18
23
  * its income — what it can field over the next few turns.
@@ -284,14 +289,20 @@ export function gameProfile(input) {
284
289
  standing = 'behind';
285
290
  standingSource ??= 'visible';
286
291
  }
292
+ else if (format === '1v1' && (standing === 'ahead' || standing === 'even') && theirArmies >= OUTNUMBERED_RATIO * sideArmies) {
293
+ // #287 (owner, 1v1 only): outnumbered by a quarter or more in view is no even game, whatever the incomes.
294
+ // Not in a free-for-all: a clear leader above me (#167) would always read behind and the profile defend.
295
+ notes.push(`Standing behind, not ${standing} (#287): ${theirsText} visible armies are at least ${OUTNUMBERED_RATIO}× ${mineText}, and what it shows is the least it has.`);
296
+ standing = 'behind';
297
+ standingSource ??= 'visible';
298
+ }
287
299
  else if (standing === 'ahead' && sideArmies < BEHIND_RATIO * theirArmies) {
288
300
  notes.push(`Not ahead: the income comparison says so, but ${mineText} visible armies are below ${BEHIND_RATIO}× ${theirsText} in view. Standing even.`);
289
301
  standing = 'even';
290
302
  }
291
303
  }
292
304
  // #275 (b): an observation broke an opponent's estimate: what it really earns is unknown and above it,
293
- // so the game is not even. Only a running tripwire does this: reading `behind` on armies in view alone
294
- // (an opponent's ≥ 1.25 × mine, no tripwire) is not part of #275 — it is deferred to #287.
305
+ // so the game is not even (armies in view alone at OUTNUMBERED_RATIO × mine are #287's 1v1 rule above).
295
306
  if (standing === 'even') {
296
307
  const running = enemies.filter((e) => untrustedFigure.has(e.playerId)).map((e) => e.playerId).sort((a, b) => a - b);
297
308
  if (running.length) {
@@ -497,7 +497,10 @@ export function stressPlan(input) {
497
497
  // Worst first: my commander, an elimination undone, then income, territories held, captures undone, armies.
498
498
  const order = harmful
499
499
  .map((r, i) => ({ r, i }))
500
- .sort((a, b) => Number(b.r.commanderLost) - Number(a.r.commanderLost) ||
500
+ .sort((a, b) =>
501
+ // #376: a reply a truce rules out comes after every reply that keeps the truces, so `worst` is a real threat.
502
+ Number(a.r.breaksTruce === true) - Number(b.r.breaksTruce === true) ||
503
+ Number(b.r.commanderLost) - Number(a.r.commanderLost) ||
501
504
  b.r.eliminationsFailed.length - a.r.eliminationsFailed.length ||
502
505
  // A negative bonus lost is no reason to rank a reply below one that takes nothing.
503
506
  Math.max(0, b.r.incomeLost) - Math.max(0, a.r.incomeLost) ||
@@ -544,13 +547,16 @@ export function stressPlan(input) {
544
547
  needs: r.needs,
545
548
  bonusesLost,
546
549
  incomeLost: bonusesLost.reduce((n, b) => n + b.value, 0),
550
+ // #376: the partner of a truce covering the territory or the step to it breaks the truce to take it.
551
+ ...(covers.get(r.opponent)?.has(r.territory) || covers.get(r.opponent)?.has(r.via) ? { breaksTruce: true } : {}),
547
552
  };
548
553
  const known = exposed.get(r.territory);
549
554
  if (!known || found.attackers > known.attackers)
550
555
  exposed.set(r.territory, found);
551
556
  }
552
557
  }
553
- const exposedNextTurn = [...exposed.values()].sort((a, b) => Math.max(0, b.incomeLost) - Math.max(0, a.incomeLost) || b.needs - b.armies - (a.needs - a.armies) || a.territory - b.territory);
558
+ const exposedNextTurn = [...exposed.values()].sort((a, b) => Number(a.breaksTruce === true) - Number(b.breaksTruce === true) ||
559
+ Math.max(0, b.incomeLost) - Math.max(0, a.incomeLost) || b.needs - b.armies - (a.needs - a.armies) || a.territory - b.territory);
554
560
  return {
555
561
  exact: baseline.exact,
556
562
  assumptions: [...assumptions],
@@ -0,0 +1,55 @@
1
+ // The bonus attempt memory on disk (#298): per game and account, at
2
+ // `<dataDir>/bonus-attempts/<gameId>-<playerId>.json`, the contested bonuses whose completion my plans
3
+ // attempted (each attempt's turn, whether it was all-in, whether the next board showed it failed) and
4
+ // the drops in force. Ids and numbers only, never a name; 0600 in a 0700 directory, written atomically
5
+ // under the in-process path lock (the siege store's pattern, src/siege-store.ts). Written by
6
+ // warapp_plan_turn on a plan that is not a what-if and read back as `PlanInput.bonusAttempts`. Reads are
7
+ // loose: an unusable file is no memory, an unusable record or attempt is dropped; nothing here throws.
8
+ import { randomUUID } from 'node:crypto';
9
+ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
10
+ import { join } from 'node:path';
11
+ import { withPathLock } from './path-lock.js';
12
+ const isRec = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
13
+ const isInt = (v) => typeof v === 'number' && Number.isSafeInteger(v);
14
+ export const bonusAttemptsDir = (dir) => join(dir, 'bonus-attempts');
15
+ export const bonusAttemptsPath = (dir, gameId, playerId) => join(bonusAttemptsDir(dir), `${gameId}-${playerId}.json`);
16
+ function attemptOf(v) {
17
+ if (!isRec(v) || !isInt(v.turn) || typeof v.allIn !== 'boolean')
18
+ return undefined;
19
+ return { turn: v.turn, allIn: v.allIn, ...(typeof v.failed === 'boolean' ? { failed: v.failed } : {}) };
20
+ }
21
+ function recordOf(v) {
22
+ if (!isRec(v) || !isInt(v.bonusId) || !Array.isArray(v.attempts))
23
+ return undefined;
24
+ const attempts = v.attempts.map(attemptOf).filter((a) => a !== undefined);
25
+ const drop = isRec(v.drop) && isInt(v.drop.from) && isInt(v.drop.until) ? { from: v.drop.from, until: v.drop.until } : undefined;
26
+ return { bonusId: v.bonusId, attempts, ...(drop ? { drop } : {}) };
27
+ }
28
+ /** The attempt memory kept for `gameId` as `playerId`; `undefined` when none or unusable. Never throws. */
29
+ export async function readBonusAttempts(dir, gameId, playerId) {
30
+ try {
31
+ const c = JSON.parse(await readFile(bonusAttemptsPath(dir, gameId, playerId), 'utf8'));
32
+ if (!isRec(c) || c.gameId !== gameId || c.playerId !== playerId || !Array.isArray(c.bonuses))
33
+ return undefined;
34
+ return { bonuses: c.bonuses.map(recordOf).filter((r) => r !== undefined) };
35
+ }
36
+ catch {
37
+ return undefined;
38
+ }
39
+ }
40
+ /** Write the attempt memory, atomically, 0600. `true` when written; never throws. */
41
+ export async function writeBonusAttempts(dir, gameId, playerId, memory) {
42
+ const path = bonusAttemptsPath(dir, gameId, playerId);
43
+ return withPathLock(path, async () => {
44
+ try {
45
+ await mkdir(bonusAttemptsDir(dir), { recursive: true, mode: 0o700 });
46
+ const tmp = `${path}.${process.pid}.${randomUUID()}.tmp`;
47
+ await writeFile(tmp, JSON.stringify({ gameId, playerId, bonuses: memory.bonuses }), { mode: 0o600 });
48
+ await rename(tmp, path);
49
+ return true;
50
+ }
51
+ catch {
52
+ return false;
53
+ }
54
+ });
55
+ }