@chrischall/warapp-mcp 0.6.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 (111) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +100 -7
  4. package/dist/analysis/accept-surrender.js +20 -2
  5. package/dist/analysis/calibrate.js +1 -0
  6. package/dist/analysis/card-support.js +187 -20
  7. package/dist/analysis/card-threats.js +68 -3
  8. package/dist/analysis/chat-advice.js +182 -0
  9. package/dist/analysis/chat-blocks.js +106 -0
  10. package/dist/analysis/chat-intent.js +559 -0
  11. package/dist/analysis/chat-read.js +159 -0
  12. package/dist/analysis/coalition.js +55 -0
  13. package/dist/analysis/decision-replay.js +279 -0
  14. package/dist/analysis/decision-truth.js +146 -0
  15. package/dist/analysis/finished-game.js +62 -3
  16. package/dist/analysis/game-lessons.js +12 -6
  17. package/dist/analysis/local-deploy.js +14 -0
  18. package/dist/analysis/opponent-profile.js +46 -3
  19. package/dist/analysis/opponents.js +246 -19
  20. package/dist/analysis/outlook.js +323 -17
  21. package/dist/analysis/picks.js +270 -37
  22. package/dist/analysis/plan/after-leftover.js +28 -3
  23. package/dist/analysis/plan/captures.js +80 -16
  24. package/dist/analysis/plan/completed.js +8 -1
  25. package/dist/analysis/plan/conceded-out.js +16 -11
  26. package/dist/analysis/plan/deploy-estimates.js +513 -0
  27. package/dist/analysis/plan/doomed-out.js +135 -0
  28. package/dist/analysis/plan/estimates.js +73 -7
  29. package/dist/analysis/plan/free-capture.js +34 -0
  30. package/dist/analysis/plan/guard-off.js +2 -1
  31. package/dist/analysis/plan/holds.js +85 -313
  32. package/dist/analysis/plan/horizon.js +42 -0
  33. package/dist/analysis/plan/leftover.js +188 -10
  34. package/dist/analysis/plan/observe.js +896 -0
  35. package/dist/analysis/plan/orders.js +35 -1
  36. package/dist/analysis/plan/relations.js +115 -2
  37. package/dist/analysis/plan/report.js +10 -4
  38. package/dist/analysis/plan/shared.js +7 -1189
  39. package/dist/analysis/plan/stand-still.js +7 -5
  40. package/dist/analysis/plan/state.js +12 -0
  41. package/dist/analysis/plan/stockpile.js +104 -0
  42. package/dist/analysis/plan/strike-stack.js +467 -0
  43. package/dist/analysis/plan/strike.js +8 -441
  44. package/dist/analysis/plan/targets.js +374 -72
  45. package/dist/analysis/plan/threats.js +120 -9
  46. package/dist/analysis/plan/transfers.js +35 -1
  47. package/dist/analysis/plan/two-move.js +70 -0
  48. package/dist/analysis/plan/vacated.js +124 -2
  49. package/dist/analysis/plan/withdraw.js +316 -0
  50. package/dist/analysis/planner.js +356 -53
  51. package/dist/analysis/player.js +4 -0
  52. package/dist/analysis/relations.js +8 -2
  53. package/dist/analysis/since-last.js +18 -5
  54. package/dist/analysis/stress.js +1 -1
  55. package/dist/board.js +36 -2
  56. package/dist/build-id.js +106 -0
  57. package/dist/bundle.js +15863 -10242
  58. package/dist/chat-automation.js +22 -0
  59. package/dist/client.js +14 -0
  60. package/dist/decision-log.js +1093 -0
  61. package/dist/finished-store.js +5 -1
  62. package/dist/lessons-store.js +322 -21
  63. package/dist/my-games.js +2 -0
  64. package/dist/open-games.js +122 -18
  65. package/dist/outlook-log.js +42 -1
  66. package/dist/protocol/methods.js +4 -2
  67. package/dist/review-export.js +198 -0
  68. package/dist/state-bundle.js +62 -3
  69. package/dist/state-cli.js +5 -3
  70. package/dist/strategy/notes.js +56 -0
  71. package/dist/tools/accept-surrender.js +23 -9
  72. package/dist/tools/award.js +5 -1
  73. package/dist/tools/card-advice.js +102 -33
  74. package/dist/tools/card-support-advice.js +53 -8
  75. package/dist/tools/chat-advice.js +330 -0
  76. package/dist/tools/chat-inbox.js +15 -4
  77. package/dist/tools/chat.js +41 -11
  78. package/dist/tools/check-plan.js +16 -3
  79. package/dist/tools/commander-check.js +2 -1
  80. package/dist/tools/decision-capture.js +461 -0
  81. package/dist/tools/end-of-game.js +146 -18
  82. package/dist/tools/game-kind.js +92 -0
  83. package/dist/tools/how-lost.js +7 -2
  84. package/dist/tools/index.js +3 -0
  85. package/dist/tools/join-game.js +51 -9
  86. package/dist/tools/live-context.js +6 -0
  87. package/dist/tools/live.js +43 -6
  88. package/dist/tools/map-curves.js +73 -0
  89. package/dist/tools/notifications.js +4 -3
  90. package/dist/tools/open-games.js +2 -2
  91. package/dist/tools/opponents.js +2 -0
  92. package/dist/tools/past-games.js +74 -8
  93. package/dist/tools/picks.js +169 -57
  94. package/dist/tools/profile-hook.js +62 -3
  95. package/dist/tools/profile-opponents.js +2 -0
  96. package/dist/tools/push.js +2 -2
  97. package/dist/tools/relations.js +2 -0
  98. package/dist/tools/scout.js +16 -2
  99. package/dist/tools/state.js +6 -1
  100. package/dist/tools/strategy.js +3 -3
  101. package/dist/tools/stress-opponents.js +2 -0
  102. package/dist/tools/surrender-pending.js +10 -1
  103. package/dist/tools/surrender.js +18 -3
  104. package/dist/tools/turn.js +353 -19
  105. package/dist/tools/where.js +3 -1
  106. package/dist/version.js +1 -1
  107. package/manifest.json +23 -2
  108. package/mint.yaml +23 -0
  109. package/package.json +1 -1
  110. package/server.json +20 -2
  111. package/skills/warapp-mcp/SKILL.md +42 -8
@@ -1,9 +1,8 @@
1
- import { commerceRules } from '../../commerce.js';
2
1
  import { bonusTerritories } from '../bonuses.js';
3
- import { armiesForChance, armiesToTake, DEFAULT_DEFENSIVE_KILL_RATE, DEFAULT_OFFENSIVE_KILL_RATE, fewestAttackersToKill, fewestAttackersToTake, luckFraction, specialUnitStrength, straightKills, } from '../combat.js';
4
- import { neighborsOf } from '../graph.js';
5
- import { armyCapIncome, boardIncome, DEFAULT_BASE_INCOME, incomeRules, territoryIncome } from '../player.js';
2
+ import { armiesForChance, armiesToTake, DEFAULT_DEFENSIVE_KILL_RATE, DEFAULT_OFFENSIVE_KILL_RATE, luckFraction, } from '../combat.js';
3
+ import { DEFAULT_BASE_INCOME } from '../player.js';
6
4
  import { byNum } from './util.js';
5
+ export * from './observe.js';
7
6
  /** A bonus is uneconomic when its remaining capture cost exceeds this many turns of its value… */
8
7
  export const PAYBACK_TURNS = 10;
9
8
  /**
@@ -279,1189 +278,8 @@ export function guaranteedFallsReaching(saveCosts, reaches, deploy) {
279
278
  const savable = saveCosts.filter((c, i) => c <= (reaches[i] ?? deploy));
280
279
  return saveCosts.length - savable.length + guaranteedFalls(savable, deploy);
281
280
  }
282
- /**
283
- * Fog levels that hide a territory's armies. The live board names war.app's StandingFogLevel
284
- * (1 You, 2 Visible, 3 OwnerOnly, 4 Fogged; the client refuses a deploy on 3 or 4 as "fogged");
285
- * a GameFeed standing may spell it as a word or as the raw number (every GameFeed scalar is a
286
- * string).
287
- */
288
- const HIDDEN_FOG = /fog|owneronly|^\s*[34]\s*$/i;
289
- /** Fog levels that hide a territory's owner too (StandingFogLevel 4, Fogged). */
290
- const OWNER_HIDDEN_FOG = /fog|^\s*4\s*$/i;
291
- /**
292
- * `t` when a board shows both its owner (a player or a neutral) and its armies, else
293
- * `undefined`: a fogged territory (owner unknown, armies `null`), or one whose fog level hides
294
- * its armies even if a placeholder owner or count came with it (issue #69).
295
- *
296
- * One exception: an entry named `"OwnerOnly"` that still carries a count is fog level 2
297
- * (Visible) from a board cache written before #69, which misnamed it; every current board nulls
298
- * an owner-only territory's armies, and the old cache left level 3 unnamed (`"3"`).
299
- */
300
- export function visibleState(t) {
301
- if (!t || t.armies === null)
302
- return undefined;
303
- if (t.owner.kind !== 'player' && t.owner.kind !== 'neutral')
304
- return undefined;
305
- if (t.fogLevel !== undefined && HIDDEN_FOG.test(t.fogLevel) && !/^\s*owneronly\s*$/i.test(t.fogLevel))
306
- return undefined;
307
- return t;
308
- }
309
- /**
310
- * `t` when a board shows its owner (a player or a neutral), whatever its armies: visible, or
311
- * owner-only (light fog); `undefined` when fogged, even under a placeholder owner.
312
- */
313
- export function ownerShown(t) {
314
- if (!t || (t.owner.kind !== 'player' && t.owner.kind !== 'neutral'))
315
- return undefined;
316
- if (t.fogLevel !== undefined && OWNER_HIDDEN_FOG.test(t.fogLevel))
317
- return undefined;
318
- return t;
319
- }
320
- /** #294: {@link FrontierCoverage} of one opponent on one observed turn. Pure. */
321
- export function frontierCoverage(g, board, previous, playerId) {
322
- const now = new Map(board.territories.map((t) => [t.territoryId, t]));
323
- const before = new Map(previous.territories.map((t) => [t.territoryId, t]));
324
- const its = (id) => {
325
- const st = ownerShown(now.get(id));
326
- return st?.owner.kind === 'player' && st.owner.playerId === playerId;
327
- };
328
- const shownIts = [...g.territoryById.keys()].filter(its);
329
- const frontier = new Set();
330
- let inView = 0;
331
- for (const t of shownIts) {
332
- const ns = neighborsOf(g, t);
333
- if (ns.every(its))
334
- continue;
335
- frontier.add(t);
336
- const a = visibleState(now.get(t));
337
- const b = visibleState(before.get(t));
338
- if (a && b)
339
- inView++;
340
- for (const n of ns)
341
- if (!ownerShown(now.get(n)))
342
- frontier.add(n);
343
- }
344
- let hiddenBonuses = 0;
345
- for (const bonus of g.map.bonuses) {
346
- const ts = bonusTerritories(g, bonus.id);
347
- if (bonus.value <= 0 || !ts.length)
348
- continue;
349
- const taken = ts.some((t) => {
350
- const st = ownerShown(now.get(t));
351
- return st !== undefined && !(st.owner.kind === 'player' && st.owner.playerId === playerId);
352
- });
353
- if (!taken && ts.some((t) => !ownerShown(now.get(t))))
354
- hiddenBonuses++;
355
- }
356
- const share = frontier.size ? inView / frontier.size : shownIts.length ? 1 : 0;
357
- return { inView, frontier: frontier.size, share, hiddenBonuses };
358
- }
359
- /** #294: {@link TrackCoverage} over `turns` (those carrying a coverage); `null` when none does. */
360
- export function trackCoverage(turns) {
361
- const withIt = turns.filter((x) => x.coverage !== undefined);
362
- if (!withIt.length)
363
- return null;
364
- const inView = withIt.reduce((n, x) => n + x.coverage.inView, 0);
365
- const frontier = withIt.reduce((n, x) => n + x.coverage.frontier, 0);
366
- const range = (xs) => ({ min: Math.min(...xs), max: Math.max(...xs) });
367
- return {
368
- turns: withIt.map((x) => x.from),
369
- inView: range(withIt.map((x) => x.coverage.inView)),
370
- frontier: range(withIt.map((x) => x.coverage.frontier)),
371
- share: frontier ? inView / frontier : withIt.reduce((n, x) => n + x.coverage.share, 0) / withIt.length,
372
- hiddenBonuses: withIt.at(-1).coverage.hiddenBonuses,
373
- };
374
- }
375
- /**
376
- * #294: "1 of ~4 frontier territories (25%)" (a range, "1–2 of ~4–5", when the turns differ; the share
377
- * is Σ read ÷ Σ frontier), and ", N bonus(es) it could hold out of view" when any: the words beside a
378
- * tracked figure.
379
- */
380
- export function coverageText(c) {
381
- const b = c.hiddenBonuses;
382
- const range = (r) => (r.min === r.max ? `${r.min}` : `${r.min}–${r.max}`);
383
- 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` : ''}`;
384
- }
385
- /**
386
- * #226: what my failed attacks on `playerId` killed, by target, on the turn `before` → `after`: each
387
- * move of mine onto a territory it holds on both boards (shown with armies both times), from a
388
- * source mine on both (one that fell may have been taken before my attack ran), kills
389
- * round(armies × the offensive kill rate) — a straight-rounded expectation, which luck can move.
390
- * The board reads that loss as a shrink. The opponent tracker's `measureOrders` counts the same.
391
- */
392
- export function failedAttackKills(g, before, after, me, playerId, orders, rates = {}) {
393
- const offensive = rates.offensiveKillRate ?? DEFAULT_OFFENSIVE_KILL_RATE;
394
- const out = new Map();
395
- for (const m of failedAttackMoves(g, before, after, me, playerId, orders))
396
- out.set(m.to, (out.get(m.to) ?? 0) + straightKills(Math.max(0, m.armies), offensive));
397
- return out;
398
- }
399
- /**
400
- * The moves {@link failedAttackKills} counts: each move of mine onto a territory `playerId` holds on
401
- * both boards (shown with armies both times), from a source mine on both. #240 review: the armies
402
- * {@link repulsedAttacks} reports are these moves' too, so they match the kills.
403
- */
404
- function failedAttackMoves(g, before, after, me, playerId, orders) {
405
- const was = new Map(before.territories.map((t) => [t.territoryId, t]));
406
- const now = new Map(after.territories.map((t) => [t.territoryId, t]));
407
- const owns = (t, p) => {
408
- const v = visibleState(t);
409
- return v?.owner.kind === 'player' && v.owner.playerId === p;
410
- };
411
- return orders.moves.filter((m) => g.territoryById.has(m.to) &&
412
- owns(was.get(m.from), me) &&
413
- owns(now.get(m.from), me) &&
414
- owns(was.get(m.to), playerId) &&
415
- owns(now.get(m.to), playerId));
416
- }
417
- /**
418
- * #271 review: the territories an order of mine touched that `orders.moves` does not carry, so what
419
- * they held after my orders is not known: a move order in `sent` beyond the plain ones `moves` keeps on
420
- * the same pair (#165 leaves out Transfer Only, Attack Only and percentage orders), both its ends; and
421
- * each territory a card play names (an Airlift's `from` and `to`, a card's `target`).
422
- */
423
- function ordersNotInMoves(orders) {
424
- const out = new Set();
425
- const key = (from, to) => `${from}>${to}`;
426
- const carried = new Map();
427
- for (const m of orders.moves)
428
- carried.set(key(m.from, m.to), (carried.get(key(m.from, m.to)) ?? 0) + 1);
429
- for (const o of orders.sent ?? []) {
430
- const left = carried.get(key(o.from, o.to)) ?? 0;
431
- if (left > 0)
432
- carried.set(key(o.from, o.to), left - 1);
433
- else
434
- out.add(o.from).add(o.to);
435
- }
436
- for (const c of orders.cards ?? [])
437
- for (const id of [c.from, c.to, c.target])
438
- if (id !== undefined)
439
- out.add(id);
440
- return out;
441
- }
442
- /**
443
- * My holds (mine, with armies, on both boards) that lost armies my orders do not explain, by id: the
444
- * defenders were my armies there plus what I deployed there, less what I sent out; what the later
445
- * board shows less (what I moved in from a territory mine on the earlier board counted on top) is what
446
- * an attack on it that failed killed. A hold I attacked out of and failed is skipped: the survivors of
447
- * my own attack came back to it, so its loss is not known. So is a hold an order `moves` does not carry
448
- * touched (#271 review, {@link ordersNotInMoves}: a Transfer Only, Attack Only or percentage order, a
449
- * card play), and a transfer from a source one touched is not surely whole. The opponent tracker's attacks on my holds
450
- * and the #271 bound ({@link repelledFloor}) both read these.
451
- */
452
- export function holdLosses(g, before, after, me, orders, guard = 1) {
453
- const was = new Map(before.territories.map((t) => [t.territoryId, t]));
454
- const now = new Map(after.territories.map((t) => [t.territoryId, t]));
455
- const owns = (t, p) => t?.owner.kind === 'player' && t.owner.playerId === p;
456
- const held = (id) => owns(visibleState(was.get(id)), me) && owns(visibleState(now.get(id)), me);
457
- const deployed = new Map();
458
- for (const d of orders.deploys)
459
- deployed.set(d.territoryId, (deployed.get(d.territoryId) ?? 0) + Math.max(0, d.armies));
460
- const sent = new Map();
461
- const came = new Map();
462
- /** The sources of what `came`, by the hold they sent to. */
463
- const cameFrom = new Map();
464
- const failedFrom = new Set();
465
- const untracked = ordersNotInMoves(orders);
466
- for (const m of orders.moves) {
467
- const armies = Math.max(0, m.armies);
468
- sent.set(m.from, (sent.get(m.from) ?? 0) + armies);
469
- if (held(m.to) && owns(visibleState(was.get(m.from)), me)) {
470
- came.set(m.to, (came.get(m.to) ?? 0) + armies);
471
- if (armies > 0)
472
- cameFrom.set(m.to, (cameFrom.get(m.to) ?? new Set()).add(m.from));
473
- }
474
- if (!owns(visibleState(was.get(m.to)), me) && !owns(visibleState(now.get(m.to)), me))
475
- failedFrom.add(m.from);
476
- }
477
- /**
478
- * #271 review: a source that surely sent all ordered from it ({@link HoldLoss.inflowSure}): mine on
479
- * both boards, no failed attack of mine out of it, nothing moved into it (when that arrived is not
480
- * known), and it shows exactly what my orders leave there. An order sends what is left down to the
481
- * guard, so a loss before it shows only when my orders leave more than the guard there; else only
482
- * when no other player (nor the fog) was beside it to attack or bomb it.
483
- */
484
- const sentWhole = (id) => {
485
- if (!held(id) || failedFrom.has(id) || came.has(id) || untracked.has(id))
486
- return false;
487
- const left = visibleState(was.get(id)).armies + (deployed.get(id) ?? 0) - (sent.get(id) ?? 0);
488
- if (left < 0 || visibleState(now.get(id)).armies !== left)
489
- return false;
490
- if (left > guard)
491
- return true;
492
- return neighborsOf(g, id).every((n) => {
493
- const o = ownerShown(was.get(n))?.owner;
494
- return o !== undefined && (o.kind === 'neutral' || (o.kind === 'player' && o.playerId === me));
495
- });
496
- };
497
- const out = [];
498
- for (const id of [...new Set(after.territories.map((t) => t.territoryId))].sort(byNum)) {
499
- if (!g.territoryById.has(id) || !held(id) || failedFrom.has(id) || untracked.has(id))
500
- continue;
501
- const standing = visibleState(was.get(id)).armies + (deployed.get(id) ?? 0);
502
- const defenders = Math.max(0, standing - (sent.get(id) ?? 0));
503
- const loss = defenders + (came.get(id) ?? 0) - visibleState(now.get(id)).armies;
504
- const inflowSure = [...(cameFrom.get(id) ?? [])].every(sentWhole);
505
- if (loss > 0)
506
- out.push({ territoryId: id, defenders, loss, standing, inflowSure });
507
- }
508
- return out;
509
- }
510
- /**
511
- * #271: a failed attack on a hold of mine is a measurement, the mirror of #226. My loss there
512
- * ({@link holdLosses}: what my orders do not explain) needed at least {@link fewestAttackersToKill}
513
- * attackers (every attacker killing its most, luck included), and without Multi-Attack each army
514
- * moves once, so they all came from its territories beside the hold at the start of the turn: their
515
- * armies then (less the guard) plus what it deployed there. A hold counts only when every neighbour
516
- * showed its owner on the earlier board, every territory of `playerId` beside it showed its armies,
517
- * and `playerId` is the only other player beside it. Over every such hold the bound is the larger of
518
- * the best single hold and all of them together (the attackers summed against the stacks beside any
519
- * of them, each counted once).
520
- * #271 review: a hold reads only when what I moved in surely arrived whole ({@link HoldLoss.inflowSure}),
521
- * so the bound uses the least my orders can have brought. On a turn an opponent may have played a Bomb
522
- * card (`bomb`, {@link bombPossibleOn}), which halves a territory of mine beside the bomber after the
523
- * deploys and reads as an attack, the most it could take (half the stack before any move, rounded up)
524
- * is left out of the loss first. Orders cached without `sent` or `cards` (before they were kept) bound
525
- * nothing: an order `moves` leaves out, or a card play, may have moved armies out of a hold.
526
- */
527
- export function repelledFloor(g, before, after, me, playerId, orders, settings = {}, guard = (settings.oneArmyStandsGuard ?? true) ? 1 : 0, bomb = false) {
528
- const none = { territories: [], attackers: 0, supply: 0, floor: 0 };
529
- // #271 review: orders cached before `sent` and `cards` were kept may have left out an order or a card
530
- // play that moved armies out of a hold: what ran is unknown, so they bound nothing.
531
- if (settings.multiAttack || !orders.sent || !orders.cards)
532
- return none;
533
- const was = new Map(before.territories.map((t) => [t.territoryId, t]));
534
- const sendable = (id) => {
535
- const st = visibleState(was.get(id));
536
- return Math.max(0, st.armies - guard) + specialUnitStrength(st.specialUnits?.filter((u) => u.playerId === playerId));
537
- };
538
- const holds = [];
539
- for (const h of holdLosses(g, before, after, me, orders, guard)) {
540
- if (!h.inflowSure)
541
- continue;
542
- const loss = h.loss - (bomb ? Math.ceil(h.standing / 2) : 0);
543
- if (loss <= 0)
544
- continue;
545
- const ns = neighborsOf(g, h.territoryId);
546
- if (ns.some((n) => !ownerShown(was.get(n))))
547
- continue;
548
- const others = new Set();
549
- const beside = [];
550
- let hidden = false;
551
- for (const n of ns) {
552
- const o = ownerShown(was.get(n)).owner;
553
- if (o.kind !== 'player' || o.playerId === me)
554
- continue;
555
- others.add(o.playerId);
556
- if (o.playerId === playerId) {
557
- if (!visibleState(was.get(n)))
558
- hidden = true;
559
- beside.push(n);
560
- }
561
- }
562
- if (hidden || others.size !== 1 || !others.has(playerId))
563
- continue;
564
- const attackers = fewestAttackersToKill(loss, settings, settings.luckModifier, settings.roundingMode);
565
- if (attackers === null)
566
- continue;
567
- holds.push({ id: h.territoryId, attackers, beside });
568
- }
569
- if (!holds.length)
570
- return none;
571
- const supplyOf = (ids) => [...new Set(ids)].reduce((n, id) => n + sendable(id), 0);
572
- let best = { ...none, territories: holds.map((h) => h.id) };
573
- const all = {
574
- attackers: holds.reduce((n, h) => n + h.attackers, 0),
575
- supply: supplyOf(holds.flatMap((h) => h.beside)),
576
- };
577
- best = { ...best, ...all, floor: Math.max(0, all.attackers - all.supply) };
578
- for (const h of holds) {
579
- const supply = supplyOf(h.beside);
580
- if (h.attackers - supply > best.floor)
581
- best = { ...best, attackers: h.attackers, supply, floor: h.attackers - supply };
582
- }
583
- return best;
584
- }
585
- /** #240: the turns {@link repulsedAttacks} looks back over, ending on the board being planned. */
586
- export const REPULSE_WINDOW = 3;
587
- /** #240: failed, reinforced attacks on one territory within the window that make it repulsed. */
588
- export const REPULSE_MIN = 2;
589
- /**
590
- * #240: repeated failure is evidence. Over my board history (`boards`, the newest being the board
591
- * being planned; consecutive turns only, each with my cached orders — `TurnBoard.orders`, what
592
- * warapp_submit_turn sent), a failed attack of mine on a territory — its owner the same player on
593
- * both boards, my source mine on both ({@link failedAttackKills}) — whose owner reinforced it: its
594
- * armies after plus what my attack killed exceed its armies before (after = before + deploys and
595
- * transfers in − kills). A territory with such an attack on {@link REPULSE_MIN} or more of the last
596
- * {@link REPULSE_WINDOW} turns, still that player's on the newest board, is reported, by id. Kill
597
- * counts are straight-rounded expectations: luck can move them. Pure; unknown orders give nothing.
598
- */
599
- export function repulsedAttacks(g, boards, me, rates = {}) {
600
- const sorted = [...boards].sort((a, b) => a.turn - b.turn);
601
- const newest = sorted[sorted.length - 1];
602
- if (!newest)
603
- return [];
604
- // #240 review: kept per territory and owner, so failed attacks on a territory under an earlier
605
- // owner never hide those under its newest one (the filter below keeps the newest owner's only).
606
- const found = new Map();
607
- for (let i = 0; i + 1 < sorted.length; i++) {
608
- const was = sorted[i];
609
- const now = sorted[i + 1];
610
- if (!was.orders || now.turn !== was.turn + 1 || was.turn < newest.turn - REPULSE_WINDOW)
611
- continue;
612
- const orders = was.orders;
613
- const before = new Map(was.board.territories.map((t) => [t.territoryId, t]));
614
- const after = new Map(now.board.territories.map((t) => [t.territoryId, t]));
615
- const owners = new Set();
616
- for (const m of orders.moves) {
617
- const o = visibleState(before.get(m.to))?.owner;
618
- if (o?.kind === 'player' && o.playerId !== me)
619
- owners.add(o.playerId);
620
- }
621
- for (const p of [...owners].sort(byNum)) {
622
- for (const [t, kills] of [...failedAttackKills(g, was.board, now.board, me, p, orders, rates)].sort(([a], [b]) => a - b)) {
623
- const b = visibleState(before.get(t)).armies;
624
- const a = visibleState(after.get(t)).armies;
625
- if (kills <= 0 || a + kills <= b)
626
- continue;
627
- const armies = failedAttackMoves(g, was.board, now.board, me, p, orders)
628
- .filter((m) => m.to === t)
629
- .reduce((n, m) => n + Math.max(0, m.armies), 0);
630
- // #361: a single-army jab never tries to take it (one army takes no defended territory): no evidence.
631
- if (armies <= 1)
632
- continue;
633
- const attack = { turn: was.turn, armies, before: b, after: a, kills };
634
- const key = `${t}:${p}`;
635
- const entry = found.get(key);
636
- if (!entry)
637
- found.set(key, { territoryId: t, playerId: p, attacks: [attack] });
638
- else
639
- entry.attacks.push(attack);
640
- }
641
- }
642
- }
643
- const latest = new Map(newest.board.territories.map((t) => [t.territoryId, t]));
644
- return [...found.values()]
645
- .filter((r) => {
646
- const o = visibleState(latest.get(r.territoryId))?.owner;
647
- return r.attacks.length >= REPULSE_MIN && o?.kind === 'player' && o.playerId === r.playerId;
648
- })
649
- .sort((a, b) => a.territoryId - b.territoryId);
650
- }
651
- /**
652
- * One opponent's deploy last turn as seen across two boards (issues #57, #69): the *net*
653
- * change of its visible armies plus what it visibly lost attacking, floored at 0. Only
654
- * territories visible on both boards count ({@link visibleState}): one hidden last time
655
- * (fogged, or under a fog level that hid its armies) only came into view, so it is a fog
656
- * reveal whoever holds it now — never growth, never a capture.
657
- * - under it both times: armies now − armies then, shrinks included — a transfer between
658
- * its own territories nets to zero, so it is never read as deploy;
659
- * - taken from another visible owner (another player, me included, or a visible neutral): what
660
- * the capture cost it — the attackers the previous defenders killed at the game's defensive
661
- * kill rate (`straightKills`, as in `armiesToTake`); taken from me (given `context.me`), the
662
- * defenders are the guard I may have left, not my stack last turn (#123, `emptied`: I may have
663
- * attacked out of it) — plus the armies now on it up to what its territories next to it, shown
664
- * on both boards, visibly sent away (their total shrink, each army claimed by one capture only):
665
- * those moved in from a visible source, whose shrink they cancel, so source shrink + destination
666
- * gain nets to the attrition (issue #86). An unchanged visible neighbour sent nothing, so it
667
- * explains nothing. The rest, when a neighbour was hidden on either board, is ambiguous (#123):
668
- * a deploy on a visible source that shrank into it (`reinforced`), or a move out of the fog —
669
- * never income (`fromFog`), still a threat to the borders next to it. With every neighbour in
670
- * view it can only be a deploy on the source.
671
- * - growth on its territory next to a hidden one is ambiguous the same way (`grewFromFog`).
672
- * Ambiguous armies count as deploy while the turn's total stays within {@link ambiguousBound}
673
- * (twice `context.expected`, never past `context.most`); the rest are moves. Without `expected`,
674
- * growth is all deploy and a capture's surplus counts up to `most` (none without it, #86).
675
- * `low` and `high` read every ambiguous army one way or the other (fog moves and the guard, or
676
- * deploys and my stack standing there).
677
- * Not counted: armies it lost on a territory it attacked but did not take. The defender's
678
- * count there also moves with the defender's own deploys and transfers (mine included —
679
- * this board says nothing about my orders), so the loss cannot be read off it; leaving it
680
- * out keeps the figure a lower bound (the failed attack's losses still shrink its source). The
681
- * opponent tracker adds it back when my orders that turn are known (#119, `measureOrders`).
682
- * Given those orders here (`context.myOrders`, #226), the defenders my failed attack killed on a
683
- * territory that stayed its count back into its growth there (`attacked`, `attackKills`): after =
684
- * before + deploy + transfers in − kills, so deploy ≥ after + kills − before — beside the fog an
685
- * ambiguous growth like any other, read as deploy up to the turn's bound. #271: given those orders,
686
- * a failed attack on a hold of mine bounds the deploy from below ({@link repelledFloor}: `deploy`,
687
- * `low` and `high` never below it). A capture also claims, after the visible sources, what its stacks
688
- * in view last turn and hidden now could have sent (`arrivals`: no figure counts them but `high`); a
689
- * capture of a neutral beside the fog that no visible source sent into reads the attackers it needed
690
- * beyond its cost ({@link fewestAttackersToTake}) as ambiguous, deploy up to the bound
691
- * (`unseenAttackers`; the tracker reads a pattern of them as income), the rest a move out of the fog.
692
- * One turn only, not smoothed (the tracker reads a history). Transfers in from (or out to) the
693
- * fog still bias it — income in the fog is unseen anyway.
694
- */
695
- export function observeDeploy(g, board, previous, playerId, rates = {}, context = {}) {
696
- const { signed: _signed, ...o } = observeSigned(g, board, previous, playerId, rates, context);
697
- return o;
698
- }
699
- /**
700
- * {@link observeDeploy} with its total before the floor at 0 (`signed`): the opponent tracker
701
- * adds what my own orders measure (#119) to it before flooring.
702
- */
703
- export function observeSigned(g, board, previous, playerId, rates = {}, context = {}) {
704
- const before = new Map(previous.territories.map((t) => [t.territoryId, t]));
705
- let total = 0;
706
- /** What `low` and `high` differ from `total` by. */
707
- let lowExtra = 0;
708
- let highExtra = 0;
709
- const counted = [];
710
- const captured = [];
711
- const fromFog = [];
712
- let fogArmies = 0;
713
- const reveals = [];
714
- const reinforced = [];
715
- const emptied = [];
716
- let emptiedHigh = 0;
717
- /**
718
- * The ambiguous armies (#123): growth on its held territories next to a hidden one (a stack
719
- * may have walked in) and a capture's surplus over what a visible source that shrank into it
720
- * sent (deploy-then-capture, or a stack out of the fog joined). Read after the loop against
721
- * one bound, the same for both ({@link ambiguousBound}).
722
- */
723
- const ambiguous = [];
724
- const now = new Map(board.territories.map((t) => [t.territoryId, t]));
725
- const defensive = rates.defensiveKillRate ?? DEFAULT_DEFENSIVE_KILL_RATE;
726
- const guard = Math.max(0, context.guard ?? 1);
727
- // #226: my failed attacks' kills, by target: they count back into its growth there.
728
- const kills = context.me !== undefined && context.myOrders
729
- ? failedAttackKills(g, previous, board, context.me, playerId, context.myOrders, rates)
730
- : new Map();
731
- const killsAt = (id) => kills.get(id) ?? 0;
732
- /** Held by the observed player (`playerId`, not me) and shown with armies on both boards. */
733
- const heldBothTimes = (id) => {
734
- const a = visibleState(now.get(id));
735
- const b = visibleState(before.get(id));
736
- return a?.owner.kind === 'player' && a.owner.playerId === playerId && b?.owner.kind === 'player' && b.owner.playerId === playerId;
737
- };
738
- /**
739
- * What each of its territories shown with armies on both boards visibly sent away (its
740
- * shrink): the most a capture next to it can have received from it. A capture draws on it
741
- * (ascending ids), so two captures never both claim the same armies. What my failed attack killed
742
- * there (#226: these are exactly {@link failedAttackKills}' targets) is a loss, not armies sent
743
- * away, so it is taken out of the shrink.
744
- */
745
- const shrinkLeft = new Map();
746
- for (const t of board.territories)
747
- if (g.territoryById.has(t.territoryId) && heldBothTimes(t.territoryId))
748
- shrinkLeft.set(t.territoryId, Math.max(0, visibleState(before.get(t.territoryId)).armies - t.armies - killsAt(t.territoryId)));
749
- /** Not shown with armies on both boards: armies could have left it unseen. */
750
- const hidden = (id) => !visibleState(now.get(id)) || !visibleState(before.get(id));
751
- // #294: each grown stack's growth split, against its own copy of the shrinks (captures claim theirs below).
752
- // The stacks with no hidden neighbour claim first (what they leave can only be deploy, so a shrink
753
- // taken by a stack beside the fog would turn a move into a false "can only be deploy"), then those
754
- // beside the fog; each in id order, and reported in id order.
755
- const stacks = [];
756
- const shrinkForSplit = new Map(shrinkLeft);
757
- const grown = [...shrinkLeft.keys()]
758
- .sort(byNum)
759
- .map((id) => ({
760
- id,
761
- growth: visibleState(now.get(id)).armies - visibleState(before.get(id)).armies + killsAt(id),
762
- beside: neighborsOf(g, id).some(hidden),
763
- }))
764
- .filter((x) => x.growth > 0);
765
- for (const { id, growth, beside } of [...grown.filter((x) => !x.beside), ...grown.filter((x) => x.beside)]) {
766
- let left = growth;
767
- const moved = [];
768
- for (const n of [...neighborsOf(g, id)].sort(byNum)) {
769
- const can = shrinkForSplit.get(n);
770
- if (!can || !left)
771
- continue;
772
- const take = Math.min(can, left);
773
- shrinkForSplit.set(n, can - take);
774
- left -= take;
775
- moved.push({ from: n, armies: take });
776
- }
777
- stacks.push({ territoryId: id, growth, moved, fog: beside ? left : 0, deploy: beside ? 0 : left });
778
- }
779
- stacks.sort((a, b) => a.territoryId - b.territoryId);
780
- /**
781
- * #271 (3): its territories shown with armies on the earlier board and hidden on the later one: what
782
- * each could have sent (its armies less the guard), the most a capture beside it can have received
783
- * from it. Claimed after `shrinkLeft`, in ascending ids, each army once.
784
- * #271 review, a known under-read: a stack hidden now is claimed whether or not it emptied, and it is
785
- * usually hidden because the capture took my territory and my sight of it with it. So a real
786
- * deploy-then-capture beside a source in view both times and such a stack reads its surplus as an
787
- * arrival (counted only in `high`), not deploy. Accepted: a merge read as deploy once read +45.
788
- */
789
- const hiddenLeft = new Map();
790
- for (const t of previous.territories) {
791
- const b = visibleState(t);
792
- if (!g.territoryById.has(t.territoryId) || b?.owner.kind !== 'player' || b.owner.playerId !== playerId)
793
- continue;
794
- if (!visibleState(now.get(t.territoryId)))
795
- hiddenLeft.set(t.territoryId, Math.max(0, b.armies - guard));
796
- }
797
- let arrivals = 0;
798
- const unseenAttackers = [];
799
- let unseenAttackerArmies = 0;
800
- for (const t of [...board.territories].sort((a, b) => a.territoryId - b.territoryId)) {
801
- if (!g.territoryById.has(t.territoryId) || !visibleState(t))
802
- continue;
803
- if (t.owner.kind !== 'player' || t.owner.playerId !== playerId)
804
- continue;
805
- const was = visibleState(before.get(t.territoryId));
806
- if (!was) {
807
- reveals.push(t.territoryId);
808
- continue;
809
- }
810
- counted.push(t.territoryId);
811
- const ns = [...neighborsOf(g, t.territoryId)].sort((a, b) => a - b);
812
- if (was.owner.kind === 'player' && was.owner.playerId === playerId) {
813
- // #226: what my failed attack killed there stood there too: defenders after = before + deploy
814
- // + transfers in − kills.
815
- const growth = t.armies - was.armies + killsAt(t.territoryId);
816
- if (growth > 0 && ns.some(hidden))
817
- ambiguous.push({ id: t.territoryId, armies: growth, kind: 'growth' });
818
- else
819
- total += growth;
820
- }
821
- else {
822
- captured.push(t.territoryId);
823
- // What the capture cost it, always. Taken from me (#123), the defenders were what I left
824
- // there, which this board cannot tell (I may have attacked out of it): priced at the guard,
825
- // my stack last turn the high reading.
826
- if (context.me !== undefined && was.owner.kind === 'player' && was.owner.playerId === context.me) {
827
- const least = straightKills(Math.min(was.armies, guard), defensive);
828
- total += least;
829
- highExtra += straightKills(was.armies, defensive) - least;
830
- emptiedHigh += straightKills(was.armies, defensive) - least;
831
- emptied.push(t.territoryId);
832
- }
833
- else
834
- total += straightKills(was.armies, defensive);
835
- // The armies standing there only as far as a visible source's shrink accounts for them
836
- // (it cancels them). Beyond that, with a neighbour that was hidden on either board: when a
837
- // visible source did shrink into it, the attack came from that stack and the rest was
838
- // deployed on it first (deploy-then-capture, #123); when none did, the rest arrived from
839
- // the fog — a move, not income (#86). With no hidden neighbour, the rest can only be a
840
- // deploy on a visible source before it attacked.
841
- let arrived = t.armies;
842
- let claimed = 0;
843
- for (const n of ns) {
844
- const left = shrinkLeft.get(n);
845
- if (!left || !arrived)
846
- continue;
847
- const take = Math.min(left, arrived);
848
- shrinkLeft.set(n, left - take);
849
- arrived -= take;
850
- claimed += take;
851
- total += take;
852
- }
853
- // #271 (3): its stacks in view last turn beside it, hidden now, may have moved in: arrivals.
854
- let came = 0;
855
- for (const n of ns) {
856
- const left = hiddenLeft.get(n);
857
- if (!left || !arrived)
858
- continue;
859
- const take = Math.min(left, arrived);
860
- hiddenLeft.set(n, left - take);
861
- arrived -= take;
862
- came += take;
863
- }
864
- arrivals += came;
865
- // Had its source stayed put (hidden now, it may have), they were deployed: the high reading.
866
- highExtra += came;
867
- if (arrived > 0 && ns.some(hidden)) {
868
- // #271 (2): a neutral in view needed attackers; what stands there beyond what its stacks in
869
- // view sent, up to what that need leaves standing, came from out of sight.
870
- let unseen = 0;
871
- if (was.owner.kind === 'neutral') {
872
- const need = fewestAttackersToTake(was.armies, rates, rates.luckModifier, rates.roundingMode);
873
- const cost = straightKills(was.armies, defensive);
874
- unseen = need === null ? 0 : Math.min(arrived, Math.max(0, need - cost - claimed - came));
875
- if (unseen > 0) {
876
- unseenAttackers.push(t.territoryId);
877
- // The attackers out of sight: what the capture needed less what came from view
878
- // (need − claimed − came), within what stands there.
879
- unseenAttackerArmies += unseen + cost;
880
- }
881
- }
882
- if (claimed > 0)
883
- ambiguous.push({ id: t.territoryId, armies: arrived, kind: 'capture' });
884
- else {
885
- if (unseen > 0)
886
- ambiguous.push({ id: t.territoryId, armies: unseen, kind: 'needed' });
887
- const rest = arrived - unseen;
888
- if (rest > 0) {
889
- fromFog.push(t.territoryId);
890
- fogArmies += rest;
891
- highExtra += rest;
892
- }
893
- }
894
- }
895
- else
896
- total += arrived;
897
- }
898
- }
899
- // #123: the ambiguous armies, read as deploy up to one bound on the turn's deploy — the same
900
- // bound for growth beside the fog and a reinforced capture's surplus, shared in id order —
901
- // and the rest as moves out of the fog. The low reading takes all of them out, the high one
902
- // counts all of them.
903
- const grewFromFog = [];
904
- let fogGrowth = 0;
905
- const bound = ambiguousBound(context);
906
- // Without an expected deploy (a board-only reading), growth is all deploy, as before #123.
907
- if (bound === null)
908
- for (const x of ambiguous)
909
- if (x.kind === 'growth')
910
- total += x.armies;
911
- // A board-only reading (neither `expected` nor `most`) has no room at all: a negative total (a
912
- // stack of its own that shrank into the fog) must not make room for a capture's surplus.
913
- let room = bound === null && context.most === undefined ? 0 : Math.max(0, (bound ?? Math.max(0, context.most)) - total);
914
- // #293: under Local Deployment, the territories a bonus pool could have paid into on the turn read
915
- // (the bonuses it could hold on the earlier board); growth beside the fog elsewhere draws on `freeLeft`.
916
- const local = rates.localDeployments === true && bound !== null && context.localFree !== undefined;
917
- const pooledOn = new Set();
918
- if (local)
919
- for (const b of g.map.bonuses) {
920
- if (b.value <= 0)
921
- continue;
922
- const ts = bonusTerritories(g, b.id);
923
- const possible = ts.every((t) => {
924
- const o = ownerShown(before.get(t))?.owner;
925
- return o === undefined || (o.kind === 'player' && o.playerId === playerId);
926
- });
927
- if (possible)
928
- for (const t of ts)
929
- pooledOn.add(t);
930
- }
931
- let freeLeft = Math.max(0, context.localFree ?? 0);
932
- const localCut = [];
933
- // #293 review: a walled growth's walk draws on the shrink the captures left (`shrinkLeft`, after
934
- // the capture loop), less what the other grown stacks' splits took (their growth already nets it),
935
- // in ascending ids: one claim pass, so one neighbour's shrink never offsets a capture and a walk both.
936
- const walled = (x) => local && x.kind === 'growth' && !pooledOn.has(x.id);
937
- const walkLeft = new Map(shrinkLeft);
938
- if (local) {
939
- const walledIds = new Set(ambiguous.filter(walled).map((x) => x.id));
940
- for (const st of stacks)
941
- if (!walledIds.has(st.territoryId))
942
- for (const m of st.moved)
943
- walkLeft.set(m.from, Math.max(0, (walkLeft.get(m.from) ?? 0) - m.armies));
944
- }
945
- for (const x of [...ambiguous].sort((a, b) => a.id - b.id)) {
946
- if (bound === null && x.kind === 'growth') {
947
- lowExtra -= x.armies;
948
- continue;
949
- }
950
- // #293: a walk from a neighbour in view (the growth split) nets its shrink; the rest is deploy only
951
- // as far as the free income still reaches.
952
- const isWalled = walled(x);
953
- let walk = 0;
954
- if (isWalled)
955
- for (const n of [...neighborsOf(g, x.id)].sort(byNum)) {
956
- const can = walkLeft.get(n);
957
- if (!can || walk >= x.armies)
958
- continue;
959
- const take = Math.min(can, x.armies - walk);
960
- walkLeft.set(n, can - take);
961
- walk += take;
962
- }
963
- total += walk;
964
- room = Math.max(0, room - walk);
965
- const deployed = Math.min(x.armies - walk, room, isWalled ? freeLeft : Infinity);
966
- if (isWalled)
967
- freeLeft -= deployed;
968
- room -= deployed;
969
- total += deployed;
970
- lowExtra -= deployed;
971
- const moved = x.armies - walk - deployed;
972
- if (isWalled && moved > 0)
973
- localCut.push(x.id);
974
- highExtra += moved;
975
- if (x.kind === 'capture') {
976
- if (deployed > 0)
977
- reinforced.push(x.id);
978
- if (moved > 0)
979
- fromFog.push(x.id);
980
- }
981
- else if (x.kind === 'needed') {
982
- if (moved > 0 && !fromFog.includes(x.id))
983
- fromFog.push(x.id);
984
- }
985
- else if (moved > 0) {
986
- grewFromFog.push(x.id);
987
- fogGrowth += moved;
988
- }
989
- fogArmies += moved;
990
- }
991
- fromFog.sort((a, b) => a - b);
992
- // #271 (1): a failed attack on a hold of mine bounds its deploy from below, fog or not.
993
- const repelled = context.me !== undefined && context.myOrders
994
- ? repelledFloor(g, previous, board, context.me, playerId, context.myOrders, rates, guard, context.bomb === true)
995
- : { territories: [], floor: 0 };
996
- const floor = repelled.floor;
997
- return {
998
- stacks,
999
- deploy: Math.max(0, total, floor),
1000
- signed: total,
1001
- counted,
1002
- captured,
1003
- fromFog,
1004
- fogArmies,
1005
- reveals,
1006
- reinforced,
1007
- grewFromFog,
1008
- fogGrowth,
1009
- ...(localCut.length ? { localCut: { free: Math.max(0, context.localFree ?? 0), territories: localCut } } : {}),
1010
- expected: context.expected ?? null,
1011
- attacked: [...kills.keys()].sort(byNum),
1012
- attackKills: [...kills.values()].reduce((n, k) => n + k, 0),
1013
- emptied,
1014
- emptiedHigh,
1015
- arrivals,
1016
- unseenAttackers,
1017
- unseenAttackerArmies,
1018
- repelled: repelled.territories,
1019
- repelledFloor: floor,
1020
- low: Math.max(0, total + lowExtra, floor),
1021
- high: Math.max(0, total + highExtra, floor),
1022
- };
1023
- }
1024
- /**
1025
- * How much more than it was expected to deploy an opponent may earn unseen (#123 review): under
1026
- * fog the visible income reads 2–3× low (#119), so ambiguous armies count as deploy up to twice
1027
- * the expected figure. A one-off stack out of the fog is not read as a phantom income; a steady
1028
- * hidden bonus (as large as the visible income) still is, and the tracker, which raises the
1029
- * expected figure to its carried income, learns a larger one over a few turns.
1030
- */
1031
- export const HIDDEN_INCOME_FACTOR = 2;
1032
- /**
1033
- * The most an opponent's deploy may total once ambiguous armies are counted (#123): twice what
1034
- * it was expected to deploy ({@link HIDDEN_INCOME_FACTOR}), never more than it could earn
1035
- * (`most`). Null without an expected figure: then growth is all deploy and a capture's surplus
1036
- * counts up to `most` (none without it, #86).
1037
- */
1038
- function ambiguousBound(context) {
1039
- if (context.expected === undefined)
1040
- return null;
1041
- const twice = HIDDEN_INCOME_FACTOR * Math.max(0, context.expected);
1042
- return context.most !== undefined ? Math.min(Math.max(0, context.most), twice) : twice;
1043
- }
1044
- /** {@link observeDeploy}'s deploy figure alone. */
1045
- export function observedDeploy(g, board, previous, playerId, rates = {}) {
1046
- return observeDeploy(g, board, previous, playerId, rates).deploy;
1047
- }
1048
- /**
1049
- * The army count every visible player territory holds, when they all hold the same one (the
1050
- * initial allotment). Neutrals are left out (#128): their stacks are not the starting stacks on
1051
- * ordinary maps, so counting them meant this never fired. Only the first turn can be the opening
1052
- * board (#128): with a previous board, or a known turn past the first, equal stacks are a
1053
- * coincidence of the mid-game, and reading them as the opening would drop visible bonuses.
1054
- */
1055
- export function openingArmies(g, board, when = {}) {
1056
- if (when.previous !== undefined || (when.turn !== null && when.turn !== undefined && when.turn > 1))
1057
- return null;
1058
- const counts = new Set();
1059
- for (const t of board.territories)
1060
- if (g.territoryById.has(t.territoryId) && t.armies !== null && t.owner.kind === 'player')
1061
- counts.add(t.armies);
1062
- return counts.size === 1 ? [...counts][0] : null;
1063
- }
1064
- /**
1065
- * #368: an opponent's tracked figure as of each of its last three consecutive observed turns — the most
1066
- * it was seen to earn (`earned`) over that turn and the two before it, the tracker's max-observed window —
1067
- * when it rose on both steps; else `null` (fewer than three consecutive turns, or a step not a rise).
1068
- */
1069
- export function risingTracked(turns) {
1070
- const n = turns.length;
1071
- if (n < 3)
1072
- return null;
1073
- for (let i = n - 2; i < n; i++)
1074
- if (turns[i].from !== turns[i - 1].from + 1)
1075
- return null;
1076
- const asOf = (i) => Math.max(...turns.slice(Math.max(0, i - 2), i + 1).map((x) => x.earned));
1077
- const series = [asOf(n - 3), asOf(n - 2), asOf(n - 1)];
1078
- return series[0] < series[1] && series[1] < series[2] ? series : null;
1079
- }
1080
- /**
1081
- * Per-opponent enemy deploy estimates, one per visible enemy player (sorted by
1082
- * id): base income plus the bonuses that player visibly holds in full, never
1083
- * below max({@link MIN_ENEMY_DEPLOY}, base income). Its stack next to me does not
1084
- * limit it — income held in plain view can all be deployed on my border, however
1085
- * small the stack there. Bonuses in the fog are unseen, so this is what the
1086
- * visible board supports. On the opening board (every visible player territory holds
1087
- * the same count, with no previous board and `when.turn` unknown or the first) every
1088
- * opponent gets the floor.
1089
- */
1090
- export function enemyDeployEstimates(g, board, me, settings = {}, previous, tracks, prior, when = {}) {
1091
- const owner = new Map();
1092
- const armies = new Map();
1093
- const seenNow = new Map();
1094
- for (const t of board.territories)
1095
- if (g.territoryById.has(t.territoryId))
1096
- seenNow.set(t.territoryId, t);
1097
- // Owners count whatever the armies: an owner-only territory (light fog) is visibly held, so
1098
- // it counts toward base income and the bonuses held in full. Only stacks need the armies.
1099
- for (const t of board.territories) {
1100
- if (!g.territoryById.has(t.territoryId) || t.owner.kind !== 'player')
1101
- continue;
1102
- owner.set(t.territoryId, t.owner.playerId);
1103
- if (t.armies !== null)
1104
- armies.set(t.territoryId, t.armies);
1105
- }
1106
- const players = [...new Set([...owner.values()].filter((p) => p !== me))].sort(byNum);
1107
- const opening = openingArmies(g, board, { turn: when.turn, previous }) !== null;
1108
- // #164: under No, Light and Dense fog every owner shows, so income is exact — when this board
1109
- // shows every territory's owner too (the setting is a name, never compared by position).
1110
- const ownersAll = when.fog !== undefined &&
1111
- OWNERS_SHOWN_FOG.has(when.fog) &&
1112
- g.map.territories.every((t) => ownerShown(seenNow.get(t.id)) !== undefined);
1113
- const minimum = Math.max(0, Math.floor(settings.baseIncome ?? DEFAULT_BASE_INCOME));
1114
- const per = settings.bonusArmyPer ?? 0;
1115
- return players.map((playerId) => {
1116
- // Its visible territories are a lower bound on what it holds, so on its
1117
- // per-territory income too.
1118
- const theirs = new Set();
1119
- for (const [t, p] of owner)
1120
- if (p === playerId)
1121
- theirs.add(t);
1122
- const held = theirs.size;
1123
- const base = territoryIncome(held, minimum, per);
1124
- // The one income rule (#85) over what it visibly holds; `bonusIncome` is what it adds to the base.
1125
- const bonusIncome = boardIncome(g, theirs, { base: minimum, per }).total - base;
1126
- let adjacent = 0;
1127
- let any = 0;
1128
- for (const [t, p] of owner) {
1129
- if (p !== playerId)
1130
- continue;
1131
- const a = armies.get(t);
1132
- if (a === undefined)
1133
- continue;
1134
- any = Math.max(any, a);
1135
- if (neighborsOf(g, t).some((n) => owner.get(n) === me))
1136
- adjacent = Math.max(adjacent, a);
1137
- }
1138
- const largestStack = adjacent || any;
1139
- // Every opponent earns at least the game's base income (never below the 5 minimum), and
1140
- // never less than the bonuses it visibly holds: its stack next to me limits neither.
1141
- const floor = Math.max(MIN_ENEMY_DEPLOY, base);
1142
- const visible = opening ? floor : Math.max(floor, base + bonusIncome);
1143
- // What it was seen to deploy is cut only by what it could earn
1144
- // (#69): its base plus every bonus none of whose territories someone else visibly holds
1145
- // (an owner-only territory is visibly held: its owner shows). Both come from this board,
1146
- // so a bonus it lost since last turn is out, though it may have paid for that deploy.
1147
- let possible = 0;
1148
- /** #235: of `possible`, the bonuses it visibly holds in full (no share of them goes to another). */
1149
- let possibleOwn = 0;
1150
- for (const b of g.map.bonuses) {
1151
- const ts = bonusTerritories(g, b.id);
1152
- if (b.value <= 0 || !ts.length)
1153
- continue;
1154
- const taken = ts.some((t) => {
1155
- const st = ownerShown(seenNow.get(t));
1156
- return st !== undefined && !(st.owner.kind === 'player' && st.owner.playerId === playerId);
1157
- });
1158
- if (!taken)
1159
- possible += b.value;
1160
- if (!taken && ts.every((t) => theirs.has(t)))
1161
- possibleOwn += b.value;
1162
- }
1163
- // #226: with per-territory income, the territories it could hold pay at the rate: its visible
1164
- // ones and every one whose owner this board hides (it may hold any of them).
1165
- const couldHold = per > 0
1166
- ? g.map.territories.filter((t) => {
1167
- const st = ownerShown(seenNow.get(t.id));
1168
- return st === undefined || (st.owner.kind === 'player' && st.owner.playerId === playerId) || theirs.has(t.id);
1169
- }).length
1170
- : held;
1171
- const couldEarn = territoryIncome(couldHold, minimum, per) + possible;
1172
- // #119: the fog prior. In a symmetric-start 1v1 an opponent bordering the fog earns at least
1173
- // what I earn, capped at what it could earn on this board. It only ever raises the figure.
1174
- const fogBeside = [...theirs].some((t) => neighborsOf(g, t).some((n) => !ownerShown(seenNow.get(n))));
1175
- // #166: with its starts proven, its opening simulated from them raises the prior when it earns
1176
- // more than I do; never lowers it (the simulation is a simple player, and #119's evidence read low).
1177
- const priorBase = Math.max(prior?.myIncome ?? 0, prior?.opening?.get(playerId) ?? 0);
1178
- // #235: in a free-for-all the hidden part of the board is shared: an even share of the hidden
1179
- // territories and of the bonuses it could still hold (its own in full), never above couldEarn.
1180
- const k = prior?.format === 'ffa' && (prior.opponents ?? 0) > 1 ? prior.opponents : 0;
1181
- const priorCap = prior && k > 0
1182
- ? Math.min(couldEarn, territoryIncome(held + Math.ceil((couldHold - held) / k), minimum, per) + possibleOwn + Math.ceil((possible - possibleOwn) / k))
1183
- : null;
1184
- const priorFigure = prior && fogBeside ? Math.min(Math.max(0, Math.floor(priorBase)), priorCap ?? couldEarn) : null;
1185
- // A track over enough turns replaces the single-turn observed figure (S3).
1186
- const track = tracks?.find((t) => t.playerId === playerId);
1187
- const usable = track && track.income !== null && track.turns.length >= TRACKED_MIN_TURNS ? track : undefined;
1188
- const tracked = usable ? usable.income : null;
1189
- // #235 review: does the track end on this board? Its newest observed turn then ends at the turn
1190
- // being planned (the newest board's turn, when that is not given: tracks end on `board`).
1191
- const newestTurn = when.turn ?? usable?.lastTurn ?? null;
1192
- const newest = usable?.turns.at(-1);
1193
- const trackEndsNow = newest !== undefined && newest.to === newestTurn;
1194
- // #123: what it was expected to deploy before this observation (its visible income, and its
1195
- // tracked income when it has a usable track, else the prior): ambiguous armies beyond twice that
1196
- // are moves out of the fog ({@link ambiguousBound}); a capture from me is priced at the guard.
1197
- // With a track the prior stays out of the bound, and the reading is no part of the estimate
1198
- // (#235 1c): the track replaces it. A track that ends on this board has read the newest turn
1199
- // already, so the turn is read with that track's own bound (`ObservedTurn.expected`), and the
1200
- // rationale's observed line agrees with the tracker and with the label below.
1201
- const trackBound = trackEndsNow ? newest.expected : undefined;
1202
- const observation = previous
1203
- ? observeDeploy(g, board, previous, playerId, settings, {
1204
- me,
1205
- guard: (settings.oneArmyStandsGuard ?? true) ? 1 : 0,
1206
- expected: Math.max(visible, trackBound ?? tracked ?? priorFigure ?? 0),
1207
- most: couldEarn,
1208
- // #293: under Local Deployment, growth beside the fog outside every bonus it could hold is
1209
- // deploy only up to its free income.
1210
- ...(settings.localDeployments
1211
- ? { localFree: localFreeOn(base, MIN_ENEMY_DEPLOY, when.reinforcement ?? settings.opponentReinforcement, when.turn == null ? null : when.turn - 1) }
1212
- : {}),
1213
- ...(when.previousOrders ? { myOrders: when.previousOrders } : {}),
1214
- // #271 review: the turn read is the one before the turn planned.
1215
- ...(bombPossibleOn(settings, when.turn == null ? null : when.turn - 1) ? { bomb: true } : {}),
1216
- })
1217
- : null;
1218
- // #235 1c: the track's newest turn, when it ends on this board and its bound cut armies that
1219
- // arrived beside the fog (or joined a capture): what that turn reads with them all as deploys.
1220
- // A label only: a stack walking in is not income (#123 lesson 5), so the estimate stays.
1221
- const newestCut = trackEndsNow && newest.high > newest.raw && (newest.grewFromFog.length > 0 || newest.reinforced.length > 0)
1222
- ? {
1223
- from: newest.from,
1224
- to: newest.to,
1225
- observed: newest.observed,
1226
- reading: Math.min(newest.high, newest.cap),
1227
- expected: newest.expected ?? null,
1228
- }
1229
- : null;
1230
- const observedCap = observation ? couldEarn : null;
1231
- const observedRaw = observation?.deploy ?? null;
1232
- const observed = observation ? Math.min(observation.deploy, observedCap) : null;
1233
- // A usable track replaces the single-turn observed figure (S3; #235 1c: its newest reading too).
1234
- const seenSource = tracked !== null
1235
- ? tracked > visible
1236
- ? 'tracked'
1237
- : 'visible'
1238
- : observed !== null && observed > visible
1239
- ? 'observed'
1240
- : 'visible';
1241
- const seen = seenSource === 'tracked' ? tracked : seenSource === 'observed' ? observed : visible;
1242
- // #235: the prior shrinks toward that evidence: the more consecutive observed turns, and the more
1243
- // of its edge in view, the less of its lead it keeps.
1244
- let priorBlend = null;
1245
- if (priorFigure !== null && usable) {
1246
- const toward = Math.max(tracked, visible);
1247
- if (priorFigure > toward) {
1248
- // The consecutive observed turns up to the newest board; a run that stopped earlier is none.
1249
- let turns = trackEndsNow ? 1 : 0;
1250
- const run = usable.turns;
1251
- for (let i = run.length - 1; turns > 0 && i > 0 && run[i - 1].from === run[i].from - 1; i--)
1252
- turns++;
1253
- const edge = new Set();
1254
- for (const t of theirs)
1255
- for (const n of neighborsOf(g, t))
1256
- if (!theirs.has(n))
1257
- edge.add(n);
1258
- const edgeShare = edge.size ? [...edge].filter((n) => ownerShown(seenNow.get(n)) !== undefined).length / edge.size : 0;
1259
- // #294: each turn of the run weighs what it read of its frontier (this board's edge for a turn
1260
- // that carries no coverage).
1261
- const evidence = run.slice(run.length - turns).reduce((n, x) => n + (x.coverage?.share ?? edgeShare), 0);
1262
- const share = turns ? evidence / turns : edgeShare;
1263
- const weight = PRIOR_EVIDENCE_TURNS / (PRIOR_EVIDENCE_TURNS + evidence);
1264
- const figure = toward + Math.ceil(weight * (priorFigure - toward) - 1e-9);
1265
- priorBlend = { prior: priorFigure, toward, turns, share, weight, figure };
1266
- }
1267
- }
1268
- const priorUsed = priorBlend ? priorBlend.figure : priorFigure;
1269
- // #164: with every owner shown, its income is base + held bonuses exactly; a deploy above it was
1270
- // a card (or armies the board misread), never income.
1271
- const exact = ownersAll && !opening ? Math.max(0, base + bonusIncome) : null;
1272
- const source = exact !== null ? 'exact' : priorUsed !== null && priorUsed > seen ? 'prior' : seenSource;
1273
- // #294: what its tracked figure was read from (#368: while that is little, thin evidence below).
1274
- const coverage = usable ? trackCoverage(usable.turns.filter((x) => usable.incomeTurns.includes(x.from))) : null;
1275
- const chosen = source === 'exact' ? exact : source === 'prior' ? priorUsed : seen;
1276
- // #368 (owner decision of 2026-11-19: on a hidden opponent, choose the middle until we learn
1277
- // otherwise): thin evidence — its tracked figure read from under LOW_COVERAGE of its frontier —
1278
- // sizes it for the midpoint between the lower bound (what is in view or tracked, raised to the
1279
- // trend's next step when its tracked figure rose two turns running) and the upper bound (the fog
1280
- // prior whole, else the most it could earn), moved toward what the evidence gives as the coverage
1281
- // nears LOW_COVERAGE. A rising track read from more of its frontier only raises the estimate to that
1282
- // lower bound. Never the maximum.
1283
- let thinEvidence = null;
1284
- if (source !== 'exact' && usable && tracked !== null) {
1285
- const rising = risingTracked(usable.turns);
1286
- const thinCoverage = coverage !== null && coverage.share < LOW_COVERAGE;
1287
- if (thinCoverage || rising) {
1288
- const trend = rising ? Math.min(couldEarn, rising[2] + Math.ceil((rising[2] - rising[0]) / 2 - 1e-9)) : null;
1289
- const lower = Math.min(couldEarn, Math.max(visible, tracked, trend ?? 0));
1290
- const upper = Math.max(lower, Math.min(couldEarn, priorFigure ?? couldEarn));
1291
- const midpoint = lower + Math.ceil((upper - lower) / 2 - 1e-9);
1292
- // What the evidence gives without thin evidence (the track, or #235's prior shrunk toward it),
1293
- // never below the lower bound: the figure meets it at LOW_COVERAGE, so it does not jump there.
1294
- const toward = Math.min(couldEarn, Math.max(lower, chosen));
1295
- const weight = thinCoverage ? Math.max(0, 1 - coverage.share / LOW_COVERAGE) : 0;
1296
- const figure = toward + Math.ceil(weight * (midpoint - toward) - 1e-9);
1297
- // Thin coverage: the figure replaces the estimate, up or down. A rising track alone: a raise only.
1298
- if (thinCoverage || figure > chosen)
1299
- thinEvidence = { coverage: coverage ? coverage.share : null, rising, tracked, prior: priorFigure, trend, lower, upper, midpoint, toward, weight, figure };
1300
- }
1301
- }
1302
- const income = thinEvidence ? thinEvidence.figure : chosen;
1303
- // #368: the figure thin evidence chose names its source: the prior when there is one and the figure
1304
- // lies above the lower bound, else the track.
1305
- const finalSource = thinEvidence
1306
- ? thinEvidence.prior !== null && thinEvidence.figure > thinEvidence.lower
1307
- ? 'prior'
1308
- : 'tracked'
1309
- : source;
1310
- // #164: a Reinforcement card, from the turn the clock says one can be in hand, until a deployment
1311
- // above its income is seen; the next card is due a card's capturing turns after the last one
1312
- // (pieces carry over while a card is held), never before the turn after the play.
1313
- // A play is seen as a deploy (its low reading) above the income that turn: exactly, when every
1314
- // owner shows; under fog only a jump of the card's armies over its visible income counts (a
1315
- // smaller excess may be a bonus the fog hides — and the tracked income then carries the jump).
1316
- const played = [];
1317
- if (when.reinforcement) {
1318
- const above = (low, income) => (exact !== null ? low > income : low >= income + when.reinforcement.armies);
1319
- for (const x of track?.turns ?? [])
1320
- if (above(x.low, x.visibleIncome))
1321
- played.push(x.from);
1322
- // Last turn's deploy was paid by last turn's income: what it held on the previous board (a
1323
- // bonus it lost since paid for it), never below this board's figure.
1324
- if (observation && previous && when.turn !== null && when.turn !== undefined) {
1325
- const before = new Set();
1326
- for (const t of previous.territories)
1327
- if (g.territoryById.has(t.territoryId) && t.owner.kind === 'player' && t.owner.playerId === playerId)
1328
- before.add(t.territoryId);
1329
- const paid = boardIncome(g, before, { base: minimum, per }).total;
1330
- if (above(observation.low, Math.max(exact ?? visible, paid)))
1331
- played.push(when.turn - 1);
1332
- }
1333
- }
1334
- let card = null;
1335
- let cardPlayed = null;
1336
- if (when.reinforcement && when.turn !== null && when.turn !== undefined) {
1337
- const r = when.reinforcement;
1338
- let due = r.firstTurn;
1339
- let cards = 0;
1340
- for (const t of [...new Set(played)].sort(byNum)) {
1341
- if (t < due || t >= when.turn)
1342
- continue;
1343
- cards++;
1344
- cardPlayed = t;
1345
- due = r.turnsPerCard === null ? Infinity : Math.max(t + 1, r.firstTurn + cards * Math.max(1, r.turnsPerCard));
1346
- }
1347
- if (when.turn >= due && r.armies > 0)
1348
- card = { armies: r.armies, due };
1349
- }
1350
- const estimate = income + (card?.armies ?? 0);
1351
- return {
1352
- playerId,
1353
- estimate,
1354
- held,
1355
- base,
1356
- bonusIncome,
1357
- largestStack,
1358
- opening,
1359
- observed,
1360
- observedRaw,
1361
- observedCap,
1362
- couldEarn,
1363
- couldHold,
1364
- observation,
1365
- tracked,
1366
- newestCut,
1367
- trackedTurns: usable ? usable.incomeTurns : [],
1368
- prior: priorFigure,
1369
- priorBlend,
1370
- coverage,
1371
- priorCap,
1372
- fogBeside,
1373
- source: finalSource,
1374
- thinEvidence,
1375
- exact,
1376
- card,
1377
- cardPlayed,
1378
- };
1379
- });
1380
- }
1381
- /**
1382
- * Default enemy deploy: the largest {@link enemyDeployEstimates} figure among the
1383
- * players with a stack next to me — visible, or its owner shown and its armies hidden (#164) —
1384
- * at least {@link MIN_ENEMY_DEPLOY}. Pass the turn, fog setting and Reinforcement clock (`when`)
1385
- * and the fog prior {@link planEnemyEstimates} uses, or a mid-game board of equal stacks reads as
1386
- * the opening board (#128), an opponent's card is left out (#164), and the figure disagrees with
1387
- * the planner's. Unlike the planner's, it does not know the teams: a teammate counts.
1388
- */
1389
- export function defaultEnemyDeploy(g, board, me, settings = {}, previous, tracks, prior, when = {}) {
1390
- const mineIds = new Set(board.territories.flatMap((t) => (t.owner.kind === 'player' && t.owner.playerId === me ? [t.territoryId] : [])));
1391
- const next = new Set();
1392
- for (const t of board.territories) {
1393
- if (t.owner.kind !== 'player' || t.owner.playerId === me)
1394
- continue;
1395
- if (t.armies === null && (ownerShown(t) === undefined || visibleState(t)))
1396
- continue;
1397
- if (!g.territoryById.has(t.territoryId))
1398
- continue;
1399
- if (neighborsOf(g, t.territoryId).some((n) => mineIds.has(n)))
1400
- next.add(t.owner.playerId);
1401
- }
1402
- return enemyDeployEstimates(g, board, me, settings, previous, tracks, prior, when).reduce((m, e) => (next.has(e.playerId) ? Math.max(m, e.estimate) : m), MIN_ENEMY_DEPLOY);
1403
- }
1404
- /**
1405
- * This turn's income on the board, cards aside: {@link boardIncome} over the territories `me`
1406
- * holds, cut by the game's army cap (#253, {@link armyCapIncome}: min(income, round(cap × income)
1407
- * − my armies on the board)). warapp_plan_turn and warapp_submit_turn both use it (plus the armies
1408
- * of the card plays in their orders, which the cap leaves alone), so the plan's deploy total is the
1409
- * total the submit check requires.
1410
- */
1411
- export function incomeFor(g, board, me, settings) {
1412
- return incomeDetail(g, board, me, settings).income;
1413
- }
1414
- /**
1415
- * Another player's income from what the board shows, before any army cap: base, bonuses and cities
1416
- * over the territories it visibly holds. The cap is not applied (#253): its fogged armies are
1417
- * unknown, so a cut from its visible armies alone would depend on the fog. My own income is
1418
- * {@link incomeFor}.
1419
- */
1420
- export function visibleIncomeFor(g, board, player, settings) {
1421
- const held = new Set();
1422
- let cities = 0;
1423
- for (const t of board.territories)
1424
- if (g.territoryById.has(t.territoryId) && t.owner.kind === 'player' && t.owner.playerId === player) {
1425
- held.add(t.territoryId);
1426
- cities += t.cities ?? 0;
1427
- }
1428
- return boardIncome(g, held, incomeRules(settings)).total + cityGold(cities, settings);
1429
- }
1430
- /**
1431
- * #332: the gold a commerce game's cities pay each turn (CityIncome each), part of the income like a bonus (the client's
1432
- * income function adds it after base and bonuses, before the army cap). 0 outside a commerce game with city income.
1433
- */
1434
- export function cityGold(cities, settings) {
1435
- const per = commerceRules(settings)?.cityIncome ?? 0;
1436
- return cities > 0 && per > 0 ? cities * per : 0;
1437
- }
1438
- /**
1439
- * {@link incomeFor} with the army cap's arithmetic: `cap` when the game has one and every territory
1440
- * of mine shows its armies (my own always should); `capUnknown` when one does not, and the income is
1441
- * then left uncut. The cap reads my armies from the start-of-turn standing as war.app showed it:
1442
- * callers may pass a board with the award or a prior merged in (livePlanSetup's `board`), which must
1443
- * never change my own territories' armies — a merge that did would move the cap's cut.
1444
- */
1445
- export function incomeDetail(g, board, me, settings) {
1446
- const held = new Set();
1447
- let armies = 0;
1448
- let unread = false;
1449
- let cities = 0;
1450
- for (const t of board.territories) {
1451
- if (!g.territoryById.has(t.territoryId) || t.owner.kind !== 'player' || t.owner.playerId !== me)
1452
- continue;
1453
- held.add(t.territoryId);
1454
- cities += t.cities ?? 0;
1455
- if (t.armies === null)
1456
- unread = true;
1457
- else
1458
- armies += t.armies;
1459
- }
1460
- const income = boardIncome(g, held, incomeRules(settings)).total + cityGold(cities, settings);
1461
- if (settings?.armyCap === undefined || settings.armyCap === null || !(settings.armyCap > 0))
1462
- return { income };
1463
- if (unread)
1464
- return { income, capUnknown: true };
1465
- const cap = armyCapIncome(income, settings.armyCap, armies);
1466
- return { income: cap.received, cap };
281
+ /** #419: the income a pace stands for, given my income. */
282
+ export function fogPaceIncome(p, myIncome) {
283
+ return p.basis === 'map' ? Math.max(0, Math.floor(p.income ?? 0)) : Math.ceil(Math.max(0, myIncome) * (p.ratio ?? 0) - 1e-9);
1467
284
  }
285
+ export * from './deploy-estimates.js';