@chrischall/warapp-mcp 0.4.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 (92) hide show
  1. package/.claude-plugin/marketplace.json +3 -3
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +41 -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 +48009 -39350
  40. package/dist/cards.js +7 -5
  41. package/dist/chat.js +46 -4
  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/my-games.js +1 -1
  47. package/dist/normalize.js +17 -0
  48. package/dist/profile-store.js +12 -2
  49. package/dist/protocol/bundle.js +28 -10
  50. package/dist/protocol/codec.js +1 -1
  51. package/dist/protocol/dialect.js +371 -0
  52. package/dist/protocol/interp.js +143 -66
  53. package/dist/protocol/methods.js +95 -34
  54. package/dist/protocol/rpc.js +35 -3
  55. package/dist/push/socketio.js +2 -2
  56. package/dist/relations-store.js +38 -4
  57. package/dist/siege-store.js +49 -0
  58. package/dist/state-bundle.js +525 -0
  59. package/dist/state-cli.js +69 -0
  60. package/dist/surrender-pending.js +4 -4
  61. package/dist/team-cards.js +25 -0
  62. package/dist/tools/award.js +15 -1
  63. package/dist/tools/card-advice.js +16 -5
  64. package/dist/tools/card-plays.js +2 -2
  65. package/dist/tools/card-support-advice.js +2 -1
  66. package/dist/tools/chat-inbox.js +36 -3
  67. package/dist/tools/chat-read-mark.js +3 -1
  68. package/dist/tools/chat.js +65 -6
  69. package/dist/tools/check-plan.js +54 -10
  70. package/dist/tools/commerce-deploy.js +33 -0
  71. package/dist/tools/common.js +31 -0
  72. package/dist/tools/end-of-game.js +5 -3
  73. package/dist/tools/index.js +7 -0
  74. package/dist/tools/my-games.js +10 -3
  75. package/dist/tools/notifications.js +2 -2
  76. package/dist/tools/picks.js +12 -0
  77. package/dist/tools/profile-opponents.js +2 -0
  78. package/dist/tools/push.js +2 -1
  79. package/dist/tools/relations.js +137 -0
  80. package/dist/tools/state.js +227 -0
  81. package/dist/tools/stress-opponents.js +5 -2
  82. package/dist/tools/surrender-pending.js +11 -6
  83. package/dist/tools/survival.js +11 -3
  84. package/dist/tools/team-brief.js +2 -2
  85. package/dist/tools/team.js +12 -3
  86. package/dist/tools/turn.js +332 -60
  87. package/dist/version.js +1 -1
  88. package/manifest.json +10 -2
  89. package/mint.yaml +14 -4
  90. package/package.json +4 -4
  91. package/server.json +2 -2
  92. package/skills/warapp-mcp/SKILL.md +31 -9
@@ -0,0 +1,133 @@
1
+ import { lateArrivals } from './holds.js';
2
+ /** What a held bonus's border lacks to hold once every order is planned (#215: the worse move order). */
3
+ function shortAt(pc, ps, threats, hd, id) {
4
+ const b = threats.borderAt(id, (x) => ps.captured.has(x));
5
+ if (!b)
6
+ return 0;
7
+ const need = Math.max(0, threats.holdArmies(b.threat) - pc.unitsAt(id));
8
+ return Math.max(0, need - (hd.stayAt(id) - lateArrivals(pc, ps, id)));
9
+ }
10
+ export function fundFromSecondSizing(pc, ps, book, threats, hd, caps) {
11
+ if (pc.noSplit || book.local)
12
+ return;
13
+ const { label, bonusName, territories: state, defenceAt, costAt, chanceOf } = pc;
14
+ const { moves, combined, deployed, avail, rationale, warnings } = ps;
15
+ const { worstCase, strikes } = caps;
16
+ // ---- the attacks each sized for their owner's whole deploy, by owner ----
17
+ const byOwner = new Map();
18
+ for (const m of moves) {
19
+ if (m.kind !== 'attack' || combined.has(m.to) || strikes.has(m.to))
20
+ continue;
21
+ const st = state.get(m.to);
22
+ if (st?.owner.kind !== 'player')
23
+ continue;
24
+ const extra = threats.reinforcementAt(m.to);
25
+ const d = defenceAt(m.to);
26
+ const full = costAt(m.to, d + extra);
27
+ if (extra <= 0 || full === null || m.armies < full || (worstCase.get(m.to) ?? 0) < d + extra)
28
+ continue;
29
+ const list = byOwner.get(st.owner.playerId) ?? [];
30
+ list.push(m);
31
+ byOwner.set(st.owner.playerId, list);
32
+ }
33
+ /** Each attack that may give armies up, with what it may give and the one that keeps its size. */
34
+ const spare = new Map();
35
+ const keepOf = new Map();
36
+ const ownerOf = (m) => state.get(m.to).owner.playerId;
37
+ /** What each source's deploy still has to give (two attacks from one source share it). */
38
+ const deployLeft = new Map();
39
+ for (const [owner, list] of [...byOwner].sort((a, b) => a[0] - b[0])) {
40
+ if (list.length < 2)
41
+ continue;
42
+ const keep = [...list].sort((a, b) => b.armies - a.armies || moves.indexOf(a) - moves.indexOf(b))[0];
43
+ keepOf.set(owner, keep);
44
+ for (const m of list) {
45
+ if (m === keep)
46
+ continue;
47
+ const bare = costAt(m.to, defenceAt(m.to));
48
+ if (bare === null)
49
+ continue;
50
+ const free = deployLeft.get(m.from) ?? deployed.get(m.from) ?? 0;
51
+ const room = Math.min(m.armies - bare, free);
52
+ if (room <= 0)
53
+ continue;
54
+ deployLeft.set(m.from, free - room);
55
+ spare.set(m, { room, owner, extra: threats.reinforcementAt(m.to) });
56
+ }
57
+ }
58
+ if (!spare.size)
59
+ return;
60
+ // ---- the held bonuses those armies make hold, most valuable first ----
61
+ const units = [...hd.units].sort((a, b) => b.value - a.value || a.bonusId - b.bonusId);
62
+ for (const u of units) {
63
+ if (u.value <= 0)
64
+ continue;
65
+ const ids = u.members.map((m) => m.id);
66
+ // A border an order leaves (a withdrawal, an attack out) is not one this restores.
67
+ if (moves.some((mv) => ids.includes(mv.from) && (mv.armies > 0 || mv.commander)))
68
+ continue;
69
+ const short = new Map(ids.map((id) => [id, shortAt(pc, ps, threats, hd, id)]));
70
+ const need = [...short.values()].reduce((n, x) => n + x, 0);
71
+ const pool = [...spare.values()].reduce((n, x) => n + x.room, 0);
72
+ if (need <= 0 || need > pool || need > pc.paybackTurns * u.value)
73
+ continue;
74
+ // Take it from the attacks with the most to give first (ties: the later order).
75
+ const takes = [];
76
+ let left = need;
77
+ for (const [m, x] of [...spare].sort((a, b) => b[1].room - a[1].room || moves.indexOf(b[0]) - moves.indexOf(a[0]))) {
78
+ if (left <= 0)
79
+ break;
80
+ const n = Math.min(left, x.room);
81
+ left -= n;
82
+ x.room -= n;
83
+ if (x.room <= 0)
84
+ spare.delete(m);
85
+ takes.push({ m, n, before: m.armies });
86
+ m.armies -= n;
87
+ avail.set(m.from, avail.get(m.from) + n);
88
+ book.undeploy(m.from, n);
89
+ const d = defenceAt(m.to);
90
+ m.winChance = chanceOf(m.armies, d);
91
+ if (ps.survivorsAt.has(m.to))
92
+ ps.survivorsAt.set(m.to, ps.survivorsAt.get(m.to) - n);
93
+ // What its owner could still deploy there first and lose it to this attack.
94
+ let covered = 0;
95
+ while (covered < x.extra && (costAt(m.to, d + covered + 1) ?? Infinity) <= m.armies)
96
+ covered++;
97
+ worstCase.set(m.to, d + covered);
98
+ }
99
+ const given = [];
100
+ for (const id of [...ids].sort((a, b) => a - b)) {
101
+ const n = short.get(id);
102
+ if (n > 0) {
103
+ book.deploy(id, n);
104
+ given.push(`${n} to ${label(id)}`);
105
+ }
106
+ ps.locked.add(id);
107
+ hd.heldBorders.add(id);
108
+ if (!hd.conceded.delete(id))
109
+ continue;
110
+ const conceding = `${label(id)} cannot be held `;
111
+ for (let i = warnings.length - 1; i >= 0; i--)
112
+ if (warnings[i].startsWith(conceding) && warnings[i].endsWith(': conceded'))
113
+ warnings.splice(i, 1);
114
+ }
115
+ u.conceded = false;
116
+ u.contested = false;
117
+ const conceding = `conceding bonus ${bonusName(u.bonusId)} (+${u.value}):`;
118
+ for (let i = warnings.length - 1; i >= 0; i--)
119
+ if (warnings[i].startsWith(conceding))
120
+ warnings.splice(i, 1);
121
+ const from = takes
122
+ .map(({ m, n, before }) => `${n} from the attack on ${label(m.to)} from ${label(m.from)} (${before} down to ${m.armies}: still sure against the ${defenceAt(m.to)} there now, and against up to ${worstCase.get(m.to) - defenceAt(m.to)} deployed there first)`)
123
+ .join(' and ');
124
+ const kept = [...new Map(takes.map(({ m }) => [ownerOf(m), m])).keys()]
125
+ .sort((a, b) => a - b)
126
+ .map((o) => {
127
+ const keep = keepOf.get(o);
128
+ return `player ${o}'s ~${threats.reinforcementAt(keep.to)} deploy reinforces one of its targets, not two, and the attack on ${label(keep.to)} keeps its size for it`;
129
+ })
130
+ .join('; ');
131
+ rationale.push(`Fund held bonus ${bonusName(u.bonusId)} (+${u.value}) (#277): deploy ${given.join(', ')} so each of its borders holds, ${from}. ${kept[0].toUpperCase()}${kept.slice(1)}.`);
132
+ }
133
+ }
@@ -1,3 +1,4 @@
1
+ import { commerceRules } from '../../commerce.js';
1
2
  import { bonusTerritories } from '../bonuses.js';
2
3
  import { armiesForChance, armiesToTake, DEFAULT_DEFENSIVE_KILL_RATE, DEFAULT_OFFENSIVE_KILL_RATE, fewestAttackersToKill, fewestAttackersToTake, luckFraction, specialUnitStrength, straightKills, } from '../combat.js';
3
4
  import { neighborsOf } from '../graph.js';
@@ -11,6 +12,11 @@ export const PAYBACK_TURNS = 10;
11
12
  * next turn, and a border may still be retaken or the stack turned elsewhere.
12
13
  */
13
14
  export const BREACH_WEIGHT = 0.5;
15
+ /**
16
+ * #291: the share of what a gate's loss opens (`opensBehind`: held bonuses every route from an enemy or the fog
17
+ * reaches only through it) that its protected value counts — the enemy still has to walk in, as with a breach.
18
+ */
19
+ export const OPENS_WEIGHT = 0.5;
14
20
  /** #201: the shortest payback horizon once the game is decided. */
15
21
  export const DECIDED_PAYBACK_MIN = 3;
16
22
  /** …or when one remaining territory alone costs more than this many times its value (a wasteland). */
@@ -42,16 +48,12 @@ export const TRACKED_MIN_TURNS = 2;
42
48
  export const PRIOR_EVIDENCE_TURNS = 4;
43
49
  /**
44
50
  * #294: an opponent's tracked income was read from less than this share of its frontier
45
- * ({@link frontierCoverage}, over its income window): it is read as low, and the estimate never
46
- * falls below the tracked figure × {@link LOW_COVERAGE_FACTOR}. Unmeasured.
51
+ * ({@link frontierCoverage}, over its income window): the evidence is thin. #368 (owner decision of
52
+ * 2026-11-19): the estimate is then the midpoint of its range, moved toward the tracked figure as the
53
+ * coverage nears this share ({@link EnemyDeployEstimate.thinEvidence}); it replaced #294's floor of the
54
+ * tracked figure × 1.5. Unmeasured.
47
55
  */
48
56
  export const LOW_COVERAGE = 0.5;
49
- /**
50
- * #294: while coverage is under {@link LOW_COVERAGE}, the estimate is at least the tracked figure ×
51
- * this (at most what it could earn). Unmeasured: the play session's long fogged games tracked a half
52
- * to a quarter of the income later seen, so 1.5 is a cautious floor, not a correction.
53
- */
54
- export const LOW_COVERAGE_FACTOR = 1.5;
55
57
  /** Fog reveals named in the observed-deploy rationale before "and N more". */
56
58
  export const MAX_NAMED_REVEALS = 6;
57
59
  /**
@@ -625,6 +627,9 @@ export function repulsedAttacks(g, boards, me, rates = {}) {
625
627
  const armies = failedAttackMoves(g, was.board, now.board, me, p, orders)
626
628
  .filter((m) => m.to === t)
627
629
  .reduce((n, m) => n + Math.max(0, m.armies), 0);
630
+ // #361: a single-army jab never tries to take it (one army takes no defended territory): no evidence.
631
+ if (armies <= 1)
632
+ continue;
628
633
  const attack = { turn: was.turn, armies, before: b, after: a, kills };
629
634
  const key = `${t}:${p}`;
630
635
  const entry = found.get(key);
@@ -1056,6 +1061,22 @@ export function openingArmies(g, board, when = {}) {
1056
1061
  counts.add(t.armies);
1057
1062
  return counts.size === 1 ? [...counts][0] : null;
1058
1063
  }
1064
+ /**
1065
+ * #368: an opponent's tracked figure as of each of its last three consecutive observed turns — the most
1066
+ * it was seen to earn (`earned`) over that turn and the two before it, the tracker's max-observed window —
1067
+ * when it rose on both steps; else `null` (fewer than three consecutive turns, or a step not a rise).
1068
+ */
1069
+ export function risingTracked(turns) {
1070
+ const n = turns.length;
1071
+ if (n < 3)
1072
+ return null;
1073
+ for (let i = n - 2; i < n; i++)
1074
+ if (turns[i].from !== turns[i - 1].from + 1)
1075
+ return null;
1076
+ const asOf = (i) => Math.max(...turns.slice(Math.max(0, i - 2), i + 1).map((x) => x.earned));
1077
+ const series = [asOf(n - 3), asOf(n - 2), asOf(n - 1)];
1078
+ return series[0] < series[1] && series[1] < series[2] ? series : null;
1079
+ }
1059
1080
  /**
1060
1081
  * Per-opponent enemy deploy estimates, one per visible enemy player (sorted by
1061
1082
  * id): base income plus the bonuses that player visibly holds in full, never
@@ -1249,15 +1270,43 @@ export function enemyDeployEstimates(g, board, me, settings = {}, previous, trac
1249
1270
  // a card (or armies the board misread), never income.
1250
1271
  const exact = ownersAll && !opening ? Math.max(0, base + bonusIncome) : null;
1251
1272
  const source = exact !== null ? 'exact' : priorUsed !== null && priorUsed > seen ? 'prior' : seenSource;
1252
- // #294: what its tracked figure was read from; while that is little, the estimate never falls below
1253
- // the tracked figure × LOW_COVERAGE_FACTOR (the fog hid most of where it deploys).
1273
+ // #294: what its tracked figure was read from (#368: while that is little, thin evidence below).
1254
1274
  const coverage = usable ? trackCoverage(usable.turns.filter((x) => usable.incomeTurns.includes(x.from))) : null;
1255
1275
  const chosen = source === 'exact' ? exact : source === 'prior' ? priorUsed : seen;
1256
- const lowFloor = source !== 'exact' && tracked !== null && tracked > visible && coverage !== null && coverage.share < LOW_COVERAGE
1257
- ? Math.min(couldEarn, Math.ceil(tracked * LOW_COVERAGE_FACTOR - 1e-9))
1258
- : null;
1259
- const coverageFloor = lowFloor !== null && lowFloor > chosen ? { tracked: tracked, share: coverage.share, factor: LOW_COVERAGE_FACTOR, figure: lowFloor } : null;
1260
- const income = coverageFloor ? coverageFloor.figure : chosen;
1276
+ // #368 (owner decision of 2026-11-19: on a hidden opponent, choose the middle until we learn
1277
+ // otherwise): thin evidence — its tracked figure read from under LOW_COVERAGE of its frontier —
1278
+ // sizes it for the midpoint between the lower bound (what is in view or tracked, raised to the
1279
+ // trend's next step when its tracked figure rose two turns running) and the upper bound (the fog
1280
+ // prior whole, else the most it could earn), moved toward what the evidence gives as the coverage
1281
+ // nears LOW_COVERAGE. A rising track read from more of its frontier only raises the estimate to that
1282
+ // lower bound. Never the maximum.
1283
+ let thinEvidence = null;
1284
+ if (source !== 'exact' && usable && tracked !== null) {
1285
+ const rising = risingTracked(usable.turns);
1286
+ const thinCoverage = coverage !== null && coverage.share < LOW_COVERAGE;
1287
+ if (thinCoverage || rising) {
1288
+ const trend = rising ? Math.min(couldEarn, rising[2] + Math.ceil((rising[2] - rising[0]) / 2 - 1e-9)) : null;
1289
+ const lower = Math.min(couldEarn, Math.max(visible, tracked, trend ?? 0));
1290
+ const upper = Math.max(lower, Math.min(couldEarn, priorFigure ?? couldEarn));
1291
+ const midpoint = lower + Math.ceil((upper - lower) / 2 - 1e-9);
1292
+ // What the evidence gives without thin evidence (the track, or #235's prior shrunk toward it),
1293
+ // never below the lower bound: the figure meets it at LOW_COVERAGE, so it does not jump there.
1294
+ const toward = Math.min(couldEarn, Math.max(lower, chosen));
1295
+ const weight = thinCoverage ? Math.max(0, 1 - coverage.share / LOW_COVERAGE) : 0;
1296
+ const figure = toward + Math.ceil(weight * (midpoint - toward) - 1e-9);
1297
+ // Thin coverage: the figure replaces the estimate, up or down. A rising track alone: a raise only.
1298
+ if (thinCoverage || figure > chosen)
1299
+ thinEvidence = { coverage: coverage ? coverage.share : null, rising, tracked, prior: priorFigure, trend, lower, upper, midpoint, toward, weight, figure };
1300
+ }
1301
+ }
1302
+ const income = thinEvidence ? thinEvidence.figure : chosen;
1303
+ // #368: the figure thin evidence chose names its source: the prior when there is one and the figure
1304
+ // lies above the lower bound, else the track.
1305
+ const finalSource = thinEvidence
1306
+ ? thinEvidence.prior !== null && thinEvidence.figure > thinEvidence.lower
1307
+ ? 'prior'
1308
+ : 'tracked'
1309
+ : source;
1261
1310
  // #164: a Reinforcement card, from the turn the clock says one can be in hand, until a deployment
1262
1311
  // above its income is seen; the next card is due a card's capturing turns after the last one
1263
1312
  // (pieces carry over while a card is held), never before the turn after the play.
@@ -1319,10 +1368,10 @@ export function enemyDeployEstimates(g, board, me, settings = {}, previous, trac
1319
1368
  prior: priorFigure,
1320
1369
  priorBlend,
1321
1370
  coverage,
1322
- coverageFloor,
1323
1371
  priorCap,
1324
1372
  fogBeside,
1325
- source,
1373
+ source: finalSource,
1374
+ thinEvidence,
1326
1375
  exact,
1327
1376
  card,
1328
1377
  cardPlayed,
@@ -1370,10 +1419,21 @@ export function incomeFor(g, board, me, settings) {
1370
1419
  */
1371
1420
  export function visibleIncomeFor(g, board, player, settings) {
1372
1421
  const held = new Set();
1422
+ let cities = 0;
1373
1423
  for (const t of board.territories)
1374
- if (g.territoryById.has(t.territoryId) && t.owner.kind === 'player' && t.owner.playerId === player)
1424
+ if (g.territoryById.has(t.territoryId) && t.owner.kind === 'player' && t.owner.playerId === player) {
1375
1425
  held.add(t.territoryId);
1376
- return boardIncome(g, held, incomeRules(settings)).total;
1426
+ cities += t.cities ?? 0;
1427
+ }
1428
+ return boardIncome(g, held, incomeRules(settings)).total + cityGold(cities, settings);
1429
+ }
1430
+ /**
1431
+ * #332: the gold a commerce game's cities pay each turn (CityIncome each), part of the income like a bonus (the client's
1432
+ * income function adds it after base and bonuses, before the army cap). 0 outside a commerce game with city income.
1433
+ */
1434
+ export function cityGold(cities, settings) {
1435
+ const per = commerceRules(settings)?.cityIncome ?? 0;
1436
+ return cities > 0 && per > 0 ? cities * per : 0;
1377
1437
  }
1378
1438
  /**
1379
1439
  * {@link incomeFor} with the army cap's arithmetic: `cap` when the game has one and every territory
@@ -1386,16 +1446,18 @@ export function incomeDetail(g, board, me, settings) {
1386
1446
  const held = new Set();
1387
1447
  let armies = 0;
1388
1448
  let unread = false;
1449
+ let cities = 0;
1389
1450
  for (const t of board.territories) {
1390
1451
  if (!g.territoryById.has(t.territoryId) || t.owner.kind !== 'player' || t.owner.playerId !== me)
1391
1452
  continue;
1392
1453
  held.add(t.territoryId);
1454
+ cities += t.cities ?? 0;
1393
1455
  if (t.armies === null)
1394
1456
  unread = true;
1395
1457
  else
1396
1458
  armies += t.armies;
1397
1459
  }
1398
- const income = boardIncome(g, held, incomeRules(settings)).total;
1460
+ const income = boardIncome(g, held, incomeRules(settings)).total + cityGold(cities, settings);
1399
1461
  if (settings?.armyCap === undefined || settings.armyCap === null || !(settings.armyCap > 0))
1400
1462
  return { income };
1401
1463
  if (unread)
@@ -0,0 +1,303 @@
1
+ import { bonusTerritories } from '../bonuses.js';
2
+ import { neighborsOf } from '../graph.js';
3
+ import { captureCost, ownerShown, TRACKED_MIN_TURNS } from './shared.js';
4
+ /** A target's break is scored this many times a 1v1 break, so breaks outrank completions and advances. */
5
+ export const SIEGE_BREAK_WEIGHT = 3;
6
+ /** The assault is released once the target's income falls to this share of its baseline. */
7
+ export const SIEGE_INCOME_DROP = 0.6;
8
+ /** … or my income reaches this multiple of the target's. */
9
+ export const SIEGE_INCOME_LEAD = 1.8;
10
+ /**
11
+ * The enemy bonuses I could break: every territory visible and held by one enemy, or (#72) inferred
12
+ * behind the fog: its track (over at least TRACKED_MIN_TURNS observed turns) lists it in every
13
+ * combination of bonuses that fits the opponent's income gap (all of them listed), or in its single
14
+ * best fit (the first listed, with fewer bonuses than the next), and on this board every member is
15
+ * that opponent's or hidden. Such a break is "probable".
16
+ */
17
+ export function breakableBonuses(g, state, foe, tracks) {
18
+ const breakable = [];
19
+ for (const b of [...g.map.bonuses].sort((x, y) => x.id - y.id)) {
20
+ const ts = bonusTerritories(g, b.id);
21
+ if (b.value <= 0 || !ts.length)
22
+ continue;
23
+ const owners = new Set();
24
+ let visible = true;
25
+ for (const t of ts) {
26
+ const st = state.get(t);
27
+ if (st?.owner.kind !== 'player' || !foe(st.owner.playerId) || st.armies === null)
28
+ visible = false;
29
+ else
30
+ owners.add(st.owner.playerId);
31
+ }
32
+ if (visible && owners.size === 1) {
33
+ breakable.push({ bonusId: b.id, value: b.value, player: [...owners][0] });
34
+ continue;
35
+ }
36
+ // Inferred (#72): one opponent's visible members, the rest hidden, and its track fits it.
37
+ if (owners.size !== 1)
38
+ continue;
39
+ const player = [...owners][0];
40
+ const hiddenOrTheirs = ts.every((t) => {
41
+ const st = ownerShown(state.get(t));
42
+ return st === undefined || (st.owner.kind === 'player' && st.owner.playerId === player);
43
+ });
44
+ if (!hiddenOrTheirs)
45
+ continue;
46
+ const tr = tracks?.find((x) => x.playerId === player);
47
+ const fits = tr && tr.income !== null && tr.turns.length >= TRACKED_MIN_TURNS ? tr.inferred?.candidates : undefined;
48
+ if (!fits?.length)
49
+ continue;
50
+ // "Every" only when the tracker listed every fit (no "and N more"). The best fit must be
51
+ // strictly smaller than the next: equal-sized fits are ordered only by bonus id.
52
+ const more = tr.inferred.more;
53
+ const inEvery = more === 0 && fits.every((c) => c.bonusIds.includes(b.id));
54
+ const single = fits.length === 1 && more === 0;
55
+ const inBest = fits[0].bonusIds.includes(b.id) && (single || (fits[1] !== undefined && fits[0].bonusIds.length < fits[1].bonusIds.length));
56
+ if (!inEvery && !inBest)
57
+ continue;
58
+ breakable.push({
59
+ bonusId: b.id,
60
+ value: b.value,
61
+ player,
62
+ probable: inEvery ? 'in every combination of bonuses that fits its income gap' : 'in the best fit of its income gap',
63
+ });
64
+ }
65
+ return breakable;
66
+ }
67
+ /** A siege whose newest kept turn is more than this many turns old is over: a new one starts. */
68
+ export const SIEGE_MEMORY_GAP = 3;
69
+ /** Turns a siege's memory keeps (the newest). */
70
+ export const MAX_SIEGE_TURNS = 100;
71
+ /**
72
+ * The turns of the siege on `target` before `turn` that `memory` keeps, oldest first: none when the
73
+ * memory is another target's, the turn is unknown, or its newest turn before this one is more than
74
+ * {@link SIEGE_MEMORY_GAP} turns back (that siege lapsed).
75
+ */
76
+ export function priorSiegeTurns(memory, target, turn) {
77
+ if (!memory || memory.target !== target || turn === undefined)
78
+ return [];
79
+ const before = memory.turns.filter((t) => t.turn < turn).sort((a, b) => a.turn - b.turn);
80
+ const newest = before[before.length - 1];
81
+ return newest && turn - newest.turn <= SIEGE_MEMORY_GAP ? before : [];
82
+ }
83
+ /** The memory to keep after planning `turn`: this turn's record after the earlier turns of the same siege. */
84
+ export function rememberSiegeTurn(memory, turn, r) {
85
+ const record = { turn, opponentIncome: r.opponentIncome, myIncome: r.myIncome, breaks: r.brokenThisTurn.map((b) => b.bonusId) };
86
+ return { target: r.target, turns: [...priorSiegeTurns(memory, r.target, turn), record].slice(-MAX_SIEGE_TURNS) };
87
+ }
88
+ export const SIEGE_NOTE = "The baseline is the larger of the most the tracker saw the target deploy over its window of recent boards and its income on the siege's first turn (kept per game by warapp_plan_turn while the siege runs; a gap of more than 3 turns starts a new one). A bonus counts as broken on a turn when that turn's plan took one of its members, as planned, not as the board later showed.";
89
+ const round2 = (v) => Math.round(v * 100) / 100;
90
+ /**
91
+ * The siege of this turn, or a reason it cannot run. `target`: the caller's (`siegeTarget`), else
92
+ * the strongest opponent in contact (by income; ties to the lower id).
93
+ */
94
+ export function siegeOf(o) {
95
+ const { g, state, mineAtStart, foe } = o;
96
+ const guard = o.settings.oneArmyStandsGuard === false ? 0 : 1;
97
+ const ownerOf = (t) => {
98
+ const st = state.get(t);
99
+ return st?.owner.kind === 'player' ? st.owner.playerId : undefined;
100
+ };
101
+ const inContact = new Set();
102
+ for (const x of mineAtStart)
103
+ for (const n of neighborsOf(g, x)) {
104
+ const p = ownerOf(n);
105
+ if (p !== undefined && foe(p))
106
+ inContact.add(p);
107
+ }
108
+ let target = o.target;
109
+ if (target !== undefined) {
110
+ if (!foe(target))
111
+ return { warning: `siege_target ${target} is not an opponent of mine still on the board (me, a teammate or a player at peace): no siege this turn, the plan is balanced.` };
112
+ if (![...state.values()].some((st) => st.owner.kind === 'player' && st.owner.playerId === target))
113
+ return { warning: `siege_target ${target} holds no territory in view: no siege this turn, the plan is balanced.` };
114
+ }
115
+ else {
116
+ target = [...inContact].sort((a, b) => o.incomeOfPlayer(b) - o.incomeOfPlayer(a) || a - b)[0];
117
+ if (target === undefined)
118
+ return { warning: 'goal siege: no opponent borders my territories, so there is no one to besiege: the plan is balanced.' };
119
+ }
120
+ const p = target;
121
+ const opponentIncome = Math.max(0, o.incomeOfPlayer(p));
122
+ const tr = o.tracks?.find((t) => t.playerId === p);
123
+ const observed = (tr?.turns ?? []).filter((t) => !tr?.incomeTurns.length || tr.incomeTurns.includes(t.from)).map((t) => t.observed);
124
+ const earlier = priorSiegeTurns(o.memory, p, o.turn);
125
+ const tracked = Math.max(0, ...observed);
126
+ const start = earlier[0]?.opponentIncome ?? 0;
127
+ const baseline = Math.max(opponentIncome, tracked, start);
128
+ const baselineFrom = baseline === opponentIncome ? 'now' : start > tracked ? 'siege-start' : 'tracked';
129
+ const fallenTo = baseline > 0 ? round2(opponentIncome / baseline) : null;
130
+ const ratio = opponentIncome > 0 ? round2(o.myIncome / opponentIncome) : null;
131
+ const breakable = breakableBonuses(g, state, foe, o.tracks).filter((b) => b.player === p);
132
+ const breakMembers = new Set(breakable.flatMap((b) => bonusTerritories(g, b.bonusId)));
133
+ const armiesAt = (t) => state.get(t)?.armies ?? null;
134
+ /** The cheapest capture of a visible member next to mine, at its defenders as they stand (`null`: none in reach). */
135
+ const cheapest = (bonusId) => {
136
+ const costs = bonusTerritories(g, bonusId).flatMap((t) => {
137
+ const a = armiesAt(t);
138
+ if (a === null || ownerOf(t) !== p || !neighborsOf(g, t).some((n) => mineAtStart.has(n)))
139
+ return [];
140
+ const c = captureCost(a, o.settings);
141
+ return c === null ? [] : [c];
142
+ });
143
+ return costs.length ? Math.min(...costs) : null;
144
+ };
145
+ const breaks = breakable
146
+ .map((b) => ({ bonusId: b.bonusId, value: b.value, cost: cheapest(b.bonusId), ...(b.probable ? { probable: true } : {}) }))
147
+ .sort((a, b) => (a.cost ?? Infinity) / a.value - (b.cost ?? Infinity) / b.value || a.bonusId - b.bonusId);
148
+ // The core strike: one stack of mine takes a member of a bonus the target holds in full (every
149
+ // member in view, so the break is sure) against its defenders plus the target's whole deploy.
150
+ let core;
151
+ for (const b of breakable.filter((x) => !x.probable).sort((x, y) => y.value - x.value || x.bonusId - y.bonusId)) {
152
+ for (const t of [...bonusTerritories(g, b.bonusId)].sort((x, y) => x - y)) {
153
+ const a = armiesAt(t);
154
+ if (a === null)
155
+ continue;
156
+ const need = captureCost(a + o.deployOf(p), o.settings);
157
+ if (need === null)
158
+ continue;
159
+ for (const x of neighborsOf(g, t).filter((n) => mineAtStart.has(n)).sort((m, n) => m - n)) {
160
+ const send = Math.max(0, (armiesAt(x) ?? 0) - guard);
161
+ if (send >= need && (!core || send - need > core.send - core.need))
162
+ core = { from: x, to: t, bonusId: b.bonusId, send, need };
163
+ }
164
+ }
165
+ if (core)
166
+ break;
167
+ }
168
+ const fell = (observed.length > 0 || earlier.length > 0) && baseline > 0 && opponentIncome <= SIEGE_INCOME_DROP * baseline;
169
+ const lead = opponentIncome === 0 ? o.myIncome > 0 : o.myIncome >= SIEGE_INCOME_LEAD * opponentIncome;
170
+ const trigger = fell ? 'income-fell' : lead ? 'income-lead' : core ? 'core-strike' : null;
171
+ return {
172
+ siege: {
173
+ target: p,
174
+ opponentIncome,
175
+ baseline,
176
+ baselineTurns: observed.length,
177
+ baselineFrom,
178
+ myIncome: o.myIncome,
179
+ ratio,
180
+ fallenTo,
181
+ breaks,
182
+ ready: trigger !== null,
183
+ trigger,
184
+ ...(core ? { core } : {}),
185
+ breakMembers,
186
+ rivals: [...inContact].filter((x) => x !== p).sort((a, b) => a - b).map((x) => ({ player: x, income: Math.max(0, o.incomeOfPlayer(x)) })),
187
+ ...(o.turn !== undefined ? { turn: o.turn } : {}),
188
+ earlier,
189
+ },
190
+ };
191
+ }
192
+ // ---- The profile's siege (#382 item 2) ----
193
+ /** A sure break fits a siege when it costs at most this many turns of the income it takes away. */
194
+ export const SIEGE_FIT_TURNS = 2;
195
+ /** … one turn only when the target retook that bonus on this many earlier siege turns or more. */
196
+ export const SIEGE_RETAKEN_TURNS = 2;
197
+ /** In a free-for-all the target must earn this multiple of every other opponent in contact with me. */
198
+ export const SIEGE_FFA_DOMINANCE = 1.5;
199
+ /**
200
+ * Whether the profile picks the siege (no explicit goal; #382). It fits when, against the siege's target:
201
+ * - the format is a 1v1 or a free-for-all (a team game focuses its fire by `teams-focus`), in contact
202
+ * (phase `contact` or `late`);
203
+ * - I am not ahead (ahead, the assault and the 1v1 pressure rules play; an unknown standing is no fit);
204
+ * - in a free-for-all the target is the leader on strength (not me) and earns at least
205
+ * {@link SIEGE_FFA_DOMINANCE} × every other opponent in contact with me (one war, not two fronts);
206
+ * - a sure break (every member in view, a member next to mine) costs at most {@link SIEGE_FIT_TURNS} turns of
207
+ * its bonus — one when the target retook it on {@link SIEGE_RETAKEN_TURNS} earlier siege turns — and at most
208
+ * my income, so one turn's deploys can pay for a break every turn (a siege that cannot afford its breaks only
209
+ * holds the assault back: corpus case 921, where it idled a 23-army stack beside a sure capture).
210
+ * Once the assault trigger fires the siege hands back (`handBack`): the profile's own goal plays the assault.
211
+ */
212
+ export function siegeFit(s, o) {
213
+ if (o.format === 'teams' || (o.phase !== 'contact' && o.phase !== 'late'))
214
+ return { fits: false };
215
+ if (o.standing !== 'even' && o.standing !== 'behind')
216
+ return { fits: false };
217
+ if (o.format === 'ffa' && (o.leader !== s.target || s.rivals.some((r) => r.income * SIEGE_FFA_DOMINANCE > s.opponentIncome)))
218
+ return { fits: false };
219
+ const retakes = (b) => s.earlier.filter((t) => t.breaks.includes(b)).length;
220
+ const fits = s.breaks.flatMap((b) => {
221
+ if (b.probable || b.cost === null)
222
+ return [];
223
+ const retaken = retakes(b.bonusId) >= SIEGE_RETAKEN_TURNS;
224
+ const turns = retaken ? 1 : SIEGE_FIT_TURNS;
225
+ return b.cost <= turns * b.value && b.cost <= s.myIncome ? [{ bonusId: b.bonusId, value: b.value, cost: b.cost, turns, retaken }] : [];
226
+ });
227
+ if (!fits.length)
228
+ return { fits: false };
229
+ if (s.ready)
230
+ return { fits: false, handBack: s.trigger };
231
+ return { fits: true, fit: fits[0] };
232
+ }
233
+ /** The line that says why the profile chose the siege. */
234
+ export function siegeFitLine(s, bonusName) {
235
+ const f = s.auto;
236
+ if (!f)
237
+ return undefined;
238
+ return `The profile chose the siege on player ${s.target} (#382): in contact, not ahead, ${s.rivals.length ? `every other opponent beside me earning at most 1/${SIEGE_FFA_DOMINANCE} of its income, ` : ''}and ${bonusName(f.bonusId)} (+${f.value}) for ${f.cost} breaks within ${f.turns} turn${f.turns === 1 ? '' : 's'} of its income${f.retaken ? ` (counted one turn: retaken after ${SIEGE_RETAKEN_TURNS} earlier breaks)` : ''}. Breaking it costs less than it takes away, so attrition beats an assault until the trigger fires; an explicit goal overrides it.`;
239
+ }
240
+ /** The rationale lines a siege adds (first in the plan's rationale). */
241
+ export function siegeLines(s, label, bonusName) {
242
+ const ratio = s.ratio === null ? 'it earns nothing' : `my ${s.myIncome} is ${s.ratio}× its income`;
243
+ const fell = s.baselineFrom === 'siege-start'
244
+ ? `its income ~${s.opponentIncome} against a baseline of ~${s.baseline} (${s.fallenTo === null ? '—' : `${Math.round(s.fallenTo * 100)}%`}, its income on turn ${s.earlier[0].turn}, when the siege began)`
245
+ : s.baselineTurns > 0
246
+ ? `its income ~${s.opponentIncome} against a baseline of ~${s.baseline} (${s.fallenTo === null ? '—' : `${Math.round(s.fallenTo * 100)}%`}, the most seen over ${s.baselineTurns} tracked turn${s.baselineTurns === 1 ? '' : 's'})`
247
+ : `its income ~${s.opponentIncome} (no tracked turns yet, so no baseline to fall from)`;
248
+ const so = s.earlier.length ? `; siege turn ${s.earlier.length + 1} (since turn ${s.earlier[0].turn}): its income ${[...s.earlier.map((t) => t.opponentIncome), s.opponentIncome].join(' → ')}` : '';
249
+ const head = `Siege on player ${s.target} (#382): ${fell}; ${ratio}${so}.`;
250
+ const breaks = s.breaks.length
251
+ ? `Its bonuses to break, cheapest per income lost first: ${s.breaks
252
+ .map((b) => `${bonusName(b.bonusId)} (+${b.value}${b.cost === null ? ', no member in reach' : `, ${b.cost} to take a member as it stands`}${b.probable ? ', probable' : ''})`)
253
+ .join('; ')}. Each break is sized for its defenders plus the deploy player ${s.target} may put there first where the armies allow (#120).`
254
+ : `No bonus of player ${s.target} is breakable in view this turn.`;
255
+ const state = !s.ready
256
+ ? `Assault held: player ${s.target}'s income has not fallen to ${Math.round(SIEGE_INCOME_DROP * 100)}% of its baseline, mine is not ${SIEGE_INCOME_LEAD}× its, and no stack of mine can take a member of its held bonuses against its whole deploy; only its bonus members are attacked, and the spare deploys build one strike stack facing it.`
257
+ : s.trigger === 'income-fell'
258
+ ? `Assault released: player ${s.target}'s income fell to ${Math.round((s.fallenTo ?? 0) * 100)}% of its baseline (at most ${Math.round(SIEGE_INCOME_DROP * 100)}%); the strike stack strikes.`
259
+ : s.trigger === 'income-lead'
260
+ ? `Assault released: my income is ${s.ratio ?? '∞'}× player ${s.target}'s (at least ${SIEGE_INCOME_LEAD}×); the strike stack strikes.`
261
+ : `Assault released: ${label(s.core.from)} can send ${s.core.send} to take ${label(s.core.to)} of ${bonusName(s.core.bonusId)} (${s.core.need} take it even after player ${s.target}'s whole deploy there); the strike stack strikes.`;
262
+ return [head, breaks, state];
263
+ }
264
+ /** The report of a siege once the plan's captures are known. */
265
+ export function siegeReport(s, g, captured, bonusName) {
266
+ const brokenThisTurn = s.breaks
267
+ .filter((b) => bonusTerritories(g, b.bonusId).some((t) => captured.has(t)))
268
+ .map((b) => ({ bonusId: b.bonusId, value: b.value }));
269
+ let memory;
270
+ if (s.turn !== undefined) {
271
+ const turns = [...s.earlier.map((t) => ({ turn: t.turn, breaks: t.breaks, income: t.opponentIncome })), { turn: s.turn, breaks: brokenThisTurn.map((b) => b.bonusId), income: s.opponentIncome }];
272
+ const broken = new Map();
273
+ for (const t of turns)
274
+ for (const b of t.breaks)
275
+ broken.set(b, [...(broken.get(b) ?? []), t.turn]);
276
+ const list = [...broken].sort(([a], [b]) => a - b).map(([bonusId, ts]) => ({ bonusId, turns: ts }));
277
+ memory = {
278
+ startedTurn: turns[0].turn,
279
+ turns: turns.length,
280
+ startIncome: turns[0].income,
281
+ opponentIncomeTrend: turns.map((t) => ({ turn: t.turn, income: t.income })),
282
+ broken: list,
283
+ rebroken: list.filter((b) => b.turns.length > 1).map((b) => b.bonusId),
284
+ };
285
+ }
286
+ return {
287
+ target: s.target,
288
+ opponentIncome: s.opponentIncome,
289
+ baseline: s.baseline,
290
+ baselineTurns: s.baselineTurns,
291
+ baselineFrom: s.baselineFrom,
292
+ myIncome: s.myIncome,
293
+ ratio: s.ratio,
294
+ fallenTo: s.fallenTo,
295
+ ...(memory ? { memory } : {}),
296
+ ...(s.auto ? { auto: siegeFitLine(s, bonusName ?? ((b) => `bonus ${b}`)) } : {}),
297
+ brokenThisTurn,
298
+ breaks: s.breaks,
299
+ ready: s.ready,
300
+ trigger: s.trigger,
301
+ note: SIEGE_NOTE,
302
+ };
303
+ }
@@ -330,7 +330,7 @@ export function neverStandStill(pc, ps, book, threats, hd, tgt, caps) {
330
330
  const { growthOf, facing } = threats;
331
331
  const { conceded } = hd;
332
332
  const { targets, bonusTarget, targetScoreCost, toFinish, plans, finishCost, sizeOf } = tgt;
333
- const { stopped, outgrows } = caps;
333
+ const { stopped, outgrows, gateStop } = caps;
334
334
  /**
335
335
  * #125: the step rule 4e ranked first and could not afford this turn (its size, nothing else):
336
336
  * the leftover saves toward it (rule 5) and idle stacks stage toward it (rule 6).
@@ -376,6 +376,9 @@ export function neverStandStill(pc, ps, book, threats, hd, tgt, caps) {
376
376
  // B2 (T1): never a truce's covered territory.
377
377
  if (pc.truce.noTarget(t))
378
378
  continue;
379
+ // #298: nor a missing member of a bonus dropped after repeated failed attempts.
380
+ if (tgt.droppedMembers.has(t))
381
+ continue;
379
382
  // An enemy commander is rule 1s's, sized for its owner's full deploy: never a fallback.
380
383
  if (unitsAt(t) > 0)
381
384
  continue;
@@ -612,8 +615,9 @@ export function neverStandStill(pc, ps, book, threats, hd, tgt, caps) {
612
615
  failed.set(st.t, { kind: 'hold', ...short });
613
616
  continue;
614
617
  }
615
- // #114: in contact rule 4d is a cost (ranked above), not a veto.
616
- const stop = contact ? null : outgrows(st.t);
618
+ // #114: in contact rule 4d is a cost (ranked above), not a veto — except the 1v1 gate budget (#297):
619
+ // a gate the next income cannot hold is lost next turn, armies and all.
620
+ const stop = contact ? gateStop(st.t) : outgrows(st.t);
617
621
  if (stop === null) {
618
622
  taken = pick;
619
623
  break;
@@ -1,3 +1,11 @@
1
+ // What one planning pass (`planPass` in planner.ts) works from and what it builds (#133).
2
+ //
3
+ // `PlanCtx` is read-only: the inputs and everything derived from them before the first order is
4
+ // planned (the estimates phase, plan/estimates.ts) — the graph, the board, the settings, the kill
5
+ // rates and combat model, the opponents' deploy estimates, the game profile and the goal it picks.
6
+ // `PlanState` is what the phases share and change: the warnings and rationale, and the orders the
7
+ // plan has made so far. A phase moved out of planner.ts takes `(ctx, state)` explicitly instead of
8
+ // closing over planPass's locals; planPass still names each field as the local it was.
1
9
  /** PLAN-TEAMS C3: a territory a teammate visibly holds (never one in a no-team game). */
2
10
  export function teammateAt(pc, id) {
3
11
  if (!pc.allies.size)