@chrischall/warapp-mcp 0.6.0 → 0.7.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 (90) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +99 -6
  4. package/dist/analysis/accept-surrender.js +20 -2
  5. package/dist/analysis/calibrate.js +1 -0
  6. package/dist/analysis/card-support.js +175 -16
  7. package/dist/analysis/card-threats.js +68 -3
  8. package/dist/analysis/chat-advice.js +182 -0
  9. package/dist/analysis/chat-blocks.js +106 -0
  10. package/dist/analysis/chat-intent.js +559 -0
  11. package/dist/analysis/chat-read.js +159 -0
  12. package/dist/analysis/decision-replay.js +279 -0
  13. package/dist/analysis/decision-truth.js +146 -0
  14. package/dist/analysis/finished-game.js +62 -3
  15. package/dist/analysis/game-lessons.js +12 -6
  16. package/dist/analysis/opponent-profile.js +46 -3
  17. package/dist/analysis/opponents.js +245 -19
  18. package/dist/analysis/outlook.js +323 -17
  19. package/dist/analysis/plan/after-leftover.js +4 -1
  20. package/dist/analysis/plan/captures.js +4 -3
  21. package/dist/analysis/plan/estimates.js +70 -6
  22. package/dist/analysis/plan/guard-off.js +2 -1
  23. package/dist/analysis/plan/holds.js +79 -6
  24. package/dist/analysis/plan/leftover.js +145 -5
  25. package/dist/analysis/plan/relations.js +115 -2
  26. package/dist/analysis/plan/shared.js +201 -11
  27. package/dist/analysis/plan/stand-still.js +2 -2
  28. package/dist/analysis/plan/stockpile.js +104 -0
  29. package/dist/analysis/plan/strike.js +34 -7
  30. package/dist/analysis/plan/targets.js +168 -53
  31. package/dist/analysis/plan/threats.js +108 -5
  32. package/dist/analysis/plan/transfers.js +11 -0
  33. package/dist/analysis/plan/two-move.js +70 -0
  34. package/dist/analysis/plan/vacated.js +124 -2
  35. package/dist/analysis/planner.js +302 -42
  36. package/dist/analysis/since-last.js +18 -5
  37. package/dist/board.js +36 -2
  38. package/dist/build-id.js +106 -0
  39. package/dist/bundle.js +14943 -10146
  40. package/dist/chat-automation.js +22 -0
  41. package/dist/client.js +14 -0
  42. package/dist/decision-log.js +1093 -0
  43. package/dist/finished-store.js +5 -1
  44. package/dist/lessons-store.js +322 -21
  45. package/dist/open-games.js +36 -16
  46. package/dist/outlook-log.js +42 -1
  47. package/dist/protocol/methods.js +4 -2
  48. package/dist/review-export.js +198 -0
  49. package/dist/state-bundle.js +62 -3
  50. package/dist/state-cli.js +5 -3
  51. package/dist/strategy/notes.js +56 -0
  52. package/dist/tools/accept-surrender.js +23 -9
  53. package/dist/tools/award.js +5 -1
  54. package/dist/tools/card-advice.js +77 -23
  55. package/dist/tools/card-support-advice.js +36 -7
  56. package/dist/tools/chat-advice.js +330 -0
  57. package/dist/tools/chat-inbox.js +15 -4
  58. package/dist/tools/chat.js +41 -11
  59. package/dist/tools/check-plan.js +14 -2
  60. package/dist/tools/decision-capture.js +459 -0
  61. package/dist/tools/end-of-game.js +146 -18
  62. package/dist/tools/game-kind.js +92 -0
  63. package/dist/tools/how-lost.js +7 -2
  64. package/dist/tools/index.js +3 -0
  65. package/dist/tools/join-game.js +10 -4
  66. package/dist/tools/live-context.js +6 -0
  67. package/dist/tools/live.js +10 -1
  68. package/dist/tools/map-curves.js +73 -0
  69. package/dist/tools/notifications.js +4 -3
  70. package/dist/tools/opponents.js +2 -0
  71. package/dist/tools/past-games.js +74 -8
  72. package/dist/tools/picks.js +49 -10
  73. package/dist/tools/profile-hook.js +62 -3
  74. package/dist/tools/profile-opponents.js +2 -0
  75. package/dist/tools/push.js +2 -2
  76. package/dist/tools/relations.js +2 -0
  77. package/dist/tools/scout.js +16 -2
  78. package/dist/tools/state.js +6 -1
  79. package/dist/tools/strategy.js +3 -3
  80. package/dist/tools/stress-opponents.js +2 -0
  81. package/dist/tools/surrender-pending.js +10 -1
  82. package/dist/tools/surrender.js +18 -3
  83. package/dist/tools/turn.js +313 -18
  84. package/dist/tools/where.js +3 -1
  85. package/dist/version.js +1 -1
  86. package/manifest.json +23 -2
  87. package/mint.yaml +23 -0
  88. package/package.json +1 -1
  89. package/server.json +20 -2
  90. package/skills/warapp-mcp/SKILL.md +42 -8
@@ -20,6 +20,8 @@ export function outcomeOf(players, me) {
20
20
  return players.some((p) => p.id !== me && p.state === 'Won') ? 'lost' : 'unknown';
21
21
  }
22
22
  const ownerOf = (t) => t?.owner.kind === 'player' ? t.owner.playerId : undefined;
23
+ /** A fog level that hides a territory's armies (fogged or owner-only, by word or number). */
24
+ const hidesArmies = (level) => level !== undefined && (/fog|owneronly/i.test(level) || level === '3' || level === '4');
23
25
  /**
24
26
  * Each of `players` on `board`: its income by THE income rule (`boardIncome`, src/analysis/player.ts:
25
27
  * base or per-territory income, plus every full bonus; the map's values with the game's overrides
@@ -29,12 +31,21 @@ const ownerOf = (t) => t?.owner.kind === 'player' ? t.owner.playerId : undefined
29
31
  export function turnIncomes(g, board, players, settings) {
30
32
  const held = new Map(players.map((p) => [p, new Set()]));
31
33
  const armies = new Map(players.map((p) => [p, 0]));
34
+ const unread = new Map();
35
+ const commanders = new Map();
32
36
  for (const t of board.territories) {
33
37
  const o = ownerOf(t);
34
38
  if (o === undefined || !held.has(o) || !g.territoryById.has(t.territoryId))
35
39
  continue;
36
40
  held.get(o).add(t.territoryId);
41
+ const own = t.specialUnits?.filter((u) => u.kind === 'commander' && u.playerId === o).length ?? 0;
42
+ if (own)
43
+ commanders.set(o, (commanders.get(o) ?? 0) + own);
37
44
  const a = armies.get(o);
45
+ if (t.armies === null && !hidesArmies(t.fogLevel)) {
46
+ unread.set(o, (unread.get(o) ?? 0) + 1);
47
+ continue;
48
+ }
38
49
  armies.set(o, a === null || t.armies === null ? null : a + t.armies);
39
50
  }
40
51
  const rules = incomeRules(settings);
@@ -46,11 +57,15 @@ export function turnIncomes(g, board, players, settings) {
46
57
  continue;
47
58
  }
48
59
  const inc = boardIncome(g, land, rules);
60
+ const u = unread.get(p);
61
+ const c = commanders.get(p);
49
62
  out.set(p, {
50
63
  income: inc.total,
51
64
  territories: land.size,
52
65
  armies: armies.get(p),
53
66
  bonuses: inc.bonuses.map((b) => b.bonusId).sort((a, b) => a - b),
67
+ ...(u ? { armiesUnread: u } : {}),
68
+ ...(c ? { commanders: c } : {}),
54
69
  });
55
70
  }
56
71
  return out;
@@ -118,19 +133,63 @@ export function failedAttacks(boards, orders, me) {
118
133
  }
119
134
  return out;
120
135
  }
136
+ /** Outcomes in which my seat left the game, so my orders of that turn never ran (#437). */
137
+ const LEFT = new Set(['surrendered', 'booted']);
138
+ /**
139
+ * The turn being played when my seat left (#437): for a surrender or a boot, `leftTurn` (the decision log's
140
+ * events), else my out turn on the history; for an elimination, my out turn; `null` otherwise or unknown. Pure.
141
+ */
142
+ export function leftTurnOf(result, outTurn, leftTurn) {
143
+ if (LEFT.has(result))
144
+ return leftTurn ?? outTurn;
145
+ return result === 'eliminated' ? outTurn : null;
146
+ }
121
147
  /** The whole capture of a finished game from its history boards and my orders. Pure. */
122
148
  export function captureFinished(input) {
123
149
  const ids = input.players.map((p) => p.id).sort((a, b) => a - b);
124
150
  const boards = ascending(input.boards);
151
+ const result = outcomeOf(input.players, input.me);
152
+ const outTurn = outTurnOf(boards, input.me);
153
+ const leftTurn = leftTurnOf(result, outTurn, input.leftTurn);
154
+ // #437: my orders of the turn my seat left (a surrender or a boot) never ran: no failed attack of theirs.
155
+ const ran = LEFT.has(result) && leftTurn !== null ? (f) => f.turn < leftTurn : () => true;
125
156
  return {
126
157
  outcome: {
127
- result: outcomeOf(input.players, input.me),
158
+ result,
128
159
  turn: input.numberOfTurns ?? null,
129
- outTurn: outTurnOf(boards, input.me),
160
+ outTurn,
161
+ leftTurn,
130
162
  winners: input.players.filter((p) => p.state === 'Won').map((p) => p.id).sort((a, b) => a - b),
131
163
  },
132
164
  starts: startsOf(boards, ids),
133
165
  turns: input.graph ? boards.map(({ turn, board }) => ({ afterTurn: turn, players: turnIncomes(input.graph, board, ids, input.settings) })) : [],
134
- failedAttacks: failedAttacks(boards, input.orders, input.me),
166
+ failedAttacks: failedAttacks(boards, input.orders, input.me).filter(ran),
135
167
  };
136
168
  }
169
+ export const GAME_KINDS = ['lottery', 'no-show', 'legacy', 'team'];
170
+ /** The kinds kept out of the lessons, the map record and the profile folds. */
171
+ export const EXCLUDED_KINDS = ['lottery', 'no-show'];
172
+ /** The kinds of a finished game ({@link GameKind}), in {@link GAME_KINDS} order. Pure. */
173
+ export function gameKinds(k) {
174
+ const out = new Set();
175
+ const lottery = k.territories !== undefined ? k.territories <= k.lotteryMaxTerritories : k.joinLottery !== undefined || k.lotteryShape === true;
176
+ if (lottery)
177
+ out.add('lottery');
178
+ const legacy = !k.hasLog && !k.hasBoards;
179
+ // Never committed: only where this server kept the game (a legacy game's orders were never cached).
180
+ const neverCommitted = !legacy && k.committedTurns === 0 && k.result !== 'won';
181
+ // Booted before turn 2 was played: seen booted while turn 1 or 2 was being played (a boot at turn 1's
182
+ // deadline is first seen on turn 2), or the game ended with at most one turn completed.
183
+ const bootedEarly = k.result === 'booted' && ((k.leftTurn !== null && k.leftTurn <= 2) || (k.numberOfTurns !== null && k.numberOfTurns <= 1));
184
+ if (neverCommitted || bootedEarly)
185
+ out.add('no-show');
186
+ if (legacy)
187
+ out.add('legacy');
188
+ if (k.team)
189
+ out.add('team');
190
+ return GAME_KINDS.filter((x) => out.has(x));
191
+ }
192
+ /** The kind a game is kept apart for (lottery first), or `undefined` when it counts. Pure. */
193
+ export function excludedKind(kinds) {
194
+ return kinds.includes('lottery') ? 'lottery' : kinds.includes('no-show') ? 'no-show' : undefined;
195
+ }
@@ -87,19 +87,25 @@ export const MAX_CURVE_POINTS = 60;
87
87
  /** The boards the pace is read on: the income after these completed turns. */
88
88
  export const PACE_TURNS = [4, 8];
89
89
  const incomeAfter = (curve, n) => curve.find((c) => c.afterTurn === n)?.income ?? null;
90
+ /** A curve as a map record keeps it: index = completed turns up to its last board, `null` where none read, at most {@link MAX_CURVE_POINTS}. Pure. */
91
+ export function curvePoints(curve) {
92
+ const last = Math.min(MAX_CURVE_POINTS, curve.length ? curve.at(-1).afterTurn + 1 : 0);
93
+ return Array.from({ length: last }, (_, i) => incomeAfter(curve, i));
94
+ }
90
95
  /**
91
96
  * My start region and income curve (index = completed turns, `null` where no board read, at most
92
- * {@link MAX_CURVE_POINTS}), and each winner's start region and income after turns 4 and 8 (the pace
93
- * to beat). Pure.
97
+ * {@link MAX_CURVE_POINTS}), and each winner's start region, income curve (#419, the same shape) and
98
+ * income after turns 4 and 8 (the pace to beat). Pure.
94
99
  */
95
100
  export function mapFacts(g, me, winners, starts, turns) {
96
101
  const mine = incomeCurve(turns, me);
97
- const last = Math.min(MAX_CURVE_POINTS, mine.length ? mine.at(-1).afterTurn + 1 : 0);
98
- const income = Array.from({ length: last }, (_, i) => incomeAfter(mine, i));
99
102
  const pace = (curve) => ({ income4: incomeAfter(curve, PACE_TURNS[0]), income8: incomeAfter(curve, PACE_TURNS[1]) });
100
103
  return {
101
- me: { ...startRegion(g, starts.get(me) ?? []), income, ...pace(mine) },
102
- winners: [...winners].sort((a, b) => a - b).map((w) => ({ ...startRegion(g, starts.get(w) ?? []), ...pace(incomeCurve(turns, w)) })),
104
+ me: { ...startRegion(g, starts.get(me) ?? []), income: curvePoints(mine), ...pace(mine) },
105
+ winners: [...winners].sort((a, b) => a - b).map((w) => {
106
+ const curve = incomeCurve(turns, w);
107
+ return { ...startRegion(g, starts.get(w) ?? []), income: curvePoints(curve), ...pace(curve) };
108
+ }),
103
109
  };
104
110
  }
105
111
  /**
@@ -70,7 +70,8 @@ function leastFailing(armies, from, off, def) {
70
70
  * My orders as cached (`MyOrders`): `moves` holds only plain orders; a percentage, Attack Only or
71
71
  * Transfer Only order is in `sent` alone, and card plays in `cards`. A territory such an order leaves
72
72
  * or enters, or one of my Airlifts touches, is never tested for `attackedMe` and gives no `reinforce`
73
- * reading (its armies are not known); `iAttacked` counts every non-transfer order of `sent`. When the
73
+ * reading (its armies are not known); `iAttacked` counts every non-transfer order of `sent` (#442: onto its
74
+ * territory on T, or onto one not mine on T that is its on T+1 — my attack ran into its fresh capture). When the
74
75
  * orders do not record card plays (`cards` absent: a cache written before they were) and the game may
75
76
  * have Airlift, nothing is tested from armies at all, and when it may have Gift — orders unknown
76
77
  * included — captures cannot be told (`tookFromMe: null`; it may have been my gift), so a game with
@@ -155,8 +156,10 @@ export function observeTurn(input) {
155
156
  const contact = ids.some((id) => ownsWas(id) && neighborsOf(graph, id).some(mineWas));
156
157
  const tookFromMe = giftUnknown ? null : ids.filter((id) => mineWas(id) && ownsNow(id) && !gifted.has(id));
157
158
  const lostToMe = ids.filter((id) => ownsWas(id) && mineNow(id));
158
- const iAttacked = moves.some((m) => ownsWas(m.to) && m.armies > 0 && !transferOnly.has(`${m.from}:${m.to}`)) ||
159
- sent.some((m) => ownsWas(m.to) && !m.transferOnly && sentCount(m) > plain(m));
159
+ // #442: or onto a territory not mine on T that is its on T+1 — its fresh capture my attack ran into.
160
+ const hit = (to) => ownsWas(to) || (!mineWas(to) && ownsNow(to));
161
+ const iAttacked = moves.some((m) => hit(m.to) && m.armies > 0 && !transferOnly.has(`${m.from}:${m.to}`)) ||
162
+ sent.some((m) => hit(m.to) && !m.transferOnly && sentCount(m) > plain(m));
160
163
  // attackedMe
161
164
  let attackedMe = tookFromMe?.length ? true : null;
162
165
  // #361: the borders read whose drop is exactly what one attacking army kills (a single-army jab);
@@ -435,6 +438,46 @@ export function habitsOf(turns) {
435
438
  }
436
439
  return h;
437
440
  }
441
+ // ---- #420: the one profile read the planner may make (P1 amended, owner decision of 2026-11-20) ----
442
+ /** #420: the contact turns (each one whose attack on me could be told) a quiet neighbour needs. */
443
+ export const QUIET_CONTACT_TURNS = 10;
444
+ /** #420: the most attacks on me per contact turn a quiet neighbour may show. */
445
+ export const QUIET_ATTACK_RATE = 0.1;
446
+ /**
447
+ * #420 (owner decision of 2026-11-20): the one case P1 lets the planner read a profile. Over this
448
+ * game's observed turns in order, a contact turn whose attack on me could be told counts; once there are
449
+ * {@link QUIET_CONTACT_TURNS} or more at an attack rate of {@link QUIET_ATTACK_RATE} or less it is quiet,
450
+ * until its first attack on me after that, which ends it for the game (full sizing at once). Pure.
451
+ */
452
+ export function quietNeighbour(turns) {
453
+ const by = new Map();
454
+ for (const t of turns)
455
+ by.set(t.turn, t.primitives);
456
+ let n = 0;
457
+ let e = 0;
458
+ let since;
459
+ let attackedOn;
460
+ for (const t of [...by.keys()].sort(byNum)) {
461
+ const p = by.get(t);
462
+ if (!p.contact || p.attackedMe === null)
463
+ continue;
464
+ n++;
465
+ if (p.attackedMe) {
466
+ e++;
467
+ if (since !== undefined && attackedOn === undefined)
468
+ attackedOn = t;
469
+ }
470
+ if (since === undefined && n >= QUIET_CONTACT_TURNS && e <= QUIET_ATTACK_RATE * n)
471
+ since = t;
472
+ }
473
+ return {
474
+ contactTurns: n,
475
+ attacks: e,
476
+ quiet: since !== undefined && attackedOn === undefined,
477
+ ...(since !== undefined ? { since } : {}),
478
+ ...(attackedOn !== undefined ? { attackedOn } : {}),
479
+ };
480
+ }
438
481
  // ---- the estimate (B1): this game pooled with past games, shrunk toward the population or a default ----
439
482
  /** How many opportunities the prior weighs as (docs/PLAN-PROFILES.md B1). */
440
483
  export const PROFILE_PRIOR_WEIGHT = 4;
@@ -2,9 +2,9 @@ import { holdsSeat } from '../player-states.js';
2
2
  import { carriesTeam, isTeamGame } from '../teams.js';
3
3
  import { neutralizeSeats, staticSeats } from './static-seats.js';
4
4
  import { bonusTerritories } from './bonuses.js';
5
- import { DEFAULT_DEFENSIVE_KILL_RATE, DEFAULT_OFFENSIVE_KILL_RATE, straightKills } from './combat.js';
5
+ import { DEFAULT_DEFENSIVE_KILL_RATE, DEFAULT_OFFENSIVE_KILL_RATE, guaranteedKills, luckFraction, 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, TRACKED_MIN_TURNS, trackCoverage, visibleState, } from './planner.js';
7
+ import { bombPossibleOn, captureFloor, 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;
@@ -35,8 +35,8 @@ const NEUTRAL_CAPTURE_LOSS = 1;
35
35
  /**
36
36
  * {@link TrackGame} from GameFeed's players and settings: each player's starting armies are
37
37
  * TerritoryLimit × InitialPlayerArmiesPerTerritory, unless either is missing, the game uses full
38
- * distribution (DistributionMode -1: every territory is split among the players, TerritoryLimit
39
- * ignored — unverified, docs/WARAPP-API.md) or a map distribution that is not `normal` (a
38
+ * distribution ({@link fullDistribution}, #428: DistributionMode 0 with no TerritoryLimit — every
39
+ * territory is split among the players; -1 is a limited start) or a map distribution that is not `normal` (a
40
40
  * scenario sets its own starts). A Sanctions card is an income caveat: it can cut income below
41
41
  * the base the bound counts.
42
42
  */
@@ -57,7 +57,7 @@ endRules) {
57
57
  const seats = [...staticSeats(list, endRules).keys()].sort(byNum);
58
58
  const base = { players: list, ...(seats.length ? { staticSeats: seats } : {}), ...(caveats.length ? { incomeCaveats: caveats } : {}) };
59
59
  const perTerritory = settings?.initialPlayerArmiesPerTerritory !== undefined ? { startArmiesPerTerritory: Math.max(0, settings.initialPlayerArmiesPerTerritory) } : {};
60
- if (settings?.distributionMode === FULL_DISTRIBUTION)
60
+ if (fullDistribution(settings))
61
61
  return {
62
62
  ...base,
63
63
  startUnknown: 'the game uses full distribution, which splits every territory among the players whatever the territory limit',
@@ -87,8 +87,20 @@ export function staticSeatsFor(game, me) {
87
87
  }
88
88
  /** TerritoryLimit assumed when the settings do not say (war.app's usual default). */
89
89
  export const DEFAULT_TERRITORY_LIMIT = 3;
90
- /** GameFeed's DistributionMode for full distribution (unverified, docs/WARAPP-API.md). */
91
- const FULL_DISTRIBUTION = -1;
90
+ /**
91
+ * GameFeed's DistributionMode for full distribution: the client's id (docs/WARAPP-API.md, #235). #428:
92
+ * -1 is a limited start (the client's random warlords: TerritoryLimit territories each), verified on
93
+ * three finished games, where reading it as full distribution put an opponent's start at 189 for a real 9.
94
+ */
95
+ const FULL_DISTRIBUTION = 0;
96
+ /**
97
+ * #428: the game deals every territory among the players — DistributionMode 0 with no TerritoryLimit
98
+ * (unset or 0: the client's "no cap"). Mode 0 with a TerritoryLimit stays a limited start (the client
99
+ * caps each player's share by the limit; that a full-distribution game never sends one is unverified).
100
+ */
101
+ export function fullDistribution(settings) {
102
+ return settings?.distributionMode === FULL_DISTRIBUTION && !(settings.territoryLimit !== undefined && settings.territoryLimit > 0);
103
+ }
92
104
  /** GameFeed's DistributionMode for a custom scenario (the client's id; unverified on GameFeed, docs/WARAPP-API.md). */
93
105
  const CUSTOM_SCENARIO = -3;
94
106
  /**
@@ -118,6 +130,15 @@ export function symmetricStart(settings) {
118
130
  /** Player states still in the game (absent counts as playing), as the profile counts them. */
119
131
  const playing = (p) => (p.state ?? 'Playing') === 'Playing';
120
132
  const byNum = (a, b) => a - b;
133
+ /**
134
+ * #418: a rise no turn read in full confirmed ({@link confirmedBy}) is held to this many times the
135
+ * income carried before it, each turn: walk-ins beside the fog are read up to twice the carry (#123),
136
+ * so without it they compounded (10, 20, 40, …) while nothing backed them. Unmeasured beyond #418's
137
+ * calibration run.
138
+ */
139
+ export const RISE_CAP = 1.3;
140
+ /** #418: my armies in view against its own, at or above which I lead it on the board ({@link ObservedTurn.leadIncome}). */
141
+ export const LEAD_ARMIES = 3;
121
142
  /**
122
143
  * Income over a window of observed turns (#99). Each observed deploy is a LOWER BOUND on that
123
144
  * turn's income: deploys onto fogged territories are unseen, and so are armies moved into the
@@ -168,6 +189,16 @@ export function incomeBasis(t) {
168
189
  : `carried from ${span}, ${range}: no bonus it visibly held has been visibly broken since`;
169
190
  if (t.incomeMethod === 'max-observed')
170
191
  return `max observed over ${span}, ${range}`;
192
+ if (t.incomeMethod === 'rise-capped')
193
+ return t.incomeRise
194
+ ? t.incomeRise.proven !== undefined
195
+ ? `max observed over ${span}, ${range}, held at the +${t.incomeRise.proven} a capture with every source in view proved (above ${RISE_CAP}× the ~${t.incomeRise.before} before it): no turn read in full reached ${t.incomeRise.read}`
196
+ : `max observed over ${span}, ${range}, held to ${RISE_CAP}× the ~${t.incomeRise.before} before it: no turn read in full reached ${t.incomeRise.read}`
197
+ : `max observed over ${span}, ${range}, a rise held to ${RISE_CAP}× a turn`;
198
+ if (t.incomeMethod === 'tripped')
199
+ return t.incomeTrip
200
+ ? `stepped down from ~${t.incomeTrip.from} toward +${t.incomeTrip.proven}: every army it could deploy was in view on turn ${t.incomeTrip.turn}, which read +${t.incomeTrip.proven} (one ${RISE_CAP}× step a turn, never below that reading; ${span}, ${range})`
201
+ : `stepped down toward a turn read with every army it could deploy in view (${span}, ${range})`;
171
202
  if (t.incomeMethod === 'stock-flow')
172
203
  return `visible army growth plus losses (fog arrivals left out) over ${span}, ${range}`;
173
204
  if (t.incomeMethod === 'fog-captures')
@@ -507,13 +538,96 @@ function fogCapturePattern(observed) {
507
538
  const income = Math.min(last.cap, Math.ceil(armies / (last.from - hits[0].from + 1)));
508
539
  return { turns: hits.map((x) => x.from), armies, income };
509
540
  }
541
+ /**
542
+ * #418: {@link trackedIncome} with the tripwire's ceiling on the readings of the turns it covers: those
543
+ * count at most its value, the later ones whole; method `tripped` when that lowers the figure.
544
+ */
545
+ function ceiledIncome(window, visibleIncome, ceiling) {
546
+ const est = trackedIncome(window, visibleIncome);
547
+ if (!ceiling || !window.some((x) => x.from <= ceiling.through))
548
+ return est;
549
+ const later = window.filter((x) => x.from > ceiling.through);
550
+ const income = Math.max(visibleIncome, Math.min(est.income, ceiling.value), later.length ? trackedIncome(later, visibleIncome).income : 0);
551
+ return income >= est.income ? est : { ...est, income, method: 'tripped' };
552
+ }
553
+ /**
554
+ * #418, the over-read tripwire (owner decision of 2026-11-20): proof may lower an estimate only when every
555
+ * army the opponent could have deployed that turn is accounted for in view. Its deploy lands only on its
556
+ * own territories, so the turn is read in full when every territory it held on either board shows its
557
+ * armies on both, nothing beside them hides its owner on either board (#294's whole frontier read: a
558
+ * territory of its cut off in deep fog, beside none of its land in view, is the one gap), and nothing
559
+ * beside it could hide a fight that cost it armies the board does not show: no third player beside it
560
+ * (another's attack, or a failed attack of its on another, is unseen), no neutral beside it that shrank or
561
+ * changed hands (a failed attack of its), no territory of its lost, and — beside my land — my orders known
562
+ * in full (`sent` and `cards`, so `measureOrders` counts what my attacks killed and what its failed attacks
563
+ * on me cost) with no card of mine on its land. A failed attack must always show: one army kills at least
564
+ * one defender ({@link guaranteedKills}); with a capture, luck is off under straight rounding (else its cost
565
+ * varies). Not in a commerce game with an army price (it may save gold rather than deploy).
566
+ */
567
+ export function everyArmyInView(g, before, after, playerId, me, orders, settings = {}) {
568
+ if (settings.armyCostMultiplier)
569
+ return false;
570
+ const was = new Map(before.territories.map((t) => [t.territoryId, t]));
571
+ const now = new Map(after.territories.map((t) => [t.territoryId, t]));
572
+ const its = (t) => t?.owner.kind === 'player' && t.owner.playerId === playerId;
573
+ const land = new Set();
574
+ for (const id of g.territoryById.keys())
575
+ if (its(ownerShown(was.get(id))) || its(ownerShown(now.get(id))))
576
+ land.add(id);
577
+ if (!land.size)
578
+ return false;
579
+ let captured = false;
580
+ for (const id of land) {
581
+ const b = visibleState(was.get(id));
582
+ const a = visibleState(now.get(id));
583
+ if (!b || !a || !its(a))
584
+ return false;
585
+ if (!its(b))
586
+ captured = true;
587
+ }
588
+ let bordersMe = false;
589
+ for (const id of land)
590
+ for (const n of neighborsOf(g, id)) {
591
+ if (land.has(n))
592
+ continue;
593
+ const b = ownerShown(was.get(n));
594
+ const a = ownerShown(now.get(n));
595
+ if (!b || !a)
596
+ return false;
597
+ for (const o of [b.owner, a.owner]) {
598
+ if (o.kind !== 'player')
599
+ continue;
600
+ if (o.playerId !== me)
601
+ return false;
602
+ bordersMe = true;
603
+ }
604
+ if (b.owner.kind === 'neutral') {
605
+ const vb = visibleState(b);
606
+ const va = visibleState(a);
607
+ if (a.owner.kind !== 'neutral' || !vb || !va || va.armies < vb.armies)
608
+ return false;
609
+ }
610
+ }
611
+ if (bordersMe) {
612
+ if (!orders?.sent || !orders.cards)
613
+ return false;
614
+ if (orders.cards.some((c) => [c.from, c.to, c.target].some((t) => t !== undefined && land.has(t))))
615
+ return false;
616
+ }
617
+ const luck = luckFraction(settings.luckModifier);
618
+ const straight = (settings.roundingMode ?? 'StraightRound') === 'StraightRound';
619
+ if (captured && (luck > 0 || !straight))
620
+ return false;
621
+ return guaranteedKills(1, settings.offensiveKillRate ?? DEFAULT_OFFENSIVE_KILL_RATE, settings.luckModifier, settings.roundingMode) >= 1;
622
+ }
510
623
  /**
511
624
  * #123 review: a turn read in full — no ambiguous army was read as a move out of the fog (the
512
- * bound cut nothing) — whose observed deploy reaches `income` confirms it. A figure only bound-cut
625
+ * bound cut nothing) — whose observed deploy reaches `income` confirms it, and so does a pattern of
626
+ * fog captures (#271) or a capture floor (#418, {@link ObservedTurn.captureFloor}) that reaches it. A figure only bound-cut
513
627
  * readings reached (each up to twice the income carried so far) is a guess, however often it
514
628
  * compounded.
515
629
  */
516
- const confirmedBy = (window, income) => window.some((x) => (x.fogArmies === 0 && x.observed >= income) || (x.fogCaptures?.income ?? 0) >= income);
630
+ const confirmedBy = (window, income) => window.some((x) => (x.fogArmies === 0 && x.observed >= income) || (x.fogCaptures?.income ?? 0) >= income || (x.captureFloor ?? 0) >= income);
517
631
  /**
518
632
  * #119: no decay. Walk the observed turns: each window's figure (as `trackedIncome` reads it)
519
633
  * replaces the carried one only when larger; otherwise the carried figure stays, less the
@@ -526,9 +640,22 @@ const confirmedBy = (window, income) => window.some((x) => (x.fogArmies === 0 &&
526
640
  * staying pinned). The trade-off: a hidden income beyond twice the visible one, learnt only from
527
641
  * bound-cut readings (section 7's +20 read 10, 20, …), is dropped the first time it deploys into
528
642
  * the fog and shows less in full — unless a turn read in full had already confirmed it.
643
+ *
644
+ * #418: while I lead it ({@link ObservedTurn.leadIncome} above the carry before the turn, or that
645
+ * turn's visible income when larger — not above the reading, which an over-read would pass), a window
646
+ * figure above the carry that no turn read in full confirmed rises at most to {@link RISE_CAP} × that
647
+ * figure, rounded up; on a turn read in full that observed less than the carry it does not rise at all.
648
+ * #418: never below a capture floor in the window (proof may always raise an estimate).
649
+ *
650
+ * #418, the over-read tripwire: on a turn with every army it could have deployed in view
651
+ * ({@link ObservedTurn.accounted}), a carry above that turn's reading steps down at most one step,
652
+ * to ⌈carry ÷ {@link RISE_CAP}⌉, never below the reading nor its visible income; the readings of the
653
+ * turns up to it then count at most the stepped figure in every later window ({@link ceiledIncome}),
654
+ * so the next turn does not read the over-read back.
529
655
  */
530
656
  function carryIncome(observed) {
531
657
  let carry = null;
658
+ let ceiling = null;
532
659
  /**
533
660
  * #271 (2): the latest pattern of captures that needed attackers out of sight, as a carry: it is
534
661
  * evidence, not a bound-cut guess, so no later turn read in full disproves it; like any carry it
@@ -538,7 +665,7 @@ function carryIncome(observed) {
538
665
  for (let i = 0; i < observed.length; i++) {
539
666
  const x = observed[i];
540
667
  const window = observed.slice(Math.max(0, i - INCOME_TURNS + 1), i + 1);
541
- const est = trackedIncome(window, 0);
668
+ const est = ceiledIncome(window, 0, ceiling);
542
669
  const fresh = { income: est.income, set: est.income, window, est, confirmed: confirmedBy(window, est.income) };
543
670
  if (pattern)
544
671
  pattern = { ...pattern, income: Math.min(x.cap, pattern.income - x.brokenValue) };
@@ -552,12 +679,37 @@ function carryIncome(observed) {
552
679
  else {
553
680
  const disproved = !prev.confirmed && x.fogArmies === 0 && x.observed < prev.income;
554
681
  const kept = Math.min(x.cap, prev.income - x.brokenValue);
555
- carry = disproved || est.income >= kept ? fresh : { ...prev, income: kept };
682
+ if (!(disproved || est.income >= kept))
683
+ carry = { ...prev, income: kept };
684
+ else {
685
+ const before = Math.max(prev.income, x.visibleIncome);
686
+ // #418: proof may always raise an estimate: the hold never goes below a capture floor in the window.
687
+ const proof = Math.max(0, ...window.map((w) => w.captureFloor ?? 0));
688
+ const limit = Math.max(disproved ? prev.income : Math.ceil(before * RISE_CAP - 1e-9), proof);
689
+ // #418 review: the lead is judged against the carry before the rise (or its visible income), never
690
+ // against the reading being judged: an over-read above my income must not switch its own cap off.
691
+ carry =
692
+ (x.leadIncome ?? 0) > before && !fresh.confirmed && fresh.income > limit
693
+ ? { ...fresh, income: limit, set: limit, rise: { read: fresh.income, before, ...(proof >= limit ? { proven: proof } : {}) } }
694
+ : fresh;
695
+ }
556
696
  }
557
697
  if (pattern && pattern.income > carry.income)
558
698
  carry = pattern;
699
+ // #418, the over-read tripwire: on a turn with every army it could deploy in view, the carry steps
700
+ // down at most one RISE_CAP step toward that turn's reading, never below it (nor its visible income).
701
+ // It steps `carry`, never `pattern`: a #271 fog-capture pattern above the stepped figure is restored by
702
+ // the line above on the next turn, so a pattern-set reading is lowered for that one turn only.
703
+ if (x.accounted && carry.income > x.observed) {
704
+ const step = Math.max(x.observed, x.visibleIncome, Math.ceil(carry.income / RISE_CAP - 1e-9));
705
+ if (step < carry.income) {
706
+ const trip = { from: carry.income, proven: x.observed, turn: x.from };
707
+ carry = { ...carry, income: step, set: step, trip };
708
+ ceiling = { value: step, through: x.from, trip };
709
+ }
710
+ }
559
711
  }
560
- return carry;
712
+ return carry && ceiling ? { ...carry, ceiling } : carry;
561
713
  }
562
714
  /** #250: a turn that reads more than this many times the most it was seen to earn before it is a jump. */
563
715
  export const INCOME_JUMP_FACTOR = 2;
@@ -728,6 +880,29 @@ export function incomeJumpText(j, income, earlier) {
728
880
  tail = `${j.verdict === 'reveal' ? `: more only counting the ${j.cameIntoView} armies that came into view` : ': no more'}.${k ? ` ${rate[0].toUpperCase()}${rate.slice(1)} it could have received up to ${k.received} by turn ${j.turn} ${from}, enough for the ${had}.` : ''}`;
729
881
  return `${lead}${cut}${amb}${sum}${tail}`;
730
882
  }
883
+ /**
884
+ * #420: the most armies one of `playerId`'s stacks beside my land grew over one turn (board `before` →
885
+ * `after`): each territory its own on both boards, shown with its armies on both (`visibleState`), and
886
+ * next to a territory of mine on `before`; a stack that shrank or stood still reads 0. `undefined` when
887
+ * there is no such stack. Growth counts deploys and armies moved in alike: what the stack facing me
888
+ * gained, the top-up a border must answer.
889
+ */
890
+ export function borderTopUp(g, before, after, playerId, me) {
891
+ const was = new Map(before.territories.map((t) => [t.territoryId, t]));
892
+ const now = new Map(after.territories.map((t) => [t.territoryId, t]));
893
+ const owns = (t, p) => t?.owner.kind === 'player' && t.owner.playerId === p;
894
+ let most;
895
+ for (const id of [...g.territoryById.keys()].sort(byNum)) {
896
+ const b = visibleState(was.get(id));
897
+ const a = visibleState(now.get(id));
898
+ if (!owns(b, playerId) || !owns(a, playerId))
899
+ continue;
900
+ if (!neighborsOf(g, id).some((n) => owns(ownerShown(was.get(n)), me)))
901
+ continue;
902
+ most = Math.max(most ?? 0, a.armies - b.armies);
903
+ }
904
+ return most;
905
+ }
731
906
  /**
732
907
  * Per opponent: its observed deploys turn by turn, an income estimate, the armies that must be
733
908
  * in the fog and the bonuses that could explain an income gap. Those visible on the newest
@@ -741,9 +916,15 @@ export function trackOpponents(g, boards, me, settings = {}, game) {
741
916
  // One board per turn (the last given wins), oldest first.
742
917
  const byTurn = new Map();
743
918
  const ordersOn = new Map();
919
+ /** #420: the turns whose board came from GameFeed history (army counts unverified). */
920
+ const fromHistory = new Set();
744
921
  for (const b of boards) {
745
922
  byTurn.set(b.turn, neutralizeSeats(b.board, seats));
746
923
  ordersOn.set(b.turn, b.orders);
924
+ if (b.source === 'history')
925
+ fromHistory.add(b.turn);
926
+ else
927
+ fromHistory.delete(b.turn);
747
928
  }
748
929
  const turns = [...byTurn.keys()].sort(byNum);
749
930
  if (!turns.length)
@@ -859,13 +1040,18 @@ export function trackOpponents(g, boards, me, settings = {}, game) {
859
1040
  ...(expected !== null ? { expected: Math.max(expected, carriedSoFar) } : {}),
860
1041
  // #293: the same Local Deployment reading the board-only observation used.
861
1042
  ...(settings.localDeployments ? { localFree: localFreeOn(e.base, DEFAULT_BASE_INCOME, settings.opponentReinforcement, from) } : {}),
1043
+ // #418: a Bomb it may have played halves a capture's defenders before the proof reads them.
1044
+ ...(bombPossibleOn(settings, from) ? { bomb: true } : {}),
862
1045
  };
863
1046
  const { signed, ...o } = expected !== null && carriedSoFar > expected
864
1047
  ? observeSigned(g, after, before, playerId, settings, context)
865
1048
  : { ...e.observation, signed: e.observedRaw };
866
1049
  // #271 (1): a failed attack on a hold of mine bounds its deploy from below, fog or not.
867
1050
  const repelled = orders ? repelledFloor(g, before, after, me, playerId, orders, settings, guard, bombPossibleOn(settings, from)) : null;
868
- const floor = repelled?.floor ?? 0;
1051
+ // #418: a capture with every source army in view proves a minimum deploy (my orders known: one
1052
+ // beside my land reads too). Proof may always raise the reading.
1053
+ const proof = captureFloor(g, before, after, playerId, settings, guard, { me, orders, bomb: bombPossibleOn(settings, from) });
1054
+ const floor = Math.max(repelled?.floor ?? 0, proof.floor);
869
1055
  const raw = Math.max(measured ? Math.max(0, observeSigned(g, after, before, playerId, settings, context).signed + measured) : Math.max(0, signed), floor);
870
1056
  const losses = Math.max(0, change.losses + measured);
871
1057
  // #123: with my orders known, what stood on an emptied capture is measured: no high reading.
@@ -873,10 +1059,28 @@ export function trackOpponents(g, boards, me, settings = {}, game) {
873
1059
  const high = Math.max(raw, o.high + measured - (orders ? o.emptiedHigh : 0));
874
1060
  const seenObserved = Math.min(raw, e.observedCap);
875
1061
  const broken = visiblyBroken(g, before, after, playerId);
1062
+ // #418: did I lead it on the board read?
1063
+ const myLand = new Set();
1064
+ let myArmies = 0;
1065
+ let itsArmies = 0;
1066
+ for (const t of after.territories) {
1067
+ if (!g.territoryById.has(t.territoryId) || t.owner.kind !== 'player')
1068
+ continue;
1069
+ if (t.owner.playerId === me) {
1070
+ myLand.add(t.territoryId);
1071
+ myArmies += t.armies ?? 0;
1072
+ }
1073
+ else if (t.owner.playerId === playerId)
1074
+ itsArmies += t.armies ?? 0;
1075
+ }
1076
+ const leadIncome = myArmies >= LEAD_ARMIES * itsArmies ? boardIncome(g, myLand, rules).total : null;
1077
+ const topUp = fromHistory.has(from) || fromHistory.has(to) ? undefined : borderTopUp(g, before, after, playerId, me);
876
1078
  observed.push({
877
1079
  from,
878
1080
  to,
879
1081
  coverage: frontierCoverage(g, after, before, playerId),
1082
+ ...(topUp !== undefined ? { topUp } : {}),
1083
+ ...(leadIncome !== null ? { leadIncome } : {}),
880
1084
  observed: seenObserved,
881
1085
  raw,
882
1086
  ...(context.expected !== undefined ? { expected: context.expected } : {}),
@@ -898,7 +1102,9 @@ export function trackOpponents(g, boards, me, settings = {}, game) {
898
1102
  unseenAttackers: o.unseenAttackers,
899
1103
  unseenAttackerArmies: o.unseenAttackerArmies,
900
1104
  repelled: repelled?.territories.length ? repelled : null,
901
- repelledFloor: floor,
1105
+ repelledFloor: repelled?.floor ?? 0,
1106
+ ...(proof.floor > 0 ? { proven: proof.territories, captureFloor: proof.floor } : {}),
1107
+ ...(everyArmyInView(g, before, after, playerId, me, orders, settings) ? { accounted: true } : {}),
902
1108
  combat: combatLosses(g, before, after, playerId, orders
903
1109
  ? {
904
1110
  me,
@@ -929,15 +1135,26 @@ export function trackOpponents(g, boards, me, settings = {}, game) {
929
1135
  const turnsUnseen = visible ? 0 : lastTurn - back;
930
1136
  const turnsUnseenAtLeast = turnsUnseen > 0 && back >= 1 && !byTurn.has(back);
931
1137
  const recent = observed.slice(-INCOME_TURNS);
932
- const lastWindow = recent.length ? trackedIncome(recent, visibleIncome) : null;
933
1138
  // #119: no decay ({@link carryIncome}). The last three turns alone read a real 31 as 12 once
934
1139
  // it aged out.
935
1140
  const carry = carryIncome(observed);
1141
+ // #418: the readings an over-read tripwire stepped down from count at most its ceiling.
1142
+ const lastWindow = recent.length ? ceiledIncome(recent, visibleIncome, carry?.ceiling) : null;
936
1143
  const carried = carry !== null && lastWindow !== null && carry.income > lastWindow.income ? carry : null;
1144
+ // #418: an unconfirmed rise held below what the last window reads keeps the held figure.
1145
+ const held = !carried && carry?.rise && lastWindow !== null && carry.income < lastWindow.income ? carry : null;
937
1146
  const estimate = carried
938
- ? { ...carried.est, income: carried.income, method: 'carried' }
939
- : lastWindow;
940
- const incomeWindow = carried ? carried.window : recent;
1147
+ ? { ...carried.est, income: carried.income, method: (carried.trip ? 'tripped' : 'carried') }
1148
+ : held
1149
+ ? {
1150
+ ...held.est,
1151
+ income: Math.max(visibleIncome, held.income),
1152
+ method: (visibleIncome >= held.income ? 'visible' : 'rise-capped'),
1153
+ }
1154
+ : lastWindow;
1155
+ const incomeRise = held && estimate.method === 'rise-capped' ? held.rise : null;
1156
+ const incomeTrip = estimate?.method === 'tripped' ? (carried?.trip ?? carry?.ceiling?.trip ?? null) : null;
1157
+ const incomeWindow = carried ? carried.window : held ? held.window : recent;
941
1158
  const income = estimate?.income ?? null;
942
1159
  // #250: an income set by one turn far above the turns before it, with the evidence for it. Its
943
1160
  // starting armies, when known (under full distribution, an even share: an upper bound).
@@ -998,8 +1215,14 @@ export function trackOpponents(g, boards, me, settings = {}, game) {
998
1215
  incomeTurns: incomeWindow.map((x) => x.from),
999
1216
  observedRange: estimate.observedRange,
1000
1217
  incomeLowered: carried ? carried.set - carried.income : 0,
1218
+ incomeRise,
1219
+ incomeTrip,
1001
1220
  });
1002
- if (carried)
1221
+ if (incomeTrip)
1222
+ notes.push(`Income ~${income} (${basis}): proof lowers an estimate only on a turn with every army it could deploy in view, and then by one step a turn (#418). Each observed deploy is a lower bound under fog.`);
1223
+ else if (incomeRise)
1224
+ notes.push(`Income ~${income} (${basis}): a rise is held to ${RISE_CAP}× a turn until a turn read in full (no army read as a move out of the fog) confirms it, since armies walking in beside the fog are read up to twice the income carried (#418). Each observed deploy is a lower bound under fog.`);
1225
+ else if (carried)
1003
1226
  notes.push(`Income ~${income} (${basis}): an income does not decay — it is kept until a bonus it visibly held is visibly broken (less its value) or it could no longer earn it; its last ${recent.length} observed turns alone give ~${lastWindow.income}. Each observed deploy is a lower bound under fog.`);
1004
1227
  else
1005
1228
  notes.push(`Income ~${income} (${basis}): the larger of the most it was observed to deploy (each observation is a lower bound under fog, so the largest is the tightest) and its visible army growth plus losses per turn, fog arrivals left out (${estimate.stockFlow}), capped at the most it could earn (${estimate.cap}), at least its visible income ${visibleIncome}.`);
@@ -1238,8 +1461,11 @@ export function trackOpponents(g, boards, me, settings = {}, game) {
1238
1461
  observedRange: estimate?.observedRange ?? null,
1239
1462
  incomeMethod: estimate?.method ?? null,
1240
1463
  incomeLowered: carried ? carried.set - carried.income : 0,
1464
+ ...(incomeRise ? { incomeRise } : {}),
1465
+ ...(incomeTrip ? { incomeTrip } : {}),
1241
1466
  unexplained,
1242
1467
  inferred,
1468
+ topUp: observed.reduce((n, x) => (x.topUp === undefined ? n : Math.max(n ?? 0, x.topUp)), null),
1243
1469
  visible,
1244
1470
  turnsUnseen,
1245
1471
  turnsUnseenAtLeast,