@chrischall/warapp-mcp 0.0.0 → 0.2.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 (194) hide show
  1. package/.claude-plugin/marketplace.json +4 -4
  2. package/.claude-plugin/plugin.json +2 -2
  3. package/README.md +211 -9
  4. package/dist/analysis/accept-surrender.js +56 -0
  5. package/dist/analysis/award.js +159 -0
  6. package/dist/analysis/bonuses.js +98 -0
  7. package/dist/analysis/breach.js +62 -0
  8. package/dist/analysis/calibrate.js +239 -0
  9. package/dist/analysis/card-support.js +329 -0
  10. package/dist/analysis/card-threats.js +234 -0
  11. package/dist/analysis/cards-in-effect.js +130 -0
  12. package/dist/analysis/chains.js +59 -0
  13. package/dist/analysis/chokepoints.js +140 -0
  14. package/dist/analysis/combat.js +231 -0
  15. package/dist/analysis/commander-safety.js +149 -0
  16. package/dist/analysis/commitments.js +338 -0
  17. package/dist/analysis/exchange.js +155 -0
  18. package/dist/analysis/finished-game.js +136 -0
  19. package/dist/analysis/game-lessons.js +217 -0
  20. package/dist/analysis/graph.js +82 -0
  21. package/dist/analysis/guard-off.js +54 -0
  22. package/dist/analysis/guess.js +351 -0
  23. package/dist/analysis/headroom.js +241 -0
  24. package/dist/analysis/hold-diff.js +64 -0
  25. package/dist/analysis/how-lost.js +130 -0
  26. package/dist/analysis/index.js +14 -0
  27. package/dist/analysis/local-deploy.js +179 -0
  28. package/dist/analysis/lookahead.js +108 -0
  29. package/dist/analysis/opponent-profile.js +552 -0
  30. package/dist/analysis/opponents.js +1253 -0
  31. package/dist/analysis/outlook.js +695 -0
  32. package/dist/analysis/overrides.js +60 -0
  33. package/dist/analysis/picks.js +1879 -0
  34. package/dist/analysis/plan/after-leftover.js +140 -0
  35. package/dist/analysis/plan/cap-spend.js +242 -0
  36. package/dist/analysis/plan/captures.js +1195 -0
  37. package/dist/analysis/plan/commander.js +236 -0
  38. package/dist/analysis/plan/completed.js +29 -0
  39. package/dist/analysis/plan/conceded-out.js +131 -0
  40. package/dist/analysis/plan/estimates.js +715 -0
  41. package/dist/analysis/plan/guard-off.js +232 -0
  42. package/dist/analysis/plan/holds.js +1631 -0
  43. package/dist/analysis/plan/leftover.js +760 -0
  44. package/dist/analysis/plan/move-order.js +319 -0
  45. package/dist/analysis/plan/orders.js +317 -0
  46. package/dist/analysis/plan/relations.js +702 -0
  47. package/dist/analysis/plan/report.js +672 -0
  48. package/dist/analysis/plan/shared.js +1405 -0
  49. package/dist/analysis/plan/stand-still.js +823 -0
  50. package/dist/analysis/plan/state.js +44 -0
  51. package/dist/analysis/plan/strike.js +1416 -0
  52. package/dist/analysis/plan/targets.js +651 -0
  53. package/dist/analysis/plan/team.js +299 -0
  54. package/dist/analysis/plan/threats.js +1001 -0
  55. package/dist/analysis/plan/transfers.js +328 -0
  56. package/dist/analysis/plan/util.js +5 -0
  57. package/dist/analysis/plan/vacated.js +285 -0
  58. package/dist/analysis/planner.js +2927 -0
  59. package/dist/analysis/player-record.js +144 -0
  60. package/dist/analysis/player.js +268 -0
  61. package/dist/analysis/profile.js +347 -0
  62. package/dist/analysis/relations.js +1030 -0
  63. package/dist/analysis/schedule.js +88 -0
  64. package/dist/analysis/since-last.js +50 -0
  65. package/dist/analysis/static-seats.js +71 -0
  66. package/dist/analysis/stress.js +584 -0
  67. package/dist/analysis/team-brief.js +151 -0
  68. package/dist/analysis/tripwire.js +644 -0
  69. package/dist/analysis/turn-sim.js +259 -0
  70. package/dist/analysis/whereabouts.js +1112 -0
  71. package/dist/board.js +105 -0
  72. package/dist/bundle.js +121082 -36148
  73. package/dist/calibration-source.js +75 -0
  74. package/dist/cards.js +435 -0
  75. package/dist/chat-cursor.js +135 -0
  76. package/dist/chat.js +265 -0
  77. package/dist/client.js +439 -0
  78. package/dist/config.js +62 -0
  79. package/dist/direct/link.js +102 -0
  80. package/dist/direct/session.js +267 -0
  81. package/dist/direct/transport.js +424 -0
  82. package/dist/finished-store.js +357 -0
  83. package/dist/guess-salt.js +65 -0
  84. package/dist/hosted.js +24 -0
  85. package/dist/index.js +33 -0
  86. package/dist/join-color.js +140 -0
  87. package/dist/lessons-store.js +356 -0
  88. package/dist/live.js +287 -0
  89. package/dist/map-details.js +127 -0
  90. package/dist/map-stats.js +160 -0
  91. package/dist/map-store.js +242 -0
  92. package/dist/move-order.js +141 -0
  93. package/dist/my-games.js +218 -0
  94. package/dist/normalize.js +443 -0
  95. package/dist/notifications.js +143 -0
  96. package/dist/open-games.js +537 -0
  97. package/dist/outlook-log.js +165 -0
  98. package/dist/path-lock.js +22 -0
  99. package/dist/pick-list.js +193 -0
  100. package/dist/player-record-store.js +231 -0
  101. package/dist/player-states.js +31 -0
  102. package/dist/profile-store.js +727 -0
  103. package/dist/protocol/bundle.js +375 -0
  104. package/dist/protocol/codec.js +556 -0
  105. package/dist/protocol/decoded.js +12 -0
  106. package/dist/protocol/interp.js +1904 -0
  107. package/dist/protocol/methods.js +615 -0
  108. package/dist/protocol/rpc.js +202 -0
  109. package/dist/push/listener.js +393 -0
  110. package/dist/push/packets.js +66 -0
  111. package/dist/push/socketio.js +333 -0
  112. package/dist/push/websocket.js +179 -0
  113. package/dist/redact.js +62 -0
  114. package/dist/relations-store.js +242 -0
  115. package/dist/replay.js +227 -0
  116. package/dist/scalars.js +28 -0
  117. package/dist/scout.js +346 -0
  118. package/dist/stats.js +291 -0
  119. package/dist/strategy/card-clock.js +185 -0
  120. package/dist/strategy/map-notes.js +128 -0
  121. package/dist/strategy/notes.js +2223 -0
  122. package/dist/surrender-pending.js +126 -0
  123. package/dist/team-cards.js +84 -0
  124. package/dist/team-orders.js +150 -0
  125. package/dist/teams.js +19 -0
  126. package/dist/tools/accept-surrender.js +311 -0
  127. package/dist/tools/award.js +206 -0
  128. package/dist/tools/begin-turn.js +162 -0
  129. package/dist/tools/board.js +77 -0
  130. package/dist/tools/card-advice.js +256 -0
  131. package/dist/tools/card-effects.js +49 -0
  132. package/dist/tools/card-plays.js +434 -0
  133. package/dist/tools/card-support-advice.js +140 -0
  134. package/dist/tools/chat-inbox.js +158 -0
  135. package/dist/tools/chat-read-mark.js +179 -0
  136. package/dist/tools/chat.js +525 -0
  137. package/dist/tools/check-plan.js +689 -0
  138. package/dist/tools/commander-check.js +103 -0
  139. package/dist/tools/commitments.js +216 -0
  140. package/dist/tools/common.js +143 -0
  141. package/dist/tools/diplomacy.js +342 -0
  142. package/dist/tools/end-of-game.js +384 -0
  143. package/dist/tools/game.js +151 -0
  144. package/dist/tools/guess-view.js +56 -0
  145. package/dist/tools/healthcheck.js +90 -0
  146. package/dist/tools/hints.js +34 -0
  147. package/dist/tools/how-lost.js +154 -0
  148. package/dist/tools/index.js +152 -0
  149. package/dist/tools/join-game.js +327 -0
  150. package/dist/tools/leave-game.js +181 -0
  151. package/dist/tools/live-context.js +339 -0
  152. package/dist/tools/live.js +404 -0
  153. package/dist/tools/map-details.js +88 -0
  154. package/dist/tools/map-stats.js +130 -0
  155. package/dist/tools/map.js +141 -0
  156. package/dist/tools/my-games.js +193 -0
  157. package/dist/tools/notifications.js +484 -0
  158. package/dist/tools/open-games.js +104 -0
  159. package/dist/tools/opponents.js +163 -0
  160. package/dist/tools/order-options.js +135 -0
  161. package/dist/tools/past-games.js +94 -0
  162. package/dist/tools/picks.js +305 -0
  163. package/dist/tools/profile-hook.js +156 -0
  164. package/dist/tools/profile-opponents.js +121 -0
  165. package/dist/tools/profile-reads.js +99 -0
  166. package/dist/tools/push.js +445 -0
  167. package/dist/tools/relations.js +611 -0
  168. package/dist/tools/resolve.js +45 -0
  169. package/dist/tools/route.js +36 -0
  170. package/dist/tools/scout.js +87 -0
  171. package/dist/tools/session.js +163 -0
  172. package/dist/tools/strategy.js +257 -0
  173. package/dist/tools/stress-opponents.js +83 -0
  174. package/dist/tools/surrender-pending.js +74 -0
  175. package/dist/tools/surrender.js +247 -0
  176. package/dist/tools/survival.js +189 -0
  177. package/dist/tools/team-brief.js +266 -0
  178. package/dist/tools/team-source.js +222 -0
  179. package/dist/tools/team.js +178 -0
  180. package/dist/tools/turn.js +2825 -0
  181. package/dist/tools/uncommit.js +160 -0
  182. package/dist/tools/where.js +300 -0
  183. package/dist/tools/write-kit.js +164 -0
  184. package/dist/transport-bridge.js +33 -0
  185. package/dist/trend.js +577 -0
  186. package/dist/version.js +4 -0
  187. package/manifest.json +194 -4
  188. package/mint.yaml +106 -14
  189. package/package.json +11 -6
  190. package/server.json +40 -3
  191. package/skills/warapp-api/SKILL.md +95 -4
  192. package/skills/warapp-api/references/scout.mjs +348 -0
  193. package/skills/warapp-api/scripts/warapp.sh +69 -8
  194. package/skills/warapp-mcp/SKILL.md +1096 -21
@@ -0,0 +1,98 @@
1
+ // Per-bonus geometry: flattened membership, borders, entry points, and an
2
+ // "easiest bonus" ranking. Pure and deterministic.
3
+ import { neighborsOf } from './graph.js';
4
+ const byNum = (a, b) => a - b;
5
+ const flattened = new WeakMap();
6
+ /**
7
+ * All territories of a bonus, flattening member bonuses (cycle-safe). Unknown bonus → `[]`.
8
+ * Remembered per graph and frozen: the planner asks for the same bonus thousands of times in
9
+ * one plan (it was most of a plan's time on a large map), and a graph's bonuses never change.
10
+ */
11
+ export function bonusTerritories(g, bonusId) {
12
+ let cache = flattened.get(g);
13
+ if (!cache)
14
+ flattened.set(g, (cache = new Map()));
15
+ const hit = cache.get(bonusId);
16
+ if (hit)
17
+ return hit;
18
+ const out = new Set();
19
+ const seen = new Set();
20
+ const visit = (id) => {
21
+ const b = g.bonusById.get(id);
22
+ if (!b || seen.has(id))
23
+ return;
24
+ seen.add(id);
25
+ for (const t of b.territoryIds)
26
+ out.add(t);
27
+ for (const sub of b.bonusIds)
28
+ visit(sub);
29
+ };
30
+ visit(bonusId);
31
+ const ts = Object.freeze([...out].sort(byNum));
32
+ cache.set(bonusId, ts);
33
+ return ts;
34
+ }
35
+ export function analyzeBonus(g, bonusId) {
36
+ const b = g.bonusById.get(bonusId);
37
+ if (!b)
38
+ return undefined;
39
+ const territoryIds = [...bonusTerritories(g, bonusId)];
40
+ const inside = new Set(territoryIds);
41
+ const borders = [];
42
+ const entries = new Set();
43
+ for (const t of territoryIds) {
44
+ let border = false;
45
+ for (const n of neighborsOf(g, t)) {
46
+ if (inside.has(n))
47
+ continue;
48
+ border = true;
49
+ entries.add(n);
50
+ }
51
+ if (border)
52
+ borders.push(t);
53
+ }
54
+ const size = territoryIds.length;
55
+ return {
56
+ bonusId: b.id,
57
+ name: b.name,
58
+ value: b.value,
59
+ territoryIds,
60
+ memberBonusIds: [...b.bonusIds].sort(byNum),
61
+ isSuperbonus: b.bonusIds.length > 0,
62
+ borderTerritoryIds: borders,
63
+ entryPointIds: [...entries].sort(byNum),
64
+ valuePerTerritory: size ? b.value / size : 0,
65
+ valuePerBorder: borders.length ? b.value / borders.length : b.value,
66
+ score: size ? b.value / (size + borders.length) : 0,
67
+ };
68
+ }
69
+ /**
70
+ * Each entry point of a bonus (a territory outside it next to one of its territories) with
71
+ * the number of its territories that entry point borders, ascending by id. One that borders
72
+ * two or more is a double border: a single stack there threatens several members at once.
73
+ * Unknown bonus → empty.
74
+ */
75
+ export function entryTouches(g, bonusId) {
76
+ const inside = new Set(bonusTerritories(g, bonusId));
77
+ const touches = new Map();
78
+ for (const t of inside)
79
+ for (const n of neighborsOf(g, t))
80
+ if (!inside.has(n))
81
+ touches.set(n, (touches.get(n) ?? 0) + 1);
82
+ return new Map([...touches].sort((a, b) => a[0] - b[0]));
83
+ }
84
+ /** Every bonus on the map, in map order. */
85
+ export function analyzeBonuses(g) {
86
+ return g.map.bonuses.map((b) => analyzeBonus(g, b.id));
87
+ }
88
+ /** Bonuses ordered easiest first: score desc, then value desc, size asc, id asc. */
89
+ export function rankBonuses(g, opts = {}) {
90
+ const minValue = opts.minValue ?? 1;
91
+ const ranked = analyzeBonuses(g)
92
+ .filter((b) => b.value >= minValue)
93
+ .sort((a, b) => b.score - a.score ||
94
+ b.value - a.value ||
95
+ a.territoryIds.length - b.territoryIds.length ||
96
+ a.bonusId - b.bonusId);
97
+ return opts.limit !== undefined ? ranked.slice(0, opts.limit) : ranked;
98
+ }
@@ -0,0 +1,62 @@
1
+ // The breach cost of a border (#275, pattern 2): with the guard off every interior territory may
2
+ // hold 0, so one breach by a large stack puts everything behind the border one move away. Pure and
3
+ // deterministic; ties resolve on ascending ids.
4
+ //
5
+ // The territories a border `t` alone shields are my territories within BREACH_DEPTH (2) steps of it
6
+ // through my holdings that face no enemy themselves (no neighbour of a foe, none in the fog), and
7
+ // whose only front within BREACH_DEPTH steps (through my holdings) is `t`: a territory a second front
8
+ // also reaches is that front's too, so no breach cost is counted twice. Only a hollow territory
9
+ // counts (`hollow`, the caller's test: in the planner, none of my territories beside it, itself
10
+ // included, holds the stack that would come through; a 120-army stack one step behind answers a
11
+ // breach, #214's boards). The cost is the positive
12
+ // bonuses I hold in full with a member among them, leaving out every bonus `t` itself is in (losing
13
+ // `t` breaks those already). The planner adds per-territory income itself.
14
+ import { bonusTerritories } from './bonuses.js';
15
+ import { neighborsOf } from './graph.js';
16
+ /** How far behind a border a breach reaches: the stack takes the border, then walks on. */
17
+ export const BREACH_DEPTH = 2;
18
+ const byNum = (a, b) => a - b;
19
+ /** My territories within `depth` steps of `from` through `holdings` (`from` itself left out). */
20
+ function within(graph, holdings, from, depth) {
21
+ const dist = new Map([[from, 0]]);
22
+ let frontier = [from];
23
+ for (let d = 1; d <= depth; d++) {
24
+ const next = [];
25
+ for (const x of frontier)
26
+ for (const n of neighborsOf(graph, x))
27
+ if (holdings.has(n) && !dist.has(n)) {
28
+ dist.set(n, d);
29
+ next.push(n);
30
+ }
31
+ frontier = next;
32
+ }
33
+ dist.delete(from);
34
+ return dist;
35
+ }
36
+ /**
37
+ * What a breach of my border `t` opens (see the header). `front(x)`: my `x` faces an enemy or the
38
+ * fog. `skip`: territories already counted elsewhere (what losing `t` cuts off, #235). `hollow(x)`:
39
+ * a breach walks into `x` (default: always). Empty when `t` is not mine or not a front.
40
+ */
41
+ export function breachBehind(graph, holdings, front, t, skip = new Set(), hollow = () => true) {
42
+ const none = { ids: [], bonuses: [], income: 0 };
43
+ if (!holdings.has(t) || !front(t))
44
+ return none;
45
+ const ids = [...within(graph, holdings, t, BREACH_DEPTH).keys()]
46
+ .filter((x) => !skip.has(x) && !front(x) && hollow(x))
47
+ .filter((x) => [...within(graph, holdings, x, BREACH_DEPTH).keys()].filter(front).every((y) => y === t))
48
+ .sort(byNum);
49
+ if (!ids.length)
50
+ return none;
51
+ const inside = new Set(ids);
52
+ const bonuses = [];
53
+ for (const b of [...graph.bonusById.values()].sort((a, c) => a.id - c.id)) {
54
+ if (b.value <= 0)
55
+ continue;
56
+ const ts = bonusTerritories(graph, b.id);
57
+ if (!ts.length || ts.includes(t) || !ts.every((x) => holdings.has(x)) || !ts.some((x) => inside.has(x)))
58
+ continue;
59
+ bonuses.push({ id: b.id, value: b.value });
60
+ }
61
+ return { ids, bonuses, income: bonuses.reduce((n, b) => n + b.value, 0) };
62
+ }
@@ -0,0 +1,239 @@
1
+ import { symmetricStart, trackOpponents, unevenStart } from './opponents.js';
2
+ import { turnIncomes } from './finished-game.js';
3
+ import { aggregateCalibration, calibrationSamples, } from './game-lessons.js';
4
+ import { planTurn } from './planner.js';
5
+ import { planEnemyEstimates } from './plan/estimates.js';
6
+ import { boardIncome, incomeRules } from './player.js';
7
+ import { simulateTurn } from './turn-sim.js';
8
+ const landOf = (b, p) => new Set(b.territories.flatMap((t) => (t.owner.kind === 'player' && t.owner.playerId === p ? [t.territoryId] : [])));
9
+ // ---- (a) calibration ----
10
+ /** The figures scored. */
11
+ export const ESTIMATORS = ['tracker', 'prior', 'plan'];
12
+ /**
13
+ * For each turn T I cached a board for whose history board T − 1 the history has, every opponent with
14
+ * land on that board: the tracker (E2's `calibrationSamples`), the fog prior and the plan's estimate
15
+ * (`planEnemyEstimates` as warapp_plan_turn calls it: my income on my board, the previous cached board
16
+ * and my orders on it, the tracks, the seats with a player holding no land on the truth board read as
17
+ * out). A turn on which none of the three has a figure is left out. Pure.
18
+ */
19
+ export function estimateSamples(input) {
20
+ const tracker = new Map(calibrationSamples(input).map((s) => [`${s.turn}:${s.opponent}`, s]));
21
+ const truthBoard = new Map(input.history.map((b) => [b.turn, b.board]));
22
+ const cached = [...input.cached].sort((a, b) => a.turn - b.turn);
23
+ const rules = incomeRules(input.incomeSettings);
24
+ const out = [];
25
+ for (const cur of cached) {
26
+ const truth = truthBoard.get(cur.turn - 1);
27
+ if (!truth)
28
+ continue;
29
+ const upTo = cached.filter((b) => b.turn <= cur.turn);
30
+ const tracks = upTo.length >= 2 ? trackOpponents(input.graph, upTo, input.me, input.plannerSettings, input.game) : [];
31
+ const previous = cached.find((b) => b.turn === cur.turn - 1);
32
+ const real = turnIncomes(input.graph, truth, input.opponents, input.incomeSettings);
33
+ const uneven = unevenStart(input.settings);
34
+ const { estimates } = planEnemyEstimates({
35
+ graph: input.graph,
36
+ board: cur.board,
37
+ me: input.me,
38
+ income: boardIncome(input.graph, landOf(cur.board, input.me), rules).total,
39
+ settings: input.plannerSettings,
40
+ ...(previous ? { previousBoard: previous.board } : {}),
41
+ ...(previous?.orders ? { previousOrders: previous.orders } : {}),
42
+ tracks,
43
+ game: {
44
+ players: input.players.map((p) => ({ ...p, state: p.id === input.me || (real.get(p.id)?.territories ?? 1) > 0 ? 'Playing' : 'Eliminated' })),
45
+ turn: cur.turn,
46
+ symmetricStart: symmetricStart(input.settings),
47
+ ...(uneven ? { unevenStart: uneven } : {}),
48
+ ...(input.settings?.fog !== undefined ? { fog: input.settings.fog } : {}),
49
+ },
50
+ turn: cur.turn,
51
+ });
52
+ for (const o of [...input.opponents].sort((a, b) => a - b)) {
53
+ const t = real.get(o);
54
+ if (!t || t.income <= 0)
55
+ continue;
56
+ const tr = tracker.get(`${cur.turn}:${o}`);
57
+ const e = estimates.find((x) => x.playerId === o);
58
+ const coverage = tr?.coverage ?? tracks.find((x) => x.playerId === o)?.coverage?.share ?? null;
59
+ const sample = {
60
+ turn: cur.turn,
61
+ opponent: o,
62
+ truth: t.income,
63
+ coverage,
64
+ tracker: tr?.estimate ?? null,
65
+ prior: e?.prior ?? null,
66
+ plan: e?.estimate ?? null,
67
+ };
68
+ if (sample.tracker !== null || sample.prior !== null || sample.plan !== null)
69
+ out.push(sample);
70
+ }
71
+ }
72
+ return out;
73
+ }
74
+ /** Each estimator's samples counted by coverage band (E2's `aggregateCalibration`): ratios only. Pure. */
75
+ export function aggregateEstimates(samples) {
76
+ const out = {};
77
+ for (const k of ESTIMATORS) {
78
+ const of = samples.flatMap((s) => (s[k] === null ? [] : [{ turn: s.turn, opponent: s.opponent, estimate: s[k], truth: s.truth, coverage: s.coverage }]));
79
+ if (of.length)
80
+ out[k] = aggregateCalibration(of);
81
+ }
82
+ return out;
83
+ }
84
+ const r3 = (x) => Math.round(x * 1000) / 1000;
85
+ /** {@link RatioStats} read out; `null` without samples. Pure. */
86
+ export function ratioSummary(s) {
87
+ if (!s || s.n <= 0)
88
+ return null;
89
+ const mean = s.sum / s.n;
90
+ return {
91
+ n: s.n,
92
+ mean: r3(mean),
93
+ geoMean: r3(Math.exp(s.logSum / s.n)),
94
+ sd: r3(Math.sqrt(Math.max(0, s.sq / s.n - mean * mean))),
95
+ under: r3(s.under / s.n),
96
+ over: r3(s.over / s.n),
97
+ };
98
+ }
99
+ // ---- (b) the opening benchmark ----
100
+ /** The turns the opening benchmark replays. */
101
+ export const BENCHMARK_TURNS = 8;
102
+ /** "Land without bonuses" (#318 finding 2): this many territories or more on at most {@link LAND_POOR_INCOME}, after {@link GAP_TURN}. */
103
+ export const LAND_POOR_TERRITORIES = 11;
104
+ export const LAND_POOR_INCOME = 8;
105
+ /** The board the opening is judged on, and the gap that lost it (#318 finding 1: an opponent at 1.5× my income). */
106
+ export const GAP_TURN = 4;
107
+ export const GAP_FACTOR = 1.5;
108
+ const simSettingsOf = (s) => ({
109
+ ...(s.offensiveKillRate !== undefined ? { offensiveKillRate: s.offensiveKillRate } : {}),
110
+ ...(s.defensiveKillRate !== undefined ? { defensiveKillRate: s.defensiveKillRate } : {}),
111
+ ...(s.luckModifier !== undefined ? { luckModifier: s.luckModifier } : {}),
112
+ ...(s.roundingMode !== undefined ? { roundingMode: s.roundingMode } : {}),
113
+ ...(s.oneArmyStandsGuard !== undefined ? { oneArmyStandsGuard: s.oneArmyStandsGuard } : {}),
114
+ ...(s.multiAttack !== undefined ? { multiAttack: s.multiAttack } : {}),
115
+ });
116
+ const territory = (territoryId, owner, armies) => ({
117
+ territoryId,
118
+ owner: typeof owner === 'number' ? { kind: 'player', playerId: owner } : owner === 'neutral' ? { kind: 'neutral' } : { kind: 'unknown' },
119
+ armies: owner === 'unknown' ? null : armies,
120
+ });
121
+ /**
122
+ * The next replayed board: land I hold after my replayed orders stays mine with its armies; any other
123
+ * territory an opponent holds on the history board is the history's (owner and armies); the rest keeps
124
+ * its replayed state (a neutral my attack wore down, or one I really took but did not take here). Pure.
125
+ */
126
+ export function overlayHistory(g, sim, history, me) {
127
+ const real = new Map(history.territories.map((t) => [t.territoryId, t]));
128
+ const territories = [];
129
+ for (const id of [...g.territoryById.keys()].sort((a, b) => a - b)) {
130
+ const r = sim.get(id);
131
+ const h = real.get(id);
132
+ if (r?.owner === me)
133
+ territories.push(territory(id, me, r.armies));
134
+ else if (h && h.owner.kind === 'player' && h.owner.playerId !== me)
135
+ territories.push({ territoryId: id, owner: h.owner, armies: h.armies });
136
+ else if (r)
137
+ territories.push(territory(id, r.owner, r.armies));
138
+ else if (h)
139
+ territories.push({ territoryId: id, owner: h.owner.kind === 'player' ? { kind: 'neutral' } : h.owner, armies: h.armies });
140
+ }
141
+ return { source: 'gamefeed', verified: false, territories };
142
+ }
143
+ /**
144
+ * My opening replayed from my real start (see the header for what is approximated): each turn the
145
+ * planner plans on the replayed board, the turn simulator resolves my deploys and moves alone, and the
146
+ * opponents are put back where the history shows them ({@link overlayHistory}). After each turn, my
147
+ * replayed income and territories beside the real ones, the winner's and the best opponent's. Pure.
148
+ */
149
+ export function openingBenchmark(input) {
150
+ const history = new Map(input.history.map((b) => [b.turn, b.board]));
151
+ const start = history.get(0);
152
+ if (!start || !landOf(start, input.me).size)
153
+ return { turns: [], exact: true, stopped: 'no-start' };
154
+ const plan = input.plan ?? planTurn;
155
+ const rules = incomeRules(input.incomeSettings);
156
+ const ids = [...new Set([...input.players.map((p) => p.id), input.me])].sort((a, b) => a - b);
157
+ const teams = new Map(input.players.flatMap((p) => (typeof p.team === 'number' && p.team >= 0 ? [[p.id, p.team]] : [])));
158
+ const sim = simSettingsOf(input.plannerSettings);
159
+ const turns = [];
160
+ let exact = true;
161
+ let board = start;
162
+ for (let n = 1; n <= (input.turns ?? BENCHMARK_TURNS); n++) {
163
+ const next = history.get(n);
164
+ if (!next)
165
+ return { turns, exact, stopped: 'history-ends' };
166
+ const income = boardIncome(input.graph, landOf(board, input.me), rules).total;
167
+ const held = new Map(ids.map((p) => [p, landOf(board, p).size]));
168
+ const p = plan({
169
+ graph: input.graph,
170
+ board,
171
+ me: input.me,
172
+ income,
173
+ settings: input.plannerSettings,
174
+ turn: n,
175
+ game: {
176
+ players: input.players.map((x) => ({ ...x, state: (held.get(x.id) ?? 0) > 0 ? 'Playing' : 'Eliminated' })),
177
+ turn: n,
178
+ fog: 'NoFog',
179
+ },
180
+ });
181
+ const r = simulateTurn({
182
+ graph: input.graph,
183
+ board,
184
+ deploys: p.deploys.map((d) => ({ player: input.me, territoryId: d.territoryId, armies: d.armies })),
185
+ orders: [{ player: input.me, orders: p.moves.map((m) => ({ from: m.from, to: m.to, armies: m.armies })) }],
186
+ moveOrder: [input.me],
187
+ settings: sim,
188
+ ...(teams.size ? { teams } : {}),
189
+ });
190
+ exact &&= r.exact;
191
+ board = overlayHistory(input.graph, r.territories, next, input.me);
192
+ const truth = turnIncomes(input.graph, next, ids, input.incomeSettings);
193
+ const real = truth.get(input.me);
194
+ const winners = input.winners.map((w) => truth.get(w)?.income ?? 0);
195
+ const mineNow = landOf(board, input.me);
196
+ turns.push({
197
+ afterTurn: n,
198
+ replay: { income: boardIncome(input.graph, mineNow, rules).total, territories: mineNow.size },
199
+ real: real && real.territories > 0 ? { income: real.income, territories: real.territories } : null,
200
+ winner: winners.length ? Math.max(...winners) : null,
201
+ bestOpponent: Math.max(0, ...ids.filter((id) => id !== input.me).map((id) => truth.get(id)?.income ?? 0)),
202
+ });
203
+ }
204
+ return { turns, exact };
205
+ }
206
+ const mean = (xs) => r3(xs.reduce((a, b) => a + b, 0) / xs.length);
207
+ /** Many {@link Benchmark}s aggregated. A turn where I held nothing in the real game counts the real income as 0. Pure. */
208
+ export function aggregateBenchmarks(results) {
209
+ const byTurn = new Map();
210
+ for (const r of results)
211
+ for (const t of r.turns)
212
+ byTurn.set(t.afterTurn, [...(byTurn.get(t.afterTurn) ?? []), t]);
213
+ const poor = (x) => x !== null && x.territories >= LAND_POOR_TERRITORIES && x.income <= LAND_POOR_INCOME;
214
+ const behind = (mine, best) => best >= GAP_FACTOR * mine;
215
+ const at = results.flatMap((r) => r.turns.filter((t) => t.afterTurn === GAP_TURN));
216
+ return {
217
+ games: results.length,
218
+ inexact: results.filter((r) => !r.exact).length,
219
+ byTurn: [...byTurn]
220
+ .sort(([a], [b]) => a - b)
221
+ .map(([afterTurn, ts]) => {
222
+ const winners = ts.flatMap((t) => (t.winner === null ? [] : [t.winner]));
223
+ return {
224
+ afterTurn,
225
+ n: ts.length,
226
+ replay: mean(ts.map((t) => t.replay.income)),
227
+ real: mean(ts.map((t) => t.real?.income ?? 0)),
228
+ winner: winners.length ? mean(winners) : null,
229
+ replayAhead: ts.filter((t) => t.replay.income > (t.real?.income ?? 0)).length,
230
+ replayBehind: ts.filter((t) => t.replay.income < (t.real?.income ?? 0)).length,
231
+ };
232
+ }),
233
+ landWithoutBonuses: { replay: at.filter((t) => poor(t.replay)).length, real: at.filter((t) => poor(t.real)).length },
234
+ outpaced: {
235
+ replay: at.filter((t) => behind(t.replay.income, t.bestOpponent)).length,
236
+ real: at.filter((t) => behind(t.real?.income ?? 0, t.bestOpponent)).length,
237
+ },
238
+ };
239
+ }