@chrischall/warapp-mcp 0.7.0 → 0.8.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 (53) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +2 -2
  4. package/dist/analysis/card-support.js +12 -4
  5. package/dist/analysis/coalition.js +55 -0
  6. package/dist/analysis/local-deploy.js +14 -0
  7. package/dist/analysis/opponents.js +2 -1
  8. package/dist/analysis/picks.js +270 -37
  9. package/dist/analysis/plan/after-leftover.js +26 -4
  10. package/dist/analysis/plan/captures.js +76 -13
  11. package/dist/analysis/plan/completed.js +8 -1
  12. package/dist/analysis/plan/conceded-out.js +16 -11
  13. package/dist/analysis/plan/deploy-estimates.js +513 -0
  14. package/dist/analysis/plan/doomed-out.js +135 -0
  15. package/dist/analysis/plan/estimates.js +3 -1
  16. package/dist/analysis/plan/free-capture.js +34 -0
  17. package/dist/analysis/plan/holds.js +8 -309
  18. package/dist/analysis/plan/horizon.js +42 -0
  19. package/dist/analysis/plan/leftover.js +43 -5
  20. package/dist/analysis/plan/observe.js +896 -0
  21. package/dist/analysis/plan/orders.js +35 -1
  22. package/dist/analysis/plan/report.js +10 -4
  23. package/dist/analysis/plan/shared.js +4 -1376
  24. package/dist/analysis/plan/stand-still.js +5 -3
  25. package/dist/analysis/plan/state.js +12 -0
  26. package/dist/analysis/plan/strike-stack.js +467 -0
  27. package/dist/analysis/plan/strike.js +3 -463
  28. package/dist/analysis/plan/targets.js +213 -26
  29. package/dist/analysis/plan/threats.js +12 -4
  30. package/dist/analysis/plan/transfers.js +24 -1
  31. package/dist/analysis/plan/two-move.js +1 -1
  32. package/dist/analysis/plan/withdraw.js +316 -0
  33. package/dist/analysis/planner.js +54 -11
  34. package/dist/analysis/player.js +4 -0
  35. package/dist/analysis/relations.js +8 -2
  36. package/dist/analysis/stress.js +1 -1
  37. package/dist/bundle.js +8008 -7184
  38. package/dist/my-games.js +2 -0
  39. package/dist/open-games.js +94 -10
  40. package/dist/tools/card-advice.js +26 -11
  41. package/dist/tools/card-support-advice.js +17 -1
  42. package/dist/tools/check-plan.js +2 -1
  43. package/dist/tools/commander-check.js +2 -1
  44. package/dist/tools/decision-capture.js +4 -2
  45. package/dist/tools/join-game.js +44 -8
  46. package/dist/tools/live.js +33 -5
  47. package/dist/tools/open-games.js +2 -2
  48. package/dist/tools/picks.js +120 -47
  49. package/dist/tools/turn.js +43 -4
  50. package/dist/version.js +1 -1
  51. package/manifest.json +1 -1
  52. package/package.json +1 -1
  53. package/server.json +2 -2
@@ -0,0 +1,896 @@
1
+ import { bonusTerritories } from '../bonuses.js';
2
+ import { DEFAULT_DEFENSIVE_KILL_RATE, DEFAULT_OFFENSIVE_KILL_RATE, fewestAttackersToKill, fewestAttackersToTake, guaranteedKills, specialUnitStrength, straightKills, } from '../combat.js';
3
+ import { neighborsOf } from '../graph.js';
4
+ import { byNum } from './util.js';
5
+ /**
6
+ * Fog levels that hide a territory's armies. The live board names war.app's StandingFogLevel
7
+ * (1 You, 2 Visible, 3 OwnerOnly, 4 Fogged; the client refuses a deploy on 3 or 4 as "fogged");
8
+ * a GameFeed standing may spell it as a word or as the raw number (every GameFeed scalar is a
9
+ * string).
10
+ */
11
+ const HIDDEN_FOG = /fog|owneronly|^\s*[34]\s*$/i;
12
+ /** Fog levels that hide a territory's owner too (StandingFogLevel 4, Fogged). */
13
+ const OWNER_HIDDEN_FOG = /fog|^\s*4\s*$/i;
14
+ /**
15
+ * `t` when a board shows both its owner (a player or a neutral) and its armies, else
16
+ * `undefined`: a fogged territory (owner unknown, armies `null`), or one whose fog level hides
17
+ * its armies even if a placeholder owner or count came with it (issue #69).
18
+ *
19
+ * One exception: an entry named `"OwnerOnly"` that still carries a count is fog level 2
20
+ * (Visible) from a board cache written before #69, which misnamed it; every current board nulls
21
+ * an owner-only territory's armies, and the old cache left level 3 unnamed (`"3"`).
22
+ */
23
+ export function visibleState(t) {
24
+ if (!t || t.armies === null)
25
+ return undefined;
26
+ if (t.owner.kind !== 'player' && t.owner.kind !== 'neutral')
27
+ return undefined;
28
+ if (t.fogLevel !== undefined && HIDDEN_FOG.test(t.fogLevel) && !/^\s*owneronly\s*$/i.test(t.fogLevel))
29
+ return undefined;
30
+ return t;
31
+ }
32
+ /**
33
+ * `t` when a board shows its owner (a player or a neutral), whatever its armies: visible, or
34
+ * owner-only (light fog); `undefined` when fogged, even under a placeholder owner.
35
+ */
36
+ export function ownerShown(t) {
37
+ if (!t || (t.owner.kind !== 'player' && t.owner.kind !== 'neutral'))
38
+ return undefined;
39
+ if (t.fogLevel !== undefined && OWNER_HIDDEN_FOG.test(t.fogLevel))
40
+ return undefined;
41
+ return t;
42
+ }
43
+ /** #294: {@link FrontierCoverage} of one opponent on one observed turn. Pure. */
44
+ export function frontierCoverage(g, board, previous, playerId) {
45
+ const now = new Map(board.territories.map((t) => [t.territoryId, t]));
46
+ const before = new Map(previous.territories.map((t) => [t.territoryId, t]));
47
+ const its = (id) => {
48
+ const st = ownerShown(now.get(id));
49
+ return st?.owner.kind === 'player' && st.owner.playerId === playerId;
50
+ };
51
+ const shownIts = [...g.territoryById.keys()].filter(its);
52
+ const frontier = new Set();
53
+ let inView = 0;
54
+ for (const t of shownIts) {
55
+ const ns = neighborsOf(g, t);
56
+ if (ns.every(its))
57
+ continue;
58
+ frontier.add(t);
59
+ const a = visibleState(now.get(t));
60
+ const b = visibleState(before.get(t));
61
+ if (a && b)
62
+ inView++;
63
+ for (const n of ns)
64
+ if (!ownerShown(now.get(n)))
65
+ frontier.add(n);
66
+ }
67
+ let hiddenBonuses = 0;
68
+ for (const bonus of g.map.bonuses) {
69
+ const ts = bonusTerritories(g, bonus.id);
70
+ if (bonus.value <= 0 || !ts.length)
71
+ continue;
72
+ const taken = ts.some((t) => {
73
+ const st = ownerShown(now.get(t));
74
+ return st !== undefined && !(st.owner.kind === 'player' && st.owner.playerId === playerId);
75
+ });
76
+ if (!taken && ts.some((t) => !ownerShown(now.get(t))))
77
+ hiddenBonuses++;
78
+ }
79
+ const share = frontier.size ? inView / frontier.size : shownIts.length ? 1 : 0;
80
+ return { inView, frontier: frontier.size, share, hiddenBonuses };
81
+ }
82
+ /** #294: {@link TrackCoverage} over `turns` (those carrying a coverage); `null` when none does. */
83
+ export function trackCoverage(turns) {
84
+ const withIt = turns.filter((x) => x.coverage !== undefined);
85
+ if (!withIt.length)
86
+ return null;
87
+ const inView = withIt.reduce((n, x) => n + x.coverage.inView, 0);
88
+ const frontier = withIt.reduce((n, x) => n + x.coverage.frontier, 0);
89
+ const range = (xs) => ({ min: Math.min(...xs), max: Math.max(...xs) });
90
+ return {
91
+ turns: withIt.map((x) => x.from),
92
+ inView: range(withIt.map((x) => x.coverage.inView)),
93
+ frontier: range(withIt.map((x) => x.coverage.frontier)),
94
+ share: frontier ? inView / frontier : withIt.reduce((n, x) => n + x.coverage.share, 0) / withIt.length,
95
+ hiddenBonuses: withIt.at(-1).coverage.hiddenBonuses,
96
+ };
97
+ }
98
+ /**
99
+ * #294: "1 of ~4 frontier territories (25%)" (a range, "1–2 of ~4–5", when the turns differ; the share
100
+ * is Σ read ÷ Σ frontier), and ", N bonus(es) it could hold out of view" when any: the words beside a
101
+ * tracked figure.
102
+ */
103
+ export function coverageText(c) {
104
+ const b = c.hiddenBonuses;
105
+ const range = (r) => (r.min === r.max ? `${r.min}` : `${r.min}–${r.max}`);
106
+ return `${range(c.inView)} of ~${range(c.frontier)} frontier territories (${Math.round(c.share * 100)}%)${b ? `, ${b} ${b === 1 ? 'bonus' : 'bonuses'} it could hold out of view` : ''}`;
107
+ }
108
+ /**
109
+ * #226: what my failed attacks on `playerId` killed, by target, on the turn `before` → `after`: each
110
+ * move of mine onto a territory it holds on both boards (shown with armies both times), from a
111
+ * source mine on both (one that fell may have been taken before my attack ran), kills
112
+ * round(armies × the offensive kill rate) — a straight-rounded expectation, which luck can move.
113
+ * The board reads that loss as a shrink. The opponent tracker's `measureOrders` counts the same.
114
+ */
115
+ export function failedAttackKills(g, before, after, me, playerId, orders, rates = {}) {
116
+ const offensive = rates.offensiveKillRate ?? DEFAULT_OFFENSIVE_KILL_RATE;
117
+ const out = new Map();
118
+ for (const m of failedAttackMoves(g, before, after, me, playerId, orders))
119
+ out.set(m.to, (out.get(m.to) ?? 0) + straightKills(Math.max(0, m.armies), offensive));
120
+ return out;
121
+ }
122
+ /**
123
+ * The moves {@link failedAttackKills} counts: each move of mine onto a territory `playerId` holds on
124
+ * both boards (shown with armies both times), from a source mine on both. #240 review: the armies
125
+ * {@link repulsedAttacks} reports are these moves' too, so they match the kills.
126
+ */
127
+ function failedAttackMoves(g, before, after, me, playerId, orders) {
128
+ const was = new Map(before.territories.map((t) => [t.territoryId, t]));
129
+ const now = new Map(after.territories.map((t) => [t.territoryId, t]));
130
+ const owns = (t, p) => {
131
+ const v = visibleState(t);
132
+ return v?.owner.kind === 'player' && v.owner.playerId === p;
133
+ };
134
+ return orders.moves.filter((m) => g.territoryById.has(m.to) &&
135
+ owns(was.get(m.from), me) &&
136
+ owns(now.get(m.from), me) &&
137
+ owns(was.get(m.to), playerId) &&
138
+ owns(now.get(m.to), playerId));
139
+ }
140
+ /**
141
+ * #271 review: the territories an order of mine touched that `orders.moves` does not carry, so what
142
+ * they held after my orders is not known: a move order in `sent` beyond the plain ones `moves` keeps on
143
+ * the same pair (#165 leaves out Transfer Only, Attack Only and percentage orders), both its ends; and
144
+ * each territory a card play names (an Airlift's `from` and `to`, a card's `target`).
145
+ */
146
+ function ordersNotInMoves(orders) {
147
+ const out = new Set();
148
+ const key = (from, to) => `${from}>${to}`;
149
+ const carried = new Map();
150
+ for (const m of orders.moves)
151
+ carried.set(key(m.from, m.to), (carried.get(key(m.from, m.to)) ?? 0) + 1);
152
+ for (const o of orders.sent ?? []) {
153
+ const left = carried.get(key(o.from, o.to)) ?? 0;
154
+ if (left > 0)
155
+ carried.set(key(o.from, o.to), left - 1);
156
+ else
157
+ out.add(o.from).add(o.to);
158
+ }
159
+ for (const c of orders.cards ?? [])
160
+ for (const id of [c.from, c.to, c.target])
161
+ if (id !== undefined)
162
+ out.add(id);
163
+ return out;
164
+ }
165
+ /**
166
+ * My holds (mine, with armies, on both boards) that lost armies my orders do not explain, by id: the
167
+ * defenders were my armies there plus what I deployed there, less what I sent out; what the later
168
+ * board shows less (what I moved in from a territory mine on the earlier board counted on top) is what
169
+ * an attack on it that failed killed. A hold I attacked out of and failed is skipped: the survivors of
170
+ * my own attack came back to it, so its loss is not known. So is a hold an order `moves` does not carry
171
+ * touched (#271 review, {@link ordersNotInMoves}: a Transfer Only, Attack Only or percentage order, a
172
+ * card play), and a transfer from a source one touched is not surely whole. The opponent tracker's attacks on my holds
173
+ * and the #271 bound ({@link repelledFloor}) both read these.
174
+ */
175
+ export function holdLosses(g, before, after, me, orders, guard = 1) {
176
+ const was = new Map(before.territories.map((t) => [t.territoryId, t]));
177
+ const now = new Map(after.territories.map((t) => [t.territoryId, t]));
178
+ const owns = (t, p) => t?.owner.kind === 'player' && t.owner.playerId === p;
179
+ const held = (id) => owns(visibleState(was.get(id)), me) && owns(visibleState(now.get(id)), me);
180
+ const deployed = new Map();
181
+ for (const d of orders.deploys)
182
+ deployed.set(d.territoryId, (deployed.get(d.territoryId) ?? 0) + Math.max(0, d.armies));
183
+ const sent = new Map();
184
+ const came = new Map();
185
+ /** The sources of what `came`, by the hold they sent to. */
186
+ const cameFrom = new Map();
187
+ const failedFrom = new Set();
188
+ const untracked = ordersNotInMoves(orders);
189
+ for (const m of orders.moves) {
190
+ const armies = Math.max(0, m.armies);
191
+ sent.set(m.from, (sent.get(m.from) ?? 0) + armies);
192
+ if (held(m.to) && owns(visibleState(was.get(m.from)), me)) {
193
+ came.set(m.to, (came.get(m.to) ?? 0) + armies);
194
+ if (armies > 0)
195
+ cameFrom.set(m.to, (cameFrom.get(m.to) ?? new Set()).add(m.from));
196
+ }
197
+ if (!owns(visibleState(was.get(m.to)), me) && !owns(visibleState(now.get(m.to)), me))
198
+ failedFrom.add(m.from);
199
+ }
200
+ /**
201
+ * #271 review: a source that surely sent all ordered from it ({@link HoldLoss.inflowSure}): mine on
202
+ * both boards, no failed attack of mine out of it, nothing moved into it (when that arrived is not
203
+ * known), and it shows exactly what my orders leave there. An order sends what is left down to the
204
+ * guard, so a loss before it shows only when my orders leave more than the guard there; else only
205
+ * when no other player (nor the fog) was beside it to attack or bomb it.
206
+ */
207
+ const sentWhole = (id) => {
208
+ if (!held(id) || failedFrom.has(id) || came.has(id) || untracked.has(id))
209
+ return false;
210
+ const left = visibleState(was.get(id)).armies + (deployed.get(id) ?? 0) - (sent.get(id) ?? 0);
211
+ if (left < 0 || visibleState(now.get(id)).armies !== left)
212
+ return false;
213
+ if (left > guard)
214
+ return true;
215
+ return neighborsOf(g, id).every((n) => {
216
+ const o = ownerShown(was.get(n))?.owner;
217
+ return o !== undefined && (o.kind === 'neutral' || (o.kind === 'player' && o.playerId === me));
218
+ });
219
+ };
220
+ const out = [];
221
+ for (const id of [...new Set(after.territories.map((t) => t.territoryId))].sort(byNum)) {
222
+ if (!g.territoryById.has(id) || !held(id) || failedFrom.has(id) || untracked.has(id))
223
+ continue;
224
+ const standing = visibleState(was.get(id)).armies + (deployed.get(id) ?? 0);
225
+ const defenders = Math.max(0, standing - (sent.get(id) ?? 0));
226
+ const loss = defenders + (came.get(id) ?? 0) - visibleState(now.get(id)).armies;
227
+ const inflowSure = [...(cameFrom.get(id) ?? [])].every(sentWhole);
228
+ if (loss > 0)
229
+ out.push({ territoryId: id, defenders, loss, standing, inflowSure });
230
+ }
231
+ return out;
232
+ }
233
+ /**
234
+ * #271: a failed attack on a hold of mine is a measurement, the mirror of #226. My loss there
235
+ * ({@link holdLosses}: what my orders do not explain) needed at least {@link fewestAttackersToKill}
236
+ * attackers (every attacker killing its most, luck included), and without Multi-Attack each army
237
+ * moves once, so they all came from its territories beside the hold at the start of the turn: their
238
+ * armies then (less the guard) plus what it deployed there. A hold counts only when every neighbour
239
+ * showed its owner on the earlier board, every territory of `playerId` beside it showed its armies,
240
+ * and `playerId` is the only other player beside it. Over every such hold the bound is the larger of
241
+ * the best single hold and all of them together (the attackers summed against the stacks beside any
242
+ * of them, each counted once).
243
+ * #271 review: a hold reads only when what I moved in surely arrived whole ({@link HoldLoss.inflowSure}),
244
+ * so the bound uses the least my orders can have brought. On a turn an opponent may have played a Bomb
245
+ * card (`bomb`, {@link bombPossibleOn}), which halves a territory of mine beside the bomber after the
246
+ * deploys and reads as an attack, the most it could take (half the stack before any move, rounded up)
247
+ * is left out of the loss first. Orders cached without `sent` or `cards` (before they were kept) bound
248
+ * nothing: an order `moves` leaves out, or a card play, may have moved armies out of a hold.
249
+ */
250
+ export function repelledFloor(g, before, after, me, playerId, orders, settings = {}, guard = (settings.oneArmyStandsGuard ?? true) ? 1 : 0, bomb = false) {
251
+ const none = { territories: [], attackers: 0, supply: 0, floor: 0 };
252
+ // #271 review: orders cached before `sent` and `cards` were kept may have left out an order or a card
253
+ // play that moved armies out of a hold: what ran is unknown, so they bound nothing.
254
+ if (settings.multiAttack || !orders.sent || !orders.cards)
255
+ return none;
256
+ const was = new Map(before.territories.map((t) => [t.territoryId, t]));
257
+ const sendable = (id) => {
258
+ const st = visibleState(was.get(id));
259
+ return Math.max(0, st.armies - guard) + specialUnitStrength(st.specialUnits?.filter((u) => u.playerId === playerId));
260
+ };
261
+ const holds = [];
262
+ for (const h of holdLosses(g, before, after, me, orders, guard)) {
263
+ if (!h.inflowSure)
264
+ continue;
265
+ const loss = h.loss - (bomb ? Math.ceil(h.standing / 2) : 0);
266
+ if (loss <= 0)
267
+ continue;
268
+ const ns = neighborsOf(g, h.territoryId);
269
+ if (ns.some((n) => !ownerShown(was.get(n))))
270
+ continue;
271
+ const others = new Set();
272
+ const beside = [];
273
+ let hidden = false;
274
+ for (const n of ns) {
275
+ const o = ownerShown(was.get(n)).owner;
276
+ if (o.kind !== 'player' || o.playerId === me)
277
+ continue;
278
+ others.add(o.playerId);
279
+ if (o.playerId === playerId) {
280
+ if (!visibleState(was.get(n)))
281
+ hidden = true;
282
+ beside.push(n);
283
+ }
284
+ }
285
+ if (hidden || others.size !== 1 || !others.has(playerId))
286
+ continue;
287
+ const attackers = fewestAttackersToKill(loss, settings, settings.luckModifier, settings.roundingMode);
288
+ if (attackers === null)
289
+ continue;
290
+ holds.push({ id: h.territoryId, attackers, beside });
291
+ }
292
+ if (!holds.length)
293
+ return none;
294
+ const supplyOf = (ids) => [...new Set(ids)].reduce((n, id) => n + sendable(id), 0);
295
+ let best = { ...none, territories: holds.map((h) => h.id) };
296
+ const all = {
297
+ attackers: holds.reduce((n, h) => n + h.attackers, 0),
298
+ supply: supplyOf(holds.flatMap((h) => h.beside)),
299
+ };
300
+ best = { ...best, ...all, floor: Math.max(0, all.attackers - all.supply) };
301
+ for (const h of holds) {
302
+ const supply = supplyOf(h.beside);
303
+ if (h.attackers - supply > best.floor)
304
+ best = { ...best, attackers: h.attackers, supply, floor: h.attackers - supply };
305
+ }
306
+ return best;
307
+ }
308
+ /**
309
+ * #418 (the owner's decision of 2026-11-20: proof may always raise an estimate): the fewest armies that
310
+ * can kill `defenders` however the attack is split into orders. One attack of `a` kills at most
311
+ * round(a × the best kill rate luck allows) (straight; weighted rounding rounds up a fraction); a split
312
+ * gains most per army at the smallest attack, so the most kills per army is the best over small attacks.
313
+ */
314
+ function fewestAttackersAnySplit(defenders, settings) {
315
+ if (defenders <= 0)
316
+ return 0;
317
+ let perArmy = 0;
318
+ for (let a = 1; a <= 20; a++) {
319
+ // The most kills `a` attackers can make: the largest k with fewestAttackersToKill(k) ≤ a.
320
+ let k = 0;
321
+ for (;;) {
322
+ const need = fewestAttackersToKill(k + 1, settings, settings.luckModifier, settings.roundingMode);
323
+ if (need === null || need > a)
324
+ break;
325
+ k++;
326
+ }
327
+ perArmy = Math.max(perArmy, k / a);
328
+ }
329
+ return perArmy > 0 ? Math.ceil(defenders / perArmy - 1e-9) : null;
330
+ }
331
+ /**
332
+ * #418: a capture with every source army in view proves a minimum deploy. Without Multi-Attack each army
333
+ * moves once, so every attacker on a territory it took — and every army that then moved in — came from
334
+ * its territories beside the target at the start of the turn: their armies then (less the guard, a
335
+ * commander as 7) plus what it deployed on them. What arrived is at least what stands there now plus the
336
+ * attacker the last defender surely killed ({@link guaranteedKills} of one), and at least the fewest
337
+ * armies that kill every defender however the attack was split ({@link fewestAttackersAnySplit}); what
338
+ * that leaves beyond the supply was deployed.
339
+ * A capture reads only when: the target was a neutral or mine, shown with its armies, and its now, shown
340
+ * with its armies, no special unit on it; every neighbour of the target showed its owner on the earlier
341
+ * board and each of its showed its armies (a hidden one may have sent a stack); no other player borders
342
+ * the target on either board (it may have worn the defenders down first); and, when the target was mine
343
+ * or borders mine, my orders are known in full (`sent` and `cards`) and none of them leaves the target,
344
+ * enters it or plays a card on it (a move of mine out of it leaves fewer defenders; an attack of mine in
345
+ * kills some first). A Bomb it may have played (`bomb`) halves the defenders first. Over every such
346
+ * capture the floor is the larger of the best single capture and all of them together (their attackers
347
+ * summed against the stacks beside any of them, each counted once), as {@link repelledFloor} does.
348
+ */
349
+ export function captureFloor(g, before, after, playerId, settings = {}, guard = (settings.oneArmyStandsGuard ?? true) ? 1 : 0, opts = {}) {
350
+ const none = { territories: [], attackers: 0, supply: 0, floor: 0 };
351
+ if (settings.multiAttack)
352
+ return none;
353
+ const was = new Map(before.territories.map((t) => [t.territoryId, t]));
354
+ const now = new Map(after.territories.map((t) => [t.territoryId, t]));
355
+ const { me, orders } = opts;
356
+ const ordersKnown = !!orders?.sent && !!orders.cards;
357
+ const touchedByMe = (id) => !ordersKnown ||
358
+ orders.sent.some((m) => m.from === id || m.to === id) ||
359
+ orders.moves.some((m) => m.from === id || m.to === id) ||
360
+ orders.cards.some((c) => c.from === id || c.to === id || c.target === id);
361
+ const its = (t) => t?.owner.kind === 'player' && t.owner.playerId === playerId;
362
+ const sendable = (id) => {
363
+ const st = visibleState(was.get(id));
364
+ return Math.max(0, st.armies - guard) + specialUnitStrength(st.specialUnits?.filter((u) => u.playerId === playerId));
365
+ };
366
+ const lastKill = guaranteedKills(1, settings.defensiveKillRate ?? DEFAULT_DEFENSIVE_KILL_RATE, settings.luckModifier, settings.roundingMode);
367
+ const caps = [];
368
+ for (const t of [...after.territories].sort((a, b) => a.territoryId - b.territoryId)) {
369
+ const id = t.territoryId;
370
+ if (!g.territoryById.has(id))
371
+ continue;
372
+ const a = visibleState(t);
373
+ const b = visibleState(was.get(id));
374
+ if (!its(a) || !b || its(b) || a.specialUnits?.length || b.specialUnits?.length)
375
+ continue;
376
+ const mineBefore = me !== undefined && b.owner.kind === 'player' && b.owner.playerId === me;
377
+ if (b.owner.kind !== 'neutral' && !mineBefore)
378
+ continue;
379
+ const ns = neighborsOf(g, id);
380
+ let ok = true;
381
+ let bordersMe = false;
382
+ const beside = [];
383
+ for (const n of ns) {
384
+ const o = ownerShown(was.get(n));
385
+ if (!o) {
386
+ ok = false;
387
+ break;
388
+ }
389
+ for (const side of [o, ownerShown(now.get(n))]) {
390
+ if (side?.owner.kind !== 'player' || side.owner.playerId === playerId)
391
+ continue;
392
+ if (side.owner.playerId === me)
393
+ bordersMe = true;
394
+ else
395
+ ok = false;
396
+ }
397
+ if (its(o)) {
398
+ if (!visibleState(o))
399
+ ok = false;
400
+ else
401
+ beside.push(n);
402
+ }
403
+ }
404
+ if (!ok || ((mineBefore || bordersMe) && touchedByMe(id)))
405
+ continue;
406
+ const defenders = opts.bomb ? Math.floor(b.armies / 2) : b.armies;
407
+ const kill = fewestAttackersAnySplit(defenders, settings);
408
+ if (kill === null)
409
+ continue;
410
+ const attackers = Math.max(kill, a.armies + (defenders > 0 ? lastKill : 0));
411
+ caps.push({ id, attackers, beside });
412
+ }
413
+ if (!caps.length)
414
+ return none;
415
+ const supplyOf = (ids) => [...new Set(ids)].reduce((n, id) => n + sendable(id), 0);
416
+ const all = { attackers: caps.reduce((n, c) => n + c.attackers, 0), supply: supplyOf(caps.flatMap((c) => c.beside)) };
417
+ let best = { territories: caps.map((c) => c.id), ...all, floor: Math.max(0, all.attackers - all.supply) };
418
+ for (const c of caps) {
419
+ const supply = supplyOf(c.beside);
420
+ if (c.attackers - supply > best.floor)
421
+ best = { ...best, attackers: c.attackers, supply, floor: c.attackers - supply };
422
+ }
423
+ return best;
424
+ }
425
+ /** #240: the turns {@link repulsedAttacks} looks back over, ending on the board being planned. */
426
+ export const REPULSE_WINDOW = 3;
427
+ /** #240: failed, reinforced attacks on one territory within the window that make it repulsed. */
428
+ export const REPULSE_MIN = 2;
429
+ /**
430
+ * #240: repeated failure is evidence. Over my board history (`boards`, the newest being the board
431
+ * being planned; consecutive turns only, each with my cached orders — `TurnBoard.orders`, what
432
+ * warapp_submit_turn sent), a failed attack of mine on a territory — its owner the same player on
433
+ * both boards, my source mine on both ({@link failedAttackKills}) — whose owner reinforced it: its
434
+ * armies after plus what my attack killed exceed its armies before (after = before + deploys and
435
+ * transfers in − kills). A territory with such an attack on {@link REPULSE_MIN} or more of the last
436
+ * {@link REPULSE_WINDOW} turns, still that player's on the newest board, is reported, by id. Kill
437
+ * counts are straight-rounded expectations: luck can move them. Pure; unknown orders give nothing.
438
+ */
439
+ export function repulsedAttacks(g, boards, me, rates = {}) {
440
+ const sorted = [...boards].sort((a, b) => a.turn - b.turn);
441
+ const newest = sorted[sorted.length - 1];
442
+ if (!newest)
443
+ return [];
444
+ // #240 review: kept per territory and owner, so failed attacks on a territory under an earlier
445
+ // owner never hide those under its newest one (the filter below keeps the newest owner's only).
446
+ const found = new Map();
447
+ for (let i = 0; i + 1 < sorted.length; i++) {
448
+ const was = sorted[i];
449
+ const now = sorted[i + 1];
450
+ if (!was.orders || now.turn !== was.turn + 1 || was.turn < newest.turn - REPULSE_WINDOW)
451
+ continue;
452
+ const orders = was.orders;
453
+ const before = new Map(was.board.territories.map((t) => [t.territoryId, t]));
454
+ const after = new Map(now.board.territories.map((t) => [t.territoryId, t]));
455
+ const owners = new Set();
456
+ for (const m of orders.moves) {
457
+ const o = visibleState(before.get(m.to))?.owner;
458
+ if (o?.kind === 'player' && o.playerId !== me)
459
+ owners.add(o.playerId);
460
+ }
461
+ for (const p of [...owners].sort(byNum)) {
462
+ for (const [t, kills] of [...failedAttackKills(g, was.board, now.board, me, p, orders, rates)].sort(([a], [b]) => a - b)) {
463
+ const b = visibleState(before.get(t)).armies;
464
+ const a = visibleState(after.get(t)).armies;
465
+ if (kills <= 0 || a + kills <= b)
466
+ continue;
467
+ const armies = failedAttackMoves(g, was.board, now.board, me, p, orders)
468
+ .filter((m) => m.to === t)
469
+ .reduce((n, m) => n + Math.max(0, m.armies), 0);
470
+ // #361: a single-army jab never tries to take it (one army takes no defended territory): no evidence.
471
+ if (armies <= 1)
472
+ continue;
473
+ const attack = { turn: was.turn, armies, before: b, after: a, kills };
474
+ const key = `${t}:${p}`;
475
+ const entry = found.get(key);
476
+ if (!entry)
477
+ found.set(key, { territoryId: t, playerId: p, attacks: [attack] });
478
+ else
479
+ entry.attacks.push(attack);
480
+ }
481
+ }
482
+ }
483
+ const latest = new Map(newest.board.territories.map((t) => [t.territoryId, t]));
484
+ return [...found.values()]
485
+ .filter((r) => {
486
+ const o = visibleState(latest.get(r.territoryId))?.owner;
487
+ return r.attacks.length >= REPULSE_MIN && o?.kind === 'player' && o.playerId === r.playerId;
488
+ })
489
+ .sort((a, b) => a.territoryId - b.territoryId);
490
+ }
491
+ /**
492
+ * One opponent's deploy last turn as seen across two boards (issues #57, #69): the *net*
493
+ * change of its visible armies plus what it visibly lost attacking, floored at 0. Only
494
+ * territories visible on both boards count ({@link visibleState}): one hidden last time
495
+ * (fogged, or under a fog level that hid its armies) only came into view, so it is a fog
496
+ * reveal whoever holds it now — never growth, never a capture.
497
+ * - under it both times: armies now − armies then, shrinks included — a transfer between
498
+ * its own territories nets to zero, so it is never read as deploy;
499
+ * - taken from another visible owner (another player, me included, or a visible neutral): what
500
+ * the capture cost it — the attackers the previous defenders killed at the game's defensive
501
+ * kill rate (`straightKills`, as in `armiesToTake`); taken from me (given `context.me`), the
502
+ * defenders are the guard I may have left, not my stack last turn (#123, `emptied`: I may have
503
+ * attacked out of it) — plus the armies now on it up to what its territories next to it, shown
504
+ * on both boards, visibly sent away (their total shrink, each army claimed by one capture only):
505
+ * those moved in from a visible source, whose shrink they cancel, so source shrink + destination
506
+ * gain nets to the attrition (issue #86). An unchanged visible neighbour sent nothing, so it
507
+ * explains nothing. The rest, when a neighbour was hidden on either board, is ambiguous (#123):
508
+ * a deploy on a visible source that shrank into it (`reinforced`), or a move out of the fog —
509
+ * never income (`fromFog`), still a threat to the borders next to it. With every neighbour in
510
+ * view it can only be a deploy on the source.
511
+ * - growth on its territory next to a hidden one is ambiguous the same way (`grewFromFog`).
512
+ * Ambiguous armies count as deploy while the turn's total stays within {@link ambiguousBound}
513
+ * (twice `context.expected`, never past `context.most`); the rest are moves. Without `expected`,
514
+ * growth is all deploy and a capture's surplus counts up to `most` (none without it, #86).
515
+ * `low` and `high` read every ambiguous army one way or the other (fog moves and the guard, or
516
+ * deploys and my stack standing there).
517
+ * Not counted: armies it lost on a territory it attacked but did not take. The defender's
518
+ * count there also moves with the defender's own deploys and transfers (mine included —
519
+ * this board says nothing about my orders), so the loss cannot be read off it; leaving it
520
+ * out keeps the figure a lower bound (the failed attack's losses still shrink its source). The
521
+ * opponent tracker adds it back when my orders that turn are known (#119, `measureOrders`).
522
+ * Given those orders here (`context.myOrders`, #226), the defenders my failed attack killed on a
523
+ * territory that stayed its count back into its growth there (`attacked`, `attackKills`): after =
524
+ * before + deploy + transfers in − kills, so deploy ≥ after + kills − before — beside the fog an
525
+ * ambiguous growth like any other, read as deploy up to the turn's bound. #271: given those orders,
526
+ * a failed attack on a hold of mine bounds the deploy from below ({@link repelledFloor}: `deploy`,
527
+ * `low` and `high` never below it), and so does a capture with every source army in view (#418,
528
+ * {@link captureFloor}: proof may always raise an estimate). A capture also claims, after the visible sources, what its stacks
529
+ * in view last turn and hidden now could have sent (`arrivals`: no figure counts them but `high`); a
530
+ * capture of a neutral beside the fog that no visible source sent into reads the attackers it needed
531
+ * beyond its cost ({@link fewestAttackersToTake}) as ambiguous, deploy up to the bound
532
+ * (`unseenAttackers`; the tracker reads a pattern of them as income), the rest a move out of the fog.
533
+ * One turn only, not smoothed (the tracker reads a history). Transfers in from (or out to) the
534
+ * fog still bias it — income in the fog is unseen anyway.
535
+ */
536
+ export function observeDeploy(g, board, previous, playerId, rates = {}, context = {}) {
537
+ const { signed: _signed, ...o } = observeSigned(g, board, previous, playerId, rates, context);
538
+ return o;
539
+ }
540
+ /**
541
+ * {@link observeDeploy} with its total before the floor at 0 (`signed`): the opponent tracker
542
+ * adds what my own orders measure (#119) to it before flooring.
543
+ */
544
+ export function observeSigned(g, board, previous, playerId, rates = {}, context = {}) {
545
+ const before = new Map(previous.territories.map((t) => [t.territoryId, t]));
546
+ let total = 0;
547
+ /** What `low` and `high` differ from `total` by. */
548
+ let lowExtra = 0;
549
+ let highExtra = 0;
550
+ const counted = [];
551
+ const captured = [];
552
+ const fromFog = [];
553
+ let fogArmies = 0;
554
+ const reveals = [];
555
+ const reinforced = [];
556
+ const emptied = [];
557
+ let emptiedHigh = 0;
558
+ /**
559
+ * The ambiguous armies (#123): growth on its held territories next to a hidden one (a stack
560
+ * may have walked in) and a capture's surplus over what a visible source that shrank into it
561
+ * sent (deploy-then-capture, or a stack out of the fog joined). Read after the loop against
562
+ * one bound, the same for both ({@link ambiguousBound}).
563
+ */
564
+ const ambiguous = [];
565
+ const now = new Map(board.territories.map((t) => [t.territoryId, t]));
566
+ const defensive = rates.defensiveKillRate ?? DEFAULT_DEFENSIVE_KILL_RATE;
567
+ const guard = Math.max(0, context.guard ?? 1);
568
+ // #226: my failed attacks' kills, by target: they count back into its growth there.
569
+ const kills = context.me !== undefined && context.myOrders
570
+ ? failedAttackKills(g, previous, board, context.me, playerId, context.myOrders, rates)
571
+ : new Map();
572
+ const killsAt = (id) => kills.get(id) ?? 0;
573
+ /** Held by the observed player (`playerId`, not me) and shown with armies on both boards. */
574
+ const heldBothTimes = (id) => {
575
+ const a = visibleState(now.get(id));
576
+ const b = visibleState(before.get(id));
577
+ return a?.owner.kind === 'player' && a.owner.playerId === playerId && b?.owner.kind === 'player' && b.owner.playerId === playerId;
578
+ };
579
+ /**
580
+ * What each of its territories shown with armies on both boards visibly sent away (its
581
+ * shrink): the most a capture next to it can have received from it. A capture draws on it
582
+ * (ascending ids), so two captures never both claim the same armies. What my failed attack killed
583
+ * there (#226: these are exactly {@link failedAttackKills}' targets) is a loss, not armies sent
584
+ * away, so it is taken out of the shrink.
585
+ */
586
+ const shrinkLeft = new Map();
587
+ for (const t of board.territories)
588
+ if (g.territoryById.has(t.territoryId) && heldBothTimes(t.territoryId))
589
+ shrinkLeft.set(t.territoryId, Math.max(0, visibleState(before.get(t.territoryId)).armies - t.armies - killsAt(t.territoryId)));
590
+ /** Not shown with armies on both boards: armies could have left it unseen. */
591
+ const hidden = (id) => !visibleState(now.get(id)) || !visibleState(before.get(id));
592
+ // #294: each grown stack's growth split, against its own copy of the shrinks (captures claim theirs below).
593
+ // The stacks with no hidden neighbour claim first (what they leave can only be deploy, so a shrink
594
+ // taken by a stack beside the fog would turn a move into a false "can only be deploy"), then those
595
+ // beside the fog; each in id order, and reported in id order.
596
+ const stacks = [];
597
+ const shrinkForSplit = new Map(shrinkLeft);
598
+ const grown = [...shrinkLeft.keys()]
599
+ .sort(byNum)
600
+ .map((id) => ({
601
+ id,
602
+ growth: visibleState(now.get(id)).armies - visibleState(before.get(id)).armies + killsAt(id),
603
+ beside: neighborsOf(g, id).some(hidden),
604
+ }))
605
+ .filter((x) => x.growth > 0);
606
+ for (const { id, growth, beside } of [...grown.filter((x) => !x.beside), ...grown.filter((x) => x.beside)]) {
607
+ let left = growth;
608
+ const moved = [];
609
+ for (const n of [...neighborsOf(g, id)].sort(byNum)) {
610
+ const can = shrinkForSplit.get(n);
611
+ if (!can || !left)
612
+ continue;
613
+ const take = Math.min(can, left);
614
+ shrinkForSplit.set(n, can - take);
615
+ left -= take;
616
+ moved.push({ from: n, armies: take });
617
+ }
618
+ stacks.push({ territoryId: id, growth, moved, fog: beside ? left : 0, deploy: beside ? 0 : left });
619
+ }
620
+ stacks.sort((a, b) => a.territoryId - b.territoryId);
621
+ /**
622
+ * #271 (3): its territories shown with armies on the earlier board and hidden on the later one: what
623
+ * each could have sent (its armies less the guard), the most a capture beside it can have received
624
+ * from it. Claimed after `shrinkLeft`, in ascending ids, each army once.
625
+ * #271 review, a known under-read: a stack hidden now is claimed whether or not it emptied, and it is
626
+ * usually hidden because the capture took my territory and my sight of it with it. So a real
627
+ * deploy-then-capture beside a source in view both times and such a stack reads its surplus as an
628
+ * arrival (counted only in `high`), not deploy. Accepted: a merge read as deploy once read +45.
629
+ */
630
+ const hiddenLeft = new Map();
631
+ for (const t of previous.territories) {
632
+ const b = visibleState(t);
633
+ if (!g.territoryById.has(t.territoryId) || b?.owner.kind !== 'player' || b.owner.playerId !== playerId)
634
+ continue;
635
+ if (!visibleState(now.get(t.territoryId)))
636
+ hiddenLeft.set(t.territoryId, Math.max(0, b.armies - guard));
637
+ }
638
+ let arrivals = 0;
639
+ const unseenAttackers = [];
640
+ let unseenAttackerArmies = 0;
641
+ for (const t of [...board.territories].sort((a, b) => a.territoryId - b.territoryId)) {
642
+ if (!g.territoryById.has(t.territoryId) || !visibleState(t))
643
+ continue;
644
+ if (t.owner.kind !== 'player' || t.owner.playerId !== playerId)
645
+ continue;
646
+ const was = visibleState(before.get(t.territoryId));
647
+ if (!was) {
648
+ reveals.push(t.territoryId);
649
+ continue;
650
+ }
651
+ counted.push(t.territoryId);
652
+ const ns = [...neighborsOf(g, t.territoryId)].sort((a, b) => a - b);
653
+ if (was.owner.kind === 'player' && was.owner.playerId === playerId) {
654
+ // #226: what my failed attack killed there stood there too: defenders after = before + deploy
655
+ // + transfers in − kills.
656
+ const growth = t.armies - was.armies + killsAt(t.territoryId);
657
+ if (growth > 0 && ns.some(hidden))
658
+ ambiguous.push({ id: t.territoryId, armies: growth, kind: 'growth' });
659
+ else
660
+ total += growth;
661
+ }
662
+ else {
663
+ captured.push(t.territoryId);
664
+ // What the capture cost it, always. Taken from me (#123), the defenders were what I left
665
+ // there, which this board cannot tell (I may have attacked out of it): priced at the guard,
666
+ // my stack last turn the high reading.
667
+ if (context.me !== undefined && was.owner.kind === 'player' && was.owner.playerId === context.me) {
668
+ const least = straightKills(Math.min(was.armies, guard), defensive);
669
+ total += least;
670
+ highExtra += straightKills(was.armies, defensive) - least;
671
+ emptiedHigh += straightKills(was.armies, defensive) - least;
672
+ emptied.push(t.territoryId);
673
+ }
674
+ else
675
+ total += straightKills(was.armies, defensive);
676
+ // The armies standing there only as far as a visible source's shrink accounts for them
677
+ // (it cancels them). Beyond that, with a neighbour that was hidden on either board: when a
678
+ // visible source did shrink into it, the attack came from that stack and the rest was
679
+ // deployed on it first (deploy-then-capture, #123); when none did, the rest arrived from
680
+ // the fog — a move, not income (#86). With no hidden neighbour, the rest can only be a
681
+ // deploy on a visible source before it attacked.
682
+ let arrived = t.armies;
683
+ let claimed = 0;
684
+ for (const n of ns) {
685
+ const left = shrinkLeft.get(n);
686
+ if (!left || !arrived)
687
+ continue;
688
+ const take = Math.min(left, arrived);
689
+ shrinkLeft.set(n, left - take);
690
+ arrived -= take;
691
+ claimed += take;
692
+ total += take;
693
+ }
694
+ // #271 (3): its stacks in view last turn beside it, hidden now, may have moved in: arrivals.
695
+ let came = 0;
696
+ for (const n of ns) {
697
+ const left = hiddenLeft.get(n);
698
+ if (!left || !arrived)
699
+ continue;
700
+ const take = Math.min(left, arrived);
701
+ hiddenLeft.set(n, left - take);
702
+ arrived -= take;
703
+ came += take;
704
+ }
705
+ arrivals += came;
706
+ // Had its source stayed put (hidden now, it may have), they were deployed: the high reading.
707
+ highExtra += came;
708
+ if (arrived > 0 && ns.some(hidden)) {
709
+ // #271 (2): a neutral in view needed attackers; what stands there beyond what its stacks in
710
+ // view sent, up to what that need leaves standing, came from out of sight.
711
+ let unseen = 0;
712
+ if (was.owner.kind === 'neutral') {
713
+ const need = fewestAttackersToTake(was.armies, rates, rates.luckModifier, rates.roundingMode);
714
+ const cost = straightKills(was.armies, defensive);
715
+ unseen = need === null ? 0 : Math.min(arrived, Math.max(0, need - cost - claimed - came));
716
+ if (unseen > 0) {
717
+ unseenAttackers.push(t.territoryId);
718
+ // The attackers out of sight: what the capture needed less what came from view
719
+ // (need − claimed − came), within what stands there.
720
+ unseenAttackerArmies += unseen + cost;
721
+ }
722
+ }
723
+ if (claimed > 0)
724
+ ambiguous.push({ id: t.territoryId, armies: arrived, kind: 'capture' });
725
+ else {
726
+ if (unseen > 0)
727
+ ambiguous.push({ id: t.territoryId, armies: unseen, kind: 'needed' });
728
+ const rest = arrived - unseen;
729
+ if (rest > 0) {
730
+ fromFog.push(t.territoryId);
731
+ fogArmies += rest;
732
+ highExtra += rest;
733
+ }
734
+ }
735
+ }
736
+ else
737
+ total += arrived;
738
+ }
739
+ }
740
+ // #123: the ambiguous armies, read as deploy up to one bound on the turn's deploy — the same
741
+ // bound for growth beside the fog and a reinforced capture's surplus, shared in id order —
742
+ // and the rest as moves out of the fog. The low reading takes all of them out, the high one
743
+ // counts all of them.
744
+ const grewFromFog = [];
745
+ let fogGrowth = 0;
746
+ const bound = ambiguousBound(context);
747
+ // Without an expected deploy (a board-only reading), growth is all deploy, as before #123.
748
+ if (bound === null)
749
+ for (const x of ambiguous)
750
+ if (x.kind === 'growth')
751
+ total += x.armies;
752
+ // A board-only reading (neither `expected` nor `most`) has no room at all: a negative total (a
753
+ // stack of its own that shrank into the fog) must not make room for a capture's surplus.
754
+ let room = bound === null && context.most === undefined ? 0 : Math.max(0, (bound ?? Math.max(0, context.most)) - total);
755
+ // #293: under Local Deployment, the territories a bonus pool could have paid into on the turn read
756
+ // (the bonuses it could hold on the earlier board); growth beside the fog elsewhere draws on `freeLeft`.
757
+ const local = rates.localDeployments === true && bound !== null && context.localFree !== undefined;
758
+ const pooledOn = new Set();
759
+ if (local)
760
+ for (const b of g.map.bonuses) {
761
+ if (b.value <= 0)
762
+ continue;
763
+ const ts = bonusTerritories(g, b.id);
764
+ const possible = ts.every((t) => {
765
+ const o = ownerShown(before.get(t))?.owner;
766
+ return o === undefined || (o.kind === 'player' && o.playerId === playerId);
767
+ });
768
+ if (possible)
769
+ for (const t of ts)
770
+ pooledOn.add(t);
771
+ }
772
+ let freeLeft = Math.max(0, context.localFree ?? 0);
773
+ const localCut = [];
774
+ // #293 review: a walled growth's walk draws on the shrink the captures left (`shrinkLeft`, after
775
+ // the capture loop), less what the other grown stacks' splits took (their growth already nets it),
776
+ // in ascending ids: one claim pass, so one neighbour's shrink never offsets a capture and a walk both.
777
+ const walled = (x) => local && x.kind === 'growth' && !pooledOn.has(x.id);
778
+ const walkLeft = new Map(shrinkLeft);
779
+ if (local) {
780
+ const walledIds = new Set(ambiguous.filter(walled).map((x) => x.id));
781
+ for (const st of stacks)
782
+ if (!walledIds.has(st.territoryId))
783
+ for (const m of st.moved)
784
+ walkLeft.set(m.from, Math.max(0, (walkLeft.get(m.from) ?? 0) - m.armies));
785
+ }
786
+ for (const x of [...ambiguous].sort((a, b) => a.id - b.id)) {
787
+ if (bound === null && x.kind === 'growth') {
788
+ lowExtra -= x.armies;
789
+ continue;
790
+ }
791
+ // #293: a walk from a neighbour in view (the growth split) nets its shrink; the rest is deploy only
792
+ // as far as the free income still reaches.
793
+ const isWalled = walled(x);
794
+ let walk = 0;
795
+ if (isWalled)
796
+ for (const n of [...neighborsOf(g, x.id)].sort(byNum)) {
797
+ const can = walkLeft.get(n);
798
+ if (!can || walk >= x.armies)
799
+ continue;
800
+ const take = Math.min(can, x.armies - walk);
801
+ walkLeft.set(n, can - take);
802
+ walk += take;
803
+ }
804
+ total += walk;
805
+ room = Math.max(0, room - walk);
806
+ const deployed = Math.min(x.armies - walk, room, isWalled ? freeLeft : Infinity);
807
+ if (isWalled)
808
+ freeLeft -= deployed;
809
+ room -= deployed;
810
+ total += deployed;
811
+ lowExtra -= deployed;
812
+ const moved = x.armies - walk - deployed;
813
+ if (isWalled && moved > 0)
814
+ localCut.push(x.id);
815
+ highExtra += moved;
816
+ if (x.kind === 'capture') {
817
+ if (deployed > 0)
818
+ reinforced.push(x.id);
819
+ if (moved > 0)
820
+ fromFog.push(x.id);
821
+ }
822
+ else if (x.kind === 'needed') {
823
+ if (moved > 0 && !fromFog.includes(x.id))
824
+ fromFog.push(x.id);
825
+ }
826
+ else if (moved > 0) {
827
+ grewFromFog.push(x.id);
828
+ fogGrowth += moved;
829
+ }
830
+ fogArmies += moved;
831
+ }
832
+ fromFog.sort((a, b) => a - b);
833
+ // #271 (1): a failed attack on a hold of mine bounds its deploy from below, fog or not.
834
+ const repelled = context.me !== undefined && context.myOrders
835
+ ? repelledFloor(g, previous, board, context.me, playerId, context.myOrders, rates, guard, context.bomb === true)
836
+ : { territories: [], floor: 0 };
837
+ // #418: a capture with every source army in view proves a minimum deploy, fog or not.
838
+ const proof = captureFloor(g, previous, board, playerId, rates, guard, {
839
+ ...(context.me !== undefined ? { me: context.me } : {}),
840
+ orders: context.myOrders,
841
+ bomb: context.bomb === true,
842
+ });
843
+ const floor = Math.max(repelled.floor, proof.floor);
844
+ return {
845
+ stacks,
846
+ deploy: Math.max(0, total, floor),
847
+ signed: total,
848
+ counted,
849
+ captured,
850
+ fromFog,
851
+ fogArmies,
852
+ reveals,
853
+ reinforced,
854
+ grewFromFog,
855
+ fogGrowth,
856
+ ...(localCut.length ? { localCut: { free: Math.max(0, context.localFree ?? 0), territories: localCut } } : {}),
857
+ expected: context.expected ?? null,
858
+ attacked: [...kills.keys()].sort(byNum),
859
+ attackKills: [...kills.values()].reduce((n, k) => n + k, 0),
860
+ emptied,
861
+ emptiedHigh,
862
+ arrivals,
863
+ unseenAttackers,
864
+ unseenAttackerArmies,
865
+ repelled: repelled.territories,
866
+ repelledFloor: repelled.floor,
867
+ proven: proof.territories,
868
+ captureFloor: proof.floor,
869
+ low: Math.max(0, total + lowExtra, floor),
870
+ high: Math.max(0, total + highExtra, floor),
871
+ };
872
+ }
873
+ /**
874
+ * How much more than it was expected to deploy an opponent may earn unseen (#123 review): under
875
+ * fog the visible income reads 2–3× low (#119), so ambiguous armies count as deploy up to twice
876
+ * the expected figure. A one-off stack out of the fog is not read as a phantom income; a steady
877
+ * hidden bonus (as large as the visible income) still is, and the tracker, which raises the
878
+ * expected figure to its carried income, learns a larger one over a few turns.
879
+ */
880
+ export const HIDDEN_INCOME_FACTOR = 2;
881
+ /**
882
+ * The most an opponent's deploy may total once ambiguous armies are counted (#123): twice what
883
+ * it was expected to deploy ({@link HIDDEN_INCOME_FACTOR}), never more than it could earn
884
+ * (`most`). Null without an expected figure: then growth is all deploy and a capture's surplus
885
+ * counts up to `most` (none without it, #86).
886
+ */
887
+ function ambiguousBound(context) {
888
+ if (context.expected === undefined)
889
+ return null;
890
+ const twice = HIDDEN_INCOME_FACTOR * Math.max(0, context.expected);
891
+ return context.most !== undefined ? Math.min(Math.max(0, context.most), twice) : twice;
892
+ }
893
+ /** {@link observeDeploy}'s deploy figure alone. */
894
+ export function observedDeploy(g, board, previous, playerId, rates = {}) {
895
+ return observeDeploy(g, board, previous, playerId, rates).deploy;
896
+ }