@chrischall/warapp-mcp 0.1.0 → 0.3.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 (86) hide show
  1. package/.claude-plugin/marketplace.json +3 -3
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +49 -20
  4. package/dist/analysis/accept-surrender.js +56 -0
  5. package/dist/analysis/calibrate.js +239 -0
  6. package/dist/analysis/finished-game.js +136 -0
  7. package/dist/analysis/game-lessons.js +217 -0
  8. package/dist/analysis/local-deploy.js +37 -17
  9. package/dist/analysis/opponent-profile.js +6 -5
  10. package/dist/analysis/opponents.js +10 -2
  11. package/dist/analysis/outlook.js +63 -1
  12. package/dist/analysis/plan/shared.js +194 -7
  13. package/dist/analysis/plan/threats.js +103 -29
  14. package/dist/analysis/planner.js +10 -5
  15. package/dist/analysis/stress.js +14 -7
  16. package/dist/analysis/whereabouts.js +3 -0
  17. package/dist/bundle.js +13214 -9759
  18. package/dist/calibration-source.js +75 -0
  19. package/dist/chat.js +73 -0
  20. package/dist/client.js +85 -7
  21. package/dist/direct/link.js +9 -5
  22. package/dist/direct/session.js +60 -6
  23. package/dist/direct/sign-in.js +296 -0
  24. package/dist/direct/transport.js +59 -24
  25. package/dist/finished-store.js +357 -0
  26. package/dist/hosted.js +6 -4
  27. package/dist/index.js +1 -1
  28. package/dist/lessons-store.js +356 -0
  29. package/dist/live.js +9 -0
  30. package/dist/map-details.js +127 -0
  31. package/dist/map-stats.js +14 -6
  32. package/dist/map-store.js +44 -6
  33. package/dist/my-games.js +44 -6
  34. package/dist/normalize.js +34 -2
  35. package/dist/notifications.js +143 -0
  36. package/dist/outlook-log.js +28 -1
  37. package/dist/player-record-store.js +2 -0
  38. package/dist/profile-store.js +61 -11
  39. package/dist/protocol/methods.js +86 -2
  40. package/dist/replay.js +16 -4
  41. package/dist/stats.js +26 -4
  42. package/dist/strategy/notes.js +64 -9
  43. package/dist/surrender-pending.js +126 -0
  44. package/dist/tools/accept-surrender.js +311 -0
  45. package/dist/tools/chat-inbox.js +17 -5
  46. package/dist/tools/chat-read-mark.js +179 -0
  47. package/dist/tools/chat.js +50 -8
  48. package/dist/tools/check-plan.js +1 -0
  49. package/dist/tools/commander-check.js +1 -0
  50. package/dist/tools/end-of-game.js +384 -0
  51. package/dist/tools/game.js +31 -6
  52. package/dist/tools/healthcheck.js +7 -1
  53. package/dist/tools/index.js +24 -8
  54. package/dist/tools/join-game.js +1 -1
  55. package/dist/tools/live-context.js +3 -1
  56. package/dist/tools/map-details.js +88 -0
  57. package/dist/tools/map-stats.js +15 -2
  58. package/dist/tools/map.js +10 -2
  59. package/dist/tools/my-games.js +78 -8
  60. package/dist/tools/notifications.js +484 -0
  61. package/dist/tools/open-games.js +5 -2
  62. package/dist/tools/opponents.js +14 -2
  63. package/dist/tools/past-games.js +94 -0
  64. package/dist/tools/picks.js +15 -2
  65. package/dist/tools/profile-opponents.js +1 -1
  66. package/dist/tools/profile-reads.js +3 -3
  67. package/dist/tools/push.js +72 -12
  68. package/dist/tools/session.js +50 -18
  69. package/dist/tools/sign-in.js +56 -0
  70. package/dist/tools/strategy.js +65 -8
  71. package/dist/tools/stress-opponents.js +1 -1
  72. package/dist/tools/surrender-pending.js +74 -0
  73. package/dist/tools/surrender.js +10 -3
  74. package/dist/tools/team-brief.js +1 -1
  75. package/dist/tools/team.js +2 -6
  76. package/dist/tools/turn.js +79 -15
  77. package/dist/tools/where.js +42 -17
  78. package/dist/tools/write-kit.js +16 -3
  79. package/dist/trend.js +145 -20
  80. package/dist/version.js +1 -1
  81. package/docs/examples/warapp-auth-flow.json +31 -0
  82. package/manifest.json +22 -2
  83. package/mint.yaml +44 -22
  84. package/package.json +3 -2
  85. package/server.json +2 -2
  86. package/skills/warapp-mcp/SKILL.md +141 -14
@@ -453,9 +453,10 @@ export function estimate(events, n, p0, k = PROFILE_PRIOR_WEIGHT) {
453
453
  /**
454
454
  * `(p0 × K + e) ÷ (K + n)` with `e` and `n` this game's and the past's together. The basis is the
455
455
  * largest weight of this game's `n`, the past's `n` and the prior's K; the prior wins a tie, then
456
- * this game.
456
+ * this game. A past basis reads `history` when `fromHistory` (the part of the past folded from
457
+ * finished games' histories) holds at least half of the past's `n` (#312 E3); the value never changes.
457
458
  */
458
- function blend(game, past, p0, prior, k = PROFILE_PRIOR_WEIGHT) {
459
+ function blend(game, past, p0, prior, k = PROFILE_PRIOR_WEIGHT, fromHistory) {
459
460
  const e = game.e + past.e;
460
461
  const n = game.n + past.n;
461
462
  let basis = prior;
@@ -465,7 +466,7 @@ function blend(game, past, p0, prior, k = PROFILE_PRIOR_WEIGHT) {
465
466
  weight = game.n;
466
467
  }
467
468
  if (past.n > weight)
468
- basis = 'past-games';
469
+ basis = fromHistory && fromHistory.n > 0 && 2 * fromHistory.n >= past.n ? 'history' : 'past-games';
469
470
  return { value: round2((p0 * k + e) / (k + n)), n: round2(n), confidence: round2(n / (n + k)), basis };
470
471
  }
471
472
  /** Every habit's estimate from a game's counts, pooled with the past and shrunk toward the prior (B1). */
@@ -482,7 +483,7 @@ export function estimateHabits(h, priors = {}) {
482
483
  };
483
484
  const rate = (name) => {
484
485
  const p = prior(name, (x) => x[name]);
485
- return blend(h[name], past[name], p.p0, p.from);
486
+ return blend(h[name], past[name], p.p0, p.from, PROFILE_PRIOR_WEIGHT, priors.pastHistory?.[name]);
486
487
  };
487
488
  const size = (x) => ({ e: x.stacking.sum, n: x.stacking.n });
488
489
  const s = prior('stacking', size);
@@ -490,7 +491,7 @@ export function estimateHabits(h, priors = {}) {
490
491
  reinforce: rate('reinforce'),
491
492
  attack: rate('attack'),
492
493
  firstStrike: rate('firstStrike'),
493
- stacking: blend(size(h), size(past), s.p0, s.from),
494
+ stacking: blend(size(h), size(past), s.p0, s.from, PROFILE_PRIOR_WEIGHT, priors.pastHistory ? size(priors.pastHistory) : undefined),
494
495
  retaliate: rate('retaliate'),
495
496
  retake: rate('retake'),
496
497
  };
@@ -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, holdLosses, observeSigned, ownerShown, repelledFloor, visibleState, } from './planner.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';
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;
@@ -832,7 +832,7 @@ export function trackOpponents(g, boards, me, settings = {}, game) {
832
832
  // about its deploy (every stack would read as a reveal, or there is no estimate at all):
833
833
  // skip it with a note rather than observe 0 or throw (#83).
834
834
  const e = seesPlayer(before, g, playerId)
835
- ? enemyDeployEstimates(g, after, me, settings, before).find((x) => x.playerId === playerId)
835
+ ? enemyDeployEstimates(g, after, me, settings, before, undefined, undefined, { turn: to }).find((x) => x.playerId === playerId)
836
836
  : undefined;
837
837
  if (!e?.observation) {
838
838
  unseen.push(seesPlayer(before, g, playerId) ? to : from);
@@ -857,6 +857,8 @@ export function trackOpponents(g, boards, me, settings = {}, game) {
857
857
  guard,
858
858
  most: e.observedCap,
859
859
  ...(expected !== null ? { expected: Math.max(expected, carriedSoFar) } : {}),
860
+ // #293: the same Local Deployment reading the board-only observation used.
861
+ ...(settings.localDeployments ? { localFree: localFreeOn(e.base, DEFAULT_BASE_INCOME, settings.opponentReinforcement, from) } : {}),
860
862
  };
861
863
  const { signed, ...o } = expected !== null && carriedSoFar > expected
862
864
  ? observeSigned(g, after, before, playerId, settings, context)
@@ -874,6 +876,7 @@ export function trackOpponents(g, boards, me, settings = {}, game) {
874
876
  observed.push({
875
877
  from,
876
878
  to,
879
+ coverage: frontierCoverage(g, after, before, playerId),
877
880
  observed: seenObserved,
878
881
  raw,
879
882
  ...(context.expected !== undefined ? { expected: context.expected } : {}),
@@ -1216,6 +1219,10 @@ export function trackOpponents(g, boards, me, settings = {}, game) {
1216
1219
  lostStacks.sort((a, b) => b.armies - a.armies || a.territoryId - b.territoryId).splice(MAX_LOST_STACKS);
1217
1220
  for (const l of lostStacks)
1218
1221
  notes.push(`A stack of ${l.armies} was last seen on territory ${l.territoryId} on turn ${l.turn} and has been out of view since (stacks of it that came into view since, within its reach, are taken as it and offset it): the planner counts it at each border it can reach by now, for ${LOST_STACK_TURNS} turns after it was seen.`);
1222
+ // #294: what its income was read from.
1223
+ const covered = estimate ? trackCoverage(incomeWindow) : null;
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` : ''}.`);
1219
1226
  notes.push(...warnings);
1220
1227
  return {
1221
1228
  playerId,
@@ -1227,6 +1234,7 @@ export function trackOpponents(g, boards, me, settings = {}, game) {
1227
1234
  visibleIncome,
1228
1235
  income,
1229
1236
  incomeTurns: incomeWindow.map((x) => x.from),
1237
+ coverage: estimate ? trackCoverage(incomeWindow) : null,
1230
1238
  observedRange: estimate?.observedRange ?? null,
1231
1239
  incomeMethod: estimate?.method ?? null,
1232
1240
  incomeLowered: carried ? carried.set - carried.income : 0,
@@ -78,6 +78,10 @@
78
78
  // then `state` is null and the basis says what each turn read. #228: given the plan's profile
79
79
  // `standing`, an `even` or `stalemate` latest turn beside `ahead` / `behind` says why the two differ
80
80
  // (the standing compares incomes; this outlook needs a decided ratio). The state never reads it.
81
+ // #304: beside the state, each turn reports what it rests on (`evidence`): the two incomes compared
82
+ // and how much of each opponent's frontier its income was read from (#294's coverage); a share under
83
+ // LOW_COVERAGE, or none measured, under fog is thin evidence, and the basis says "even" is then not safe.
84
+ // Reporting only: the state never reads it.
81
85
  //
82
86
  // OUTLOOK_RATIO (2.4×) is borrowed from a published bot's "lost" rule and has never been measured
83
87
  // for war.app: the outlook is a basis for a decision, not a verdict. The planner acts on it in one
@@ -94,6 +98,7 @@ import { boardIncome, DEFAULT_BASE_INCOME, territoryIncome } from './player.js';
94
98
  import { BEHIND_RATIO, STRENGTH_INCOME_TURNS } from './profile.js';
95
99
  import { FORECAST_TURNS, forecastBorder, mainFront } from './exchange.js';
96
100
  import { specialUnitStrength } from './combat.js';
101
+ import { coverageText, LOW_COVERAGE } from './plan/shared.js';
97
102
  /** Turns a state must hold before it is reported. */
98
103
  export const OUTLOOK_TURNS = 3;
99
104
  /** Winning at this strength ratio or more, losing at its inverse or less (borrowed, unmeasured). */
@@ -283,6 +288,7 @@ export function gameOutlook(input) {
283
288
  income: tr.income === null ? null : Math.max(tr.visibleIncome, tr.income),
284
289
  visibleIncome: tr.visibleIncome,
285
290
  observed: tr.turns.map((o) => ({ to: o.to, observed: o.observed })),
291
+ coverage: tr.coverage ?? null,
286
292
  },
287
293
  ])));
288
294
  const trackedOf = (playerId) => trackedAll().get(playerId);
@@ -531,6 +537,36 @@ export function gameOutlook(input) {
531
537
  const groundDown = ownOutcome === 'ground-down';
532
538
  const incomeBehind = lowLikely && mostTracked() > 0 && myNow <= BEHIND_RATIO * mostTracked();
533
539
  const lostOnEstimate = lowLikely && (groundDown || incomeBehind);
540
+ // #304: what the state rests on — the two incomes compared and each opponent's frontier read.
541
+ // Reporting only: nothing above reads it.
542
+ const evidenceRows = rows.map((r) => {
543
+ const tr = trackedOf(r.playerId);
544
+ const tracked = tr?.income ?? null;
545
+ const cov = tr?.coverage ?? null;
546
+ return {
547
+ playerId: r.playerId,
548
+ income: tracked ?? r.seen.income,
549
+ source: tracked !== null ? 'tracked' : 'visible',
550
+ coverage: cov ? round2(cov.share) : null,
551
+ thin: !open && (cov === null || cov.share < LOW_COVERAGE),
552
+ ...(cov ? { read: coverageText(cov) } : {}),
553
+ };
554
+ });
555
+ const compared = likely ? sides.find((x) => x.playerId === likely.playerId) : top;
556
+ const comparedRows = compared ? evidenceRows.filter((r) => (compared.players ?? [compared.playerId]).includes(r.playerId)) : [];
557
+ const evidence = {
558
+ incomes: compared
559
+ ? {
560
+ mine: myNow,
561
+ theirs: comparedRows.reduce((n, r) => n + r.income, 0),
562
+ playerId: compared.playerId,
563
+ ...sideOf(compared),
564
+ source: comparedRows.some((r) => r.source === 'tracked') ? 'tracked' : 'visible',
565
+ }
566
+ : null,
567
+ opponents: evidenceRows,
568
+ thin: evidenceRows.some((r) => r.thin),
569
+ };
534
570
  const state = bound || estimated
535
571
  ? 'winning'
536
572
  : lostOnBound || lostOnEstimate
@@ -551,6 +587,7 @@ export function gameOutlook(input) {
551
587
  state,
552
588
  ...(estimated || lostOnEstimate ? { estimated: true } : {}),
553
589
  ...(lowLikely ? { lowLikely: { myIncome: myNow, mostTracked: mostTracked(), groundDown, losing: lostOnEstimate } } : {}),
590
+ evidence,
554
591
  };
555
592
  });
556
593
  const last = turns.at(-1);
@@ -594,6 +631,23 @@ export function gameOutlook(input) {
594
631
  : state
595
632
  ? `${state[0].toUpperCase()}${state.slice(1)} for ${OUTLOOK_TURNS} turns running; ${figures}.`
596
633
  : `${last.state[0].toUpperCase()}${last.state.slice(1)} for ${heldTurns} of the ${OUTLOOK_TURNS} turns (${turns.map((t) => t.state).join(', ')}), so no state yet; ${figures}.`;
634
+ // #304: the incomes compared and each opponent's frontier read, said beside the state, and thin
635
+ // evidence named so that "even" does not read as safe.
636
+ const ev = last.evidence;
637
+ if (ev?.incomes) {
638
+ const i = ev.incomes;
639
+ reading += ` Incomes compared: ${teamGame ? "my team's" : 'mine'} ${i.mine}, ${sideName(i)}'s ${i.theirs} (${i.source === 'tracked' ? 'tracked off my boards' : 'in view, a lower bound under fog'}).`;
640
+ }
641
+ if (ev && !fullyVisible(g, byTurn.get(last.turn).board) && ev.opponents.length)
642
+ reading += ` Frontier read: ${ev.opponents.map((r) => `player ${r.playerId} ${r.read ?? 'not measured'}`).join('; ')}.`;
643
+ if (ev?.thin) {
644
+ const pct = Math.round(LOW_COVERAGE * 100);
645
+ const which = ev.opponents
646
+ .filter((r) => r.thin)
647
+ .map((r) => `player ${r.playerId} (${r.coverage === null ? 'not measured' : `${Math.round(r.coverage * 100)}%`})`)
648
+ .join(', ');
649
+ reading += ` Thin evidence: the income of ${which} was read from under ${pct}% of its frontier, so "${last.state}" is not a safe reading: an opponent may be stronger than the fog shows.`;
650
+ }
597
651
  reading += est;
598
652
  // #228: a likely ratio far below parity, said with what it took (or lacked) to read losing.
599
653
  const low = last.lowLikely;
@@ -629,5 +683,13 @@ export function gameOutlook(input) {
629
683
  reading += ` The main front (the biggest enemy stack next to me against my biggest beside it), each side deploying its whole income there every turn (mine ${fr.myIncome}, player ${fr.player}'s ${fr.theirIncome}: ${theirs}): my ${fr.mine} on #${fr.from} against its ${fr.theirs} on #${fr.at}, ${outcome}.`;
630
684
  }
631
685
  }
632
- return { state, heldTurns, turns, k, threshold: OUTLOOK_RATIO, basis: `${reading} ${measure} ${thresholdsText}` };
686
+ return {
687
+ state,
688
+ heldTurns,
689
+ turns,
690
+ k,
691
+ threshold: OUTLOOK_RATIO,
692
+ basis: `${reading} ${measure} ${thresholdsText}`,
693
+ ...(last?.evidence ? { evidence: last.evidence } : {}),
694
+ };
633
695
  }
@@ -40,6 +40,18 @@ export const TRACKED_MIN_TURNS = 2;
40
40
  * the gap. Unmeasured: four observed turns with its whole edge in view meet half-way.
41
41
  */
42
42
  export const PRIOR_EVIDENCE_TURNS = 4;
43
+ /**
44
+ * #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.
47
+ */
48
+ 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;
43
55
  /** Fog reveals named in the observed-deploy rationale before "and N more". */
44
56
  export const MAX_NAMED_REVEALS = 6;
45
57
  /**
@@ -130,6 +142,16 @@ export const NEUTRAL_BORDER_COST = 0.25;
130
142
  const CYCLIC_ORDERS = new Set(['Cycle', 'NoLuckCycle']);
131
143
  /** A cyclic move order (GameFeed's `MoveOrder`): the order reverses every turn. */
132
144
  export const isCyclicMoveOrder = (moveOrder) => moveOrder !== undefined && CYCLIC_ORDERS.has(moveOrder);
145
+ /**
146
+ * #293 review: an opponent's free income under Local Deployment on the turn read (`turn`), for
147
+ * {@link ObserveContext.localFree}: its base (never below `floor`) plus a Reinforcement card's armies
148
+ * when the clock says one can be in hand by then (unknown turn: yes, when one is in play). A card
149
+ * play is income it may deploy anywhere.
150
+ */
151
+ export function localFreeOn(base, floor, clock, turn) {
152
+ const card = clock && clock.armies > 0 && (turn === null || turn === undefined || turn >= clock.firstTurn) ? clock.armies : 0;
153
+ return Math.max(floor, base) + card;
154
+ }
133
155
  /** #271 review: whether an opponent may have played a Bomb on `turn` (unknown turn: yes, when one is in play). */
134
156
  export function bombPossibleOn(settings, turn) {
135
157
  return settings.bombFrom !== undefined && (turn === null || turn === undefined || turn >= settings.bombFrom);
@@ -293,6 +315,71 @@ export function ownerShown(t) {
293
315
  return undefined;
294
316
  return t;
295
317
  }
318
+ /** #294: {@link FrontierCoverage} of one opponent on one observed turn. Pure. */
319
+ export function frontierCoverage(g, board, previous, playerId) {
320
+ const now = new Map(board.territories.map((t) => [t.territoryId, t]));
321
+ const before = new Map(previous.territories.map((t) => [t.territoryId, t]));
322
+ const its = (id) => {
323
+ const st = ownerShown(now.get(id));
324
+ return st?.owner.kind === 'player' && st.owner.playerId === playerId;
325
+ };
326
+ const shownIts = [...g.territoryById.keys()].filter(its);
327
+ const frontier = new Set();
328
+ let inView = 0;
329
+ for (const t of shownIts) {
330
+ const ns = neighborsOf(g, t);
331
+ if (ns.every(its))
332
+ continue;
333
+ frontier.add(t);
334
+ const a = visibleState(now.get(t));
335
+ const b = visibleState(before.get(t));
336
+ if (a && b)
337
+ inView++;
338
+ for (const n of ns)
339
+ if (!ownerShown(now.get(n)))
340
+ frontier.add(n);
341
+ }
342
+ let hiddenBonuses = 0;
343
+ for (const bonus of g.map.bonuses) {
344
+ const ts = bonusTerritories(g, bonus.id);
345
+ if (bonus.value <= 0 || !ts.length)
346
+ continue;
347
+ const taken = ts.some((t) => {
348
+ const st = ownerShown(now.get(t));
349
+ return st !== undefined && !(st.owner.kind === 'player' && st.owner.playerId === playerId);
350
+ });
351
+ if (!taken && ts.some((t) => !ownerShown(now.get(t))))
352
+ hiddenBonuses++;
353
+ }
354
+ const share = frontier.size ? inView / frontier.size : shownIts.length ? 1 : 0;
355
+ return { inView, frontier: frontier.size, share, hiddenBonuses };
356
+ }
357
+ /** #294: {@link TrackCoverage} over `turns` (those carrying a coverage); `null` when none does. */
358
+ export function trackCoverage(turns) {
359
+ const withIt = turns.filter((x) => x.coverage !== undefined);
360
+ if (!withIt.length)
361
+ return null;
362
+ const inView = withIt.reduce((n, x) => n + x.coverage.inView, 0);
363
+ const frontier = withIt.reduce((n, x) => n + x.coverage.frontier, 0);
364
+ const range = (xs) => ({ min: Math.min(...xs), max: Math.max(...xs) });
365
+ return {
366
+ turns: withIt.map((x) => x.from),
367
+ inView: range(withIt.map((x) => x.coverage.inView)),
368
+ frontier: range(withIt.map((x) => x.coverage.frontier)),
369
+ share: frontier ? inView / frontier : withIt.reduce((n, x) => n + x.coverage.share, 0) / withIt.length,
370
+ hiddenBonuses: withIt.at(-1).coverage.hiddenBonuses,
371
+ };
372
+ }
373
+ /**
374
+ * #294: "1 of ~4 frontier territories (25%)" (a range, "1–2 of ~4–5", when the turns differ; the share
375
+ * is Σ read ÷ Σ frontier), and ", N bonus(es) it could hold out of view" when any: the words beside a
376
+ * tracked figure.
377
+ */
378
+ export function coverageText(c) {
379
+ const b = c.hiddenBonuses;
380
+ const range = (r) => (r.min === r.max ? `${r.min}` : `${r.min}–${r.max}`);
381
+ return `${range(c.inView)} of ~${range(c.frontier)} frontier territories (${Math.round(c.share * 100)}%)${b ? `, ${b} ${b === 1 ? 'bonus' : 'bonuses'} it could hold out of view` : ''}`;
382
+ }
296
383
  /**
297
384
  * #226: what my failed attacks on `playerId` killed, by target, on the turn `before` → `after`: each
298
385
  * move of mine onto a territory it holds on both boards (shown with armies both times), from a
@@ -654,6 +741,37 @@ export function observeSigned(g, board, previous, playerId, rates = {}, context
654
741
  for (const t of board.territories)
655
742
  if (g.territoryById.has(t.territoryId) && heldBothTimes(t.territoryId))
656
743
  shrinkLeft.set(t.territoryId, Math.max(0, visibleState(before.get(t.territoryId)).armies - t.armies - killsAt(t.territoryId)));
744
+ /** Not shown with armies on both boards: armies could have left it unseen. */
745
+ const hidden = (id) => !visibleState(now.get(id)) || !visibleState(before.get(id));
746
+ // #294: each grown stack's growth split, against its own copy of the shrinks (captures claim theirs below).
747
+ // The stacks with no hidden neighbour claim first (what they leave can only be deploy, so a shrink
748
+ // taken by a stack beside the fog would turn a move into a false "can only be deploy"), then those
749
+ // beside the fog; each in id order, and reported in id order.
750
+ const stacks = [];
751
+ const shrinkForSplit = new Map(shrinkLeft);
752
+ const grown = [...shrinkLeft.keys()]
753
+ .sort(byNum)
754
+ .map((id) => ({
755
+ id,
756
+ growth: visibleState(now.get(id)).armies - visibleState(before.get(id)).armies + killsAt(id),
757
+ beside: neighborsOf(g, id).some(hidden),
758
+ }))
759
+ .filter((x) => x.growth > 0);
760
+ for (const { id, growth, beside } of [...grown.filter((x) => !x.beside), ...grown.filter((x) => x.beside)]) {
761
+ let left = growth;
762
+ const moved = [];
763
+ for (const n of [...neighborsOf(g, id)].sort(byNum)) {
764
+ const can = shrinkForSplit.get(n);
765
+ if (!can || !left)
766
+ continue;
767
+ const take = Math.min(can, left);
768
+ shrinkForSplit.set(n, can - take);
769
+ left -= take;
770
+ moved.push({ from: n, armies: take });
771
+ }
772
+ stacks.push({ territoryId: id, growth, moved, fog: beside ? left : 0, deploy: beside ? 0 : left });
773
+ }
774
+ stacks.sort((a, b) => a.territoryId - b.territoryId);
657
775
  /**
658
776
  * #271 (3): its territories shown with armies on the earlier board and hidden on the later one: what
659
777
  * each could have sent (its armies less the guard), the most a capture beside it can have received
@@ -674,8 +792,6 @@ export function observeSigned(g, board, previous, playerId, rates = {}, context
674
792
  let arrivals = 0;
675
793
  const unseenAttackers = [];
676
794
  let unseenAttackerArmies = 0;
677
- /** Not shown with armies on both boards: armies could have left it unseen. */
678
- const hidden = (id) => !visibleState(now.get(id)) || !visibleState(before.get(id));
679
795
  for (const t of [...board.territories].sort((a, b) => a.territoryId - b.territoryId)) {
680
796
  if (!g.territoryById.has(t.territoryId) || !visibleState(t))
681
797
  continue;
@@ -790,16 +906,66 @@ export function observeSigned(g, board, previous, playerId, rates = {}, context
790
906
  // A board-only reading (neither `expected` nor `most`) has no room at all: a negative total (a
791
907
  // stack of its own that shrank into the fog) must not make room for a capture's surplus.
792
908
  let room = bound === null && context.most === undefined ? 0 : Math.max(0, (bound ?? Math.max(0, context.most)) - total);
909
+ // #293: under Local Deployment, the territories a bonus pool could have paid into on the turn read
910
+ // (the bonuses it could hold on the earlier board); growth beside the fog elsewhere draws on `freeLeft`.
911
+ const local = rates.localDeployments === true && bound !== null && context.localFree !== undefined;
912
+ const pooledOn = new Set();
913
+ if (local)
914
+ for (const b of g.map.bonuses) {
915
+ if (b.value <= 0)
916
+ continue;
917
+ const ts = bonusTerritories(g, b.id);
918
+ const possible = ts.every((t) => {
919
+ const o = ownerShown(before.get(t))?.owner;
920
+ return o === undefined || (o.kind === 'player' && o.playerId === playerId);
921
+ });
922
+ if (possible)
923
+ for (const t of ts)
924
+ pooledOn.add(t);
925
+ }
926
+ let freeLeft = Math.max(0, context.localFree ?? 0);
927
+ const localCut = [];
928
+ // #293 review: a walled growth's walk draws on the shrink the captures left (`shrinkLeft`, after
929
+ // the capture loop), less what the other grown stacks' splits took (their growth already nets it),
930
+ // in ascending ids: one claim pass, so one neighbour's shrink never offsets a capture and a walk both.
931
+ const walled = (x) => local && x.kind === 'growth' && !pooledOn.has(x.id);
932
+ const walkLeft = new Map(shrinkLeft);
933
+ if (local) {
934
+ const walledIds = new Set(ambiguous.filter(walled).map((x) => x.id));
935
+ for (const st of stacks)
936
+ if (!walledIds.has(st.territoryId))
937
+ for (const m of st.moved)
938
+ walkLeft.set(m.from, Math.max(0, (walkLeft.get(m.from) ?? 0) - m.armies));
939
+ }
793
940
  for (const x of [...ambiguous].sort((a, b) => a.id - b.id)) {
794
941
  if (bound === null && x.kind === 'growth') {
795
942
  lowExtra -= x.armies;
796
943
  continue;
797
944
  }
798
- const deployed = Math.min(x.armies, room);
945
+ // #293: a walk from a neighbour in view (the growth split) nets its shrink; the rest is deploy only
946
+ // as far as the free income still reaches.
947
+ const isWalled = walled(x);
948
+ let walk = 0;
949
+ if (isWalled)
950
+ for (const n of [...neighborsOf(g, x.id)].sort(byNum)) {
951
+ const can = walkLeft.get(n);
952
+ if (!can || walk >= x.armies)
953
+ continue;
954
+ const take = Math.min(can, x.armies - walk);
955
+ walkLeft.set(n, can - take);
956
+ walk += take;
957
+ }
958
+ total += walk;
959
+ room = Math.max(0, room - walk);
960
+ const deployed = Math.min(x.armies - walk, room, isWalled ? freeLeft : Infinity);
961
+ if (isWalled)
962
+ freeLeft -= deployed;
799
963
  room -= deployed;
800
964
  total += deployed;
801
965
  lowExtra -= deployed;
802
- const moved = x.armies - deployed;
966
+ const moved = x.armies - walk - deployed;
967
+ if (isWalled && moved > 0)
968
+ localCut.push(x.id);
803
969
  highExtra += moved;
804
970
  if (x.kind === 'capture') {
805
971
  if (deployed > 0)
@@ -824,6 +990,7 @@ export function observeSigned(g, board, previous, playerId, rates = {}, context
824
990
  : { territories: [], floor: 0 };
825
991
  const floor = repelled.floor;
826
992
  return {
993
+ stacks,
827
994
  deploy: Math.max(0, total, floor),
828
995
  signed: total,
829
996
  counted,
@@ -834,6 +1001,7 @@ export function observeSigned(g, board, previous, playerId, rates = {}, context
834
1001
  reinforced,
835
1002
  grewFromFog,
836
1003
  fogGrowth,
1004
+ ...(localCut.length ? { localCut: { free: Math.max(0, context.localFree ?? 0), territories: localCut } } : {}),
837
1005
  expected: context.expected ?? null,
838
1006
  attacked: [...kills.keys()].sort(byNum),
839
1007
  attackKills: [...kills.values()].reduce((n, k) => n + k, 0),
@@ -1016,6 +1184,11 @@ export function enemyDeployEstimates(g, board, me, settings = {}, previous, trac
1016
1184
  guard: (settings.oneArmyStandsGuard ?? true) ? 1 : 0,
1017
1185
  expected: Math.max(visible, trackBound ?? tracked ?? priorFigure ?? 0),
1018
1186
  most: couldEarn,
1187
+ // #293: under Local Deployment, growth beside the fog outside every bonus it could hold is
1188
+ // deploy only up to its free income.
1189
+ ...(settings.localDeployments
1190
+ ? { localFree: localFreeOn(base, MIN_ENEMY_DEPLOY, when.reinforcement ?? settings.opponentReinforcement, when.turn == null ? null : when.turn - 1) }
1191
+ : {}),
1019
1192
  ...(when.previousOrders ? { myOrders: when.previousOrders } : {}),
1020
1193
  // #271 review: the turn read is the one before the turn planned.
1021
1194
  ...(bombPossibleOn(settings, when.turn == null ? null : when.turn - 1) ? { bomb: true } : {}),
@@ -1061,8 +1234,12 @@ export function enemyDeployEstimates(g, board, me, settings = {}, previous, trac
1061
1234
  for (const n of neighborsOf(g, t))
1062
1235
  if (!theirs.has(n))
1063
1236
  edge.add(n);
1064
- const share = edge.size ? [...edge].filter((n) => ownerShown(seenNow.get(n)) !== undefined).length / edge.size : 0;
1065
- const weight = PRIOR_EVIDENCE_TURNS / (PRIOR_EVIDENCE_TURNS + turns * share);
1237
+ const edgeShare = edge.size ? [...edge].filter((n) => ownerShown(seenNow.get(n)) !== undefined).length / edge.size : 0;
1238
+ // #294: each turn of the run weighs what it read of its frontier (this board's edge for a turn
1239
+ // that carries no coverage).
1240
+ const evidence = run.slice(run.length - turns).reduce((n, x) => n + (x.coverage?.share ?? edgeShare), 0);
1241
+ const share = turns ? evidence / turns : edgeShare;
1242
+ const weight = PRIOR_EVIDENCE_TURNS / (PRIOR_EVIDENCE_TURNS + evidence);
1066
1243
  const figure = toward + Math.ceil(weight * (priorFigure - toward) - 1e-9);
1067
1244
  priorBlend = { prior: priorFigure, toward, turns, share, weight, figure };
1068
1245
  }
@@ -1072,7 +1249,15 @@ export function enemyDeployEstimates(g, board, me, settings = {}, previous, trac
1072
1249
  // a card (or armies the board misread), never income.
1073
1250
  const exact = ownersAll && !opening ? Math.max(0, base + bonusIncome) : null;
1074
1251
  const source = exact !== null ? 'exact' : priorUsed !== null && priorUsed > seen ? 'prior' : seenSource;
1075
- const income = source === 'exact' ? exact : source === 'prior' ? priorUsed : seen;
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).
1254
+ const coverage = usable ? trackCoverage(usable.turns.filter((x) => usable.incomeTurns.includes(x.from))) : null;
1255
+ 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;
1076
1261
  // #164: a Reinforcement card, from the turn the clock says one can be in hand, until a deployment
1077
1262
  // above its income is seen; the next card is due a card's capturing turns after the last one
1078
1263
  // (pieces carry over while a card is held), never before the turn after the play.
@@ -1133,6 +1318,8 @@ export function enemyDeployEstimates(g, board, me, settings = {}, previous, trac
1133
1318
  trackedTurns: usable ? usable.incomeTurns : [],
1134
1319
  prior: priorFigure,
1135
1320
  priorBlend,
1321
+ coverage,
1322
+ coverageFloor,
1136
1323
  priorCap,
1137
1324
  fogBeside,
1138
1325
  source,