@chrischall/warapp-mcp 0.19.0 → 0.21.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.
@@ -381,15 +381,22 @@ export function frontierCosts(pc, threats, hd, prev) {
381
381
  * held; facing an enemy when a visible enemy is next to it, and then `need` is the deploys it
382
382
  * needs next turn to hold (the R3 arithmetic: threat = movable + max(deploy, growth) per player).
383
383
  */
384
+ // #603: the opponent's one floating deploy counts once, at the border it adds most to, not on every border.
385
+ const deployOnce = pc.opts.experiments?.includes('legacy-frontier') !== true;
384
386
  const borderOf = (x, held, have) => {
385
387
  if (neighborsOf(g, x).every((n) => held.has(n)))
386
- return { border: false, enemy: false, need: 0 };
388
+ return { border: false, enemy: false, need: 0, needStack: 0, player: -1 };
387
389
  // G2: next turn's threat — a player a Diplomacy card shields me from only this turn counts.
388
390
  const th = nextTurnAt(x, (n) => held.has(n));
389
391
  if (!th)
390
- return { border: true, enemy: false, need: 0 };
392
+ return { border: true, enemy: false, need: 0, needStack: 0, player: -1 };
391
393
  const units = mineSet.has(x) ? unitsAt(x) : 0;
392
- return { border: true, enemy: true, need: Math.max(0, holdArmies(th.threat) - have - units) };
394
+ const need = Math.max(0, holdArmies(th.threat) - have - units);
395
+ if (!deployOnce)
396
+ return { border: true, enemy: true, need, needStack: need, player: th.player };
397
+ const st = nextTurnAt(x, (n) => held.has(n), 0);
398
+ const needStack = st ? Math.min(need, Math.max(0, holdArmies(st.threat) - have - units)) : 0;
399
+ return { border: true, enemy: true, need, needStack, player: th.player };
393
400
  };
394
401
  /**
395
402
  * A border's cost in armies: {@link NEUTRAL_BORDER_COST}, plus its hold need when it faces an
@@ -456,13 +463,20 @@ export function frontierCosts(pc, threats, hd, prev) {
456
463
  let borders = 0;
457
464
  let enemyBorders = 0;
458
465
  let holdCost = 0;
466
+ /** deploy-once: per opponent, the most its one floating deploy adds to any one border's need. */
467
+ const floating = new Map();
459
468
  for (const x of [...held].sort(byNum)) {
460
469
  const b = borderOf(x, held, haveOf(x));
461
470
  borders += Number(b.border);
462
471
  enemyBorders += Number(b.enemy);
463
- if (!conceded.has(x) || stood.has(x))
464
- holdCost += b.need;
472
+ if (!conceded.has(x) || stood.has(x)) {
473
+ holdCost += b.needStack;
474
+ if (b.need > b.needStack)
475
+ floating.set(b.player, Math.max(floating.get(b.player) ?? 0, b.need - b.needStack));
476
+ }
465
477
  }
478
+ for (const v of floating.values())
479
+ holdCost += v;
466
480
  return { borders, enemyBorders, holdCost };
467
481
  };
468
482
  /**
@@ -508,16 +522,6 @@ export function bonusScoring(pc, ps, threats, prev) {
508
522
  const wasteShare = s.wastelands && s.wastelands.count > 0 && s.wastelands.size > 0 && g.territoryById.size > 0
509
523
  ? Math.min(1, s.wastelands.count / g.territoryById.size)
510
524
  : 0;
511
- /**
512
- * #432: a visible neutral at the game's wasteland size or more, when the game has wastelands larger than its
513
- * ordinary neutrals (`neutralArmies`, when the settings give it).
514
- */
515
- const isWasteland = (st) => s.wastelands !== undefined &&
516
- s.wastelands.count > 0 &&
517
- s.wastelands.size > (s.neutralArmies ?? 0) &&
518
- st.owner.kind === 'neutral' &&
519
- st.armies !== null &&
520
- st.armies >= s.wastelands.size;
521
525
  const wasteCost = wasteShare > 0 ? (costOf(s.wastelands.size) ?? Infinity) : 0;
522
526
  const wasteLoss = wasteShare > 0 ? Math.min(wasteCost - 1, straightKills(s.wastelands.size, rates.defensiveKillRate)) + 1 : 0;
523
527
  /** Every positive bonus worth completing (net > 0) still missing members: its armies to finish (rule 4e). */
@@ -624,8 +628,6 @@ export function bonusScoring(pc, ps, threats, prev) {
624
628
  // #125: the economy test charges the armies lost, not the armies sent.
625
629
  let loss = 0;
626
630
  let worstLoss = 0;
627
- /** #432: its missing members in view that are wastelands. */
628
- const wastelands = [];
629
631
  const known = (t, armies) => {
630
632
  const c = costAt(t, armies) ?? Infinity;
631
633
  cost += c;
@@ -674,8 +676,6 @@ export function bonusScoring(pc, ps, threats, prev) {
674
676
  const c = costAt(t) ?? Infinity;
675
677
  cost += c;
676
678
  worst = Math.max(worst, c);
677
- if (isWasteland(st))
678
- wastelands.push(t);
679
679
  const l = econCostAt(t);
680
680
  loss += l;
681
681
  worstLoss = Math.max(worstLoss, l);
@@ -716,10 +716,7 @@ export function bonusScoring(pc, ps, threats, prev) {
716
716
  cost += fogged * fogEach + foggedNeutral * neutralEach;
717
717
  loss += fogged * fogLoss + foggedNeutral * neutralEachLoss;
718
718
  const fogNeutral = foggedNeutral ? { count: foggedNeutral, each: neutralEach, size: neutralSize } : undefined;
719
- // #432: while the gate budget is short, no bonus is built through a wasteland: its armies go to the gates —
720
- // unless this turn's captures can complete it (owner decision 2026-11-22: a completing wasteland is taken).
721
- const wasteStop = !isFocus && pc.shortGates !== undefined && wastelands.length > 0 && !remaining.every(bonusTarget);
722
- const economic = isFocus || (loss <= paybackTurns * net && worstLoss <= WASTELAND_FACTOR * net && !wasteStop);
719
+ const economic = isFocus || (loss <= paybackTurns * net && worstLoss <= WASTELAND_FACTOR * net);
723
720
  // #435: a shared bonus I am nearer to but that is not worth working stays as C3.3 left it — skipped
724
721
  // with its members plain expansion, never marked uneconomic (45701358 turn 1: a 344-member super-bonus,
725
722
  // 6 members to my teammate's 5, would otherwise have stopped expansion into all its members).
@@ -734,10 +731,6 @@ export function bonusScoring(pc, ps, threats, prev) {
734
731
  (economic ? economicMember : uneconomicMember).add(t);
735
732
  if (!remaining.some(bonusTarget))
736
733
  continue;
737
- if (!economic && wasteStop && loss <= paybackTurns * net && worstLoss <= WASTELAND_FACTOR * net) {
738
- rationale.push(`Skip bonus ${b.name} (#${b.id}): finishing it means taking the wasteland${wastelands.length === 1 ? '' : 's'} ${wastelands.map(label).join(', ')} (${s.wastelands.size} armies or more) while the gates facing player ${pc.shortGates.player} are ${pc.shortGates.deficit} short (#432).`);
739
- continue;
740
- }
741
734
  if (!economic) {
742
735
  rationale.push(`Skip bonus ${b.name} (#${b.id}): uneconomic for +${net === b.value ? b.value : `${b.value} (net +${net})`} (${toFinish(cost, { fogged, fogEach, fogNeutral })}, losing ~${loss}; ${worstLoss} lost on its costliest territory).`);
743
736
  continue;
@@ -531,7 +531,8 @@ export function threatForces(pc, ps, src, valueOf) {
531
531
  * #420 (owner decision of 2026-11-20, "One opponent's deploy"): an opponent deploys its income in one
532
532
  * place, so its full deploy sizes only its single most valuable border of mine (by protected value —
533
533
  * `valueOf` —, then its movable armies beside it, then id); each other border of mine its stacks face is
534
- * sized at those stacks plus its largest top-up seen (`topUpOf`), never above the full deploy. `capAt`:
534
+ * sized at those stacks alone (#603: the self-play arena; before it, those stacks plus its largest top-up seen,
535
+ * which kept every border sized for nearly the whole deploy once the opponent had once dumped it on one). `capAt`:
535
536
  * by my territory, the players capped there and the figure; `primary`: each such player's full border.
536
537
  * Not on my commander's territory (rule 1k's worst case), nor for an untrusted estimate (#275) at that
537
538
  * border, a player with no top-up seen, or one facing a single border of mine. A quiet neighbour
@@ -564,7 +565,10 @@ export function threatForces(pc, ps, src, valueOf) {
564
565
  if (pc.myCommanders.has(t) || untrustedAt(player, t) > 0)
565
566
  continue;
566
567
  const m = oneBorderMemo.capAt.get(t) ?? new Map();
567
- m.set(player, src.topUpOf.get(player));
568
+ // #603: the deploy floats once — a border other than the most valuable one holds against the stacks beside
569
+ // it alone (a quiet neighbour, #420's P1 amendment, keeps its largest top-up seen on every border).
570
+ const legacy = pc.opts.experiments?.includes('legacy-topup') === true;
571
+ m.set(player, quiet || legacy ? src.topUpOf.get(player) : 0);
568
572
  oneBorderMemo.capAt.set(t, m);
569
573
  }
570
574
  }
@@ -601,9 +605,10 @@ export function threatForces(pc, ps, src, valueOf) {
601
605
  const full = truced === player
602
606
  ? 0
603
607
  : deployReaching(player, [...p.stacks.map((x) => x.id), ...(p.behind ?? [])], Math.max(pc.deployOf(player), untrustedAt(player, t)));
604
- // #420: off its most valuable border, the stack plus its largest top-up seen.
608
+ // #420/#603: off its most valuable border, the stack alone (a quiet neighbour: plus its largest top-up seen).
605
609
  const cap = oneBorder().capAt.get(t)?.get(player);
606
- const deploy = cap !== undefined ? Math.min(full, cap) : full;
610
+ const capped = cap !== undefined ? Math.min(full, cap) : full;
611
+ const deploy = o.deployCap !== undefined ? Math.min(capped, o.deployCap) : capped;
607
612
  const growth = truced === player ? 0 : p.growth;
608
613
  const movable = p.stacks.reduce((n, x) => n + x.movable, 0);
609
614
  const add = Math.max(deploy, growth);
@@ -684,10 +689,17 @@ export function threatForces(pc, ps, src, valueOf) {
684
689
  * {@link threatAt} for next turn (G2): the same force, with the players a Diplomacy card shields me
685
690
  * from only this turn counted again ({@link foeNext}). The same as threatAt when there is none.
686
691
  */
687
- const nextTurnAt = (t, gone) => {
688
- if (!returning.size && !behindNext)
692
+ const nextTurnAt = (t, gone, deployCap) => {
693
+ if (!returning.size && !behindNext && deployCap === undefined)
689
694
  return threatAt(t, gone);
690
- const f = forceAt(t, gone, { trend: true, allPlayers: true, solo: ps.soloHeld.has(t), nextTurn: true, behind: behindNext });
695
+ const f = forceAt(t, gone, {
696
+ trend: true,
697
+ allPlayers: true,
698
+ solo: ps.soloHeld.has(t),
699
+ nextTurn: true,
700
+ behind: behindNext,
701
+ ...(deployCap !== undefined ? { deployCap } : {}),
702
+ });
691
703
  return f ? { player: f.player, threat: f.threat } : null;
692
704
  };
693
705
  /**
@@ -930,7 +942,7 @@ export function borderThreats(pc, ps, input, src, forces) {
930
942
  if (!rest.length)
931
943
  continue;
932
944
  const one = rest.length === 1;
933
- rationale.push(`Player ${player} deploys its ~${full} in one place (#420): its full deploy is sized only on its most valuable border, ${label(top)}; ${rest.map(label).join(', ')} ${one ? 'is' : 'are'} sized at its stack beside ${one ? 'it' : 'them'} plus its largest top-up seen, +${capAt.get(rest[0]).get(player)} (the most one of its stacks beside my land grew in a turn).`);
945
+ rationale.push(`Player ${player} deploys its ~${full} in one place (#420): its full deploy is sized only on its most valuable border, ${label(top)}; ${rest.map(label).join(', ')} ${one ? 'is' : 'are'} sized at its ${capAt.get(rest[0]).get(player) ? `stack beside ${one ? 'it' : 'them'} plus its largest top-up seen, +${capAt.get(rest[0]).get(player)} (the most one of its stacks beside my land grew in a turn)` : `stacks beside ${one ? 'it' : 'them'} alone: one deploy cannot land on two borders (#603)`}.`);
934
946
  }
935
947
  }
936
948
  // #199: say where a Multi-Attack chain sets a border's threat.
@@ -296,8 +296,7 @@ export function reconsiderAndGarrison(pc, ps, book, threats, hb, prev) {
296
296
  continue;
297
297
  const cost = todo.reduce((n, x) => n + x.d, 0);
298
298
  const worth = b.value + have / paybackTurns;
299
- // #421: the strike share holds back captures only, never this garrison.
300
- if (cost > paybackTurns * b.value || cost > CONCEDE_FACTOR * worth || cost > ps.budget - (reserve - pc.strikeShare))
299
+ if (cost > paybackTurns * b.value || cost > CONCEDE_FACTOR * worth || cost > ps.budget - reserve)
301
300
  continue;
302
301
  // The pools are checked for the members together: each may fit the free pool on its own
303
302
  // while together they overdraw it.
@@ -209,9 +209,6 @@
209
209
  // builds the same stack facing the opponent beside me whose visible armies mine outnumber
210
210
  // STOCKPILE_LEAD× (fewest first, then id; never an income estimate), never on my commander's
211
211
  // territory, and spends it as above ("Stockpile (#421): …").
212
- // #421, the strike share: in contact on a flat income (a stack built as above), STRIKE_SHARE
213
- // of the income is held out of captures for the stack (holds keep their exact need first),
214
- // unless that lowers next income (`planShare`) ("Strike share (#421): …").
215
212
  // #421, the break spend: on the pile (`pc.pile`), rule 4a runs the break of the strongest
216
213
  // opponent's cheapest visible bonus before every other capture, never skipped as a second
217
214
  // front ("Stockpile spend (#421): …").
@@ -1099,13 +1096,10 @@
1099
1096
  // territory my commander walks from — all that stands there is its transit hold (rule 1w,
1100
1097
  // `commanderTransit` sizes it on the whole stack); a commander that stays keeps its worst-case
1101
1098
  // hold through `keepOf`, as from any capture.
1102
- // #297, a 1v1 only: every border of mine facing the opponent is a gate, each sized for its stack plus the
1103
- // opponent's whole deploy, since that one deploy floats to whichever it picks. A capture that adds a gate is
1104
- // stopped when the frontier would then need more next turn than the next income and more than without it
1105
- // (`gateStop`, src/analysis/plan/captures.ts) — rule 4d's start-of-turn escape does not apply in a 1v1, and
1106
- // rule 4e's contact fallback, where 4d is only a cost (#114), runs it too. The plan reports `gates` (each gate's
1107
- // need and armies, conceded ones marked, the summed need, what stands on them, the per-gate deficit, the next
1108
- // income and the shortfall) and warns when its own captures open a gate the income cannot hold.
1099
+ // #297, a 1v1 only: the plan reports `gates` (each border of mine facing the opponent, its need and armies,
1100
+ // conceded ones marked, the summed need, what stands on them, the per-gate deficit, the next income and the
1101
+ // shortfall). #603: a report only — the veto and #432's short-gates horizon are gone; rule 4d's total counts
1102
+ // the opponent's one floating deploy once.
1109
1103
  // #426 (draft): a no-loss neutral (its defenders kill none of my attackers, `noLossNeutral`) is taken
1110
1104
  // by pass 3 even in an uneconomic bonus, and rule 4d lets one through when only the fog faces its new
1111
1105
  // border and the hold it adds is at most 1× the next income (`outgrows`, not in a 1v1); a stack idle two
@@ -1704,7 +1698,6 @@ import { neutralizeSeats, seatTerritories, staticSeats } from './static-seats.js
1704
1698
  import { deployBook } from './plan/orders.js';
1705
1699
  import { holdsPhase, priorOnlyHold } from './plan/holds.js';
1706
1700
  import { threatsPhase } from './plan/threats.js';
1707
- import { applyShortGates } from './plan/horizon.js';
1708
1701
  import { targetsPhase } from './plan/targets.js';
1709
1702
  import { capturesPhase } from './plan/captures.js';
1710
1703
  import { spreadBind } from './plan/spread-bind.js';
@@ -1912,11 +1905,11 @@ function planAttempts(input) {
1912
1905
  const turn = input.turn;
1913
1906
  const none = new Set();
1914
1907
  if (!input.bonusAttempts || turn === undefined)
1915
- return planShare(input.stockpileAllIn?.size ? withPush(input, none, none) : input);
1908
+ return planSettled(input.stockpileAllIn?.size ? withPush(input, none, none) : input);
1916
1909
  const judged = judgeAttempts(input.bonusAttempts, turn, input.graph, input.board, input.me);
1917
1910
  const verdicts = bonusVerdicts(judged, turn).filter((v) => input.graph.bonusById.has(v.bonusId));
1918
1911
  if (!verdicts.length)
1919
- return planShare(input.stockpileAllIn?.size ? withPush(input, none, none) : input);
1912
+ return planSettled(input.stockpileAllIn?.size ? withPush(input, none, none) : input);
1920
1913
  const entries = new Map();
1921
1914
  for (const v of verdicts)
1922
1915
  if (v.kind === 'dropped')
@@ -1941,7 +1934,7 @@ function planAttempts(input) {
1941
1934
  let plan;
1942
1935
  for (;;) {
1943
1936
  const ids = new Set(allIn.map((v) => v.bonusId));
1944
- plan = planShare(withPush(input, ids, new Set([...entries.keys()])));
1937
+ plan = planSettled(withPush(input, ids, new Set([...entries.keys()])));
1945
1938
  const tries = allInOutcome.get(plan);
1946
1939
  const taken = new Set(plan.expected.captures);
1947
1940
  const failing = allIn.flatMap((v) => {
@@ -1991,29 +1984,11 @@ function planAttempts(input) {
1991
1984
  plan.bonusPush = push;
1992
1985
  return plan;
1993
1986
  }
1994
- /** #421: per plan, the strike share its pass held out of captures (absent when none). */
1995
- const shareOutcome = new WeakMap();
1996
1987
  const closenessOutcome = new WeakMap();
1997
1988
  /** #505: rule 4f's nearest bonus and turns to finish for a plan `planTurn` made; `undefined` for any other object. */
1998
1989
  export function planCloseness(plan) {
1999
1990
  return closenessOutcome.get(plan);
2000
1991
  }
2001
- /**
2002
- * #421 (owner decision, 2026-11-20): the strike share is held out of captures, ahead of comfort margins,
2003
- * but never at the cost of next income — when the plan without it earns more next turn (a completion the
2004
- * share starves), that plan stands and says why.
2005
- */
2006
- function planShare(input) {
2007
- const plan = planSettled(input);
2008
- const share = shareOutcome.get(plan);
2009
- if (!share)
2010
- return plan;
2011
- const without = planSettled({ ...input, options: { ...input.options, strikeShare: false } });
2012
- if (without.expected.nextIncome <= plan.expected.nextIncome)
2013
- return plan;
2014
- without.rationale.push(`Strike share (#421) not held this turn: holding ${share} of the income out of captures for the strike stack would lower next income from ${without.expected.nextIncome} to ${plan.expected.nextIncome} (a capture it starves completes a bonus).`);
2015
- return without;
2016
- }
2017
1992
  function planSettled(input) {
2018
1993
  const plan = planRun(input, false);
2019
1994
  const bare = runOutcome.get(plan);
@@ -2092,9 +2067,6 @@ function planPass(input, pass) {
2092
2067
  const local = pools !== null && pools.bonuses.length > 0;
2093
2068
  // ---- 1t. threat trend, 1. defence (plan/threats.ts) ----
2094
2069
  const threats = threatsPhase(pc, ps, input, book.valueOf);
2095
- // #432: a 1v1 whose gates are short at the start judges its captures on a shorter payback horizon from here on
2096
- // (every capture test after this reads `pc.capturePaybackTurns`; holds keep `paybackTurns`).
2097
- applyShortGates(pc, ps, threats);
2098
2070
  const { growthOf, reinforcementAt, borders, facing, borderAt } = threats;
2099
2071
  // ---- 1. holds, #172, 1h, 1b, 1c, #122 garrisons (plan/holds.ts) ----
2100
2072
  const hd = holdsPhase(pc, ps, book, threats, pass);
@@ -3619,8 +3591,6 @@ function planPass(input, pass) {
3619
3591
  }
3620
3592
  if (tgt.allInTries.size)
3621
3593
  allInOutcome.set(plan, tgt.allInTries);
3622
- if (pc.strikeShare > 0)
3623
- shareOutcome.set(plan, pc.strikeShare);
3624
3594
  {
3625
3595
  const nearest = tgt.committing ? (tgt.byCloseness.find((p) => !p.focus) ?? tgt.byCloseness[0]) : undefined;
3626
3596
  const near = tgt.spreadNearest ?? nearest;
@@ -0,0 +1,243 @@
1
+ import { bonusTerritories } from './bonuses.js';
2
+ import { armiesToTake } from './combat.js';
3
+ import { neighborsOf } from './graph.js';
4
+ /** The most territories listed (a huge map lists the ones nearest my land first). */
5
+ export const MAX_SITUATION_TERRITORIES = 400;
6
+ /** The most bonuses listed. */
7
+ export const MAX_SITUATION_BONUSES = 60;
8
+ /** The most earlier turns summarised (the newest). */
9
+ export const SITUATION_PAST_TURNS = 10;
10
+ const ownerOf = (t, me) => {
11
+ if (!t || t.owner.kind === 'unknown')
12
+ return 'fog';
13
+ if (t.owner.kind !== 'player')
14
+ return 'neutral';
15
+ return t.owner.playerId === me ? 'me' : t.owner.playerId;
16
+ };
17
+ /** The facts on this board (see the file header). */
18
+ export function situation(input) {
19
+ const { graph: g, board, me } = input;
20
+ const guard = input.guard === false ? 0 : 1;
21
+ const state = new Map(board.territories.map((t) => [t.territoryId, t]));
22
+ const owner = (id) => ownerOf(state.get(id), me);
23
+ const armiesOf = (id) => state.get(id)?.armies ?? null;
24
+ const mine = [...state.keys()].filter((id) => owner(id) === 'me').sort((a, b) => a - b);
25
+ const mineSet = new Set(mine);
26
+ const take = (n) => armiesToTake(n, input.rates);
27
+ // Hops from my land, through any territory.
28
+ const dist = new Map(mine.map((m) => [m, 0]));
29
+ let frontier = mine;
30
+ while (frontier.length) {
31
+ const next = [];
32
+ for (const t of frontier)
33
+ for (const n of neighborsOf(g, t))
34
+ if (!dist.has(n)) {
35
+ dist.set(n, dist.get(t) + 1);
36
+ next.push(n);
37
+ }
38
+ frontier = next;
39
+ }
40
+ const bonusesOf = new Map();
41
+ for (const b of g.map.bonuses)
42
+ for (const t of bonusTerritories(g, b.id))
43
+ bonusesOf.set(t, [...(bonusesOf.get(t) ?? []), b.id]);
44
+ // Every territory in view, plus every hidden one beside my land; nearest first.
45
+ const listed = [...g.territoryById.keys()]
46
+ .filter((id) => owner(id) !== 'fog' || neighborsOf(g, id).some((n) => mineSet.has(n)))
47
+ .sort((a, b) => (dist.get(a) ?? Infinity) - (dist.get(b) ?? Infinity) || a - b);
48
+ const territories = listed.slice(0, MAX_SITUATION_TERRITORIES).map((id) => {
49
+ const t = state.get(id);
50
+ const units = t?.specialUnits?.map((u) => ({ kind: u.kind, owner: u.playerId === me ? 'me' : u.playerId }));
51
+ return {
52
+ id,
53
+ name: g.territoryById.get(id)?.name ?? String(id),
54
+ owner: owner(id),
55
+ armies: armiesOf(id),
56
+ ...(units?.length ? { units } : {}),
57
+ distance: dist.get(id) ?? -1,
58
+ bonuses: bonusesOf.get(id) ?? [],
59
+ neighbors: [...neighborsOf(g, id)],
60
+ };
61
+ });
62
+ // Every positive bonus I touch, that is beside my land, or that another player visibly holds in full.
63
+ const bonuses = [];
64
+ for (const b of g.map.bonuses) {
65
+ if (b.value <= 0)
66
+ continue;
67
+ const members = bonusTerritories(g, b.id);
68
+ let mineN = 0;
69
+ let neutral = 0;
70
+ let fogged = 0;
71
+ const players = new Map();
72
+ for (const t of members) {
73
+ const o = owner(t);
74
+ if (o === 'me')
75
+ mineN++;
76
+ else if (o === 'neutral')
77
+ neutral++;
78
+ else if (o === 'fog')
79
+ fogged++;
80
+ else
81
+ players.set(o, (players.get(o) ?? 0) + 1);
82
+ }
83
+ const heldBy = mineN === members.length ? 'me' : players.size === 1 && [...players.values()][0] === members.length ? [...players.keys()][0] : null;
84
+ const near = members.some((t) => (dist.get(t) ?? Infinity) <= 1);
85
+ if (!near && heldBy === null)
86
+ continue;
87
+ const missing = members.filter((t) => owner(t) !== 'me');
88
+ const hidden = missing.some((t) => armiesOf(t) === null);
89
+ bonuses.push({
90
+ bonusId: b.id,
91
+ name: b.name,
92
+ value: b.value,
93
+ size: members.length,
94
+ mine: mineN,
95
+ neutral,
96
+ fogged,
97
+ players: [...players].sort((x, y) => x[0] - y[0]).map(([player, count]) => ({ player, count })),
98
+ heldBy,
99
+ missing,
100
+ armiesToFinish: hidden ? null : missing.reduce((n, t) => n + (take(armiesOf(t)) ?? Infinity), 0),
101
+ reachable: missing.filter((t) => neighborsOf(g, t).some((n) => mineSet.has(n))),
102
+ });
103
+ }
104
+ // Mine first, then the nearest to done (fewest missing), then the most valuable.
105
+ bonuses.sort((a, b) => Number(b.heldBy === 'me') - Number(a.heldBy === 'me') ||
106
+ a.missing.length - b.missing.length ||
107
+ b.value - a.value ||
108
+ a.bonusId - b.bonusId);
109
+ const opponents = [...input.opponents]
110
+ .filter((o) => o.playerId !== me && !input.friends?.has(o.playerId))
111
+ .sort((a, b) => a.playerId - b.playerId)
112
+ .map((o) => {
113
+ const theirs = [...state.keys()].filter((id) => owner(id) === o.playerId);
114
+ const besideMe = theirs
115
+ .filter((id) => neighborsOf(g, id).some((n) => mineSet.has(n)))
116
+ .map((id) => ({ territoryId: id, armies: armiesOf(id) ?? 0, borders: neighborsOf(g, id).filter((n) => mineSet.has(n)) }));
117
+ return {
118
+ player: o.playerId,
119
+ income: {
120
+ estimate: o.estimate,
121
+ ...(o.source !== undefined ? { source: o.source } : {}),
122
+ ...(o.visibleIncome !== undefined ? { visible: o.visibleIncome } : {}),
123
+ ...(o.tracked !== undefined ? { tracked: o.tracked } : {}),
124
+ ...(o.range !== undefined ? { range: o.range } : {}),
125
+ ...(o.coverage !== undefined ? { coverage: o.coverage } : {}),
126
+ },
127
+ ...(o.history?.length ? { history: o.history.map((h) => ({ turn: h.turn, observed: h.observed })) } : {}),
128
+ territoriesInView: theirs.length,
129
+ armiesInView: theirs.reduce((n, id) => n + (armiesOf(id) ?? 0), 0),
130
+ bonusesHeld: bonuses.filter((b) => b.heldBy === o.playerId).map((b) => ({ bonusId: b.bonusId, value: b.value })),
131
+ besideMe,
132
+ movableBesideMe: besideMe.reduce((n, s) => n + Math.max(0, s.armies - guard), 0),
133
+ };
134
+ });
135
+ let changes = null;
136
+ if (input.previousBoard) {
137
+ const prev = new Map(input.previousBoard.territories.map((t) => [t.territoryId, t]));
138
+ const was = (id) => ownerOf(prev.get(id), me);
139
+ const lost = [];
140
+ const gained = [];
141
+ const moved = [];
142
+ for (const id of [...new Set([...prev.keys(), ...state.keys()])].sort((a, b) => a - b)) {
143
+ const before = was(id);
144
+ const now = owner(id);
145
+ if (before === 'me' && now !== 'me')
146
+ lost.push({ territoryId: id, to: now });
147
+ else if (now === 'me' && before !== 'me')
148
+ gained.push({ territoryId: id, from: before });
149
+ else if (typeof now === 'number' && before === now) {
150
+ const a = prev.get(id)?.armies;
151
+ const b = armiesOf(id);
152
+ if (a !== null && a !== undefined && b !== null && a !== b)
153
+ moved.push({ territoryId: id, owner: now, was: a, now: b });
154
+ }
155
+ }
156
+ moved.sort((x, y) => Math.abs(y.now - y.was) - Math.abs(x.now - x.was) || x.territoryId - y.territoryId);
157
+ changes = { lost, gained, moved: moved.slice(0, MAX_SITUATION_BONUSES) };
158
+ }
159
+ const past = [...(input.pastBoards ?? [])]
160
+ .sort((a, b) => a.turn - b.turn)
161
+ .slice(-SITUATION_PAST_TURNS)
162
+ .map((p) => {
163
+ const at = new Map(p.board.territories.map((t) => [t.territoryId, t]));
164
+ const sides = new Map();
165
+ for (const t of p.board.territories) {
166
+ const o = ownerOf(t, me);
167
+ if (o === 'fog' || o === 'neutral')
168
+ continue;
169
+ const side = sides.get(o) ?? { territories: 0, armies: 0 };
170
+ side.territories++;
171
+ side.armies += t.armies ?? 0;
172
+ sides.set(o, side);
173
+ }
174
+ const held = (o) => g.map.bonuses
175
+ .filter((b) => b.value > 0 && bonusTerritories(g, b.id).every((t) => ownerOf(at.get(t), me) === o))
176
+ .map((b) => b.id);
177
+ return {
178
+ turn: p.turn,
179
+ sides: [...sides]
180
+ .sort((a, b) => (a[0] === 'me' ? -1 : b[0] === 'me' ? 1 : a[0] - b[0]))
181
+ .map(([o, v]) => ({ owner: o, ...v, bonusesHeld: held(o) })),
182
+ ...(p.orders
183
+ ? {
184
+ myOrders: {
185
+ deploys: p.orders.deploys.map((d) => ({ territoryId: d.territoryId, armies: d.armies })),
186
+ moves: p.orders.moves.map((m) => ({ from: m.from, to: m.to, armies: m.armies })),
187
+ },
188
+ }
189
+ : {}),
190
+ };
191
+ });
192
+ return {
193
+ me: {
194
+ income: input.myIncome,
195
+ incomeHistory: [...(input.incomeHistory ?? [])],
196
+ territories: mine.length,
197
+ armies: mine.reduce((n, id) => n + (armiesOf(id) ?? 0), 0),
198
+ bonusesHeld: bonuses.filter((b) => b.heldBy === 'me').map((b) => ({ bonusId: b.bonusId, value: b.value })),
199
+ },
200
+ territories,
201
+ territoriesOmitted: Math.max(0, listed.length - MAX_SITUATION_TERRITORIES),
202
+ bonuses: bonuses.slice(0, MAX_SITUATION_BONUSES),
203
+ bonusesOmitted: Math.max(0, bonuses.length - MAX_SITUATION_BONUSES),
204
+ opponents,
205
+ changes,
206
+ past,
207
+ };
208
+ }
209
+ /** The parts of {@link Situation} a caller can ask for by name. */
210
+ export const FACT_PARTS = ['me', 'territories', 'bonuses', 'opponents', 'changes', 'past'];
211
+ /** What each part holds, for telling the caller what it can ask for. */
212
+ export const FACTS_AVAILABLE = {
213
+ me: 'my income and its history, land, armies and bonuses held',
214
+ territories: 'every territory in view and each hidden one beside my land, nearest first: owner, armies, special units, bonuses, neighbours',
215
+ bonuses: 'each bonus that matters: who holds how much of it, what finishing it costs, the members in reach',
216
+ opponents: "each opponent's income estimate with how it was read (source, visible, tracked, range, coverage, per-turn deploys), its bonuses and its stacks beside me",
217
+ changes: 'what changed since last turn: territories lost and gained, stacks that grew or shrank',
218
+ past: 'each of the last 10 turns kept: every side in view, its bonuses, my orders',
219
+ };
220
+ /** Only the parts asked for (the omitted counts go with their part). */
221
+ export function pickFacts(s, parts) {
222
+ const want = new Set(parts);
223
+ return {
224
+ ...(want.has('me') ? { me: s.me } : {}),
225
+ ...(want.has('territories') ? { territories: s.territories, territoriesOmitted: s.territoriesOmitted } : {}),
226
+ ...(want.has('bonuses') ? { bonuses: s.bonuses, bonusesOmitted: s.bonusesOmitted } : {}),
227
+ ...(want.has('opponents') ? { opponents: s.opponents } : {}),
228
+ ...(want.has('changes') ? { changes: s.changes } : {}),
229
+ ...(want.has('past') ? { past: s.past } : {}),
230
+ };
231
+ }
232
+ /** The one line every plan carries: what more the caller can ask warapp_plan_turn for. */
233
+ export const MORE_ON_REQUEST = 'Ask for more when you want to weigh the plan or build your own: strategy: true adds ranked captures and holds and the plan ' +
234
+ 'beside expand/defend alternatives, each stress-tested; facts: ["me","territories","bonuses","opponents","changes","past"] ' +
235
+ '(any of them) adds the raw game state behind them. Test any orders with warapp_check_plan.';
236
+ /** What to do with the facts: the tools that let the model test and act on its own plan. */
237
+ export const OWN_PLAN_STEPS = [
238
+ 'The plan, options and alternatives are inputs to your judgement, not the answer; ask warapp_plan_turn for the facts your decision needs (facts: me, territories, bonuses, opponents, changes, past).',
239
+ 'Write your own deploys and moves (any mix of the options, the alternatives or neither).',
240
+ 'Test them with warapp_check_plan (every opponent\'s replies, both move orders, one turn ahead); change and test again as needed.',
241
+ 'Look deeper when it matters: warapp_turn_history (what happened turn by turn), warapp_track_opponents and warapp_profile_opponents (how each opponent plays), warapp_plan_route (paths), warapp_get_map (the whole map), warapp_strategy (notes for this game), warapp_get_chat.',
242
+ 'Submit with warapp_submit_turn; when your orders differ from the plan, pass override_reason so the decision log keeps why.',
243
+ ];