@chrischall/warapp-mcp 0.0.0 → 0.1.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 (177) hide show
  1. package/.claude-plugin/marketplace.json +4 -4
  2. package/.claude-plugin/plugin.json +2 -2
  3. package/README.md +199 -8
  4. package/dist/analysis/award.js +159 -0
  5. package/dist/analysis/bonuses.js +98 -0
  6. package/dist/analysis/breach.js +62 -0
  7. package/dist/analysis/card-support.js +329 -0
  8. package/dist/analysis/card-threats.js +234 -0
  9. package/dist/analysis/cards-in-effect.js +130 -0
  10. package/dist/analysis/chains.js +59 -0
  11. package/dist/analysis/chokepoints.js +140 -0
  12. package/dist/analysis/combat.js +231 -0
  13. package/dist/analysis/commander-safety.js +149 -0
  14. package/dist/analysis/commitments.js +338 -0
  15. package/dist/analysis/exchange.js +155 -0
  16. package/dist/analysis/graph.js +82 -0
  17. package/dist/analysis/guard-off.js +54 -0
  18. package/dist/analysis/guess.js +351 -0
  19. package/dist/analysis/headroom.js +241 -0
  20. package/dist/analysis/hold-diff.js +64 -0
  21. package/dist/analysis/how-lost.js +130 -0
  22. package/dist/analysis/index.js +14 -0
  23. package/dist/analysis/local-deploy.js +159 -0
  24. package/dist/analysis/lookahead.js +108 -0
  25. package/dist/analysis/opponent-profile.js +551 -0
  26. package/dist/analysis/opponents.js +1245 -0
  27. package/dist/analysis/outlook.js +633 -0
  28. package/dist/analysis/overrides.js +60 -0
  29. package/dist/analysis/picks.js +1879 -0
  30. package/dist/analysis/plan/after-leftover.js +140 -0
  31. package/dist/analysis/plan/cap-spend.js +242 -0
  32. package/dist/analysis/plan/captures.js +1195 -0
  33. package/dist/analysis/plan/commander.js +236 -0
  34. package/dist/analysis/plan/completed.js +29 -0
  35. package/dist/analysis/plan/conceded-out.js +131 -0
  36. package/dist/analysis/plan/estimates.js +715 -0
  37. package/dist/analysis/plan/guard-off.js +232 -0
  38. package/dist/analysis/plan/holds.js +1631 -0
  39. package/dist/analysis/plan/leftover.js +760 -0
  40. package/dist/analysis/plan/move-order.js +319 -0
  41. package/dist/analysis/plan/orders.js +317 -0
  42. package/dist/analysis/plan/relations.js +702 -0
  43. package/dist/analysis/plan/report.js +672 -0
  44. package/dist/analysis/plan/shared.js +1218 -0
  45. package/dist/analysis/plan/stand-still.js +823 -0
  46. package/dist/analysis/plan/state.js +44 -0
  47. package/dist/analysis/plan/strike.js +1416 -0
  48. package/dist/analysis/plan/targets.js +651 -0
  49. package/dist/analysis/plan/team.js +299 -0
  50. package/dist/analysis/plan/threats.js +927 -0
  51. package/dist/analysis/plan/transfers.js +328 -0
  52. package/dist/analysis/plan/util.js +5 -0
  53. package/dist/analysis/plan/vacated.js +285 -0
  54. package/dist/analysis/planner.js +2922 -0
  55. package/dist/analysis/player-record.js +144 -0
  56. package/dist/analysis/player.js +268 -0
  57. package/dist/analysis/profile.js +347 -0
  58. package/dist/analysis/relations.js +1030 -0
  59. package/dist/analysis/schedule.js +88 -0
  60. package/dist/analysis/since-last.js +50 -0
  61. package/dist/analysis/static-seats.js +71 -0
  62. package/dist/analysis/stress.js +577 -0
  63. package/dist/analysis/team-brief.js +151 -0
  64. package/dist/analysis/tripwire.js +644 -0
  65. package/dist/analysis/turn-sim.js +259 -0
  66. package/dist/analysis/whereabouts.js +1109 -0
  67. package/dist/board.js +105 -0
  68. package/dist/bundle.js +117959 -36172
  69. package/dist/cards.js +435 -0
  70. package/dist/chat-cursor.js +135 -0
  71. package/dist/chat.js +192 -0
  72. package/dist/client.js +361 -0
  73. package/dist/config.js +62 -0
  74. package/dist/direct/link.js +102 -0
  75. package/dist/direct/session.js +267 -0
  76. package/dist/direct/transport.js +424 -0
  77. package/dist/guess-salt.js +65 -0
  78. package/dist/hosted.js +24 -0
  79. package/dist/index.js +33 -0
  80. package/dist/join-color.js +140 -0
  81. package/dist/live.js +278 -0
  82. package/dist/map-stats.js +152 -0
  83. package/dist/map-store.js +204 -0
  84. package/dist/move-order.js +141 -0
  85. package/dist/my-games.js +180 -0
  86. package/dist/normalize.js +411 -0
  87. package/dist/open-games.js +537 -0
  88. package/dist/outlook-log.js +138 -0
  89. package/dist/path-lock.js +22 -0
  90. package/dist/pick-list.js +193 -0
  91. package/dist/player-record-store.js +229 -0
  92. package/dist/player-states.js +31 -0
  93. package/dist/profile-store.js +677 -0
  94. package/dist/protocol/bundle.js +375 -0
  95. package/dist/protocol/codec.js +556 -0
  96. package/dist/protocol/decoded.js +12 -0
  97. package/dist/protocol/interp.js +1904 -0
  98. package/dist/protocol/methods.js +531 -0
  99. package/dist/protocol/rpc.js +202 -0
  100. package/dist/push/listener.js +393 -0
  101. package/dist/push/packets.js +66 -0
  102. package/dist/push/socketio.js +333 -0
  103. package/dist/push/websocket.js +179 -0
  104. package/dist/redact.js +62 -0
  105. package/dist/relations-store.js +242 -0
  106. package/dist/replay.js +215 -0
  107. package/dist/scalars.js +28 -0
  108. package/dist/scout.js +346 -0
  109. package/dist/stats.js +269 -0
  110. package/dist/strategy/card-clock.js +185 -0
  111. package/dist/strategy/map-notes.js +128 -0
  112. package/dist/strategy/notes.js +2168 -0
  113. package/dist/team-cards.js +84 -0
  114. package/dist/team-orders.js +150 -0
  115. package/dist/teams.js +19 -0
  116. package/dist/tools/award.js +206 -0
  117. package/dist/tools/begin-turn.js +162 -0
  118. package/dist/tools/board.js +77 -0
  119. package/dist/tools/card-advice.js +256 -0
  120. package/dist/tools/card-effects.js +49 -0
  121. package/dist/tools/card-plays.js +434 -0
  122. package/dist/tools/card-support-advice.js +140 -0
  123. package/dist/tools/chat-inbox.js +146 -0
  124. package/dist/tools/chat.js +483 -0
  125. package/dist/tools/check-plan.js +688 -0
  126. package/dist/tools/commander-check.js +102 -0
  127. package/dist/tools/commitments.js +216 -0
  128. package/dist/tools/common.js +143 -0
  129. package/dist/tools/diplomacy.js +342 -0
  130. package/dist/tools/game.js +126 -0
  131. package/dist/tools/guess-view.js +56 -0
  132. package/dist/tools/healthcheck.js +90 -0
  133. package/dist/tools/hints.js +34 -0
  134. package/dist/tools/how-lost.js +154 -0
  135. package/dist/tools/index.js +142 -0
  136. package/dist/tools/join-game.js +327 -0
  137. package/dist/tools/leave-game.js +181 -0
  138. package/dist/tools/live-context.js +339 -0
  139. package/dist/tools/live.js +404 -0
  140. package/dist/tools/map-stats.js +117 -0
  141. package/dist/tools/map.js +133 -0
  142. package/dist/tools/my-games.js +123 -0
  143. package/dist/tools/open-games.js +104 -0
  144. package/dist/tools/opponents.js +151 -0
  145. package/dist/tools/order-options.js +135 -0
  146. package/dist/tools/picks.js +292 -0
  147. package/dist/tools/profile-hook.js +156 -0
  148. package/dist/tools/profile-opponents.js +121 -0
  149. package/dist/tools/profile-reads.js +99 -0
  150. package/dist/tools/push.js +385 -0
  151. package/dist/tools/relations.js +611 -0
  152. package/dist/tools/resolve.js +45 -0
  153. package/dist/tools/route.js +36 -0
  154. package/dist/tools/scout.js +87 -0
  155. package/dist/tools/session.js +163 -0
  156. package/dist/tools/strategy.js +200 -0
  157. package/dist/tools/stress-opponents.js +83 -0
  158. package/dist/tools/surrender.js +240 -0
  159. package/dist/tools/survival.js +189 -0
  160. package/dist/tools/team-brief.js +266 -0
  161. package/dist/tools/team-source.js +222 -0
  162. package/dist/tools/team.js +182 -0
  163. package/dist/tools/turn.js +2761 -0
  164. package/dist/tools/uncommit.js +160 -0
  165. package/dist/tools/where.js +275 -0
  166. package/dist/tools/write-kit.js +158 -0
  167. package/dist/transport-bridge.js +33 -0
  168. package/dist/trend.js +452 -0
  169. package/dist/version.js +4 -0
  170. package/manifest.json +174 -4
  171. package/mint.yaml +101 -14
  172. package/package.json +11 -6
  173. package/server.json +40 -3
  174. package/skills/warapp-api/SKILL.md +95 -4
  175. package/skills/warapp-api/references/scout.mjs +348 -0
  176. package/skills/warapp-api/scripts/warapp.sh +69 -8
  177. package/skills/warapp-mcp/SKILL.md +969 -21
@@ -0,0 +1,1245 @@
1
+ import { holdsSeat } from '../player-states.js';
2
+ import { carriesTeam, isTeamGame } from '../teams.js';
3
+ import { neutralizeSeats, staticSeats } from './static-seats.js';
4
+ import { bonusTerritories } from './bonuses.js';
5
+ import { DEFAULT_DEFENSIVE_KILL_RATE, DEFAULT_OFFENSIVE_KILL_RATE, straightKills } from './combat.js';
6
+ import { bfsDistances, neighborsOf } from './graph.js';
7
+ import { bombPossibleOn, enemyDeployEstimates, failedAttackKills, holdLosses, observeSigned, ownerShown, repelledFloor, visibleState, } from './planner.js';
8
+ import { boardIncome, DEFAULT_BASE_INCOME } from './player.js';
9
+ /** #164: a stack is large when its armies are at least this many turns of its visible income. */
10
+ const LOST_STACK_INCOMES = 2;
11
+ /** #164: lost stacks kept per opponent. */
12
+ export const MAX_LOST_STACKS = 5;
13
+ /**
14
+ * #164: the planner counts a lost stack for this many turns after it was last seen, then drops it:
15
+ * by then it has been spent, split or seen without the tracker telling which.
16
+ */
17
+ export const LOST_STACK_TURNS = 6;
18
+ /** Observed turns (the latest) feeding the income estimate (#99: {@link trackedIncome}). */
19
+ const INCOME_TURNS = 3;
20
+ /**
21
+ * #271 (2): turns with a capture of a neutral in view that needed attackers out of sight, among the
22
+ * last {@link FOG_CAPTURE_TURNS} turns, that make a pattern: income, not a move.
23
+ */
24
+ export const FOG_CAPTURE_MIN = 3;
25
+ /** #271 (2): the turns a pattern of such captures is looked for in. */
26
+ export const FOG_CAPTURE_TURNS = 6;
27
+ /** Most bonuses in one inferred combination. */
28
+ const MAX_COMBINATION = 3;
29
+ /** Inferred combinations listed; when more fit, none is (#123: too many to name any). */
30
+ export const MAX_LISTED_COMBINATIONS = 8;
31
+ /** #123: an inferred bonus has a member within this many hops of a territory it visibly holds. */
32
+ export const INFER_REACH = 4;
33
+ /** #123: the least a territory it is not seen holding cost it to take (a 2-army neutral at 70%). */
34
+ const NEUTRAL_CAPTURE_LOSS = 1;
35
+ /**
36
+ * {@link TrackGame} from GameFeed's players and settings: each player's starting armies are
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
40
+ * scenario sets its own starts). A Sanctions card is an income caveat: it can cut income below
41
+ * the base the bound counts.
42
+ */
43
+ export function trackGame(players, settings, map,
44
+ /** #270: the game's end rules (`Game.endRules`): whether a surrendered or booted seat is played by an AI. */
45
+ endRules) {
46
+ const list = players.map((p) => ({
47
+ id: p.id,
48
+ ...(p.name !== undefined ? { name: p.name } : {}),
49
+ ...(p.team !== undefined ? { team: p.team } : {}),
50
+ ...(p.state !== undefined ? { state: p.state } : {}),
51
+ ...(p.humanTurnedIntoAI ? { humanTurnedIntoAI: true } : {}),
52
+ }));
53
+ const caveats = settings?.cards?.includes('Sanctions')
54
+ ? ['the game has the Sanctions card, which can cut a sanctioned player\'s income below the base']
55
+ : [];
56
+ // Every static seat; a reader leaves out me and my teammates (`staticSeatsFor`).
57
+ const seats = [...staticSeats(list, endRules).keys()].sort(byNum);
58
+ const base = { players: list, ...(seats.length ? { staticSeats: seats } : {}), ...(caveats.length ? { incomeCaveats: caveats } : {}) };
59
+ const perTerritory = settings?.initialPlayerArmiesPerTerritory !== undefined ? { startArmiesPerTerritory: Math.max(0, settings.initialPlayerArmiesPerTerritory) } : {};
60
+ if (settings?.distributionMode === FULL_DISTRIBUTION)
61
+ return {
62
+ ...base,
63
+ startUnknown: 'the game uses full distribution, which splits every territory among the players whatever the territory limit',
64
+ ...perTerritory,
65
+ fullDistribution: true,
66
+ };
67
+ const mode = map?.distributionModes.find((d) => d.id === settings?.distributionMode);
68
+ if (mode?.type !== undefined && mode.type !== 'normal')
69
+ return { ...base, startUnknown: `the game uses the map's "${mode.name}" distribution (${mode.type}), which sets its own starting armies` };
70
+ const territories = settings?.territoryLimit;
71
+ const armiesPerTerritory = settings?.initialPlayerArmiesPerTerritory;
72
+ if (territories === undefined || territories <= 0)
73
+ return { ...base, startUnknown: "the settings do not give the territories each player started with (TerritoryLimit)", ...perTerritory };
74
+ if (armiesPerTerritory === undefined)
75
+ return { ...base, startUnknown: 'the settings do not give the armies each starting territory had (InitialPlayerArmiesPerTerritory)' };
76
+ return { ...base, start: { territories, armiesPerTerritory: Math.max(0, armiesPerTerritory) } };
77
+ }
78
+ /**
79
+ * #270: the static seats of {@link TrackGame.staticSeats} that are not `me` nor a teammate of mine, by
80
+ * id with their state: the players whose territories a reader treats as neutrals.
81
+ */
82
+ export function staticSeatsFor(game, me) {
83
+ const ids = new Set(game?.staticSeats ?? []);
84
+ if (!ids.size)
85
+ return new Map();
86
+ return staticSeats(game.players.filter((p) => ids.has(p.id) || p.id === me), undefined, me);
87
+ }
88
+ /** TerritoryLimit assumed when the settings do not say (war.app's usual default). */
89
+ export const DEFAULT_TERRITORY_LIMIT = 3;
90
+ /** GameFeed's DistributionMode for full distribution (unverified, docs/WARAPP-API.md). */
91
+ const FULL_DISTRIBUTION = -1;
92
+ /** GameFeed's DistributionMode for a custom scenario (the client's id; unverified on GameFeed, docs/WARAPP-API.md). */
93
+ const CUSTOM_SCENARIO = -3;
94
+ /**
95
+ * Why the start may not have been even (#119: the planner's fog prior needs an even one), or
96
+ * `undefined` when every player started with the same territories and armies. #235: the client's
97
+ * own rules (docs/WARAPP-API.md "Starting armies and DistributionMode"): full, random warlords,
98
+ * random cities and every map distribution — a map's "scenario" distribution included, which only
99
+ * says WHERE each player or team starts and still gives each the same number of territories at the
100
+ * same armies — start even; only a custom scenario (DistributionMode -3, or a `CustomScenario`
101
+ * setting), the game creator's own territory-by-territory start, may not. Unknown (no settings, no
102
+ * DistributionMode) is not even: the prior stays off.
103
+ */
104
+ export function unevenStart(settings) {
105
+ const mode = settings?.distributionMode;
106
+ if (mode === undefined)
107
+ return 'the settings do not say how the territories were distributed (DistributionMode)';
108
+ const custom = settings?.raw?.CustomScenario;
109
+ const set = custom !== undefined && custom !== null && custom !== false && !(typeof custom === 'string' && /^\s*(null|none|false)?\s*$/i.test(custom));
110
+ if (mode === CUSTOM_SCENARIO || set)
111
+ return "the game uses a custom scenario, which sets each player's starting territories and armies by hand";
112
+ return undefined;
113
+ }
114
+ /** Every player started with the same territories and armies ({@link unevenStart} names no reason). */
115
+ export function symmetricStart(settings) {
116
+ return unevenStart(settings) === undefined;
117
+ }
118
+ /** Player states still in the game (absent counts as playing), as the profile counts them. */
119
+ const playing = (p) => (p.state ?? 'Playing') === 'Playing';
120
+ const byNum = (a, b) => a - b;
121
+ /**
122
+ * Income over a window of observed turns (#99). Each observed deploy is a LOWER BOUND on that
123
+ * turn's income: deploys onto fogged territories are unseen, and so are armies moved into the
124
+ * fog or lost in failed attacks. The median of lower bounds is no bound at all — one quiet turn
125
+ * (an opponent deploying into the fog) drags it to the floor — so the estimate is the largest:
126
+ * the tightest lower bound the window gives. Its stock and flow is the change of its visible
127
+ * armies over territories visible on both boards of each pair, plus what it visibly lost, less
128
+ * the armies that arrived out of the fog (#86: a stack out of the fog moved, it is not income),
129
+ * summed over the window and divided by its length — rounded up, erring high on an opponent as
130
+ * the planner does, and at least 0. With the fog arrivals out it is each turn's uncapped
131
+ * observed deploy averaged, so it sets the income only when a turn's observation was cut by a
132
+ * lower could-earn cap than the window's highest. The larger of the two is capped at the
133
+ * highest per-turn could-earn cap in the window (each observation already is), then floored at
134
+ * what it visibly earns, `visibleIncome`. Ties name the floor first, then the observation.
135
+ */
136
+ export function trackedIncome(window, visibleIncome) {
137
+ const observed = window.map((x) => x.observed);
138
+ const maxObserved = Math.max(...observed);
139
+ const stockFlow = Math.max(0, Math.ceil(window.reduce((s, x) => s + x.net + x.losses - x.fogArmies - (x.arrivals ?? 0), 0) / window.length));
140
+ const cap = Math.max(...window.map((x) => x.cap));
141
+ const flow = Math.min(cap, stockFlow);
142
+ // #271 (2): a pattern of captures that needed attackers out of sight, ending in the window.
143
+ const pattern = Math.max(0, ...window.map((x) => x.fogCaptures?.income ?? 0));
144
+ const fromWindow = Math.max(maxObserved, flow, pattern);
145
+ const method = visibleIncome >= fromWindow ? 'visible' : maxObserved >= Math.max(flow, pattern) ? 'max-observed' : flow >= pattern ? 'stock-flow' : 'fog-captures';
146
+ return {
147
+ income: Math.max(visibleIncome, fromWindow),
148
+ method,
149
+ observedRange: { min: Math.min(...observed), max: maxObserved },
150
+ stockFlow,
151
+ cap,
152
+ };
153
+ }
154
+ /** `turn 4` or `turns 4–6`. */
155
+ const turnSpan = (turns) => turns.length === 1 ? `turn ${turns[0]}` : `turns ${turns[0]}–${turns.at(-1)}`;
156
+ /**
157
+ * How a track's income was reached, for a rationale line or a note, e.g. "max observed over
158
+ * turns 9–11, observed 3–31"; `null` before any observed turn.
159
+ */
160
+ export function incomeBasis(t) {
161
+ if (!t.incomeMethod || !t.observedRange || !t.incomeTurns.length)
162
+ return null;
163
+ const span = turnSpan(t.incomeTurns);
164
+ const range = `observed ${t.observedRange.min}–${t.observedRange.max}`;
165
+ if (t.incomeMethod === 'carried')
166
+ return t.incomeLowered
167
+ ? `carried from ${span}, ${range}, less ${t.incomeLowered} for what it has visibly lost since`
168
+ : `carried from ${span}, ${range}: no bonus it visibly held has been visibly broken since`;
169
+ if (t.incomeMethod === 'max-observed')
170
+ return `max observed over ${span}, ${range}`;
171
+ if (t.incomeMethod === 'stock-flow')
172
+ return `visible army growth plus losses (fog arrivals left out) over ${span}, ${range}`;
173
+ if (t.incomeMethod === 'fog-captures')
174
+ return `captures of neutrals in view that needed attackers out of sight, ending in ${span}, ${range}`;
175
+ return `its visible base + bonuses, ${range} over ${span}`;
176
+ }
177
+ /**
178
+ * Its army change over territories visible on both boards, and what it visibly lost. A capture
179
+ * from me is priced at the guard, as observeDeploy prices it (#123); my orders correct both.
180
+ */
181
+ function armyChange(g, before, after, playerId, defensive, me, guard) {
182
+ const was = new Map(before.territories.map((t) => [t.territoryId, t]));
183
+ const ids = [...new Set(after.territories.map((t) => t.territoryId))].sort(byNum);
184
+ let net = 0;
185
+ let losses = 0;
186
+ const now = new Map(after.territories.map((t) => [t.territoryId, t]));
187
+ for (const id of ids) {
188
+ if (!g.territoryById.has(id))
189
+ continue;
190
+ const a = visibleState(now.get(id));
191
+ const b = visibleState(was.get(id));
192
+ if (!a || !b) {
193
+ // #164: under fog that hides the stacks (Dense / Heavy fog), a territory whose owner shows on
194
+ // both boards and that it took is still a capture in view: it left at least the guard there,
195
+ // and the capture cost what the defenders killed (their armies when shown, a capture from me
196
+ // priced at the guard; a hidden defender NEUTRAL_CAPTURE_LOSS at least). Without this its
197
+ // unaccounted armies under Dense fog would be everything it earned.
198
+ const ao = ownerShown(now.get(id));
199
+ const bo = ownerShown(was.get(id));
200
+ if (!ao || !bo || ao.owner.kind !== 'player' || ao.owner.playerId !== playerId)
201
+ continue;
202
+ if (bo.owner.kind === 'player' && bo.owner.playerId === playerId)
203
+ continue;
204
+ net += a ? a.armies : guard;
205
+ const fromMe = bo.owner.kind === 'player' && bo.owner.playerId === me;
206
+ losses += b ? straightKills(fromMe ? Math.min(b.armies, guard) : b.armies, defensive) : NEUTRAL_CAPTURE_LOSS;
207
+ continue;
208
+ }
209
+ const mineNow = a.owner.kind === 'player' && a.owner.playerId === playerId;
210
+ const mineThen = b.owner.kind === 'player' && b.owner.playerId === playerId;
211
+ if (mineNow && mineThen)
212
+ net += a.armies - b.armies;
213
+ else if (mineNow) {
214
+ // The stack now standing there came into view (from a visible source or the fog): it
215
+ // counts in `net`; the capture cost what the defenders killed, as in observeDeploy (#86).
216
+ net += a.armies;
217
+ const fromMe = b.owner.kind === 'player' && b.owner.playerId === me;
218
+ losses += straightKills(fromMe ? Math.min(b.armies, guard) : b.armies, defensive);
219
+ }
220
+ else if (mineThen) {
221
+ net -= b.armies;
222
+ losses += b.armies; // destroyed defending
223
+ }
224
+ }
225
+ return { net, losses };
226
+ }
227
+ function seesPlayer(board, g, playerId) {
228
+ return board.territories.some((t) => g.territoryById.has(t.territoryId) && t.owner.kind === 'player' && t.owner.playerId === playerId && ownerShown(t));
229
+ }
230
+ /** Bonuses `playerId` could hold but does not visibly hold in full, on `board`. */
231
+ function possibleBonuses(g, board, playerId) {
232
+ const seen = new Map(board.territories.map((t) => [t.territoryId, t]));
233
+ // Hops from its visible territories (breadth first, over the whole map).
234
+ const hops = new Map();
235
+ let frontier = [];
236
+ for (const t of board.territories) {
237
+ const st = ownerShown(t);
238
+ if (g.territoryById.has(t.territoryId) && st?.owner.kind === 'player' && st.owner.playerId === playerId) {
239
+ hops.set(t.territoryId, 0);
240
+ frontier.push(t.territoryId);
241
+ }
242
+ }
243
+ for (let d = 1; frontier.length; d++) {
244
+ const next = [];
245
+ for (const t of frontier)
246
+ for (const n of g.neighbors.get(t) ?? [])
247
+ if (!hops.has(n)) {
248
+ hops.set(n, d);
249
+ next.push(n);
250
+ }
251
+ frontier = next;
252
+ }
253
+ const out = [];
254
+ for (const b of [...g.map.bonuses].sort((x, y) => x.id - y.id)) {
255
+ const ts = bonusTerritories(g, b.id);
256
+ if (b.value <= 0 || !ts.length)
257
+ continue;
258
+ let held = 0;
259
+ let taken = false;
260
+ for (const t of ts) {
261
+ const st = ownerShown(seen.get(t));
262
+ if (!st)
263
+ continue;
264
+ if (st.owner.kind === 'player' && st.owner.playerId === playerId)
265
+ held++;
266
+ else
267
+ taken = true;
268
+ }
269
+ if (!taken && held < ts.length)
270
+ out.push({
271
+ id: b.id,
272
+ value: b.value,
273
+ hops: Math.min(...ts.map((t) => hops.get(t) ?? Infinity)),
274
+ cost: (ts.length - held) * NEUTRAL_CAPTURE_LOSS,
275
+ });
276
+ }
277
+ return out;
278
+ }
279
+ /** Positive bonuses `playerId` visibly holds in full on `board`: every member shown as its. */
280
+ function visiblyHeld(g, board, playerId) {
281
+ const seen = new Map(board.territories.map((t) => [t.territoryId, t]));
282
+ return [...g.map.bonuses]
283
+ .sort((x, y) => x.id - y.id)
284
+ .filter((b) => {
285
+ const ts = bonusTerritories(g, b.id);
286
+ if (b.value <= 0 || !ts.length)
287
+ return false;
288
+ return ts.every((t) => {
289
+ const st = ownerShown(seen.get(t));
290
+ return st?.owner.kind === 'player' && st.owner.playerId === playerId;
291
+ });
292
+ })
293
+ .map((b) => ({ id: b.id, value: b.value }));
294
+ }
295
+ /** Of the bonuses it visibly held in full on `before`, those `after` shows a member of held by someone else. */
296
+ function visiblyBroken(g, before, after, playerId) {
297
+ const now = new Map(after.territories.map((t) => [t.territoryId, t]));
298
+ return visiblyHeld(g, before, playerId).filter((b) => bonusTerritories(g, b.id).some((t) => {
299
+ const st = ownerShown(now.get(t));
300
+ return st !== undefined && !(st.owner.kind === 'player' && st.owner.playerId === playerId);
301
+ }));
302
+ }
303
+ /**
304
+ * What my own orders on the turn `before` → `after` measure of `playerId`'s deploy (#119), to add
305
+ * to the board's reading ({@link observeSigned}) — which leaves both out, as
306
+ * {@link observeDeploy}'s comment says:
307
+ * - a failed attack of mine (a move onto a territory it shows on both boards): its defenders lost
308
+ * what my attackers killed, round(armies × the offensive kill rate) — the board reads that loss
309
+ * as a shrink, so it counts back. Not when its source fell this turn: it may have been taken
310
+ * before my attack ran;
311
+ * - a hold of mine that fell to it: its defenders were my armies there plus what I deployed there
312
+ * less what I sent out of it; the board reading priced the capture at the guard (#123, the
313
+ * least I may have left), so the difference in what they killed (at the defensive kill rate)
314
+ * is the correction;
315
+ * - its failed attack on a hold of mine ({@link attacksOnMyHolds}): what it lost there — the board
316
+ * reads that loss as a shrink, so it counts back.
317
+ * Kill counts are straight-rounded expectations: luck can move them.
318
+ */
319
+ export function measureOrders(g, before, after, me, playerId, orders, settings = {}) {
320
+ const offensive = settings.offensiveKillRate ?? DEFAULT_OFFENSIVE_KILL_RATE;
321
+ const defensive = settings.defensiveKillRate ?? DEFAULT_DEFENSIVE_KILL_RATE;
322
+ const guard = (settings.oneArmyStandsGuard ?? true) ? 1 : 0;
323
+ const was = new Map(before.territories.map((t) => [t.territoryId, t]));
324
+ const now = new Map(after.territories.map((t) => [t.territoryId, t]));
325
+ const owns = (t, p) => t?.owner.kind === 'player' && t.owner.playerId === p;
326
+ const deployed = new Map();
327
+ for (const d of orders.deploys)
328
+ deployed.set(d.territoryId, (deployed.get(d.territoryId) ?? 0) + Math.max(0, d.armies));
329
+ const sent = new Map();
330
+ for (const m of orders.moves)
331
+ sent.set(m.from, (sent.get(m.from) ?? 0) + Math.max(0, m.armies));
332
+ // My failed attacks (a source that fell this turn may have been taken before my attack ran: not
333
+ // measured): the same count the planner's single-turn reading uses (#226, failedAttackKills).
334
+ let measured = 0;
335
+ for (const k of failedAttackKills(g, before, after, me, playerId, orders, { offensiveKillRate: offensive }).values())
336
+ measured += k;
337
+ const ids = [...new Set(after.territories.map((t) => t.territoryId))].sort(byNum);
338
+ for (const id of ids) {
339
+ if (!g.territoryById.has(id))
340
+ continue;
341
+ const b = visibleState(was.get(id));
342
+ if (!owns(b, me) || !owns(visibleState(now.get(id)), playerId))
343
+ continue;
344
+ const defenders = Math.max(0, b.armies + (deployed.get(id) ?? 0) - (sent.get(id) ?? 0));
345
+ measured += straightKills(defenders, defensive) - straightKills(Math.min(b.armies, guard), defensive);
346
+ }
347
+ for (const a of attacksOnMyHolds(g, before, after, me, orders, settings))
348
+ if (a.attacker === playerId)
349
+ measured += a.attackerLoss;
350
+ return measured;
351
+ }
352
+ /**
353
+ * My holds (mine, with armies, on both boards) that lost armies my orders do not explain: the
354
+ * defenders were my armies there plus what I deployed there and moved in, less what I sent out;
355
+ * what the later board shows less is what an attack that failed killed. Its attackers were that
356
+ * loss ÷ the offensive kill rate, and it lost them all, up to what the defenders killed (at the
357
+ * defensive kill rate). A hold I attacked out of and failed is skipped: the survivors of my own
358
+ * attack came back to it, so its loss is not known. Straight-rounded expectations: luck can move them.
359
+ */
360
+ function attacksOnMyHolds(g, before, after, me, orders, settings) {
361
+ const offensive = settings.offensiveKillRate ?? DEFAULT_OFFENSIVE_KILL_RATE;
362
+ const defensive = settings.defensiveKillRate ?? DEFAULT_DEFENSIVE_KILL_RATE;
363
+ const was = new Map(before.territories.map((t) => [t.territoryId, t]));
364
+ return holdLosses(g, before, after, me, orders).map(({ territoryId, defenders, loss }) => {
365
+ const others = new Set();
366
+ for (const n of neighborsOf(g, territoryId)) {
367
+ const st = visibleState(was.get(n));
368
+ if (st?.owner.kind === 'player' && st.owner.playerId !== me)
369
+ others.add(st.owner.playerId);
370
+ }
371
+ const attackers = Math.round((loss * 100) / offensive);
372
+ return {
373
+ territoryId,
374
+ loss,
375
+ attacker: others.size === 1 ? [...others][0] : null,
376
+ attackerLoss: Math.min(attackers, straightKills(defenders, defensive)),
377
+ };
378
+ });
379
+ }
380
+ /**
381
+ * What `playerId` may have lost fighting on the turn `before` → `after` (#123): on each of its
382
+ * territories shown with armies on both boards that shrank, each neighbour of another player
383
+ * shown with armies on both boards that shrank too (claimed once, ascending ids) counts
384
+ * round(its shrink × offensive ÷ defensive kill rate) — the armies a failed attack that cost the
385
+ * neighbour that many killed. When my orders measured the turn (`measured`), a hold of mine counts
386
+ * only where an attack on it is pinned on no one ({@link attacksOnMyHolds}: more than one other
387
+ * player beside it), with the loss my orders do not explain as its shrink; the rest of mine are
388
+ * left out (my orders explain them, or {@link measureOrders} counted them).
389
+ * The board cannot tell a fight from a transfer, nor whom the neighbour fought (a third player)
390
+ * or where its armies went: it can overcount, so only the unexplained armies use it (where it only
391
+ * makes the count more cautious); {@link incomeJump} leaves it out, since there it would make a case.
392
+ * The ratio is a heuristic: a failed attack's real loss runs from about 0.6x to 1.43x the
393
+ * attacker's shrink, depending on how many attacked; offensive ÷ defensive (about 0.86x at the
394
+ * defaults) sits inside that range and needs only the two shrinks the boards show.
395
+ */
396
+ function combatLosses(g, before, after, playerId, measured, settings) {
397
+ const offensive = settings.offensiveKillRate ?? DEFAULT_OFFENSIVE_KILL_RATE;
398
+ const defensive = settings.defensiveKillRate ?? DEFAULT_DEFENSIVE_KILL_RATE;
399
+ const was = new Map(before.territories.map((t) => [t.territoryId, t]));
400
+ const now = new Map(after.territories.map((t) => [t.territoryId, t]));
401
+ /** Its shrink when one player shows it with armies on both boards; else null. */
402
+ const shrinkOf = (id) => {
403
+ const a = visibleState(now.get(id));
404
+ const b = visibleState(was.get(id));
405
+ if (a?.owner.kind !== 'player' || b?.owner.kind !== 'player' || a.owner.playerId !== b.owner.playerId)
406
+ return null;
407
+ return { player: a.owner.playerId, shrink: b.armies - a.armies };
408
+ };
409
+ const claimed = new Set();
410
+ let lost = 0;
411
+ for (const id of [...new Set(after.territories.map((t) => t.territoryId))].sort(byNum)) {
412
+ if (!g.territoryById.has(id))
413
+ continue;
414
+ const own = shrinkOf(id);
415
+ if (own?.player !== playerId || own.shrink <= 0)
416
+ continue;
417
+ for (const n of [...neighborsOf(g, id)].sort(byNum)) {
418
+ if (claimed.has(n))
419
+ continue;
420
+ const seen = shrinkOf(n);
421
+ const other = seen && measured && seen.player === measured.me ? { ...seen, shrink: measured.unpinned.get(n) ?? 0 } : seen;
422
+ if (!other || other.player === playerId || other.shrink <= 0)
423
+ continue;
424
+ claimed.add(n);
425
+ lost += Math.round((other.shrink * offensive) / defensive);
426
+ }
427
+ }
428
+ return lost;
429
+ }
430
+ /**
431
+ * The combinations of up to {@link MAX_COMBINATION} bonuses whose total comes closest to `gap`
432
+ * (within max(1, a quarter of the gap)), fewest bonuses first, then nearest (summed hops), then
433
+ * by ids. Only plausible bonuses take part (#123): a member within {@link INFER_REACH} hops of a
434
+ * territory it visibly holds, and a combination costing no more than `budget` (what it could
435
+ * have received). When more than {@link MAX_LISTED_COMBINATIONS} fit, none is listed.
436
+ * The cost binds mostly early and on large bonuses: one army per member against what it earned
437
+ * (seen, or the base income on the turns not seen). The reach filter does most of the work.
438
+ */
439
+ function inferBonuses(all, gap, budget) {
440
+ const tolerance = Math.max(1, Math.round(gap / 4));
441
+ const options = all.filter((b) => b.hops <= INFER_REACH && b.cost <= budget);
442
+ const sorted = [...options].sort((a, b) => a.value - b.value || a.id - b.id);
443
+ let best = Infinity;
444
+ let found = [];
445
+ const pick = [];
446
+ const visit = (start, sum, cost) => {
447
+ if (pick.length) {
448
+ const diff = Math.abs(sum - gap);
449
+ if (diff <= tolerance && diff <= best) {
450
+ if (diff < best) {
451
+ best = diff;
452
+ found = [];
453
+ }
454
+ found.push({ bonusIds: pick.map((p) => p.id).sort(byNum), total: sum, hops: pick.reduce((h, p) => h + p.hops, 0) });
455
+ }
456
+ }
457
+ if (pick.length === MAX_COMBINATION)
458
+ return;
459
+ for (let i = start; i < sorted.length; i++) {
460
+ const b = sorted[i];
461
+ // Values only grow from here: past the gap plus the tolerance nothing fits.
462
+ if (sum + b.value > gap + tolerance)
463
+ break;
464
+ if (cost + b.cost > budget)
465
+ continue;
466
+ pick.push(b);
467
+ visit(i + 1, sum + b.value, cost + b.cost);
468
+ pick.pop();
469
+ }
470
+ };
471
+ visit(0, 0, 0);
472
+ found.sort((a, b) => {
473
+ if (a.bonusIds.length !== b.bonusIds.length)
474
+ return a.bonusIds.length - b.bonusIds.length;
475
+ if (a.hops !== b.hops)
476
+ return a.hops - b.hops;
477
+ for (let i = 0; i < a.bonusIds.length; i++)
478
+ if (a.bonusIds[i] !== b.bonusIds[i])
479
+ return a.bonusIds[i] - b.bonusIds[i];
480
+ return 0;
481
+ });
482
+ const tooMany = found.length > MAX_LISTED_COMBINATIONS;
483
+ return {
484
+ gap,
485
+ exact: best === 0,
486
+ candidates: tooMany ? [] : found,
487
+ more: tooMany ? found.length : 0,
488
+ implausible: all.length - options.length,
489
+ };
490
+ }
491
+ /**
492
+ * #271 (2): a pattern of captures of neutrals in view that needed attackers out of sight, ending on
493
+ * the newest observed turn: {@link FOG_CAPTURE_MIN} or more turns with one among the observed turns
494
+ * of the last {@link FOG_CAPTURE_TURNS} (by turn number, the newest included). One such capture may
495
+ * be a banked stack walking out of the fog; three in six turns are income it earns out of sight. The
496
+ * attackers they needed (beyond what its stacks in view sent) are spread over the turns from the
497
+ * first of them to the newest, rounded up, at most the newest turn's could-earn cap. Null without one.
498
+ */
499
+ function fogCapturePattern(observed) {
500
+ const last = observed.at(-1);
501
+ if (!last)
502
+ return null;
503
+ const hits = observed.filter((x) => x.from > last.from - FOG_CAPTURE_TURNS && (x.unseenAttackerArmies ?? 0) > 0);
504
+ if (hits.length < FOG_CAPTURE_MIN)
505
+ return null;
506
+ const armies = hits.reduce((n, x) => n + (x.unseenAttackerArmies ?? 0), 0);
507
+ const income = Math.min(last.cap, Math.ceil(armies / (last.from - hits[0].from + 1)));
508
+ return { turns: hits.map((x) => x.from), armies, income };
509
+ }
510
+ /**
511
+ * #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
513
+ * readings reached (each up to twice the income carried so far) is a guess, however often it
514
+ * compounded.
515
+ */
516
+ const confirmedBy = (window, income) => window.some((x) => (x.fogArmies === 0 && x.observed >= income) || (x.fogCaptures?.income ?? 0) >= income);
517
+ /**
518
+ * #119: no decay. Walk the observed turns: each window's figure (as `trackedIncome` reads it)
519
+ * replaces the carried one only when larger; otherwise the carried figure stays, less the
520
+ * bonuses it visibly held that were visibly broken that turn, and never above that turn's
521
+ * could-earn cap. Null with no observed turn.
522
+ *
523
+ * #123 review: a carry no turn read in full ever confirmed does not outlive a later turn read in
524
+ * full that observed less: the window's figure takes over (so walk-ins over several turns, each
525
+ * read up to twice the carry before it, age out of the window as a one-off does, rather than
526
+ * staying pinned). The trade-off: a hidden income beyond twice the visible one, learnt only from
527
+ * bound-cut readings (section 7's +20 read 10, 20, …), is dropped the first time it deploys into
528
+ * the fog and shows less in full — unless a turn read in full had already confirmed it.
529
+ */
530
+ function carryIncome(observed) {
531
+ let carry = null;
532
+ /**
533
+ * #271 (2): the latest pattern of captures that needed attackers out of sight, as a carry: it is
534
+ * evidence, not a bound-cut guess, so no later turn read in full disproves it; like any carry it
535
+ * falls with the bonuses visibly broken since and never stays above a turn's could-earn cap.
536
+ */
537
+ let pattern = null;
538
+ for (let i = 0; i < observed.length; i++) {
539
+ const x = observed[i];
540
+ const window = observed.slice(Math.max(0, i - INCOME_TURNS + 1), i + 1);
541
+ const est = trackedIncome(window, 0);
542
+ const fresh = { income: est.income, set: est.income, window, est, confirmed: confirmedBy(window, est.income) };
543
+ if (pattern)
544
+ pattern = { ...pattern, income: Math.min(x.cap, pattern.income - x.brokenValue) };
545
+ if (x.fogCaptures && x.fogCaptures.income >= (pattern?.income ?? 0)) {
546
+ const income = x.fogCaptures.income;
547
+ pattern = { income, set: income, window, est: { ...est, income, method: 'fog-captures' }, confirmed: true };
548
+ }
549
+ const prev = carry;
550
+ if (!prev)
551
+ carry = fresh;
552
+ else {
553
+ const disproved = !prev.confirmed && x.fogArmies === 0 && x.observed < prev.income;
554
+ const kept = Math.min(x.cap, prev.income - x.brokenValue);
555
+ carry = disproved || est.income >= kept ? fresh : { ...prev, income: kept };
556
+ }
557
+ if (pattern && pattern.income > carry.income)
558
+ carry = pattern;
559
+ }
560
+ return carry;
561
+ }
562
+ /** #250: a turn that reads more than this many times the most it was seen to earn before it is a jump. */
563
+ export const INCOME_JUMP_FACTOR = 2;
564
+ /** The armies of `playerId` on territories shown with armies on `board`, and their armies by id. */
565
+ function armiesInView(g, board, playerId) {
566
+ let total = 0;
567
+ const ids = new Map();
568
+ for (const t of board.territories) {
569
+ if (!g.territoryById.has(t.territoryId))
570
+ continue;
571
+ const st = visibleState(t);
572
+ if (st?.owner.kind !== 'player' || st.owner.playerId !== playerId)
573
+ continue;
574
+ total += st.armies;
575
+ ids.set(t.territoryId, st.armies);
576
+ }
577
+ return { total, ids };
578
+ }
579
+ /**
580
+ * #250: when the income was set by the most observed in its window (`max-observed`, or carried from
581
+ * such a window) and that turn read more than {@link INCOME_JUMP_FACTOR} × the most it was seen to
582
+ * earn on the consecutive observed turns just before it (up to {@link INCOME_TURNS} − 1 of them),
583
+ * weigh the boards: its armies in view after the jump plus what it was seen to lose since the first
584
+ * of those turns, against its armies in view then plus what it was seen to earn since (the jump turn
585
+ * at its visible income only). More than that, even without the armies that only came into view, is
586
+ * armies it could not have banked: `supported`. Given its starting armies (`startArmies`), the whole
587
+ * game is weighed too ({@link IncomeJump.stock}), which no reveal of old armies can explain. Undefined
588
+ * without such a jump, without the boards to weigh it, or when a later observed turn also reads more
589
+ * than {@link INCOME_JUMP_FACTOR} × that most (the income then rests on more than one turn).
590
+ */
591
+ export function incomeJump(g, byTurn, playerId, observed, window, method, startArmies, me) {
592
+ if (method !== 'max-observed' || !window.length)
593
+ return undefined;
594
+ const max = Math.max(...window.map((x) => x.observed));
595
+ const x = window.find((w) => w.observed === max);
596
+ // The consecutive observed turns just before it (at most INCOME_TURNS − 1): a carried window may
597
+ // start at the jump (#119), so they are looked up in the whole history.
598
+ const at = observed.indexOf(x);
599
+ let first = at;
600
+ while (first > 0 && at - first < INCOME_TURNS - 1 && observed[first - 1].to === observed[first].from)
601
+ first--;
602
+ const prev = observed.slice(first, at);
603
+ if (!prev.length)
604
+ return undefined;
605
+ const before = Math.max(...prev.map((p) => p.earned));
606
+ // `earned` is floored at its visible income (base income + visibly held bonuses), so a fogged turn
607
+ // that read 0 still counts at least its base income here: `before` is 0 only in a game whose base
608
+ // income is 0 with no bonus held in view, where no ratio means anything (any positive turn would be
609
+ // "more than twice"), so no line is given.
610
+ if (before <= 0 || x.observed <= INCOME_JUMP_FACTOR * before)
611
+ return undefined;
612
+ // A later observed turn that also reads more than INCOME_JUMP_FACTOR × `before` backs it: the
613
+ // income no longer rests on one turn, and a line weighing that turn alone would hedge a figure
614
+ // two readings carry.
615
+ if (observed.some((p) => p.from > x.from && p.observed > INCOME_JUMP_FACTOR * before))
616
+ return undefined;
617
+ const since = prev[0].from;
618
+ const start = byTurn.get(since);
619
+ const end = byTurn.get(x.to);
620
+ if (!start || !end)
621
+ return undefined;
622
+ const then = armiesInView(g, start, playerId);
623
+ const now = armiesInView(g, end, playerId);
624
+ const span = [...prev, x];
625
+ const earnedSince = prev.reduce((s, p) => s + p.earned, 0) + x.visibleIncome;
626
+ // `losses` only: `combat` is a guess that can count a transfer as a fight ({@link combatLosses}),
627
+ // and on this side it would make the case for the jump.
628
+ const lossesSeen = span.reduce((s, p) => s + p.losses, 0);
629
+ // The jump turn's ambiguous armies (#123) read as deploy may be a stack out of the fog: counting
630
+ // them as income would make the case for the jump with the very armies it is about.
631
+ const ambiguous = Math.max(0, x.observed - x.low);
632
+ // #271 (3): arrivals from its stacks hidden after came into view too.
633
+ let cameIntoView = span.reduce((s, p) => s + p.fogArmies + (p.arrivals ?? 0), 0) + ambiguous;
634
+ // A territory it holds after the jump that some board from `since` up to the jump did not show
635
+ // (owner and armies): its armies may be old ones revealed. One shown on every one of them is no
636
+ // reveal, whoever held it: a capture there (from a neutral or a player in view) is in the readings.
637
+ const boards = span.map((p) => byTurn.get(p.from));
638
+ const shownThroughout = (id) => boards.every((b) => b?.territories.some((t) => t.territoryId === id && visibleState(t)));
639
+ // Less what it had in view there on the board of `since`: those armies are in `armiesBefore` already.
640
+ for (const [id, armies] of now.ids)
641
+ if (!shownThroughout(id))
642
+ cameIntoView += Math.max(0, armies - (then.ids.get(id) ?? 0));
643
+ const seen = now.total + lossesSeen;
644
+ const banked = then.total + earnedSince;
645
+ let stock;
646
+ if (startArmies !== undefined) {
647
+ // Every observed turn before the jump, not only the ones `before` weighs: a high reading earlier
648
+ // in the game is income it may have kept earning out of sight.
649
+ const rate = Math.max(x.visibleIncome, ...observed.filter((p) => p.from < x.from).map((p) => p.earned));
650
+ const turns = Math.max(0, x.from);
651
+ const lossesAll = observed.filter((p) => p.from <= x.from).reduce((s, p) => s + p.losses, 0);
652
+ stock = { start: startArmies, rate, turns, received: startArmies + rate * turns, lossesAll };
653
+ }
654
+ // #250: the captures from me on the jump turn, and what stands on them after it.
655
+ let fromMe;
656
+ const jumpBoard = byTurn.get(x.from);
657
+ if (me !== undefined && jumpBoard) {
658
+ const taken = x.captured.filter((id) => jumpBoard.territories.some((t) => {
659
+ if (t.territoryId !== id)
660
+ return false;
661
+ const st = visibleState(t);
662
+ return st?.owner.kind === 'player' && st.owner.playerId === me;
663
+ }));
664
+ if (taken.length)
665
+ fromMe = {
666
+ territories: [...taken].sort((a, b) => a - b),
667
+ armies: taken.reduce((s, id) => s + (now.ids.get(id) ?? 0), 0),
668
+ guardPriced: !x.measured && taken.some((id) => x.emptied.includes(id)),
669
+ low: x.low,
670
+ high: x.high,
671
+ };
672
+ }
673
+ const verdict = seen - cameIntoView > banked || (stock && now.total + stock.lossesAll > stock.received) ? 'supported' : seen > banked ? 'reveal' : 'banked';
674
+ return {
675
+ turn: x.from,
676
+ observed: x.observed,
677
+ before,
678
+ since,
679
+ armiesBefore: then.total,
680
+ earnedSince,
681
+ armiesNow: now.total,
682
+ lossesSeen,
683
+ cameIntoView,
684
+ ambiguous,
685
+ low: x.low,
686
+ high: x.high,
687
+ ...(fromMe ? { fromMe } : {}),
688
+ ...(stock ? { stock } : {}),
689
+ verdict,
690
+ };
691
+ }
692
+ /**
693
+ * #250: the line for an {@link IncomeJump} (the subject — "Player X's" — prefixed by the caller). #254:
694
+ * the verdict comes first in about a dozen words, then one sentence of numbers; every figure is in
695
+ * the track tool's `income.jump`.
696
+ */
697
+ export function incomeJumpText(j, income, earlier) {
698
+ const seen = j.armiesNow + j.lossesSeen;
699
+ const banked = j.armiesBefore + j.earnedSince;
700
+ const readings = earlier.map((p) => `+${p.earned}`).join(', ');
701
+ const onJump = j.earnedSince - earlier.reduce((s, p) => s + p.earned, 0);
702
+ const proven = j.verdict === 'supported' && seen - j.cameIntoView > banked;
703
+ const verdict = proven
704
+ ? 'confirmed — armies it could not have banked; do not lower it'
705
+ : j.verdict === 'supported'
706
+ ? 'kept — more armies than its earlier rate allows; not proof of this turn'
707
+ : `not confirmed, kept as a lower bound; could be ${j.verdict === 'reveal' ? 'old armies revealed' : 'armies it had banked'}`;
708
+ const lead = `+${j.observed} on one turn (turn ${j.turn}): ${verdict}.`;
709
+ // A carried figure (#119) may have been cut since: a bonus it held visibly broken, or more than it could earn.
710
+ const cut = income < j.observed ? ` Tracked ~${income}/turn, less ${j.observed - income} since (a bonus broken, or more than it could earn).` : '';
711
+ // #123: armies the jump turn read as deploy that may be a stack out of the fog.
712
+ const amb = j.ambiguous ? ` Turn ${j.turn} reads +${j.low} to +${j.high}: ${j.ambiguous} may be a stack out of the fog.` : '';
713
+ const m = j.fromMe;
714
+ const fromMe = m
715
+ ? `, ${m.armies} on territor${m.territories.length === 1 ? 'y' : 'ies'} ${m.territories.join(', ')} taken from me${m.guardPriced ? ` (priced at the guard I may have left: turn ${j.turn} reads +${m.low} to +${m.high})` : ''}`
716
+ : '';
717
+ const sum = ` Over ${INCOME_JUMP_FACTOR}× the ${j.before} before it; ${j.armiesNow} in view on turn ${j.turn + 1}${fromMe} + ${j.lossesSeen} lost = ${seen}, vs ${j.armiesBefore} on turn ${j.since} + ${j.earnedSince} earned (${readings ? `${readings}, then ` : ''}+${onJump} visible on turn ${j.turn}) = ${banked}`;
718
+ const k = j.stock;
719
+ const had = k ? j.armiesNow + k.lossesAll : 0;
720
+ const rate = k ? `at ${k.rate} a turn` : '';
721
+ const from = k ? `(starting armies ${k.start} + ${k.rate} × ${k.turns} turns)` : '';
722
+ let tail;
723
+ if (proven)
724
+ tail = `: more by ${seen - banked}${j.cameIntoView ? `, ${seen - j.cameIntoView - banked} without the ${j.cameIntoView} that came into view` : ''}.`;
725
+ else if (j.verdict === 'supported' && k)
726
+ tail = `; ${rate} it could have received at most ${k.received} ${from}, yet shows ${had} with its losses, more by ${had - k.received}: armies it could not have had at that rate (cards aside).`;
727
+ else
728
+ 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
+ return `${lead}${cut}${amb}${sum}${tail}`;
730
+ }
731
+ /**
732
+ * Per opponent: its observed deploys turn by turn, an income estimate, the armies that must be
733
+ * in the fog and the bonuses that could explain an income gap. Those visible on the newest
734
+ * board come first (by id); given `game`, every other opponent still playing follows (by id),
735
+ * with its received lower bound (#94). `boards` are my views of the same game, any order; only
736
+ * consecutive turns are compared. See the module comment for the rules.
737
+ */
738
+ export function trackOpponents(g, boards, me, settings = {}, game) {
739
+ // #270: a static seat (out, no AI on it) deploys nothing: its territories read as neutrals.
740
+ const seats = staticSeatsFor(game, me);
741
+ // One board per turn (the last given wins), oldest first.
742
+ const byTurn = new Map();
743
+ const ordersOn = new Map();
744
+ for (const b of boards) {
745
+ byTurn.set(b.turn, neutralizeSeats(b.board, seats));
746
+ ordersOn.set(b.turn, b.orders);
747
+ }
748
+ const turns = [...byTurn.keys()].sort(byNum);
749
+ if (!turns.length)
750
+ return [];
751
+ const lastTurn = turns.at(-1);
752
+ const latest = byTurn.get(lastTurn);
753
+ const visibleOn = new Map();
754
+ const visibleAt = (turn) => {
755
+ let m = visibleOn.get(turn);
756
+ if (!m) {
757
+ m = new Map(enemyDeployEstimates(g, byTurn.get(turn), me, settings, undefined, undefined, undefined, { turn }).map((e) => [e.playerId, e]));
758
+ visibleOn.set(turn, m);
759
+ }
760
+ return m;
761
+ };
762
+ /** Each board's territories by id (#164: the lost-stack scan reads every territory on every board). */
763
+ const shownBy = new Map();
764
+ const shownOn = (turn) => {
765
+ let m = shownBy.get(turn);
766
+ if (!m) {
767
+ m = new Map(byTurn.get(turn).territories.map((t) => [t.territoryId, t]));
768
+ shownBy.set(turn, m);
769
+ }
770
+ return m;
771
+ };
772
+ const players = game?.players ?? [];
773
+ const teams = isTeamGame(players);
774
+ const myTeam = players.find((p) => p.id === me)?.team;
775
+ const ally = (p) => p.id === me || (teams && carriesTeam(myTeam) && p.team === myTeam);
776
+ // A teammate in view is not an opponent either (given the game's players).
777
+ const visibleIds = [...visibleAt(lastTurn).keys()].filter((id) => {
778
+ const p = players.find((x) => x.id === id);
779
+ return !p || !ally(p);
780
+ });
781
+ const unseenIds = players
782
+ .filter((p) => !ally(p) && playing(p) && !visibleIds.includes(p.id))
783
+ .map((p) => p.id)
784
+ .sort(byNum);
785
+ const nameOf = (id) => players.find((p) => p.id === id)?.name ?? String(id);
786
+ // My stacks on the newest board, against which an unseen opponent's bound is weighed.
787
+ let largestStack = 0;
788
+ let visibleArmies = 0;
789
+ for (const t of latest.territories) {
790
+ if (!g.territoryById.has(t.territoryId) || t.owner.kind !== 'player' || t.owner.playerId !== me || t.armies === null)
791
+ continue;
792
+ largestStack = Math.max(largestStack, t.armies);
793
+ visibleArmies += t.armies;
794
+ }
795
+ const rules = { base: Math.max(0, Math.floor(settings.baseIncome ?? DEFAULT_BASE_INCOME)), per: settings.bonusArmyPer ?? 0 };
796
+ const guard = (settings.oneArmyStandsGuard ?? true) ? 1 : 0;
797
+ // The one income rule over no territory: the base income floor, never a bonus. With nothing in
798
+ // view it may hold as little as one territory, and floor(1 / BonusArmyPer) never beats the base.
799
+ const baseIncome = boardIncome(g, new Set(), rules).total;
800
+ // When the base income each turn may not be a floor: a held negative bonus can take income
801
+ // below it (boardIncome clamps only the total at 0), and so can a Sanctions card.
802
+ const caveats = [
803
+ ...(g.map.bonuses.some((b) => b.value < 0) ? ['the map has a negative-value bonus, which can take income below the base'] : []),
804
+ ...(game?.incomeCaveats ?? []),
805
+ ];
806
+ // Only seated players split the map: GameFeed also lists players who never took a seat (Invited,
807
+ // Declined, RemovedByHost), and counting them would shrink the share and the start with it.
808
+ const seated = players.filter((p) => holdsSeat(p.state)).length;
809
+ const startArmies = game?.start
810
+ ? game.start.territories * game.start.armiesPerTerritory
811
+ : game?.fullDistribution && game.startArmiesPerTerritory !== undefined && seated > 0
812
+ ? Math.ceil(g.territoryById.size / seated) * game.startArmiesPerTerritory
813
+ : undefined;
814
+ return [...visibleIds, ...unseenIds].map((playerId) => {
815
+ const seenOn = turns.filter((t) => seesPlayer(byTurn.get(t), g, playerId));
816
+ const firstSeen = seenOn[0] ?? null;
817
+ const observed = [];
818
+ const missing = [];
819
+ const unseen = [];
820
+ for (let i = 1; i < turns.length; i++) {
821
+ const from = turns[i - 1];
822
+ const to = turns[i];
823
+ if (firstSeen === null || from < firstSeen)
824
+ continue;
825
+ for (let m = from + 1; m < to; m++)
826
+ missing.push(m);
827
+ if (to !== from + 1)
828
+ continue;
829
+ const before = byTurn.get(from);
830
+ const after = byTurn.get(to);
831
+ // A turn pair where the opponent has no territory in view on either board says nothing
832
+ // about its deploy (every stack would read as a reveal, or there is no estimate at all):
833
+ // skip it with a note rather than observe 0 or throw (#83).
834
+ const e = seesPlayer(before, g, playerId)
835
+ ? enemyDeployEstimates(g, after, me, settings, before).find((x) => x.playerId === playerId)
836
+ : undefined;
837
+ if (!e?.observation) {
838
+ unseen.push(seesPlayer(before, g, playerId) ? to : from);
839
+ continue;
840
+ }
841
+ // #123: what it was expected to deploy includes the income carried so far, so a hidden
842
+ // income beyond twice the visible one (`ambiguousBound`) is learnt over a few turns. No fog
843
+ // prior here (enemyDeployEstimates is called without one): visible or carried income only.
844
+ const carriedSoFar = carryIncome(observed)?.income ?? 0;
845
+ const v = visibleAt(from).get(playerId);
846
+ const visibleIncome = v ? v.base + v.bonusIncome : 0;
847
+ const change = armyChange(g, before, after, playerId, settings.defensiveKillRate ?? DEFAULT_DEFENSIVE_KILL_RATE, me, guard);
848
+ const net = change.net;
849
+ // My own orders that turn, when known, are measurements (#119).
850
+ const orders = ordersOn.get(from);
851
+ const measured = orders ? measureOrders(g, before, after, me, playerId, orders, settings) : 0;
852
+ // The same context the board-only reading used (#123): without `most`, the surplus on a
853
+ // reinforced capture would be read as a move out of the fog again.
854
+ const expected = e.observation.expected;
855
+ const context = {
856
+ me,
857
+ guard,
858
+ most: e.observedCap,
859
+ ...(expected !== null ? { expected: Math.max(expected, carriedSoFar) } : {}),
860
+ };
861
+ const { signed, ...o } = expected !== null && carriedSoFar > expected
862
+ ? observeSigned(g, after, before, playerId, settings, context)
863
+ : { ...e.observation, signed: e.observedRaw };
864
+ // #271 (1): a failed attack on a hold of mine bounds its deploy from below, fog or not.
865
+ const repelled = orders ? repelledFloor(g, before, after, me, playerId, orders, settings, guard, bombPossibleOn(settings, from)) : null;
866
+ const floor = repelled?.floor ?? 0;
867
+ const raw = Math.max(measured ? Math.max(0, observeSigned(g, after, before, playerId, settings, context).signed + measured) : Math.max(0, signed), floor);
868
+ const losses = Math.max(0, change.losses + measured);
869
+ // #123: with my orders known, what stood on an emptied capture is measured: no high reading.
870
+ const low = Math.max(0, o.low + measured, floor);
871
+ const high = Math.max(raw, o.high + measured - (orders ? o.emptiedHigh : 0));
872
+ const seenObserved = Math.min(raw, e.observedCap);
873
+ const broken = visiblyBroken(g, before, after, playerId);
874
+ observed.push({
875
+ from,
876
+ to,
877
+ observed: seenObserved,
878
+ raw,
879
+ ...(context.expected !== undefined ? { expected: context.expected } : {}),
880
+ measured,
881
+ broken: broken.map((b) => b.id),
882
+ brokenValue: broken.reduce((sum, b) => sum + b.value, 0),
883
+ cap: e.observedCap,
884
+ counted: o.counted,
885
+ captured: o.captured,
886
+ fromFog: o.fromFog,
887
+ fogArmies: o.fogArmies,
888
+ reveals: o.reveals,
889
+ low: Math.min(low, raw),
890
+ high,
891
+ reinforced: o.reinforced,
892
+ grewFromFog: o.grewFromFog,
893
+ emptied: o.emptied,
894
+ arrivals: o.arrivals,
895
+ unseenAttackers: o.unseenAttackers,
896
+ unseenAttackerArmies: o.unseenAttackerArmies,
897
+ repelled: repelled?.territories.length ? repelled : null,
898
+ repelledFloor: floor,
899
+ combat: combatLosses(g, before, after, playerId, orders
900
+ ? {
901
+ me,
902
+ unpinned: new Map(attacksOnMyHolds(g, before, after, me, orders, settings)
903
+ .filter((a) => a.attacker === null)
904
+ .map((a) => [a.territoryId, a.loss])),
905
+ }
906
+ : null, settings),
907
+ visibleIncome,
908
+ earned: Math.max(visibleIncome, seenObserved),
909
+ net,
910
+ losses,
911
+ });
912
+ // #271 (2): captures that needed attackers out of sight on enough recent turns are a pattern.
913
+ const pattern = fogCapturePattern(observed);
914
+ if (pattern)
915
+ observed[observed.length - 1].fogCaptures = pattern;
916
+ }
917
+ const v = visibleAt(lastTurn).get(playerId) ?? { base: baseIncome, bonusIncome: 0 };
918
+ const visibleIncome = v.base + v.bonusIncome;
919
+ const visible = latest.territories.filter((t) => g.territoryById.has(t.territoryId) && t.owner.kind === 'player' && t.owner.playerId === playerId && ownerShown(t)).length;
920
+ // Back from the newest board while consecutive boards show none of its territories: we stop
921
+ // on a board that shows it (exact), on turn 0 (the whole game, exact) or on a turn I have no
922
+ // board for (a gap or the oldest board): then all I know is the turns after it, a floor.
923
+ let back = lastTurn;
924
+ while (back >= 1 && byTurn.has(back) && !seesPlayer(byTurn.get(back), g, playerId))
925
+ back--;
926
+ const turnsUnseen = visible ? 0 : lastTurn - back;
927
+ const turnsUnseenAtLeast = turnsUnseen > 0 && back >= 1 && !byTurn.has(back);
928
+ const recent = observed.slice(-INCOME_TURNS);
929
+ const lastWindow = recent.length ? trackedIncome(recent, visibleIncome) : null;
930
+ // #119: no decay ({@link carryIncome}). The last three turns alone read a real 31 as 12 once
931
+ // it aged out.
932
+ const carry = carryIncome(observed);
933
+ const carried = carry !== null && lastWindow !== null && carry.income > lastWindow.income ? carry : null;
934
+ const estimate = carried
935
+ ? { ...carried.est, income: carried.income, method: 'carried' }
936
+ : lastWindow;
937
+ const incomeWindow = carried ? carried.window : recent;
938
+ const income = estimate?.income ?? null;
939
+ // #250: an income set by one turn far above the turns before it, with the evidence for it. Its
940
+ // starting armies, when known (under full distribution, an even share: an upper bound).
941
+ const jump = estimate && observed.length >= 2
942
+ ? incomeJump(g, byTurn, playerId, observed, incomeWindow, carried ? carried.est.method : estimate.method, startArmies, me)
943
+ : undefined;
944
+ const unexplained = observed.length
945
+ ? Math.max(0, observed.reduce((s, x) => s + x.earned - x.net - x.losses - x.combat, 0))
946
+ : null;
947
+ const gap = income !== null ? income - visibleIncome : 0;
948
+ // #123: what it could have spent taking bonuses out of sight: its starting armies (when the
949
+ // settings give them) plus what it earned — on each observed turn, what it was seen to earn
950
+ // (`earned`); on every other turn of the game so far, the base income (not its income now,
951
+ // which overstates the early game).
952
+ const budget = (game?.start ? game.start.territories * game.start.armiesPerTerritory : 0) +
953
+ observed.reduce((sum, x) => sum + x.earned, 0) +
954
+ baseIncome * Math.max(0, Math.max(1, lastTurn) - observed.length);
955
+ const inferred = gap > 0 ? inferBonuses(possibleBonuses(g, latest, playerId), gap, budget) : null;
956
+ const notes = [];
957
+ const warnings = [];
958
+ let earnedAtLeast = null;
959
+ if (!visible) {
960
+ const start = game?.start ? game.start.territories * game.start.armiesPerTerritory : null;
961
+ const paid = Math.max(0, lastTurn);
962
+ const total = (start ?? 0) + baseIncome * paid;
963
+ earnedAtLeast = {
964
+ total,
965
+ start,
966
+ baseIncome,
967
+ turns: paid,
968
+ largestStack,
969
+ visibleArmies,
970
+ exceedsLargest: total > largestStack,
971
+ exceedsTotal: total > visibleArmies,
972
+ };
973
+ const s = (n) => (n === 1 ? '' : 's');
974
+ const outOfSight = turnsUnseenAtLeast
975
+ ? `out of sight for at least ${turnsUnseen} turn${s(turnsUnseen)} (no board of mine for turn ${back})`
976
+ : `out of sight for ${turnsUnseen} turn${s(turnsUnseen)}`;
977
+ const startText = start !== null ? `starting armies ${start} (${game.start.territories} territories × ${game.start.armiesPerTerritory}) + ` : '';
978
+ notes.push(`It has been ${outOfSight} and has received at least ${total} armies since the game started (${startText}base income ${baseIncome} × ${paid} turn${s(paid)}, no bonus counted): a lower bound on armies received, not held — it could be banking up to roughly this, minus what its expansion cost.${start === null ? ` Its starting armies are not counted: ${game?.startUnknown ?? 'the settings do not give them'}.` : ''}${caveats.length ? ` The base income each turn may not hold: ${caveats.join('; ')}.` : ''}`);
979
+ const head = `Player ${nameOf(playerId)} has been ${outOfSight} and has received at least ${total} armies since the game started (${start !== null ? `starting armies ${start} + ` : ''}base income ${baseIncome} × ${paid} turn${s(paid)})`;
980
+ if (earnedAtLeast.exceedsLargest)
981
+ warnings.push(`${head}; it could be banking a stack larger than your largest (${largestStack}).`);
982
+ if (earnedAtLeast.exceedsTotal)
983
+ warnings.push(`${head}; it could be banking more than your total visible armies (${visibleArmies}).`);
984
+ }
985
+ if (jump)
986
+ warnings.push(`Player ${nameOf(playerId)}'s ${incomeJumpText(jump, income, observed.filter((x) => x.from >= jump.since && x.from < jump.turn))}`);
987
+ if (firstSeen === null) {
988
+ // Never in view: there is nothing else to say about it.
989
+ }
990
+ else if (observed.length < 2)
991
+ notes.push(`Only ${observed.length} observed turn${observed.length === 1 ? '' : 's'} (fewer than 2 observed turns): the planner keeps its single-turn estimate.`);
992
+ else {
993
+ const basis = incomeBasis({
994
+ incomeMethod: estimate.method,
995
+ incomeTurns: incomeWindow.map((x) => x.from),
996
+ observedRange: estimate.observedRange,
997
+ incomeLowered: carried ? carried.set - carried.income : 0,
998
+ });
999
+ if (carried)
1000
+ 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.`);
1001
+ else
1002
+ 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}.`);
1003
+ }
1004
+ if (missing.length)
1005
+ notes.push(`No board for turn ${missing.join(', ')}: only consecutive turns are compared, so those turns are not observed.`);
1006
+ if (unseen.length) {
1007
+ const ts = [...new Set(unseen)].sort(byNum);
1008
+ notes.push(`No territory of it in view on turn ${ts.join(', ')}: the turn pairs around ${ts.length === 1 ? 'it are' : 'them are'} not observed.`);
1009
+ }
1010
+ const capped = observed.filter((x) => x.raw > x.cap);
1011
+ if (capped.length)
1012
+ notes.push(`Capped at what it could earn on turn ${capped.map((x) => `${x.from} (+${x.raw} → ${x.cap})`).join(', ')}: armies from the fog or a Reinforcement card may explain the rest.`);
1013
+ const measuredTurns = observed.filter((x) => x.measured);
1014
+ if (measuredTurns.length)
1015
+ notes.push(`My own orders on turn ${measuredTurns.map((x) => `${x.from} (${x.measured > 0 ? '+' : ''}${x.measured})`).join(', ')} count as measurements: the defenders my failed attacks killed, and what a hold of mine that fell really killed.`);
1016
+ // #271 (1): its failed attacks on my holds, each a bound on that turn's deploy.
1017
+ for (const x of observed.filter((x) => (x.repelledFloor ?? 0) > 0)) {
1018
+ const r = x.repelled;
1019
+ const one = r.territories.length === 1;
1020
+ notes.push(`Turn ${x.from}: its attack on territor${one ? 'y' : 'ies'} ${r.territories.join(', ')} that held needed at least ${r.attackers} attackers for what I lost there (my orders say what stood there); its stacks beside ${one ? 'it' : 'them'} could send ${r.supply} at the start of the turn, so it deployed at least ${r.floor} that turn, fog or not.`);
1021
+ }
1022
+ // #271 (2): a pattern of captures that needed attackers out of sight (the latest one).
1023
+ const patternTurn = [...observed].reverse().find((x) => x.fogCaptures);
1024
+ if (patternTurn) {
1025
+ const p = patternTurn.fogCaptures;
1026
+ const n = observed.filter((x) => p.turns.includes(x.from)).reduce((k, x) => k + (x.unseenAttackers?.length ?? 0), 0);
1027
+ notes.push(`${n} captures of neutrals in view on turns ${p.turns.join(', ')} needed ${p.armies} attackers beyond what its stacks in view sent: ${FOG_CAPTURE_MIN} or more turns in ${FOG_CAPTURE_TURNS} are a pattern, read as income of ~${p.income}/turn (spread over turns ${p.turns[0]}–${patternTurn.from}), not stacks walking out of the fog.`);
1028
+ }
1029
+ const reveals = observed.reduce((s, x) => s + x.reveals.length, 0);
1030
+ if (reveals)
1031
+ notes.push(`${reveals} fog reveal${reveals === 1 ? '' : 's'} skipped: stacks that only came into view are not income.`);
1032
+ // A reinforced capture whose surplus passed the bound is in `fromFog` too: its note is below.
1033
+ const outOfFog = (x) => x.fromFog.filter((id) => !x.reinforced.includes(id));
1034
+ const fogCaptures = observed.filter((x) => outOfFog(x).length);
1035
+ if (fogCaptures.length) {
1036
+ const n = fogCaptures.reduce((s, x) => s + outOfFog(x).length, 0);
1037
+ notes.push(`${n} capture${n === 1 ? '' : 's'} out of the fog on turn ${fogCaptures.map((x) => x.from).join(', ')}: only what ${n === 1 ? 'it' : 'they'} cost counts as deploy; no visible stack of it shrank into ${n === 1 ? 'it' : 'them'}, so the stack most likely moved in from the fog.`);
1038
+ }
1039
+ // #123: the ambiguous readings, each with the other way it could read.
1040
+ const span = (xs) => xs.map((x) => `${x.from} (${x.low}–${x.high})`).join(', ');
1041
+ const reinforcedTurns = observed.filter((x) => x.reinforced.length);
1042
+ if (reinforcedTurns.length)
1043
+ notes.push(`Captures with more armies than its visible stack next to them sent, on turn ${span(reinforcedTurns)}: read as armies deployed on the visible stack that attacked (deploy-then-capture), up to twice what it was expected to deploy and the rest as a stack out of the fog; a stack out of the fog may have joined instead, the low figure.`);
1044
+ const fogGrowthTurns = observed.filter((x) => x.grewFromFog.length);
1045
+ if (fogGrowthTurns.length)
1046
+ notes.push(`Growth next to the fog beyond twice what it was expected to deploy, on turn ${span(fogGrowthTurns)}: read as stacks that walked in from the fog, not income; it may be income the fog hides, the high figure.`);
1047
+ const emptiedTurns = observed.filter((x) => x.emptied.length && !x.measured);
1048
+ if (emptiedTurns.length)
1049
+ notes.push(`Captures from me on turn ${span(emptiedTurns)} priced at the guard I may have left (my orders that turn are unknown); had my stack stood there, the high figure.`);
1050
+ const fought = observed.filter((x) => x.combat);
1051
+ if (fought.length)
1052
+ notes.push(`It may have lost ${fought.reduce((s, x) => s + x.combat, 0)} fighting on turn ${fought.map((x) => x.from).join(', ')} (its stack and a neighbour of another player both shrank): left out of the unexplained armies.`);
1053
+ if (unexplained)
1054
+ notes.push(`${unexplained} unexplained armies: what it earned since first seen beyond its visible army change and losses — in the fog, spent there, or a misread (a transfer or a fight the boards cannot tell apart).`);
1055
+ if (observed.length)
1056
+ notes.push('Observed deploys are lower bounds: armies moved into the fog and losses in failed attacks are unseen, and the fog may hide territories and bonuses.');
1057
+ if (inferred) {
1058
+ const n = inferred.candidates.length + inferred.more;
1059
+ const left = inferred.implausible
1060
+ ? ` (${inferred.implausible} bonus${inferred.implausible === 1 ? '' : 'es'} left out: more than ${INFER_REACH} hops from its territories, or more than it could have paid for)`
1061
+ : '';
1062
+ if (!n)
1063
+ notes.push(`No combination of bonuses it could hold explains its income gap of ${gap}${left}.`);
1064
+ else if (!inferred.candidates.length)
1065
+ notes.push(`${n} combinations fit its income gap of ${gap}${inferred.exact ? '' : ' approximately'}: too many to name any${left}.`);
1066
+ else
1067
+ notes.push(`${n} combination${n === 1 ? '' : 's'} fit${n === 1 ? 's' : ''} its income gap of ${gap}${inferred.exact ? '' : ' approximately'}, nearest first: candidates, not facts${left}.`);
1068
+ }
1069
+ // #164: stacks that left view. The last board showing each territory decides: a large stack of
1070
+ // its there, and every later board hides it (fogged, or its armies hidden).
1071
+ const largeAt = (turn, armies) => {
1072
+ const income = visibleAt(turn).get(playerId);
1073
+ return armies - guard > 0 && armies - guard >= LOST_STACK_INCOMES * (income ? income.base + income.bonusIncome : baseIncome);
1074
+ };
1075
+ const largeOn = (turn, id) => {
1076
+ const st = visibleState(shownOn(turn).get(id));
1077
+ return st && st.owner.kind === 'player' && st.owner.playerId === playerId && largeAt(turn, st.armies) ? st.armies : null;
1078
+ };
1079
+ const candidates = [];
1080
+ for (const id of [...g.territoryById.keys()].sort(byNum)) {
1081
+ let last = null;
1082
+ let lastShown = -Infinity;
1083
+ for (const turn of turns) {
1084
+ if (!visibleState(shownOn(turn).get(id)))
1085
+ continue;
1086
+ lastShown = turn;
1087
+ const armies = largeOn(turn, id);
1088
+ last = armies !== null ? { turn, armies } : null;
1089
+ }
1090
+ if (last && last.turn === lastShown && last.turn < lastTurn)
1091
+ candidates.push({ territoryId: id, turn: last.turn, armies: last.armies });
1092
+ }
1093
+ // Under Normal fog a territory next to mine never leaves view, so a stack that walks off it into
1094
+ // the fog shows as a shrink, not a hidden territory: a large stack of its that shrank between two
1095
+ // consecutive boards (its territory in view on both), beyond what its neighbours in view gained
1096
+ // (its own that grew, captures of its, the defenders those killed), with a neighbour the fog
1097
+ // hides on the later board, left view with what went missing (the guard counted on top, as on a
1098
+ // standing stack). A shrink beside a fight — a neighbour in view of anyone else's that shrank or
1099
+ // changed hands — is skipped: the board cannot tell a lost attack from a move.
1100
+ const defensive = settings.defensiveKillRate ?? DEFAULT_DEFENSIVE_KILL_RATE;
1101
+ for (let i = 1; i < turns.length; i++) {
1102
+ const from = turns[i - 1];
1103
+ const to = turns[i];
1104
+ if (to !== from + 1 || lastTurn - from > LOST_STACK_TURNS)
1105
+ continue;
1106
+ const was = shownOn(from);
1107
+ const now = shownOn(to);
1108
+ const its = (st) => st !== undefined && st.owner.kind === 'player' && st.owner.playerId === playerId;
1109
+ for (const id of [...g.territoryById.keys()].sort(byNum)) {
1110
+ const b = visibleState(was.get(id));
1111
+ const a = visibleState(now.get(id));
1112
+ if (!its(b) || !its(a) || !largeAt(from, b.armies))
1113
+ continue;
1114
+ const drop = b.armies - a.armies;
1115
+ if (drop <= 0)
1116
+ continue;
1117
+ let inView = 0;
1118
+ let fight = false;
1119
+ let hiddenNext = false;
1120
+ for (const n of neighborsOf(g, id)) {
1121
+ const nb = visibleState(was.get(n));
1122
+ const na = visibleState(now.get(n));
1123
+ if (!na) {
1124
+ hiddenNext = true;
1125
+ continue;
1126
+ }
1127
+ if (its(na)) {
1128
+ if (its(nb))
1129
+ inView += Math.max(0, na.armies - nb.armies);
1130
+ else
1131
+ inView += na.armies + (nb ? straightKills(nb.armies, defensive) : 0);
1132
+ }
1133
+ else if (nb && (its(nb) || nb.owner.kind !== na.owner.kind || (nb.owner.kind === 'player' && na.owner.kind === 'player' && nb.owner.playerId !== na.owner.playerId) || na.armies < nb.armies))
1134
+ fight = true;
1135
+ }
1136
+ const gone = drop - inView;
1137
+ if (fight || !hiddenNext || gone <= 0 || !largeAt(from, gone + guard))
1138
+ continue;
1139
+ candidates.push({ territoryId: id, turn: from, armies: gone + guard });
1140
+ }
1141
+ }
1142
+ // A stack is tracked by territory, so one that moved into view elsewhere would still read as
1143
+ // lost. Each large stack of its that appeared in view after a lost one (not large there on the
1144
+ // board before) and that the lost one could have reached by then (one move a turn) is taken as
1145
+ // that stack, or the part of it in view: it offsets the lost armies once, the largest stack it
1146
+ // can reach first; what is left stays lost while still large.
1147
+ const appeared = [];
1148
+ for (let i = 1; i < turns.length; i++)
1149
+ for (const id of [...g.territoryById.keys()].sort(byNum)) {
1150
+ const armies = largeOn(turns[i], id);
1151
+ if (armies !== null && largeOn(turns[i - 1], id) === null)
1152
+ appeared.push({ turn: turns[i], territoryId: id, armies });
1153
+ }
1154
+ const used = new Set();
1155
+ const lostStacks = [];
1156
+ for (const l of candidates.sort((a, b) => b.armies - a.armies || a.territoryId - b.territoryId)) {
1157
+ const dist = bfsDistances(g, [l.territoryId]);
1158
+ let armies = l.armies;
1159
+ const reach = appeared
1160
+ .map((a, i) => ({ ...a, i }))
1161
+ .filter((a) => !used.has(a.i) && a.turn > l.turn && (dist.get(a.territoryId) ?? Infinity) <= a.turn - l.turn)
1162
+ .sort((a, b) => b.armies - a.armies || a.turn - b.turn || a.territoryId - b.territoryId);
1163
+ for (const a of reach) {
1164
+ if (armies - guard <= 0)
1165
+ break;
1166
+ used.add(a.i);
1167
+ armies -= a.armies;
1168
+ }
1169
+ if (armies === l.armies)
1170
+ lostStacks.push(l);
1171
+ else if (largeAt(l.turn, armies))
1172
+ lostStacks.push({ ...l, armies });
1173
+ }
1174
+ // #201: an attack out of the fog fixes where a lost stack is. A territory of mine on one board
1175
+ // that is this player's on the next, with no territory of its in view beside it on the first
1176
+ // (so the attack came from a neighbour the fog hid), places the stack that made it: it stood next
1177
+ // to that territory during that turn, so it is counted as last seen there on that turn (its reach
1178
+ // from there covers every border it can reach from wherever it attacked from). The largest lost
1179
+ // stack of its that could have stood beside it by then is taken, each attack fixing one stack,
1180
+ // and the latest attack wins.
1181
+ for (let i = 1; i < turns.length; i++) {
1182
+ const from = turns[i - 1];
1183
+ const to = turns[i];
1184
+ if (to !== from + 1)
1185
+ continue;
1186
+ const was = shownOn(from);
1187
+ const now = shownOn(to);
1188
+ /** Lost stacks an attack already placed on this turn: each attack fixes one stack, once. */
1189
+ const placed = new Set();
1190
+ for (const c of [...g.territoryById.keys()].sort(byNum)) {
1191
+ const b = was.get(c);
1192
+ const a = now.get(c);
1193
+ if (b?.owner.kind !== 'player' || b.owner.playerId !== me || a?.owner.kind !== 'player' || a.owner.playerId !== playerId)
1194
+ continue;
1195
+ const nexts = neighborsOf(g, c).map((n) => was.get(n));
1196
+ if (nexts.some((n) => n?.owner.kind === 'player' && n.owner.playerId === playerId))
1197
+ continue;
1198
+ if (!nexts.some((n) => !visibleState(n) && (!n || n.owner.kind === 'unknown')))
1199
+ continue;
1200
+ const k = lostStacks
1201
+ .map((l, idx) => ({ l, idx }))
1202
+ .filter(({ l, idx }) => !placed.has(idx) && l.turn <= from && (bfsDistances(g, [l.territoryId]).get(c) ?? Infinity) <= from - l.turn + 1)
1203
+ .sort((x, y) => y.l.armies - x.l.armies || x.l.territoryId - y.l.territoryId)[0];
1204
+ if (!k || (k.l.territoryId === c && k.l.turn === from))
1205
+ continue;
1206
+ lostStacks[k.idx] = { ...k.l, territoryId: c, turn: from };
1207
+ placed.add(k.idx);
1208
+ notes.push(`Its stack of ${k.l.armies} (last seen on territory ${k.l.territoryId} on turn ${k.l.turn}) attacked territory ${c} out of the fog between turns ${from} and ${to} (#201): it stood next to ${c} then, so it is counted from there.`);
1209
+ }
1210
+ }
1211
+ // The planner drops a stack seen more than LOST_STACK_TURNS turns ago, so drop it here before the
1212
+ // cut: a stale large stack must never push a fresh one out of the MAX_LOST_STACKS kept. (Aged
1213
+ // against the newest board; the planner ages it against the turn being played, never earlier.)
1214
+ const fresh = lostStacks.filter((l) => lastTurn - l.turn <= LOST_STACK_TURNS);
1215
+ lostStacks.splice(0, lostStacks.length, ...fresh);
1216
+ lostStacks.sort((a, b) => b.armies - a.armies || a.territoryId - b.territoryId).splice(MAX_LOST_STACKS);
1217
+ for (const l of lostStacks)
1218
+ 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.`);
1219
+ notes.push(...warnings);
1220
+ return {
1221
+ playerId,
1222
+ firstSeen,
1223
+ lastTurn,
1224
+ turns: observed,
1225
+ base: v.base,
1226
+ bonusIncome: v.bonusIncome,
1227
+ visibleIncome,
1228
+ income,
1229
+ incomeTurns: incomeWindow.map((x) => x.from),
1230
+ observedRange: estimate?.observedRange ?? null,
1231
+ incomeMethod: estimate?.method ?? null,
1232
+ incomeLowered: carried ? carried.set - carried.income : 0,
1233
+ unexplained,
1234
+ inferred,
1235
+ visible,
1236
+ turnsUnseen,
1237
+ turnsUnseenAtLeast,
1238
+ earnedAtLeast,
1239
+ lostStacks,
1240
+ ...(jump ? { incomeJump: jump } : {}),
1241
+ warnings,
1242
+ notes,
1243
+ };
1244
+ });
1245
+ }