@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,136 @@
1
+ import { boardIncome, incomeRules } from './player.js';
2
+ const BY_STATE = {
3
+ Won: 'won',
4
+ Eliminated: 'eliminated',
5
+ SurrenderAccepted: 'surrendered',
6
+ Booted: 'booted',
7
+ EndedByVote: 'ended-by-vote',
8
+ };
9
+ /**
10
+ * My outcome from the final player states: my own state when it names an end, else `lost` when
11
+ * another player won, else `unknown` (also when I am not among the players).
12
+ */
13
+ export function outcomeOf(players, me) {
14
+ const mine = players.find((p) => p.id === me);
15
+ if (!mine)
16
+ return 'unknown';
17
+ const named = BY_STATE[mine.state ?? ''];
18
+ if (named)
19
+ return named;
20
+ return players.some((p) => p.id !== me && p.state === 'Won') ? 'lost' : 'unknown';
21
+ }
22
+ const ownerOf = (t) => t?.owner.kind === 'player' ? t.owner.playerId : undefined;
23
+ /**
24
+ * Each of `players` on `board`: its income by THE income rule (`boardIncome`, src/analysis/player.ts:
25
+ * base or per-territory income, plus every full bonus; the map's values with the game's overrides
26
+ * applied by the caller), the bonuses it holds, its territories and armies. A player with no land
27
+ * earns 0 (it is out). Pure.
28
+ */
29
+ export function turnIncomes(g, board, players, settings) {
30
+ const held = new Map(players.map((p) => [p, new Set()]));
31
+ const armies = new Map(players.map((p) => [p, 0]));
32
+ for (const t of board.territories) {
33
+ const o = ownerOf(t);
34
+ if (o === undefined || !held.has(o) || !g.territoryById.has(t.territoryId))
35
+ continue;
36
+ held.get(o).add(t.territoryId);
37
+ const a = armies.get(o);
38
+ armies.set(o, a === null || t.armies === null ? null : a + t.armies);
39
+ }
40
+ const rules = incomeRules(settings);
41
+ const out = new Map();
42
+ for (const p of players) {
43
+ const land = held.get(p);
44
+ if (!land.size) {
45
+ out.set(p, { income: 0, territories: 0, armies: 0, bonuses: [] });
46
+ continue;
47
+ }
48
+ const inc = boardIncome(g, land, rules);
49
+ out.set(p, {
50
+ income: inc.total,
51
+ territories: land.size,
52
+ armies: armies.get(p),
53
+ bonuses: inc.bonuses.map((b) => b.bonusId).sort((a, b) => a - b),
54
+ });
55
+ }
56
+ return out;
57
+ }
58
+ const ascending = (boards) => [...boards].sort((a, b) => a.turn - b.turn);
59
+ const landOf = (board, p) => board.territories
60
+ .filter((t) => ownerOf(t) === p)
61
+ .map((t) => t.territoryId)
62
+ .sort((a, b) => a - b);
63
+ /** Each player's territories on the first board where it holds any (its start). Pure. */
64
+ export function startsOf(boards, players) {
65
+ const out = new Map();
66
+ for (const { board } of ascending(boards))
67
+ for (const p of players) {
68
+ if (out.has(p))
69
+ continue;
70
+ const land = landOf(board, p);
71
+ if (land.length)
72
+ out.set(p, land);
73
+ }
74
+ return out;
75
+ }
76
+ /** The first board, after one where `player` held land, on which it holds none; `null` when never. Pure. */
77
+ export function outTurnOf(boards, player) {
78
+ let held = false;
79
+ for (const { turn, board } of ascending(boards)) {
80
+ const has = board.territories.some((t) => ownerOf(t) === player);
81
+ if (has)
82
+ held = true;
83
+ else if (held)
84
+ return turn;
85
+ }
86
+ return null;
87
+ }
88
+ const side = (t) => ({
89
+ owner: !t ? 'unknown' : t.owner.kind === 'player' ? t.owner.playerId : t.owner.kind === 'neutral' ? 'neutral' : 'unknown',
90
+ armies: t?.armies ?? null,
91
+ });
92
+ /**
93
+ * Every target my cached orders attacked and did not take: for orders of turn T (`orders`, by the
94
+ * turn played), the history boards T − 1 and T; a move into a territory not mine on board T − 1 that
95
+ * is still not mine on board T. Moves into one target in one turn are one entry. Pure.
96
+ */
97
+ export function failedAttacks(boards, orders, me) {
98
+ const byTurn = new Map(boards.map((b) => [b.turn, b.board]));
99
+ const out = [];
100
+ for (const turn of [...orders.keys()].sort((a, b) => a - b)) {
101
+ const was = byTurn.get(turn - 1);
102
+ const now = byTurn.get(turn);
103
+ if (!was || !now)
104
+ continue;
105
+ const before = new Map(was.territories.map((t) => [t.territoryId, t]));
106
+ const after = new Map(now.territories.map((t) => [t.territoryId, t]));
107
+ const hits = new Map();
108
+ for (const m of orders.get(turn).moves) {
109
+ if (ownerOf(before.get(m.to)) === me || ownerOf(after.get(m.to)) === me)
110
+ continue;
111
+ const h = hits.get(m.to) ?? { from: new Set(), sent: 0 };
112
+ h.from.add(m.from);
113
+ h.sent += Math.max(0, m.armies);
114
+ hits.set(m.to, h);
115
+ }
116
+ for (const [to, h] of [...hits].sort(([a], [b]) => a - b))
117
+ out.push({ turn, to, from: [...h.from].sort((a, b) => a - b), sent: h.sent, before: side(before.get(to)), after: side(after.get(to)) });
118
+ }
119
+ return out;
120
+ }
121
+ /** The whole capture of a finished game from its history boards and my orders. Pure. */
122
+ export function captureFinished(input) {
123
+ const ids = input.players.map((p) => p.id).sort((a, b) => a - b);
124
+ const boards = ascending(input.boards);
125
+ return {
126
+ outcome: {
127
+ result: outcomeOf(input.players, input.me),
128
+ turn: input.numberOfTurns ?? null,
129
+ outTurn: outTurnOf(boards, input.me),
130
+ winners: input.players.filter((p) => p.state === 'Won').map((p) => p.id).sort((a, b) => a - b),
131
+ },
132
+ starts: startsOf(boards, ids),
133
+ turns: input.graph ? boards.map(({ turn, board }) => ({ afterTurn: turn, players: turnIncomes(input.graph, board, ids, input.settings) })) : [],
134
+ failedAttacks: failedAttacks(boards, input.orders, input.me),
135
+ };
136
+ }
@@ -0,0 +1,217 @@
1
+ import { turnIncomes } from './finished-game.js';
2
+ import { howLost } from './how-lost.js';
3
+ import { habitsOf, observeTurn } from './opponent-profile.js';
4
+ import { trackOpponents } from './opponents.js';
5
+ const ownsLand = (b, p) => b.territories.some((t) => t.owner.kind === 'player' && t.owner.playerId === p);
6
+ const ascending = (xs) => [...xs].sort((a, b) => a.turn - b.turn);
7
+ /**
8
+ * Each opponent's turns as the history shows them (part C of docs/PLAN-PROFILES.md): every pair of
9
+ * consecutive history boards N, N + 1 is turn N + 1, observed with my orders of that turn when cached
10
+ * (`observeTurn`, the same rules as the live boards; a history board shows everything, so nothing is
11
+ * left out for the fog). Only while I held land on the earlier board: after I am out nothing is
12
+ * between me and anyone. Opponents ascending, turns oldest first; an opponent never observed is left
13
+ * out. Pure.
14
+ */
15
+ export function observeHistory(input) {
16
+ const boards = ascending(input.boards);
17
+ const out = new Map();
18
+ for (let i = 0; i + 1 < boards.length; i++) {
19
+ const was = boards[i];
20
+ const now = boards[i + 1];
21
+ if (now.turn !== was.turn + 1 || !ownsLand(was.board, input.me))
22
+ continue;
23
+ const turn = was.turn + 1;
24
+ const seen = observeTurn({
25
+ graph: input.graph,
26
+ me: input.me,
27
+ previous: was.board,
28
+ current: now.board,
29
+ orders: input.orders.get(turn),
30
+ settings: input.settings,
31
+ opponents: input.opponents,
32
+ ...(input.cards !== undefined ? { cards: input.cards } : {}),
33
+ });
34
+ for (const [o, primitives] of seen) {
35
+ const list = out.get(o) ?? [];
36
+ list.push({ turn, primitives });
37
+ out.set(o, list);
38
+ }
39
+ }
40
+ return new Map([...out].sort(([a], [b]) => a - b));
41
+ }
42
+ /** {@link observeHistory} added up into habits per opponent (`habitsOf`). Pure. */
43
+ export function historyHabits(input) {
44
+ return new Map([...observeHistory(input)].map(([o, turns]) => [o, habitsOf(turns)]));
45
+ }
46
+ /** `player`'s curve from the capture's turns (`FinishedCapture.turns`). Pure. */
47
+ export function incomeCurve(turns, player) {
48
+ return turns
49
+ .flatMap((t) => {
50
+ const p = t.players.get(player);
51
+ return p ? [{ afterTurn: t.afterTurn, income: p.income }] : [];
52
+ })
53
+ .sort((a, b) => a.afterTurn - b.afterTurn);
54
+ }
55
+ /** The turns of no growth that make an income flat (#312: "slope ≈ 0 for 3+ turns"). */
56
+ export const FLAT_TURNS = 3;
57
+ /** What counts as no growth over those turns: at most this share of the income (and at least 1 army). */
58
+ export const FLAT_TOLERANCE = 0.1;
59
+ /**
60
+ * The first board (by completed turns, the opening's board 0 left out) from which my income stayed
61
+ * within {@link FLAT_TOLERANCE} of it (at least 1) on each of the next {@link FLAT_TURNS} consecutive
62
+ * boards, while I held land; `null` when it never did. Pure.
63
+ */
64
+ export function flatTurn(curve) {
65
+ const at = new Map(curve.map((c) => [c.afterTurn, c.income]));
66
+ for (const { afterTurn, income } of [...curve].sort((a, b) => a.afterTurn - b.afterTurn)) {
67
+ if (afterTurn < 1 || income <= 0)
68
+ continue;
69
+ const tol = Math.max(1, FLAT_TOLERANCE * income);
70
+ let flat = true;
71
+ for (let k = 1; k <= FLAT_TURNS && flat; k++) {
72
+ const next = at.get(afterTurn + k);
73
+ flat = next !== undefined && next > 0 && Math.abs(next - income) <= tol;
74
+ }
75
+ if (flat)
76
+ return afterTurn;
77
+ }
78
+ return null;
79
+ }
80
+ /** The bonuses with a member territory in `start`, ascending. Pure. */
81
+ export function startRegion(g, start) {
82
+ const set = new Set(start);
83
+ const bonuses = [...g.bonusById.values()].filter((b) => b.territoryIds.some((t) => set.has(t))).map((b) => b.id).sort((a, b) => a - b);
84
+ return { territories: [...start].sort((a, b) => a - b), bonuses };
85
+ }
86
+ /** Income curve points kept per game (the opening and the middle game: the pace). */
87
+ export const MAX_CURVE_POINTS = 60;
88
+ /** The boards the pace is read on: the income after these completed turns. */
89
+ export const PACE_TURNS = [4, 8];
90
+ const incomeAfter = (curve, n) => curve.find((c) => c.afterTurn === n)?.income ?? null;
91
+ /**
92
+ * My start region and income curve (index = completed turns, `null` where no board read, at most
93
+ * {@link MAX_CURVE_POINTS}), and each winner's start region and income after turns 4 and 8 (the pace
94
+ * to beat). Pure.
95
+ */
96
+ export function mapFacts(g, me, winners, starts, turns) {
97
+ const mine = incomeCurve(turns, me);
98
+ const last = Math.min(MAX_CURVE_POINTS, mine.length ? mine.at(-1).afterTurn + 1 : 0);
99
+ const income = Array.from({ length: last }, (_, i) => incomeAfter(mine, i));
100
+ const pace = (curve) => ({ income4: incomeAfter(curve, PACE_TURNS[0]), income8: incomeAfter(curve, PACE_TURNS[1]) });
101
+ return {
102
+ me: { ...startRegion(g, starts.get(me) ?? []), income, ...pace(mine) },
103
+ winners: [...winners].sort((a, b) => a - b).map((w) => ({ ...startRegion(g, starts.get(w) ?? []), ...pace(incomeCurve(turns, w)) })),
104
+ };
105
+ }
106
+ /**
107
+ * How I lost, from the history (full boards): eliminated → `howLost` on the history boards (numbered
108
+ * by the turn played on them; a history board carries no special units, so a game with commanders
109
+ * reads `unknown`); surrendered or booted → that, on my out turn; lost while still holding land (a team
110
+ * game my side lost) → `still-holding`. `null` for a game I did not lose. Pure.
111
+ */
112
+ export function lessonLoss(input) {
113
+ const { result } = input;
114
+ if (result === 'surrendered' || result === 'booted')
115
+ return { cause: result, turn: input.outTurn };
116
+ if (result === 'lost')
117
+ return { cause: 'still-holding', turn: input.numberOfTurns };
118
+ if (result !== 'eliminated')
119
+ return null;
120
+ const s = input.settings;
121
+ const loss = howLost({
122
+ me: input.me,
123
+ boards: input.boards.map((b) => ({ turn: b.turn + 1, board: b.board })),
124
+ orders: input.orders,
125
+ adjacency: input.graph.neighbors,
126
+ rates: {
127
+ ...(s?.offensiveKillRate !== undefined ? { offensiveKillRate: s.offensiveKillRate } : {}),
128
+ ...(s?.defensiveKillRate !== undefined ? { defensiveKillRate: s.defensiveKillRate } : {}),
129
+ ...(s?.luckModifier !== undefined ? { luck: s.luckModifier } : {}),
130
+ ...(s?.roundingMode !== undefined ? { rounding: s.roundingMode } : {}),
131
+ },
132
+ ...(input.numberOfTurns !== null ? { turnsCompleted: input.numberOfTurns } : {}),
133
+ ...(s?.commanders !== undefined ? { commanders: s.commanders } : {}),
134
+ });
135
+ return loss ? { cause: loss.cause, turn: loss.turn } : { cause: 'unknown', turn: input.outTurn };
136
+ }
137
+ /**
138
+ * For each turn T I cached a board for and the history has the board T was played on: every
139
+ * opponent with land there and a tracked income (`trackOpponents` over my cached boards up to T, as
140
+ * the plan and the track tool read them), the estimate beside the truth and the coverage. Pure.
141
+ */
142
+ export function calibrationSamples(input) {
143
+ const truthBoard = new Map(input.history.map((b) => [b.turn, b.board]));
144
+ const cached = ascending(input.cached);
145
+ const scored = new Set(input.opponents);
146
+ const out = [];
147
+ for (const { turn } of cached) {
148
+ const truth = truthBoard.get(turn - 1);
149
+ if (!truth)
150
+ continue;
151
+ const upTo = cached.filter((b) => b.turn <= turn);
152
+ if (upTo.length < 2)
153
+ continue;
154
+ const tracks = trackOpponents(input.graph, upTo, input.me, input.plannerSettings, input.game);
155
+ const real = turnIncomes(input.graph, truth, input.opponents, input.incomeSettings);
156
+ for (const track of [...tracks].sort((a, b) => a.playerId - b.playerId)) {
157
+ if (!scored.has(track.playerId) || track.income === null)
158
+ continue;
159
+ const t = real.get(track.playerId);
160
+ if (!t || t.income <= 0)
161
+ continue;
162
+ out.push({ turn, opponent: track.playerId, estimate: track.income, truth: t.income, coverage: track.coverage?.share ?? null });
163
+ }
164
+ }
165
+ return out;
166
+ }
167
+ /** The coverage buckets a sample is counted in. */
168
+ export const COVERAGE_BUCKETS = ['none', 'under-25', '25-50', '50-75', '75-up'];
169
+ export function coverageBucket(share) {
170
+ if (share === null)
171
+ return 'none';
172
+ if (share < 0.25)
173
+ return 'under-25';
174
+ if (share < 0.5)
175
+ return '25-50';
176
+ if (share < 0.75)
177
+ return '50-75';
178
+ return '75-up';
179
+ }
180
+ /** A ratio under this reads low; over {@link CALIBRATION_HIGH}, high. */
181
+ export const CALIBRATION_LOW = 0.5;
182
+ export const CALIBRATION_HIGH = 1.5;
183
+ const round = (x) => Math.round(x * 1e6) / 1e6;
184
+ /** The samples counted by coverage bucket (aggregates only: no turn, no player). Pure. */
185
+ export function aggregateCalibration(samples) {
186
+ const out = {};
187
+ for (const s of samples) {
188
+ const r = s.estimate / s.truth;
189
+ const b = coverageBucket(s.coverage);
190
+ const x = out[b] ?? { n: 0, sum: 0, sq: 0, logSum: 0, under: 0, over: 0 };
191
+ out[b] = {
192
+ n: x.n + 1,
193
+ sum: round(x.sum + r),
194
+ sq: round(x.sq + r * r),
195
+ logSum: round(x.logSum + Math.log(Math.max(r, 1e-6))),
196
+ under: x.under + (r < CALIBRATION_LOW ? 1 : 0),
197
+ over: x.over + (r > CALIBRATION_HIGH ? 1 : 0),
198
+ };
199
+ }
200
+ return out;
201
+ }
202
+ /** Two calibrations added, `b` scaled (−1 takes it back out). Pure. */
203
+ export function addCalibration(a, b, scale = 1) {
204
+ const out = {};
205
+ for (const k of COVERAGE_BUCKETS) {
206
+ const x = a[k];
207
+ const y = b[k];
208
+ if (!x && !y)
209
+ continue;
210
+ const z = { n: 0, sum: 0, sq: 0, logSum: 0, under: 0, over: 0 };
211
+ for (const f of Object.keys(z))
212
+ z[f] = round((x?.[f] ?? 0) + scale * (y?.[f] ?? 0));
213
+ if (z.n > 0)
214
+ out[k] = z;
215
+ }
216
+ return out;
217
+ }
@@ -0,0 +1,82 @@
1
+ // Territory adjacency graph and breadth-first search over a GameMap.
2
+ //
3
+ // Pure and deterministic: adjacency lists are symmetrized, de-duplicated and
4
+ // sorted ascending, so every search visits neighbours in the same order and
5
+ // ties always resolve toward the lower territory id.
6
+ const EMPTY = Object.freeze([]);
7
+ /**
8
+ * Build the graph. A link is kept when either side declares it (maps are not
9
+ * always symmetric); self-links and links to unknown territories are dropped.
10
+ */
11
+ export function buildGraph(map) {
12
+ const territoryById = new Map(map.territories.map((t) => [t.id, t]));
13
+ const sets = new Map();
14
+ for (const t of map.territories)
15
+ sets.set(t.id, new Set());
16
+ for (const t of map.territories) {
17
+ for (const n of t.connectedTo) {
18
+ if (n === t.id || !territoryById.has(n))
19
+ continue;
20
+ sets.get(t.id).add(n);
21
+ sets.get(n).add(t.id);
22
+ }
23
+ }
24
+ const neighbors = new Map();
25
+ for (const [id, s] of sets)
26
+ neighbors.set(id, [...s].sort((a, b) => a - b));
27
+ return { map, territoryById, bonusById: new Map(map.bonuses.map((b) => [b.id, b])), neighbors };
28
+ }
29
+ export function neighborsOf(g, id) {
30
+ return g.neighbors.get(id) ?? EMPTY;
31
+ }
32
+ /** Hop distance from the nearest source to every reachable territory. Unknown sources are ignored. */
33
+ export function bfsDistances(g, sources, opts = {}) {
34
+ const dist = new Map();
35
+ const queue = [];
36
+ for (const s of [...sources].sort((a, b) => a - b)) {
37
+ if (g.territoryById.has(s) && !dist.has(s)) {
38
+ dist.set(s, 0);
39
+ queue.push(s);
40
+ }
41
+ }
42
+ for (let head = 0; head < queue.length; head++) {
43
+ const v = queue[head];
44
+ const d = dist.get(v) + 1;
45
+ for (const n of neighborsOf(g, v)) {
46
+ if (dist.has(n) || (opts.passable && !opts.passable(n)))
47
+ continue;
48
+ dist.set(n, d);
49
+ queue.push(n);
50
+ }
51
+ }
52
+ return dist;
53
+ }
54
+ /** Shortest path (inclusive of both ends), or `null` when either end is unknown or unreachable. */
55
+ export function shortestPath(g, from, to) {
56
+ if (!g.territoryById.has(from) || !g.territoryById.has(to))
57
+ return null;
58
+ const prev = new Map([[from, from]]);
59
+ const queue = [from];
60
+ for (let head = 0; head < queue.length && !prev.has(to); head++) {
61
+ const v = queue[head];
62
+ for (const n of neighborsOf(g, v)) {
63
+ if (prev.has(n))
64
+ continue;
65
+ prev.set(n, v);
66
+ queue.push(n);
67
+ }
68
+ }
69
+ if (!prev.has(to))
70
+ return null;
71
+ const path = [to];
72
+ for (let v = to; v !== from;) {
73
+ v = prev.get(v);
74
+ path.push(v);
75
+ }
76
+ return path.reverse();
77
+ }
78
+ /** Hops between two territories, or `null` when unknown or unreachable. */
79
+ export function distance(g, from, to) {
80
+ const p = shortestPath(g, from, to);
81
+ return p ? p.length - 1 : null;
82
+ }
@@ -0,0 +1,54 @@
1
+ import { neighborsOf } from './graph.js';
2
+ export function guardOffExposure(args) {
3
+ const { graph, board, me } = args;
4
+ const friends = args.friends ?? new Set();
5
+ const byId = new Map(board.territories.map((t) => [t.territoryId, t]));
6
+ const ownerOf = (id) => {
7
+ const o = byId.get(id)?.owner;
8
+ return o?.kind === 'player' ? o.playerId : undefined;
9
+ };
10
+ const isMine = (id) => ownerOf(id) === me;
11
+ const isEnemy = (id) => {
12
+ const p = ownerOf(id);
13
+ return p !== undefined && p !== me && !friends.has(p);
14
+ };
15
+ const hidden = (id) => {
16
+ const t = byId.get(id);
17
+ return !t || t.owner.kind === 'unknown' || t.armies === null;
18
+ };
19
+ const left = new Map();
20
+ for (const t of board.territories)
21
+ if (isMine(t.territoryId))
22
+ left.set(t.territoryId, t.armies ?? 0);
23
+ for (const d of args.deploys)
24
+ if (left.has(d.territoryId))
25
+ left.set(d.territoryId, left.get(d.territoryId) + d.armies);
26
+ for (const m of args.moves) {
27
+ if (left.has(m.from))
28
+ left.set(m.from, Math.max(0, left.get(m.from) - m.armies));
29
+ if (left.has(m.to))
30
+ left.set(m.to, left.get(m.to) + m.armies);
31
+ }
32
+ const hasMyCommander = (id) => byId.get(id)?.specialUnits?.some((u) => u.kind === 'commander' && u.playerId === me) ?? false;
33
+ const emptied = [...left.entries()]
34
+ .filter(([id, n]) => n === 0 && !hasMyCommander(id) && neighborsOf(graph, id).some((x) => isEnemy(x) || hidden(x)))
35
+ .map(([id]) => id)
36
+ .sort((a, b) => a - b);
37
+ const attacked = new Set(args.moves.map((m) => m.to));
38
+ const breaks = [];
39
+ for (const t of [...board.territories].sort((a, b) => a.territoryId - b.territoryId)) {
40
+ const id = t.territoryId;
41
+ const owner = ownerOf(id);
42
+ if (owner === undefined || !isEnemy(id) || t.armies !== 0 || t.specialUnits?.length || attacked.has(id))
43
+ continue;
44
+ const from = neighborsOf(graph, id).filter(isMine).sort((a, b) => a - b)[0];
45
+ if (from === undefined)
46
+ continue;
47
+ const held = [...graph.bonusById.values()]
48
+ .filter((b) => b.value > 0 && b.territoryIds.includes(id) && b.territoryIds.every((x) => ownerOf(x) === owner))
49
+ .sort((a, b) => b.value - a.value || a.id - b.id)[0];
50
+ if (held)
51
+ breaks.push({ territoryId: id, from, playerId: owner, bonusId: held.id, value: held.value });
52
+ }
53
+ return { emptied, breaks };
54
+ }