@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
@@ -159,8 +159,15 @@ export function observeTurn(input) {
159
159
  sent.some((m) => ownsWas(m.to) && !m.transferOnly && sentCount(m) > plain(m));
160
160
  // attackedMe
161
161
  let attackedMe = tookFromMe?.length ? true : null;
162
- if (attackedMe === null && orders && !airliftUnknown) {
162
+ // #361: the borders read whose drop is exactly what one attacking army kills (a single-army jab);
163
+ // `null` unless combat is exact and at least one border was read.
164
+ let jabs = null;
165
+ if (orders && !airliftUnknown) {
163
166
  let tested = false;
167
+ let dropped = false;
168
+ let read = 0;
169
+ let jabbed = 0;
170
+ const oneKill = straightKills(1, off);
164
171
  for (const id of ids) {
165
172
  if (untested.has(id))
166
173
  continue;
@@ -190,9 +197,12 @@ export function observeTurn(input) {
190
197
  if (transfersIn.some((m) => enemiesNext(m.from).size > 0 || !allShown(m.from)))
191
198
  continue;
192
199
  const expected = a.armies + (deploys.get(id) ?? 0) - sum(outOf(id)) + sum(transfersIn);
200
+ read++;
193
201
  if (b.armies < expected) {
194
- attackedMe = true;
195
- break;
202
+ dropped = true;
203
+ if (oneKill >= 1 && expected - b.armies === oneKill)
204
+ jabbed++;
205
+ continue;
196
206
  }
197
207
  // A move out that did not surely land (a failed attack, a transfer that met a territory taken
198
208
  // first, or a move into a territory another order of mine also entered, which may have been
@@ -206,9 +216,13 @@ export function observeTurn(input) {
206
216
  if (!drained && !chainedIn && !outOf(id).some((m) => m.armies > 0 && !landed(m)))
207
217
  tested = true;
208
218
  }
219
+ if (attackedMe === null && dropped)
220
+ attackedMe = true;
209
221
  // A quiet border is a "no" only when captures can be told too (a capture elsewhere would be a yes).
210
222
  if (attackedMe === null && tested && tookFromMe !== null)
211
223
  attackedMe = false;
224
+ if (exact && read > 0)
225
+ jabs = jabbed;
212
226
  }
213
227
  // reinforce
214
228
  const reinforce = { n: 0, e: 0, extra: 0 };
@@ -279,6 +293,36 @@ export function observeTurn(input) {
279
293
  }
280
294
  }
281
295
  }
296
+ // #295: my biggest stack facing it, and whether its territories facing that stack were raised past
297
+ // what the stack's movable armies plus my income (my deploys this turn) could take.
298
+ let topUp = null;
299
+ if (orders && !airliftUnknown) {
300
+ let s = null;
301
+ for (const id of ids) {
302
+ const a = seen(was.get(id));
303
+ if (a?.owner !== me || !neighborsOf(graph, id).some((n) => seen(was.get(n))?.owner === p))
304
+ continue;
305
+ if (!s || a.armies > s.armies)
306
+ s = { id, armies: a.armies };
307
+ }
308
+ const facing = s ? neighborsOf(graph, s.id).filter((n) => ownsWas(n)) : [];
309
+ const readable = (x) => seen(was.get(x))?.owner === p &&
310
+ seen(now.get(x))?.owner === p &&
311
+ !untested.has(x) &&
312
+ !into(x).length &&
313
+ !sent.some((m) => m.to === x) &&
314
+ specialUnitStrength(visibleState(was.get(x))?.specialUnits) === 0 &&
315
+ specialUnitStrength(visibleState(now.get(x))?.specialUnits) === 0;
316
+ if (s && facing.length && facing.every(readable)) {
317
+ const capacity = Math.max(0, s.armies - guard) + sum(orders.deploys);
318
+ const takeable = (d) => {
319
+ const need = armiesToTake(d, { offensiveKillRate: off, defensiveKillRate: def });
320
+ return need !== null && need <= capacity;
321
+ };
322
+ if (facing.some((x) => takeable(seen(was.get(x)).armies)))
323
+ topUp = !facing.some((x) => takeable(seen(now.get(x)).armies));
324
+ }
325
+ }
282
326
  // stack
283
327
  let top = 0;
284
328
  let total = 0;
@@ -294,11 +338,11 @@ export function observeTurn(input) {
294
338
  top = Math.max(top, g);
295
339
  }
296
340
  const stack = both >= 2 && total >= 1 ? { top, total } : null;
297
- result.set(p, { contact, attackedMe, iAttacked, reinforce, stack, tookFromMe, lostToMe });
341
+ result.set(p, { contact, attackedMe, iAttacked, reinforce, stack, tookFromMe, lostToMe, jabs, topUp });
298
342
  }
299
343
  return result;
300
344
  }
301
- export const HABIT_NAMES = ['reinforce', 'attack', 'firstStrike', 'stacking', 'retaliate', 'retake'];
345
+ export const HABIT_NAMES = ['reinforce', 'attack', 'firstStrike', 'stacking', 'retaliate', 'retake', 'jab', 'capacityTopUp'];
302
346
  /**
303
347
  * The habits of one opponent from its observed turns (any order; each turn once). Habits that span
304
348
  * turns are recomputed from the whole list, so re-deriving never double-counts:
@@ -311,7 +355,11 @@ export const HABIT_NAMES = ['reinforce', 'attack', 'firstStrike', 'stacking', 'r
311
355
  * - `retaliate`: turns I attacked it, an event when it attacked me on one of the next two turns;
312
356
  * counted only when both are observed and told, or one says it did;
313
357
  * - `retake`: territories I took from it, an event when it took them back within two turns;
314
- * counted only when both turns are observed with their captures told, or it did.
358
+ * counted only when both turns are observed with their captures told, or it did;
359
+ * - `jab` (#361): turns in contact whose borders could be read for a single-army jab (exact combat), an
360
+ * event when one was;
361
+ * - `capacityTopUp` (#295): turns it had the chance to raise the territories facing my biggest stack past
362
+ * what that stack plus my income could take, an event when it did.
315
363
  */
316
364
  export function habitsOf(turns) {
317
365
  const by = new Map();
@@ -326,6 +374,8 @@ export function habitsOf(turns) {
326
374
  stacking: { n: 0, sum: 0, sq: 0 },
327
375
  retaliate: { e: 0, n: 0 },
328
376
  retake: { e: 0, n: 0 },
377
+ jab: { e: 0, n: 0 },
378
+ capacityTopUp: { e: 0, n: 0 },
329
379
  turns: order.length,
330
380
  };
331
381
  /** Whether either of the next two turns says yes (`true`), both say no (`false`), or it cannot be told (`null`). */
@@ -353,6 +403,10 @@ export function habitsOf(turns) {
353
403
  h.reinforceExtra.sum += p.reinforce.extra;
354
404
  if (p.contact && p.attackedMe !== null)
355
405
  count(h.attack, p.attackedMe);
406
+ if (p.contact && p.jabs != null)
407
+ count(h.jab, p.jabs > 0);
408
+ if (p.topUp != null)
409
+ count(h.capacityTopUp, p.topUp);
356
410
  if (p.stack && p.stack.total > 0) {
357
411
  const share = p.stack.top / p.stack.total;
358
412
  h.stacking.n++;
@@ -394,6 +448,8 @@ export const HABIT_DEFAULTS = {
394
448
  stacking: 0.7,
395
449
  retaliate: 0.5,
396
450
  retake: 0.4,
451
+ jab: 0.1,
452
+ capacityTopUp: 0.3,
397
453
  };
398
454
  /**
399
455
  * The least opportunities (readings, for a size) a population pool needs for one habit before its
@@ -421,6 +477,8 @@ export function emptyHabits() {
421
477
  stacking: { n: 0, sum: 0, sq: 0 },
422
478
  retaliate: { e: 0, n: 0 },
423
479
  retake: { e: 0, n: 0 },
480
+ jab: { e: 0, n: 0 },
481
+ capacityTopUp: { e: 0, n: 0 },
424
482
  turns: 0,
425
483
  };
426
484
  }
@@ -440,6 +498,8 @@ export function addHabits(a, b, scale = 1) {
440
498
  stacking: { n: tidy(a.stacking.n + scale * b.stacking.n), sum: tidy(a.stacking.sum + scale * b.stacking.sum), sq: tidy(a.stacking.sq + scale * b.stacking.sq) },
441
499
  retaliate: rate(a.retaliate, b.retaliate),
442
500
  retake: rate(a.retake, b.retake),
501
+ jab: rate(a.jab, b.jab),
502
+ capacityTopUp: rate(a.capacityTopUp, b.capacityTopUp),
443
503
  turns: tidy(a.turns + scale * b.turns),
444
504
  };
445
505
  }
@@ -494,9 +554,11 @@ export function estimateHabits(h, priors = {}) {
494
554
  stacking: blend(size(h), size(past), s.p0, s.from, PROFILE_PRIOR_WEIGHT, priors.pastHistory ? size(priors.pastHistory) : undefined),
495
555
  retaliate: rate('retaliate'),
496
556
  retake: rate('retake'),
557
+ jab: rate('jab'),
558
+ capacityTopUp: rate('capacityTopUp'),
497
559
  };
498
560
  }
499
- export const PROFILE_LABELS = ['reinforcer', 'rarely-reinforces', 'stacker', 'spreader', 'rusher', 'turtle', 'avenger', 'retakes'];
561
+ export const PROFILE_LABELS = ['reinforcer', 'rarely-reinforces', 'stacker', 'spreader', 'rusher', 'turtle', 'avenger', 'retakes', 'jabber', 'tops-up'];
500
562
  /** One fixed counter-play line per label the plan gives one (docs/PLAN-PROFILES.md B1; `spreader` has none). */
501
563
  export const COUNTER_PLAY = {
502
564
  reinforcer: 'Attack two of its territories in one turn (it deploys on one), or size for its deploy.',
@@ -506,6 +568,8 @@ export const COUNTER_PLAY = {
506
568
  turtle: 'Out-expand it; a quiet border with it tends to stay quiet.',
507
569
  avenger: 'Do not poke; strike only to cripple, and garrison the source.',
508
570
  retakes: 'A capture from it needs a garrison that survives its counter.',
571
+ jabber: 'It jabs a border with one army a turn (one for one at 0% luck): keep an army above the hold there to refill.',
572
+ 'tops-up': 'It raises the territory facing your biggest stack past what that stack plus your income can take: strike where it is not looking, or build past it first.',
509
573
  };
510
574
  /** Turns back from the one being played within which an attack on me withholds `turtle` (#264). */
511
575
  export const TURTLE_QUIET_TURNS = 2;
@@ -548,5 +612,9 @@ export function labelsOf(e, recent = {}) {
548
612
  out.push('avenger');
549
613
  if (sure(e.retake) && e.retake.value >= 0.6)
550
614
  out.push('retakes');
615
+ if (sure(e.jab) && e.jab.value >= 0.5)
616
+ out.push('jabber');
617
+ if (sure(e.capacityTopUp) && e.capacityTopUp.value >= 0.6)
618
+ out.push('tops-up');
551
619
  return out;
552
620
  }
@@ -4,7 +4,7 @@ import { neutralizeSeats, staticSeats } from './static-seats.js';
4
4
  import { bonusTerritories } from './bonuses.js';
5
5
  import { DEFAULT_DEFENSIVE_KILL_RATE, DEFAULT_OFFENSIVE_KILL_RATE, straightKills } from './combat.js';
6
6
  import { bfsDistances, neighborsOf } from './graph.js';
7
- import { bombPossibleOn, enemyDeployEstimates, failedAttackKills, frontierCoverage, holdLosses, localFreeOn, observeSigned, ownerShown, repelledFloor, coverageText, LOW_COVERAGE, LOW_COVERAGE_FACTOR, TRACKED_MIN_TURNS, trackCoverage, visibleState, } from './planner.js';
7
+ import { bombPossibleOn, enemyDeployEstimates, failedAttackKills, frontierCoverage, holdLosses, localFreeOn, observeSigned, ownerShown, repelledFloor, coverageText, LOW_COVERAGE, TRACKED_MIN_TURNS, trackCoverage, visibleState, } from './planner.js';
8
8
  import { boardIncome, DEFAULT_BASE_INCOME } from './player.js';
9
9
  /** #164: a stack is large when its armies are at least this many turns of its visible income. */
10
10
  const LOST_STACK_INCOMES = 2;
@@ -1222,7 +1222,7 @@ export function trackOpponents(g, boards, me, settings = {}, game) {
1222
1222
  // #294: what its income was read from.
1223
1223
  const covered = estimate ? trackCoverage(incomeWindow) : null;
1224
1224
  if (covered && covered.share < 1)
1225
- notes.push(`Income read from ${coverageText(covered)}: the rest of where it can deploy was out of view, so the figure is a lower bound${covered.share < LOW_COVERAGE && income > visibleIncome && observed.length >= TRACKED_MIN_TURNS ? `, and the planner keeps at least ${LOW_COVERAGE_FACTOR} × it` : ''}.`);
1225
+ notes.push(`Income read from ${coverageText(covered)}: the rest of where it can deploy was out of view, so the figure is a lower bound${covered.share < LOW_COVERAGE && observed.length >= TRACKED_MIN_TURNS ? `, and the planner sizes it toward the midpoint between it and the most it could have (#368)` : ''}.`);
1226
1226
  notes.push(...warnings);
1227
1227
  return {
1228
1228
  playerId,
@@ -567,6 +567,30 @@ export function gameOutlook(input) {
567
567
  opponents: evidenceRows,
568
568
  thin: evidenceRows.some((r) => r.thin),
569
569
  };
570
+ // #368: the bonuses my side held in full on the board before and does not now.
571
+ const bonusesLost = prev
572
+ ? (() => {
573
+ const side = new Set([me, ...mates]);
574
+ const sideHeld = (b) => {
575
+ const ts = new Set();
576
+ for (const x of b.territories)
577
+ if (g.territoryById.has(x.territoryId) && x.owner.kind === 'player' && side.has(x.owner.playerId))
578
+ ts.add(x.territoryId);
579
+ return ts;
580
+ };
581
+ const before = sideHeld(prev);
582
+ const now = sideHeld(board);
583
+ const lost = [];
584
+ for (const bonus of [...g.bonusById.values()].sort((a, b) => a.id - b.id)) {
585
+ if (bonus.value <= 0)
586
+ continue;
587
+ const ts = bonusTerritories(g, bonus.id);
588
+ if (ts.length && ts.every((t) => before.has(t)) && !ts.every((t) => now.has(t)))
589
+ lost.push(bonus.id);
590
+ }
591
+ return lost;
592
+ })()
593
+ : [];
570
594
  const state = bound || estimated
571
595
  ? 'winning'
572
596
  : lostOnBound || lostOnEstimate
@@ -588,6 +612,7 @@ export function gameOutlook(input) {
588
612
  ...(estimated || lostOnEstimate ? { estimated: true } : {}),
589
613
  ...(lowLikely ? { lowLikely: { myIncome: myNow, mostTracked: mostTracked(), groundDown, losing: lostOnEstimate } } : {}),
590
614
  evidence,
615
+ ...(bonusesLost.length ? { bonusesLost } : {}),
591
616
  };
592
617
  });
593
618
  const last = turns.at(-1);
@@ -595,6 +620,17 @@ export function gameOutlook(input) {
595
620
  for (let i = turns.length - 1; i >= 0 && turns[i].state === last?.state; i--)
596
621
  heldTurns++;
597
622
  const state = last && heldTurns >= OUTLOOK_TURNS ? last.state : null;
623
+ // #368: even for OUTLOOK_TURNS turns running while a bonus of mine fell on each: leaning behind.
624
+ const leaning = state === 'even' && turns.length >= OUTLOOK_TURNS && turns.every((t) => t.bonusesLost?.length)
625
+ ? {
626
+ toward: 'behind',
627
+ turns: turns.length,
628
+ lost: turns.map((t) => ({
629
+ turn: t.turn,
630
+ value: t.bonusesLost.reduce((n, id) => n + Math.max(0, input.graph.bonusById.get(id)?.value ?? 0), 0),
631
+ })),
632
+ }
633
+ : undefined;
598
634
  const measure = teamGame
599
635
  ? `Strength = armies + ${k} × income; an opponent's is a range under fog (low: what is in view; high: the most it could have received and earn). By team: my team's strength (mine and my teammates' still playing) against the strongest enemy team's, each the sum of its players'; summed, a teammate's transfers stay inside its team's high.`
600
636
  : `Strength = armies + ${k} × income; an opponent's is a range under fog (low: what is in view; high: the most it could have received and earn). Per player: my strength alone against the single strongest opponent, teams not summed.`;
@@ -663,6 +699,8 @@ export function gameOutlook(input) {
663
699
  ? ` Losing on the estimate: ${share}, corroborated by ${[low.groundDown ? 'the main front grinding me down on the incomes read off my boards' : '', behind ? incomeText : ''].filter(Boolean).join(' and ')}.`
664
700
  : ` ${share[0].toUpperCase()}${share.slice(1)}, but that alone is no loss: the likely high counts every army an opponent could have received at ${LIKELY_INCOME_MARGIN}× its pace and none it lost, so it reads every fogged opponent strong. Losing on it needs the main front grinding me down on the incomes read off my boards (not the plan's, so the plan acts on the state shown) or my income at most ${BEHIND_RATIO}× the most an opponent is tracked earning${low.mostTracked > 0 ? ` (mine ${low.myIncome}, the most tracked ${low.mostTracked})` : ' (none is tracked)'}.`;
665
701
  }
702
+ if (leaning)
703
+ reading += ` Leaning behind: even for ${leaning.turns} turns running while I lost bonuses on each (${leaning.lost.map((x) => `turn ${x.turn} +${x.value}`).join(', ')}): the strength ratio lags a slide the board already shows, so read "even" as falling behind.`;
666
704
  // #228: the plan's profile standing is a different measure (incomes, then the armies in view).
667
705
  const standing = input.standing;
668
706
  if ((last.state === 'even' || last.state === 'stalemate') && (standing === 'ahead' || standing === 'behind'))
@@ -691,5 +729,6 @@ export function gameOutlook(input) {
691
729
  threshold: OUTLOOK_RATIO,
692
730
  basis: `${reading} ${measure} ${thresholdsText}`,
693
731
  ...(last?.evidence ? { evidence: last.evidence } : {}),
732
+ ...(leaning ? { leaning } : {}),
694
733
  };
695
734
  }
@@ -106,7 +106,12 @@
106
106
  // Otherwise in a 1v1 (a primary of one pick, or of five or more), among the equally
107
107
  // scored compact fallbacks found at its hop limit, the one farthest from the primary
108
108
  // (fewest hops between the two groups, maximised) wins, so one counter-pick cannot reach
109
- // both. A fallback that still outscores the primary is warned about. A list longer than
109
+ // both. #289: a first fallback tier of the primary's size that is one compact cluster
110
+ // and, scored alone as the primary is (nothing taken), beats it becomes the primary (the
111
+ // seeded greedy search missed it), once; the fallback is then built again. A fallback that
112
+ // still outscores the primary (its score is with the primary taken) is warned about, and the
113
+ // warning says why the primary stays first: an answering tier is granted whole only if every
114
+ // primary pick is lost, a spread one breaks the one-cluster rule. A list longer than
110
115
  // twice the limit (war.app's client allows players × territories per player,
111
116
  // `clientPickLimits`) runs in fallback tiers of the primary's size, each built as a group
112
117
  // with the primary and the earlier tiers taken; the fallback group's score, bonuses
@@ -1121,7 +1126,7 @@ function planCore(input, friendlyIds = []) {
1121
1126
  if (pickable.length < limit)
1122
1127
  warnings.push(`Only ${pickable.length} pickable territor${pickable.length === 1 ? 'y' : 'ies'} for a limit of ${limit}: the list has no full fallback.`);
1123
1128
  const primary = buildGroup(firstView, pickable, primarySize, 'primary');
1124
- const rest = pickable.filter((t) => !primary.includes(t));
1129
+ let rest = pickable.filter((t) => !primary.includes(t));
1125
1130
  // Commanders (#129): the first pick awarded carries the commander, so the primary's safest
1126
1131
  // pick goes first — the fewest other pickable territories (where other players may start)
1127
1132
  // within COMPACT_DISTANCE hops, then the fewest neighbours outside the primary, then score.
@@ -1301,6 +1306,33 @@ function planCore(input, friendlyIds = []) {
1301
1306
  maxHops: Number.isFinite(far) ? far : null,
1302
1307
  };
1303
1308
  };
1309
+ // #289: the fallback is scored with the primary taken, so its group score and the primary's
1310
+ // are on one footing only when both are scored alone. A first tier of the primary's size
1311
+ // that is one compact cluster and, scored alone, beats the primary is a better group the
1312
+ // seeded search missed (greedy growth from its seeds reached into the primary): it becomes
1313
+ // the primary, and the fallback is built again for it. Once only.
1314
+ let promoted = null;
1315
+ {
1316
+ const tier = listed.tiers[0] ?? [];
1317
+ const was = round2(simScore(primary, []));
1318
+ const now = round2(simScore(tier, []));
1319
+ if (!spread && tier.length > 1 && tier.length === primary.length && spreadOf(tier).link <= COMPACT_DISTANCE && now > was) {
1320
+ const byFirst = (a, b) => firstView.of.get(b).score - firstView.of.get(a).score || a - b;
1321
+ primary.splice(0, primary.length, ...[...tier].sort(byFirst));
1322
+ rest = pickable.filter((t) => !primary.includes(t));
1323
+ if (relaxedTo.delete('primary')) {
1324
+ for (let i = warnings.length - 1; i >= 0; i--)
1325
+ if (warnings[i].startsWith('No compact primary group'))
1326
+ warnings.splice(i, 1);
1327
+ }
1328
+ if (s.commanders) {
1329
+ ({ pick: commanderPick, exposure: commanderExposure } = safestOf(primary));
1330
+ primary.splice(0, primary.length, commanderPick, ...primary.filter((t) => t !== commanderPick));
1331
+ }
1332
+ listed = buildFallback(primary);
1333
+ promoted = { was, now };
1334
+ }
1335
+ }
1304
1336
  // The award order (#129): a list is judged by the sets it can actually yield. The worst
1305
1337
  // outcome is scored with the other players holding the picks it implies they took; the
1306
1338
  // primary's order is changed only when another order raises that worst outcome.
@@ -1464,16 +1496,33 @@ function planCore(input, friendlyIds = []) {
1464
1496
  primary: groupOf(primary, NO_TAKEN),
1465
1497
  fallback: { ...groupOf(firstTier, firstFallbackView.taken), territoryIds: fallback },
1466
1498
  };
1467
- if (groups.fallback.score > groups.primary.score)
1468
- warnings.push(`The fallback group scores more than the primary (${groups.fallback.score} vs ${groups.primary.score}): the primary keeps to ` +
1469
- (players > 2
1470
- ? `one compact cluster, since with ${players} players spread picks are likely contested.`
1471
- : spread
1472
- ? `within ${SPREAD_DISTANCE} hops unless spreading scores ${SPREAD_RELAX_GAIN}× as much.`
1473
- : answerSets
1474
- ? 'one compact cluster, so the start has one front; each fallback pick is listed for the outcomes in which a pick above it is lost.'
1475
- : 'one compact cluster, so the start has one front; the fallback covers a counter-pick.') +
1476
- ' Weigh the trade before submitting.');
1499
+ if (promoted)
1500
+ rationale.push(`The seeded search's primary scored ${promoted.was}; the first fallback group, one compact cluster of as many picks, ` +
1501
+ `scores ${promoted.now} on the same footing (each alone, nothing taken), so it is the primary now and the fallback was built again for it (#289).`);
1502
+ if (groups.fallback.score > groups.primary.score) {
1503
+ // #289: say why the primary still ranks first. The fallback's score is with the primary
1504
+ // taken (it is granted only then); a compact tier that beat the primary alone was promoted
1505
+ // above, so what is left is a fallback the primary's rules keep out of first place.
1506
+ const alone = round2(simScore(firstTier, []));
1507
+ const link = spreadOf(firstTier).link;
1508
+ const tierCompact = link <= COMPACT_DISTANCE;
1509
+ const steps = Number.isFinite(link) ? `${link} hops` : 'any distance (some are not connected)';
1510
+ const reason = answerSets
1511
+ ? 'the primary is one compact cluster, so the start has one front; each fallback pick is chosen for the outcomes in which a pick above it is lost, ' +
1512
+ 'and the fallback picks are granted together only if every primary pick is lost' +
1513
+ (tierCompact ? '' : ` (nor are they one cluster: they link up only in steps of up to ${steps})`) +
1514
+ ', so its joint score is not a start this list can choose'
1515
+ : spread
1516
+ ? `the primary keeps within ${SPREAD_DISTANCE} hops unless spreading scores ${SPREAD_RELAX_GAIN}× as much`
1517
+ : !tierCompact
1518
+ ? `the fallback is not one compact cluster (its picks link up only in steps of up to ${steps}) and the primary keeps to one, ` +
1519
+ (players > 2
1520
+ ? `since with ${players} players spread picks are likely contested`
1521
+ : 'so the start has one front; the fallback covers a counter-pick')
1522
+ : `scored alone, as the primary is, the fallback makes ${alone}, not more than the primary: the gap comes from scoring it with the primary taken`;
1523
+ warnings.push(`The fallback group scores more than the primary (${groups.fallback.score} vs ${groups.primary.score}; the fallback is scored with the primary taken, ` +
1524
+ `since it is granted only then, and makes ${alone} alone). The primary stays first: ${reason}. Weigh the trade before submitting.`);
1525
+ }
1477
1526
  if (commanderPick !== null)
1478
1527
  rationale.push(`Commanders are on: the first pick awarded carries the commander, so the primary's safest pick (${terrName(commanderPick)}: ` +
1479
1528
  `fewest other pickable territories within ${COMPACT_DISTANCE} hops) is listed first; if another player takes it, the next pick awarded carries it.`);
@@ -1544,6 +1593,8 @@ function planCore(input, friendlyIds = []) {
1544
1593
  picks,
1545
1594
  groups,
1546
1595
  ...(award ? { award } : {}),
1596
+ // #305: report only, never scored.
1597
+ side: mapSides(g, groups.primary.territoryIds, award?.worst.opponentStarts ?? []),
1547
1598
  coverage: primaryCoverage,
1548
1599
  ...(alternative ? { alternative } : {}),
1549
1600
  warnings,
@@ -1789,6 +1840,34 @@ export function impliedOpponentStarts(list, granted) {
1789
1840
  });
1790
1841
  return list.slice(0, last + 1).filter((t) => !got.has(t));
1791
1842
  }
1843
+ export function mapSides(g, primary, opponentStarts) {
1844
+ const starts = [...opponentStarts].sort((a, b) => a - b);
1845
+ if (!starts.length || !primary.length)
1846
+ return {
1847
+ known: false,
1848
+ opponentStarts: starts,
1849
+ note: 'No opponent start is implied by the award of this list, so the map is not split into my side and the rest.',
1850
+ };
1851
+ const fromMe = bfsDistances(g, primary);
1852
+ const fromThem = bfsDistances(g, starts);
1853
+ const mine = { income: 0, bonuses: [] };
1854
+ const contested = { income: 0, bonuses: [] };
1855
+ for (const b of [...g.map.bonuses].sort((x, y) => x.id - y.id)) {
1856
+ if (b.value <= 0)
1857
+ continue;
1858
+ const members = bonusTerritories(g, b.id);
1859
+ if (!members.length)
1860
+ continue;
1861
+ const near = members.every((t) => {
1862
+ const d = fromMe.get(t);
1863
+ return d !== undefined && d < (fromThem.get(t) ?? Infinity);
1864
+ });
1865
+ const side = near ? mine : contested;
1866
+ side.bonuses.push({ id: b.id, name: b.name, value: b.value });
1867
+ side.income += b.value;
1868
+ }
1869
+ return { known: true, opponentStarts: starts, mine, contested };
1870
+ }
1792
1871
  /** Every ordering of `xs`, starting with `xs` itself (lexicographic by position). */
1793
1872
  function permutations(xs) {
1794
1873
  if (xs.length <= 1)
@@ -0,0 +1,105 @@
1
+ import { bonusTerritories } from '../bonuses.js';
2
+ /** #298: failed attempts on consecutive turns that end piecemeal funding. */
3
+ export const FAILED_ATTEMPTS = 2;
4
+ /** #298: an all-in push costs at most this many turns of the bonus's value (and at most my income). */
5
+ export const ALL_IN_VALUE_TURNS = 2;
6
+ /** #298: turns a dropped bonus is not funded, the turn it is dropped on included. */
7
+ export const DROP_TURNS = 3;
8
+ /** #298: attempts older than this many turns are forgotten. */
9
+ export const ATTEMPT_MEMORY_TURNS = 6;
10
+ const complete = (g, board, me, bonusId) => {
11
+ const ts = bonusTerritories(g, bonusId);
12
+ const at = new Map(board.territories.map((t) => [t.territoryId, t]));
13
+ return ts.length > 0 && ts.every((t) => {
14
+ const o = at.get(t)?.owner;
15
+ return o?.kind === 'player' && o.playerId === me;
16
+ });
17
+ };
18
+ /**
19
+ * The memory with the attempts made on `turn − 1` judged against `turn`'s board (`board`): failed when
20
+ * the bonus is not all mine. Idempotent: planning a turn again judges them the same way.
21
+ */
22
+ export function judgeAttempts(memory, turn, g, board, me) {
23
+ return {
24
+ bonuses: memory.bonuses.map((r) => ({
25
+ ...r,
26
+ attempts: r.attempts.map((a) => (a.turn === turn - 1 && a.failed === undefined ? { ...a, failed: !complete(g, board, me, r.bonusId) } : a)),
27
+ })),
28
+ };
29
+ }
30
+ /** The failed attempts that end on `turn − 1`, on consecutive turns, oldest first. */
31
+ function failedRun(r, turn) {
32
+ const byTurn = new Map(r.attempts.map((a) => [a.turn, a]));
33
+ const run = [];
34
+ for (let t = turn - 1; byTurn.get(t)?.failed === true; t--)
35
+ run.unshift(byTurn.get(t));
36
+ return run;
37
+ }
38
+ /**
39
+ * #298: each bonus the (judged) memory gives a verdict for on `turn`, by bonus id: still dropped (a drop
40
+ * made on an earlier turn running to this one); dropped now (last turn's all-in failed); or all-in (the
41
+ * last {@link FAILED_ATTEMPTS} turns' attempts failed, none of them all-in). A drop this turn's own
42
+ * earlier plan made is ignored, so planning a turn again decides it again.
43
+ */
44
+ export function bonusVerdicts(memory, turn) {
45
+ const out = [];
46
+ for (const r of [...(memory?.bonuses ?? [])].sort((a, b) => a.bonusId - b.bonusId)) {
47
+ const run = failedRun(r, turn);
48
+ const failedTurns = run.map((a) => a.turn);
49
+ if (r.drop && r.drop.from < turn && r.drop.until >= turn) {
50
+ out.push({ bonusId: r.bonusId, kind: 'dropped', why: 'still-dropped', from: r.drop.from, until: r.drop.until, failedTurns });
51
+ continue;
52
+ }
53
+ const last = run[run.length - 1];
54
+ if (last?.allIn) {
55
+ out.push({ bonusId: r.bonusId, kind: 'dropped', why: 'all-in-failed', from: turn, until: turn + DROP_TURNS - 1, failedTurns });
56
+ continue;
57
+ }
58
+ if (run.length >= FAILED_ATTEMPTS)
59
+ out.push({ bonusId: r.bonusId, kind: 'all-in', failedTurns: failedTurns.slice(-FAILED_ATTEMPTS) });
60
+ }
61
+ return out;
62
+ }
63
+ /**
64
+ * #298: the memory to keep after planning `turn` on `board` (the start of the turn): the attempts on
65
+ * `turn - 1` judged; this turn's attempts (every contested bonus the plan expects to complete,
66
+ * `completes`, the plan's `expected.bonusesCompleted`; all-in when `push` says so) in place of any an
67
+ * earlier plan of this turn recorded; this turn's drops from `push`; nothing older than
68
+ * {@link ATTEMPT_MEMORY_TURNS} turns. Only a completion is an attempt: a turn that only advances a bonus
69
+ * leaves it incomplete by design, and a capture that also steps into a larger bonus is no try at it.
70
+ */
71
+ export function rememberBonusAttempts(memory, turn, g, board, me, completes, push = []) {
72
+ const judged = judgeAttempts(memory ?? { bonuses: [] }, turn, g, board, me);
73
+ const at = new Map(board.territories.map((t) => [t.territoryId, t]));
74
+ const records = new Map();
75
+ for (const r of judged.bonuses) {
76
+ const drop = r.drop && r.drop.from !== turn ? r.drop : undefined;
77
+ records.set(r.bonusId, { bonusId: r.bonusId, attempts: r.attempts.filter((a) => a.turn !== turn), ...(drop ? { drop } : {}) });
78
+ }
79
+ const allIn = new Set(push.filter((p) => p.kind === 'all-in').map((p) => p.bonusId));
80
+ for (const id of [...new Set(completes)].sort((a, b) => a - b)) {
81
+ const b = g.bonusById.get(id);
82
+ if (!b || b.value <= 0)
83
+ continue;
84
+ const contested = bonusTerritories(g, id).some((t) => {
85
+ const o = at.get(t)?.owner;
86
+ return o?.kind === 'player' && o.playerId !== me;
87
+ });
88
+ if (!contested)
89
+ continue;
90
+ const r = records.get(id) ?? { bonusId: id, attempts: [] };
91
+ r.attempts = [...r.attempts, { turn, allIn: allIn.has(id) }].sort((x, y) => x.turn - y.turn);
92
+ records.set(id, r);
93
+ }
94
+ for (const p of push)
95
+ if (p.kind === 'dropped' && p.from === turn) {
96
+ const r = records.get(p.bonusId) ?? { bonusId: p.bonusId, attempts: [] };
97
+ r.drop = { from: p.from, until: p.until };
98
+ records.set(p.bonusId, r);
99
+ }
100
+ const bonuses = [...records.values()]
101
+ .map((r) => ({ ...r, attempts: r.attempts.filter((a) => a.turn > turn - ATTEMPT_MEMORY_TURNS) }))
102
+ .filter((r) => r.attempts.length || (r.drop && r.drop.until >= turn))
103
+ .sort((a, b) => a.bonusId - b.bonusId);
104
+ return { bonuses };
105
+ }
@@ -0,0 +1,116 @@
1
+ // #285: capture the one enemy stack a held bonus's borders face, rather than hold them against it.
2
+ // Rule 1h holds a contested held bonus whole from what the captures leave (#118). Live, two borders
3
+ // that faced only one enemy stack were held against it and its owner's deploy (41 deployed on one
4
+ // of them), while capturing the stack would have left both borders interior. Owner decisions of
5
+ // 2026-11-19: the capture is sized against the same deploy estimate the holds are sized against
6
+ // (#368's middle figure, through `reinforcementAt`: rule 3's #120 sizing, so it lands even if the
7
+ // owner deploys there first), and the hold it saves is credited for HOLD_CREDIT_TURNS turns, since
8
+ // a border that stops being one needs no hold on the turns after this one either.
9
+ // So, once the capture passes have run and before `settleContested` holds the contested units: for
10
+ // each enemy territory S beside a contested member still unheld, the members that border no enemy,
11
+ // fog or hidden territory but S (and face no threat once S falls) are its interior set. When the
12
+ // deploy that captures S from one of them (the one needing the least; it keeps what it still must
13
+ // hold, #172's two-step keep included) is at most HOLD_CREDIT_TURNS × the hold costs of that set,
14
+ // and the turn can fund it, S is captured from there and the set is held: rule 1h no longer deploys
15
+ // to it. Largest saving first, then id; repeated while one is taken. Not under No-Split (an order
16
+ // carries the whole stack), never from my commander's territory, never a truce's covered territory,
17
+ // a buffer left standing (#179), a territory with a special unit or one whose capture lowers income.
18
+ import { neighborsOf } from '../graph.js';
19
+ import { byNum } from './util.js';
20
+ /** #285 (owner decision of 2026-11-19): the turns a hold made unnecessary by a capture is credited for. */
21
+ export const HOLD_CREDIT_TURNS = 3;
22
+ export function captureInsteadOfHold(pc, ps, book, threats, hd, tgt, caps) {
23
+ const { g, foe, territories: state, label, mineSet, unitsAt, uncounted, defenceAt, costAt, myCommanders, noSplit } = pc;
24
+ const { avail, captured, spared, rationale } = ps;
25
+ const { units, heldBorders, conceded, keepFor, twoStepKeep } = hd;
26
+ const { borderAt, reinforcementAt } = threats;
27
+ const { targets } = tgt;
28
+ const { gainWith, spareAt, orderOf } = book;
29
+ if (noSplit)
30
+ return;
31
+ const tried = new Set();
32
+ for (;;) {
33
+ const members = [
34
+ ...new Set(units
35
+ .filter((u) => u.contested && !u.conceded)
36
+ .flatMap((u) => u.members.filter((m) => !heldBorders.has(m.id) && !conceded.has(m.id) && m.holdCost > 0))),
37
+ ].sort((a, b) => a.id - b.id);
38
+ if (!members.length)
39
+ return;
40
+ const foeOf = (n) => {
41
+ const o = state.get(n)?.owner;
42
+ return o?.kind === 'player' && foe(o.playerId) ? o.playerId : undefined;
43
+ };
44
+ /** Every neighbour of `x` but `s` is mine, captured, a neutral in view or a teammate's: no frontier left. */
45
+ const closedBut = (x, s) => neighborsOf(g, x).every((y) => {
46
+ if (y === s || mineSet.has(y) || captured.has(y))
47
+ return true;
48
+ const st = state.get(y);
49
+ if (!st || st.armies === null)
50
+ return false;
51
+ return st.owner.kind === 'neutral' || (st.owner.kind === 'player' && !foe(st.owner.playerId));
52
+ });
53
+ let best;
54
+ const seen = [...new Set(members.flatMap((m) => neighborsOf(g, m.id)))].sort(byNum);
55
+ for (const s of seen) {
56
+ const player = foeOf(s);
57
+ const st = state.get(s);
58
+ if (player === undefined || !st || st.armies === null)
59
+ continue;
60
+ if (tried.has(s) || captured.has(s) || spared.has(s) || pc.truce.noTarget(s) || uncounted(s) || unitsAt(s) > 0)
61
+ continue;
62
+ const gone = (n) => n === s;
63
+ const set = members.filter((m) => neighborsOf(g, m.id).includes(s) && closedBut(m.id, s) && !borderAt(m.id, (n) => captured.has(n) || gone(n)));
64
+ if (!set.length || gainWith([s]) < 0)
65
+ continue;
66
+ const d = defenceAt(s);
67
+ const extra = reinforcementAt(s);
68
+ const cost = costAt(s, d + extra);
69
+ if (cost === null)
70
+ continue;
71
+ const credit = HOLD_CREDIT_TURNS * set.reduce((n, m) => n + m.holdCost, 0);
72
+ const src = set
73
+ .filter((m) => !myCommanders.has(m.id) && !orderOf(m.id))
74
+ .map((m) => {
75
+ const keep = Math.max(keepFor(m.id, gone), twoStepKeep(m.id, gone));
76
+ return { id: m.id, keep, need: Math.max(0, cost - (avail.get(m.id) - keep)) };
77
+ })
78
+ .filter((o) => o.need <= spareAt(o.id))
79
+ .sort((a, b) => a.need - b.need || a.id - b.id)[0];
80
+ if (!src || src.need > credit)
81
+ continue;
82
+ const c = { s, src: src.id, keep: src.keep, need: src.need, cost, d, extra, set, credit };
83
+ if (!best || c.credit - c.need > best.credit - best.need)
84
+ best = c;
85
+ }
86
+ if (!best)
87
+ return;
88
+ const c = best;
89
+ tried.add(c.s);
90
+ const prev = targets.get(c.s);
91
+ targets.set(c.s, { id: c.s, cost: c.cost, enemy: true, sources: [c.src] });
92
+ const hadWorst = caps.worstCase.get(c.s);
93
+ caps.worstCase.set(c.s, c.d + c.extra);
94
+ const player = foeOf(c.s);
95
+ const names = c.set.map((m) => label(m.id)).join(', ');
96
+ const holds = c.set.reduce((n, m) => n + m.holdCost, 0);
97
+ const reason = `takes the one enemy stack beside ${names}, sure even if player ${player} deploys its ~${c.extra} there first (${c.d} + ${c.extra} defenders), so ${c.set.length === 1 ? 'that border needs' : 'those borders need'} no hold (#285)`;
98
+ if (!caps.tryCapture(c.s, reason, { from: c.src, keep: c.keep })) {
99
+ if (prev)
100
+ targets.set(c.s, prev);
101
+ else
102
+ targets.delete(c.s);
103
+ if (hadWorst === undefined)
104
+ caps.worstCase.delete(c.s);
105
+ else
106
+ caps.worstCase.set(c.s, hadWorst);
107
+ continue;
108
+ }
109
+ for (const m of c.set)
110
+ heldBorders.add(m.id);
111
+ for (const u of units)
112
+ if (u.contested && u.members.every((m) => heldBorders.has(m.id)))
113
+ u.contested = false;
114
+ rationale.push(`Take ${label(c.s)} from ${label(c.src)} rather than hold ${names}: a deploy of ${c.need} sends ${c.cost}, sure even if player ${player} deploys its ~${c.extra} there first, against the ${holds} the ${c.set.length === 1 ? 'hold' : 'holds'} would cost this turn (${c.credit} for ${HOLD_CREDIT_TURNS} turns); once it falls ${names} ${c.set.length === 1 ? 'borders' : 'border'} no enemy (#285).`);
115
+ }
116
+ }