@chrischall/warapp-mcp 0.0.0 → 0.1.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 (177) hide show
  1. package/.claude-plugin/marketplace.json +4 -4
  2. package/.claude-plugin/plugin.json +2 -2
  3. package/README.md +199 -8
  4. package/dist/analysis/award.js +159 -0
  5. package/dist/analysis/bonuses.js +98 -0
  6. package/dist/analysis/breach.js +62 -0
  7. package/dist/analysis/card-support.js +329 -0
  8. package/dist/analysis/card-threats.js +234 -0
  9. package/dist/analysis/cards-in-effect.js +130 -0
  10. package/dist/analysis/chains.js +59 -0
  11. package/dist/analysis/chokepoints.js +140 -0
  12. package/dist/analysis/combat.js +231 -0
  13. package/dist/analysis/commander-safety.js +149 -0
  14. package/dist/analysis/commitments.js +338 -0
  15. package/dist/analysis/exchange.js +155 -0
  16. package/dist/analysis/graph.js +82 -0
  17. package/dist/analysis/guard-off.js +54 -0
  18. package/dist/analysis/guess.js +351 -0
  19. package/dist/analysis/headroom.js +241 -0
  20. package/dist/analysis/hold-diff.js +64 -0
  21. package/dist/analysis/how-lost.js +130 -0
  22. package/dist/analysis/index.js +14 -0
  23. package/dist/analysis/local-deploy.js +159 -0
  24. package/dist/analysis/lookahead.js +108 -0
  25. package/dist/analysis/opponent-profile.js +551 -0
  26. package/dist/analysis/opponents.js +1245 -0
  27. package/dist/analysis/outlook.js +633 -0
  28. package/dist/analysis/overrides.js +60 -0
  29. package/dist/analysis/picks.js +1879 -0
  30. package/dist/analysis/plan/after-leftover.js +140 -0
  31. package/dist/analysis/plan/cap-spend.js +242 -0
  32. package/dist/analysis/plan/captures.js +1195 -0
  33. package/dist/analysis/plan/commander.js +236 -0
  34. package/dist/analysis/plan/completed.js +29 -0
  35. package/dist/analysis/plan/conceded-out.js +131 -0
  36. package/dist/analysis/plan/estimates.js +715 -0
  37. package/dist/analysis/plan/guard-off.js +232 -0
  38. package/dist/analysis/plan/holds.js +1631 -0
  39. package/dist/analysis/plan/leftover.js +760 -0
  40. package/dist/analysis/plan/move-order.js +319 -0
  41. package/dist/analysis/plan/orders.js +317 -0
  42. package/dist/analysis/plan/relations.js +702 -0
  43. package/dist/analysis/plan/report.js +672 -0
  44. package/dist/analysis/plan/shared.js +1218 -0
  45. package/dist/analysis/plan/stand-still.js +823 -0
  46. package/dist/analysis/plan/state.js +44 -0
  47. package/dist/analysis/plan/strike.js +1416 -0
  48. package/dist/analysis/plan/targets.js +651 -0
  49. package/dist/analysis/plan/team.js +299 -0
  50. package/dist/analysis/plan/threats.js +927 -0
  51. package/dist/analysis/plan/transfers.js +328 -0
  52. package/dist/analysis/plan/util.js +5 -0
  53. package/dist/analysis/plan/vacated.js +285 -0
  54. package/dist/analysis/planner.js +2922 -0
  55. package/dist/analysis/player-record.js +144 -0
  56. package/dist/analysis/player.js +268 -0
  57. package/dist/analysis/profile.js +347 -0
  58. package/dist/analysis/relations.js +1030 -0
  59. package/dist/analysis/schedule.js +88 -0
  60. package/dist/analysis/since-last.js +50 -0
  61. package/dist/analysis/static-seats.js +71 -0
  62. package/dist/analysis/stress.js +577 -0
  63. package/dist/analysis/team-brief.js +151 -0
  64. package/dist/analysis/tripwire.js +644 -0
  65. package/dist/analysis/turn-sim.js +259 -0
  66. package/dist/analysis/whereabouts.js +1109 -0
  67. package/dist/board.js +105 -0
  68. package/dist/bundle.js +117959 -36172
  69. package/dist/cards.js +435 -0
  70. package/dist/chat-cursor.js +135 -0
  71. package/dist/chat.js +192 -0
  72. package/dist/client.js +361 -0
  73. package/dist/config.js +62 -0
  74. package/dist/direct/link.js +102 -0
  75. package/dist/direct/session.js +267 -0
  76. package/dist/direct/transport.js +424 -0
  77. package/dist/guess-salt.js +65 -0
  78. package/dist/hosted.js +24 -0
  79. package/dist/index.js +33 -0
  80. package/dist/join-color.js +140 -0
  81. package/dist/live.js +278 -0
  82. package/dist/map-stats.js +152 -0
  83. package/dist/map-store.js +204 -0
  84. package/dist/move-order.js +141 -0
  85. package/dist/my-games.js +180 -0
  86. package/dist/normalize.js +411 -0
  87. package/dist/open-games.js +537 -0
  88. package/dist/outlook-log.js +138 -0
  89. package/dist/path-lock.js +22 -0
  90. package/dist/pick-list.js +193 -0
  91. package/dist/player-record-store.js +229 -0
  92. package/dist/player-states.js +31 -0
  93. package/dist/profile-store.js +677 -0
  94. package/dist/protocol/bundle.js +375 -0
  95. package/dist/protocol/codec.js +556 -0
  96. package/dist/protocol/decoded.js +12 -0
  97. package/dist/protocol/interp.js +1904 -0
  98. package/dist/protocol/methods.js +531 -0
  99. package/dist/protocol/rpc.js +202 -0
  100. package/dist/push/listener.js +393 -0
  101. package/dist/push/packets.js +66 -0
  102. package/dist/push/socketio.js +333 -0
  103. package/dist/push/websocket.js +179 -0
  104. package/dist/redact.js +62 -0
  105. package/dist/relations-store.js +242 -0
  106. package/dist/replay.js +215 -0
  107. package/dist/scalars.js +28 -0
  108. package/dist/scout.js +346 -0
  109. package/dist/stats.js +269 -0
  110. package/dist/strategy/card-clock.js +185 -0
  111. package/dist/strategy/map-notes.js +128 -0
  112. package/dist/strategy/notes.js +2168 -0
  113. package/dist/team-cards.js +84 -0
  114. package/dist/team-orders.js +150 -0
  115. package/dist/teams.js +19 -0
  116. package/dist/tools/award.js +206 -0
  117. package/dist/tools/begin-turn.js +162 -0
  118. package/dist/tools/board.js +77 -0
  119. package/dist/tools/card-advice.js +256 -0
  120. package/dist/tools/card-effects.js +49 -0
  121. package/dist/tools/card-plays.js +434 -0
  122. package/dist/tools/card-support-advice.js +140 -0
  123. package/dist/tools/chat-inbox.js +146 -0
  124. package/dist/tools/chat.js +483 -0
  125. package/dist/tools/check-plan.js +688 -0
  126. package/dist/tools/commander-check.js +102 -0
  127. package/dist/tools/commitments.js +216 -0
  128. package/dist/tools/common.js +143 -0
  129. package/dist/tools/diplomacy.js +342 -0
  130. package/dist/tools/game.js +126 -0
  131. package/dist/tools/guess-view.js +56 -0
  132. package/dist/tools/healthcheck.js +90 -0
  133. package/dist/tools/hints.js +34 -0
  134. package/dist/tools/how-lost.js +154 -0
  135. package/dist/tools/index.js +142 -0
  136. package/dist/tools/join-game.js +327 -0
  137. package/dist/tools/leave-game.js +181 -0
  138. package/dist/tools/live-context.js +339 -0
  139. package/dist/tools/live.js +404 -0
  140. package/dist/tools/map-stats.js +117 -0
  141. package/dist/tools/map.js +133 -0
  142. package/dist/tools/my-games.js +123 -0
  143. package/dist/tools/open-games.js +104 -0
  144. package/dist/tools/opponents.js +151 -0
  145. package/dist/tools/order-options.js +135 -0
  146. package/dist/tools/picks.js +292 -0
  147. package/dist/tools/profile-hook.js +156 -0
  148. package/dist/tools/profile-opponents.js +121 -0
  149. package/dist/tools/profile-reads.js +99 -0
  150. package/dist/tools/push.js +385 -0
  151. package/dist/tools/relations.js +611 -0
  152. package/dist/tools/resolve.js +45 -0
  153. package/dist/tools/route.js +36 -0
  154. package/dist/tools/scout.js +87 -0
  155. package/dist/tools/session.js +163 -0
  156. package/dist/tools/strategy.js +200 -0
  157. package/dist/tools/stress-opponents.js +83 -0
  158. package/dist/tools/surrender.js +240 -0
  159. package/dist/tools/survival.js +189 -0
  160. package/dist/tools/team-brief.js +266 -0
  161. package/dist/tools/team-source.js +222 -0
  162. package/dist/tools/team.js +182 -0
  163. package/dist/tools/turn.js +2761 -0
  164. package/dist/tools/uncommit.js +160 -0
  165. package/dist/tools/where.js +275 -0
  166. package/dist/tools/write-kit.js +158 -0
  167. package/dist/transport-bridge.js +33 -0
  168. package/dist/trend.js +452 -0
  169. package/dist/version.js +4 -0
  170. package/manifest.json +174 -4
  171. package/mint.yaml +101 -14
  172. package/package.json +11 -6
  173. package/server.json +40 -3
  174. package/skills/warapp-api/SKILL.md +95 -4
  175. package/skills/warapp-api/references/scout.mjs +348 -0
  176. package/skills/warapp-api/scripts/warapp.sh +69 -8
  177. package/skills/warapp-mcp/SKILL.md +969 -21
@@ -0,0 +1,241 @@
1
+ // The headroom table (#275 a): for every border of mine, the smallest single deploy by a neighbouring
2
+ // opponent that takes it after my orders, and what falls with it. Pure and deterministic; ties resolve
3
+ // on ascending ids.
4
+ //
5
+ // The play session worked this out by hand every turn, and it was the most useful number it had: a
6
+ // hold sized for an estimate is only as good as the estimate, and the estimate is a floor (#275,
7
+ // pattern 1). Headroom says how wrong the estimate may be before a border goes.
8
+ //
9
+ // A border is a territory I hold after my orders, unanswered (captures included), beside a territory
10
+ // of an opponent whose armies are in view. For each such stack the opponent deploys d on it and attacks
11
+ // the border with everything the stack can move (its commander too), on the turn simulator
12
+ // (turn-sim.ts) with my deploys and orders, under both move orders unless the first mover is known, and
13
+ // at every place in the zigzag it can reach: it may hold the attack back behind filler orders (assumed
14
+ // to have them), so it lands before my first order, between two, or after my last — a border my later
15
+ // orders drain is met drained. Places where the same number of my orders touching the border or the
16
+ // stack has run are alike, and only one of each is tried.
17
+ // The border's headroom is the smallest d that leaves the opponent holding it at the end of the turn,
18
+ // over every stack beside it and both orders; 0 when a stack already takes it with no deploy. One
19
+ // opponent and one attack: two stacks together, several opponents, chains, cards and Local Deployment's
20
+ // bound on where the deploy lands are not tried (warapp_check_plan's stress test tries several).
21
+ //
22
+ // What falls with it: the bonuses I hold after my orders that it is in, and `behind` — my territories
23
+ // beside it that face no enemy, one step behind it — with `behindIncome`, the bonuses they complete
24
+ // that the border's own fall does not already break. And `breach` (#275, pattern 2): the territories
25
+ // within two steps behind it that only it shields (src/analysis/breach.ts: none faces an enemy or the
26
+ // fog, and no other front of mine is within two steps of them), with the bonuses I hold that they are
27
+ // in (the border's own left out) — what a breach walks into when the interior holds nothing: only a
28
+ // territory none of mine beside it (itself included) holds the stack that takes the border at its
29
+ // headroom counts, and with no deploy taking it the breach is empty. The
30
+ // planner counts BREACH_WEIGHT of it in the border's value with the guard off; the row gives it always.
31
+ import { bonusTerritories } from './bonuses.js';
32
+ import { breachBehind } from './breach.js';
33
+ import { neutralizeSeats } from './static-seats.js';
34
+ import { armiesToTake, COMMANDER_STRENGTH } from './combat.js';
35
+ import { neighborsOf } from './graph.js';
36
+ import { simTerritories, simulateTurn } from './turn-sim.js';
37
+ /** The largest deploy searched; a border no deploy up to it takes has `deploy: null`. */
38
+ export const HEADROOM_CAP = 100_000;
39
+ const byNum = (a, b) => a - b;
40
+ export function headroomTable(input) {
41
+ const { graph, me } = input;
42
+ const board = input.staticSeats ? neutralizeSeats(input.board, input.staticSeats) : input.board;
43
+ const teams = input.teams;
44
+ const start = simTerritories(board);
45
+ const sameTeam = (a, b) => teams !== undefined && teams.get(a) !== undefined && teams.get(a) === teams.get(b);
46
+ const enemy = (owner) => typeof owner === 'number' && owner !== me && !sameTeam(owner, me);
47
+ const myDeploys = input.deploys.map((d) => ({ player: me, territoryId: d.territoryId, armies: d.armies }));
48
+ const myOrders = input.moves.map((m) => ({ ...m }));
49
+ const rates = { offensiveKillRate: input.settings?.offensiveKillRate, defensiveKillRate: input.settings?.defensiveKillRate };
50
+ const guard = input.settings?.oneArmyStandsGuard === false ? 0 : 1;
51
+ // The opponent may hold its attack back behind filler orders (any transfer of its own), so it can land
52
+ // after any number of my orders: before my first, between two, or after my last. The fillers run between
53
+ // two territories of its own outside the map (ids past the map's), which touch nothing on the board.
54
+ const maxId = Math.max(0, ...graph.territoryById.keys(), ...start.keys());
55
+ const FILL_A = maxId + 1;
56
+ const FILL_B = maxId + 2;
57
+ const fillGraph = {
58
+ ...graph,
59
+ neighbors: new Map([...graph.neighbors, [FILL_A, [FILL_B]], [FILL_B, [FILL_A]]]),
60
+ };
61
+ const fillStart = (player) => new Map([...start, [FILL_A, { owner: player, armies: myOrders.length + 2 + guard }], [FILL_B, { owner: player, armies: guard }]]);
62
+ const run = (attack, first) => simulateTurn({
63
+ graph: attack?.fillers ? fillGraph : graph,
64
+ board,
65
+ ...(attack?.fillers ? { start: fillStart(attack.player) } : {}),
66
+ deploys: [...myDeploys, ...(attack && attack.deploy > 0 ? [{ player: attack.player, territoryId: attack.from, armies: attack.deploy }] : [])],
67
+ orders: [
68
+ { player: me, orders: myOrders },
69
+ ...(attack
70
+ ? [
71
+ {
72
+ player: attack.player,
73
+ orders: [
74
+ ...Array.from({ length: attack.fillers }, () => ({ from: FILL_A, to: FILL_B, armies: 1 })),
75
+ {
76
+ from: attack.from,
77
+ to: attack.to,
78
+ armies: (start.get(attack.from)?.armies ?? 0) + attack.deploy,
79
+ ...(start.get(attack.from)?.commander === attack.player ? { withCommander: true } : {}),
80
+ },
81
+ ],
82
+ },
83
+ ]
84
+ : []),
85
+ ],
86
+ moveOrder: attack ? (first === 'me' ? [me, attack.player] : [attack.player, me]) : [me],
87
+ ...(input.settings ? { settings: input.settings } : {}),
88
+ ...(teams ? { teams } : {}),
89
+ ...(input.orderPriority ? { orderPriority: [me] } : {}),
90
+ });
91
+ /**
92
+ * The filler counts worth trying for an attack from `s` on `b`: the attack, as the opponent's order
93
+ * `k` (0-based), runs after `mineBefore(k)` of my orders (zigzag, every order taking its slot). Two
94
+ * counts are alike when the same number of my orders touching `b` or `s` (from or to) ran before the
95
+ * attack: the attack meets the same armies and the same later orders. One count per kind, fewest first.
96
+ */
97
+ const fillerCounts = (b, s, first) => {
98
+ const n = myOrders.length;
99
+ const meFirst = input.orderPriority === true || first === 'me';
100
+ const mineBefore = (k) => {
101
+ let mine = 0;
102
+ let theirs = 0;
103
+ for (let round = 0;; round++) {
104
+ const row = (round % 2 === 0) === meFirst ? ['me', 'them'] : ['them', 'me'];
105
+ for (const who of row) {
106
+ if (who === 'me')
107
+ mine = Math.min(n, mine + 1);
108
+ else if (theirs++ === k)
109
+ return mine;
110
+ }
111
+ }
112
+ };
113
+ const touches = myOrders.map((o) => o.from === b || o.to === b || o.from === s || o.to === s);
114
+ const seen = new Set();
115
+ const out = [];
116
+ for (let k = 0; k <= n; k++) {
117
+ const m = mineBefore(k);
118
+ const kind = touches.slice(0, m).filter(Boolean).length;
119
+ if (seen.has(kind))
120
+ continue;
121
+ seen.add(kind);
122
+ out.push(k);
123
+ }
124
+ return out;
125
+ };
126
+ const baseline = run(undefined, 'me');
127
+ const mineAfter = new Set([...baseline.territories].filter(([, t]) => t.owner === me).map(([id]) => id));
128
+ const bonusIds = [...graph.bonusById.keys()].sort(byNum);
129
+ const held = bonusIds.filter((id) => {
130
+ const ts = bonusTerritories(graph, id);
131
+ return ts.length > 0 && ts.every((t) => mineAfter.has(t));
132
+ });
133
+ const value = (id) => graph.bonusById.get(id)?.value ?? 0;
134
+ /** A territory of mine beside an enemy stack (its owner shown, armies in view). */
135
+ const facesEnemy = (id) => neighborsOf(graph, id).some((n) => enemy(start.get(n)?.owner));
136
+ /** #275: a territory of mine beside an enemy stack or the fog (an owner the board does not show). */
137
+ const front = (id) => neighborsOf(graph, id).some((n) => enemy(start.get(n)?.owner) || (start.get(n)?.owner ?? 'unknown') === 'unknown');
138
+ /** What `player`'s stack on `s` sends with no deploy (its commander counted). */
139
+ const sendsFrom = (s, player) => Math.max(0, (start.get(s)?.armies ?? 0) - guard) + (start.get(s)?.commander === player ? COMMANDER_STRENGTH : 0);
140
+ const rows = [];
141
+ for (const b of [...mineAfter].sort(byNum)) {
142
+ const stacks = neighborsOf(graph, b)
143
+ .filter((n) => enemy(start.get(n)?.owner))
144
+ .sort(byNum);
145
+ if (!stacks.length)
146
+ continue;
147
+ const there = baseline.territories.get(b);
148
+ let best;
149
+ const orders = input.firstMover ? [input.firstMover] : ['me', 'opponent'];
150
+ for (const s of stacks) {
151
+ const player = start.get(s).owner;
152
+ const takes = (d, first, fills) => fills.some((fillers) => run({ player, from: s, to: b, deploy: d, fillers }, first).territories.get(b)?.owner === player);
153
+ const found = orders.map((first) => {
154
+ // A guess from the board after my orders: what takes it, less what the stack sends.
155
+ const defenders = there.armies + (there.commander === me ? COMMANDER_STRENGTH : 0);
156
+ const sends = sendsFrom(s, player);
157
+ const guess = Math.max(0, (armiesToTake(defenders, rates) ?? HEADROOM_CAP) - sends);
158
+ const fills = fillerCounts(b, s, first);
159
+ return { first, deploy: smallest((d) => takes(d, first, fills), Math.min(guess, HEADROOM_CAP)) };
160
+ });
161
+ const min = found.reduce((m, f) => (f.deploy === null ? m : m === null ? f.deploy : Math.min(m, f.deploy)), null);
162
+ const firstMover = orders.length > 1 && min !== null && found.filter((f) => f.deploy === min).length === 1 ? found.find((f) => f.deploy === min).first : undefined;
163
+ if (!best || (min !== null && (best.deploy === null || min < best.deploy)))
164
+ best = { opponent: player, from: s, deploy: min, ...(firstMover ? { firstMover } : {}) };
165
+ }
166
+ const bonuses = held.filter((id) => bonusTerritories(graph, id).includes(b));
167
+ const behind = neighborsOf(graph, b)
168
+ .filter((n) => mineAfter.has(n) && !facesEnemy(n))
169
+ .sort(byNum);
170
+ const behindIncome = held
171
+ .filter((id) => !bonuses.includes(id) && bonusTerritories(graph, id).some((t) => behind.includes(t)))
172
+ .reduce((n, id) => n + Math.max(0, value(id)), 0);
173
+ // The stack that takes it at its headroom; a territory behind is hollow when none of mine beside
174
+ // it (itself included) holds as many after my orders. No deploy takes it: nothing to breach.
175
+ const taker = best.deploy === null ? 0 : sendsFrom(best.from, best.opponent) + best.deploy;
176
+ const hollow = (x) => [x, ...neighborsOf(graph, x)].every((y) => {
177
+ const at = baseline.territories.get(y);
178
+ return y === b || !mineAfter.has(y) || (at?.armies ?? 0) + (at?.commander === me ? COMMANDER_STRENGTH : 0) < taker;
179
+ });
180
+ const breach = taker > 0 ? breachBehind(graph, mineAfter, front, b, new Set(), hollow) : { ids: [], income: 0 };
181
+ rows.push({
182
+ territory: b,
183
+ armies: there.armies,
184
+ opponent: best.opponent,
185
+ from: best.from,
186
+ deploy: best.deploy,
187
+ ...(best.firstMover ? { firstMover: best.firstMover } : {}),
188
+ bonuses: bonuses.map((id) => ({ id, value: value(id) })),
189
+ behind,
190
+ behindIncome,
191
+ breach: { territories: breach.ids, income: breach.income },
192
+ });
193
+ }
194
+ return rows.sort((a, b) => (a.deploy ?? Infinity) - (b.deploy ?? Infinity) || a.territory - b.territory);
195
+ }
196
+ /**
197
+ * The smallest d in [0, HEADROOM_CAP] with `ok(d)`, `ok` taken to be monotone (more armies never take
198
+ * less), starting from `guess`; `null` when even the cap fails.
199
+ */
200
+ export function smallest(ok, guess) {
201
+ let lo;
202
+ let hi;
203
+ if (ok(guess)) {
204
+ if (guess === 0)
205
+ return 0;
206
+ // Below the guess: gallop down, then bisect.
207
+ hi = guess;
208
+ let step = 1;
209
+ lo = guess - step;
210
+ while (lo > 0 && ok(lo)) {
211
+ hi = lo;
212
+ step *= 2;
213
+ lo = Math.max(0, hi - step);
214
+ }
215
+ if (lo === 0 && ok(0))
216
+ return 0;
217
+ }
218
+ else {
219
+ if (guess >= HEADROOM_CAP)
220
+ return null;
221
+ lo = guess;
222
+ let step = Math.max(1, guess);
223
+ hi = Math.min(HEADROOM_CAP, guess + step);
224
+ while (!ok(hi)) {
225
+ if (hi >= HEADROOM_CAP)
226
+ return null;
227
+ lo = hi;
228
+ step *= 2;
229
+ hi = Math.min(HEADROOM_CAP, hi + step);
230
+ }
231
+ }
232
+ // ok(hi), !ok(lo)
233
+ while (hi - lo > 1) {
234
+ const mid = Math.floor((lo + hi) / 2);
235
+ if (ok(mid))
236
+ hi = mid;
237
+ else
238
+ lo = mid;
239
+ }
240
+ return hi;
241
+ }
@@ -0,0 +1,64 @@
1
+ // Given orders against what the default plan leaves on each border (#275, pattern 3). Pure and deterministic; ties resolve
2
+ // on ascending ids.
3
+ //
4
+ // A hand-edited turn can drain a border the plan sized: a deploy moved to the interior, an extra attack
5
+ // out. The headroom table (headroom.ts) says what deploy takes a border after the given orders; this
6
+ // says which borders the given orders leave below what the default plan (planTurn on the same board,
7
+ // default options; or that plan's border guess, when the given deploys are the guess's) leaves there, and
8
+ // by how much — a diff against the plan, so it names the edit.
9
+ //
10
+ // A border is a territory I hold at the start of the turn beside an enemy stack (its owner shown, armies
11
+ // in view; a teammate is no enemy) that the plan does not concede — chosen on the start-of-turn board, so
12
+ // a border whose enemy stack the given orders capture is still one (the attack may fail against a deploy
13
+ // there). What the plan leaves on it is what stands there once the plan's deploys and moves have run on
14
+ // the turn simulator (turn-sim.ts) with no opponent order — my commander counted as COMMANDER_STRENGTH —
15
+ // and what is left is the same after the given orders. Only a border the given orders leave below the
16
+ // plan's figure is named. That figure is everything the plan leaves standing — the leftover, comfort
17
+ // margins and idle stacks included — not the least that holds the border, so a border named may still
18
+ // hold: the headroom table says what deploy takes it. Card plays are not carried out (a Blockade or an
19
+ // Airlift changes nothing here), and luck is resolved at its expectation, as the simulator does.
20
+ import { COMMANDER_STRENGTH } from './combat.js';
21
+ import { neighborsOf } from './graph.js';
22
+ import { neutralizeSeats } from './static-seats.js';
23
+ import { simTerritories, simulateTurn } from './turn-sim.js';
24
+ /** Every border the given orders leave below what the default plan leaves there, the largest shortfall first. */
25
+ export function holdsBelowPlan(input) {
26
+ const { graph, me, teams } = input;
27
+ const board = input.staticSeats ? neutralizeSeats(input.board, input.staticSeats) : input.board;
28
+ const start = simTerritories(board);
29
+ const sameTeam = (a, b) => teams !== undefined && teams.get(a) !== undefined && teams.get(a) === teams.get(b);
30
+ const enemy = (owner) => typeof owner === 'number' && owner !== me && !sameTeam(owner, me);
31
+ const conceded = new Set(input.conceded ?? []);
32
+ const borders = [...start]
33
+ .filter(([id, t]) => t.owner === me && !conceded.has(id) && neighborsOf(graph, id).some((n) => enemy(start.get(n)?.owner)))
34
+ .map(([id]) => id);
35
+ if (!borders.length)
36
+ return [];
37
+ const standing = (o) => {
38
+ const r = simulateTurn({
39
+ graph,
40
+ board,
41
+ deploys: o.deploys.map((d) => ({ player: me, territoryId: d.territoryId, armies: d.armies })),
42
+ orders: [{ player: me, orders: o.moves.map((m) => ({ ...m })) }],
43
+ moveOrder: [me],
44
+ ...(input.settings ? { settings: input.settings } : {}),
45
+ ...(teams ? { teams } : {}),
46
+ });
47
+ return (id) => {
48
+ const t = r.territories.get(id);
49
+ if (!t || t.owner !== me)
50
+ return 0;
51
+ return t.armies + (t.commander === me ? COMMANDER_STRENGTH : 0);
52
+ };
53
+ };
54
+ const planned = standing(input.plan);
55
+ const given = standing(input.given);
56
+ const out = [];
57
+ for (const id of borders) {
58
+ const planLeaves = planned(id);
59
+ const left = given(id);
60
+ if (left < planLeaves)
61
+ out.push({ territory: id, planLeaves, left, short: planLeaves - left });
62
+ }
63
+ return out.sort((a, b) => b.short - a.short || a.territory - b.territory);
64
+ }
@@ -0,0 +1,130 @@
1
+ // How a lost game was lost (#274 item 5), read from the boards this server cached while it played.
2
+ // Pure and deterministic; no I/O.
3
+ //
4
+ // The board cached for turn T is the board turn T was planned on, before it resolved, and a player
5
+ // eliminated on turn T has no board after it. So the newest cached board on which I hold anything is
6
+ // the turn I was most likely eliminated on: certain only when that is the newest completed turn
7
+ // (`turnsCompleted === T`: the game ended on it, or, #283, the others play on and it just resolved),
8
+ // since otherwise this server may simply have stopped planning. The cause
9
+ // is read from that board:
10
+ // - `commander`: my commander stands on it. Losing the commander eliminates a player, and losing every
11
+ // territory at once on a board where I held more is far less likely, so the commander's territory is
12
+ // taken to be what fell (an inference, never seen). Given my cached orders for the turn, what stood
13
+ // there is a range: `low` = armies + my deploys − my moves out (the attack after they left, before my
14
+ // moves in landed), `high` = armies + my deploys + my moves in (after they landed, before any left); the attack that took it needed at least
15
+ // `armiesToTake(low + COMMANDER_STRENGTH)` at the game's kill rates (exact only at 0% luck under
16
+ // straight rounding; with luck an expectation). `held.uncertain` marks a range my orders cannot pin:
17
+ // an order `moves` leaves out (a percentage, Attack Only or Transfer Only one, kept only in `sent`) or
18
+ // an Airlift or other card play touches the territory.
19
+ // When that turn's orders walk the commander (a move flagged `commander`), it is read at the walk's
20
+ // destination, `territoryCertain: false` (it may have fallen on its start before the walk ran): the
21
+ // range there is from after the walk landed (its armies in `low`), and the neighbours are both
22
+ // territories'. A walk known only from `sent` (a percentage order) has no army count and no range.
23
+ // - `last-territories`: no commander of mine on the board (and the game was not known to have
24
+ // commanders): the territories I still held, which all fell.
25
+ // - `unknown`: the game had commanders but the board shows none of mine (a board cached before
26
+ // special units were decoded).
27
+ // Who: the players on the territories next to what fell (by the map's adjacency; a fogged neighbour
28
+ // is `playerId: null`). `by` names a taker only when exactly one player borders it and no neighbour
29
+ // is fogged. Ids only: names are the tool's business.
30
+ import { armiesToTake, COMMANDER_STRENGTH, luckFraction } from './combat.js';
31
+ export const MAX_LAST_TERRITORIES = 5;
32
+ const ownerId = (t) => t.owner.kind === 'player' ? t.owner.playerId : t.owner.kind === 'unknown' ? null : undefined;
33
+ function neighboursOf(board, me, fallen, adjacency) {
34
+ const byId = new Map(board.territories.map((t) => [t.territoryId, t]));
35
+ const fallenSet = new Set(fallen);
36
+ const seen = new Set();
37
+ const groups = new Map();
38
+ for (const f of fallen)
39
+ for (const n of adjacency.get(f) ?? []) {
40
+ if (fallenSet.has(n) || seen.has(n))
41
+ continue;
42
+ seen.add(n);
43
+ const t = byId.get(n);
44
+ // Not on the board, mine, neutral or pickable: no attacker there.
45
+ if (!t)
46
+ continue;
47
+ const owner = ownerId(t);
48
+ if (owner === undefined || owner === me)
49
+ continue;
50
+ const g = groups.get(owner) ?? { territories: 0, armies: null };
51
+ g.territories++;
52
+ if (owner !== null && t.armies !== null)
53
+ g.armies = (g.armies ?? 0) + t.armies;
54
+ groups.set(owner, g);
55
+ }
56
+ return [...groups.entries()]
57
+ .sort(([a], [b]) => (a === null ? 1 : b === null ? -1 : a - b))
58
+ .map(([playerId, g]) => ({ playerId, ...g }));
59
+ }
60
+ /** How the game was lost, from the newest cached board on which I hold a territory; `undefined` without one. */
61
+ export function howLost(input) {
62
+ const { me } = input;
63
+ const mineOn = (b) => b.territories.filter((t) => t.owner.kind === 'player' && t.owner.playerId === me);
64
+ const last = [...input.boards].sort((a, b) => b.turn - a.turn).find((b) => mineOn(b.board).length > 0);
65
+ if (!last)
66
+ return undefined;
67
+ const { turn, board } = last;
68
+ const mine = mineOn(board);
69
+ const cmd = mine.find((t) => t.specialUnits?.some((u) => u.kind === 'commander' && u.playerId === me));
70
+ const cause = cmd ? 'commander' : input.commanders ? 'unknown' : 'last-territories';
71
+ const out = {
72
+ turn,
73
+ turnCertain: input.turnsCompleted === turn,
74
+ cause,
75
+ territoriesHeld: mine.length,
76
+ neighbours: null,
77
+ by: null,
78
+ };
79
+ let fallen = [];
80
+ if (cmd) {
81
+ const orders = input.orders.get(turn);
82
+ const start = cmd.territoryId;
83
+ const walkMove = orders?.moves.find((m) => m.commander && m.from === start);
84
+ const walkSent = orders?.sent?.find((m) => m.commander && m.from === start);
85
+ const walk = walkMove
86
+ ? { from: start, to: walkMove.to, armies: walkMove.armies }
87
+ : walkSent
88
+ ? { from: start, to: walkSent.to, armies: null }
89
+ : undefined;
90
+ const id = walk ? walk.to : start;
91
+ const at = walk ? board.territories.find((t) => t.territoryId === id) : cmd;
92
+ const armies = at && ownerId(at) === me ? (at.armies ?? 0) : 0;
93
+ const sum = (xs) => xs.reduce((s, x) => s + x.armies, 0);
94
+ const deployed = orders ? sum(orders.deploys.filter((d) => d.territoryId === id)) : null;
95
+ const movedOut = orders ? sum(orders.moves.filter((m) => m.from === id)) : null;
96
+ const movedIn = orders ? sum(orders.moves.filter((m) => m.to === id)) : null;
97
+ // An order `moves` leaves out (kept only in `sent`), or a card play, touching it: the count is a bound.
98
+ const touches = (m) => m.from === id || m.to === id || m.target === id;
99
+ const uncertain = !!orders && ((orders.sent?.filter(touches).length ?? 0) > orders.moves.filter(touches).length || (orders.cards ?? []).some(touches));
100
+ // At a walk's destination the commander stands only once the walk has landed: its armies are in `low`.
101
+ const walkIn = walk ? walk.armies : 0;
102
+ const held = deployed !== null && movedOut !== null && movedIn !== null && walkIn !== null && (!walk || (at && ownerId(at) === me))
103
+ ? { low: Math.max(0, armies + deployed - movedOut + walkIn), high: armies + deployed + movedIn, uncertain }
104
+ : null;
105
+ out.commander = {
106
+ territoryId: id,
107
+ territoryCertain: !walk,
108
+ ...(walk ? { walk } : {}),
109
+ armies,
110
+ deployed,
111
+ movedOut,
112
+ movedIn,
113
+ held,
114
+ attackersNeeded: held ? armiesToTake(held.low + COMMANDER_STRENGTH, input.rates) : null,
115
+ exact: luckFraction(input.rates.luck) === 0 && input.rates.rounding !== 'WeightedRandom',
116
+ };
117
+ fallen = walk ? [start, id] : [id];
118
+ }
119
+ else if (cause === 'last-territories') {
120
+ const sorted = [...mine].sort((a, b) => a.territoryId - b.territoryId);
121
+ out.lastTerritories = sorted.slice(0, MAX_LAST_TERRITORIES).map((t) => ({ territoryId: t.territoryId, armies: t.armies }));
122
+ fallen = sorted.map((t) => t.territoryId);
123
+ }
124
+ if (input.adjacency && fallen.length) {
125
+ out.neighbours = neighboursOf(board, me, fallen, input.adjacency);
126
+ const players = out.neighbours.filter((n) => n.playerId !== null);
127
+ out.by = players.length === 1 && players.length === out.neighbours.length ? players[0].playerId : null;
128
+ }
129
+ return out;
130
+ }
@@ -0,0 +1,14 @@
1
+ // Map + board analysis core. Pure and deterministic; no I/O.
2
+ export * from './graph.js';
3
+ export * from './bonuses.js';
4
+ export * from './chokepoints.js';
5
+ export * from './combat.js';
6
+ export * from './player.js';
7
+ export * from './planner.js';
8
+ export * from './local-deploy.js';
9
+ export * from './picks.js';
10
+ export * from './overrides.js';
11
+ export * from './profile.js';
12
+ export * from './exchange.js';
13
+ export * from './opponents.js';
14
+ export * from './guess.js';
@@ -0,0 +1,159 @@
1
+ // Local Deployment (GameFeed `LocalDeployments`): armies earned from a bonus may
2
+ // only be deployed on that bonus's territories; the rest of the income (base
3
+ // income, per-territory income, card armies) may go anywhere. Which income is
4
+ // "anywhere" is UNVERIFIED beyond the bonus rule itself — see docs/WARAPP-API.md.
5
+ // Pure and deterministic.
6
+ import { bonusTerritories } from './bonuses.js';
7
+ /**
8
+ * The deploy pools for a player holding `held` with this turn's `income`: one per
9
+ * fully held bonus of positive value (a superbonus gets its own pool over all its
10
+ * territories, beside its member bonuses' pools), and the rest anywhere.
11
+ */
12
+ export function deployPools(g, held, income) {
13
+ const bonuses = [];
14
+ for (const b of g.map.bonuses) {
15
+ if (b.value <= 0)
16
+ continue;
17
+ const ts = bonusTerritories(g, b.id);
18
+ if (!ts.length || !ts.every((t) => held.has(t)))
19
+ continue;
20
+ bonuses.push({ bonusId: b.id, name: b.name, value: b.value, territoryIds: [...ts] });
21
+ }
22
+ bonuses.sort((a, b) => a.territoryIds.length - b.territoryIds.length || a.bonusId - b.bonusId);
23
+ const total = bonuses.reduce((s, p) => s + p.value, 0);
24
+ let trimmed = 0;
25
+ // Never more pooled armies than the income: trim the outermost pools first.
26
+ for (let i = bonuses.length - 1, over = total - Math.max(0, income); i >= 0 && over > 0; i--) {
27
+ const cut = Math.min(over, bonuses[i].value);
28
+ bonuses[i].value -= cut;
29
+ over -= cut;
30
+ trimmed += cut;
31
+ }
32
+ return { anywhere: Math.max(0, income - (total - trimmed)), bonuses, trimmed };
33
+ }
34
+ /**
35
+ * Charge deploys (armies by territory) to the pools so that as few armies as possible
36
+ * draw on the anywhere pool: a maximum flow from the deployed territories to the bonus
37
+ * pools that contain them (each pool capped at its value). The deploys are valid
38
+ * exactly when `anywhereUsed ≤ anywhere`.
39
+ *
40
+ * Exact for any bonus layout — nested (member bonuses inside a superbonus) or
41
+ * overlapping without nesting. A greedy pass (innermost pool first, lowest territory
42
+ * first) seeds the flow; augmenting paths then move armies between pools until no
43
+ * more can be absorbed (Ford–Fulkerson; deterministic: BFS in pool and id order).
44
+ */
45
+ export function chargeDeploys(pools, deploys) {
46
+ const ps = pools.bonuses;
47
+ const left = new Map([...deploys].filter(([, n]) => n > 0).sort(([a], [b]) => a - b));
48
+ /** flow[i]: armies from each territory charged to pool i. */
49
+ const flow = ps.map(() => new Map());
50
+ const room = ps.map((p) => p.value);
51
+ const add = (i, t, n) => {
52
+ const f = (flow[i].get(t) ?? 0) + n;
53
+ if (f)
54
+ flow[i].set(t, f);
55
+ else
56
+ flow[i].delete(t);
57
+ room[i] -= n;
58
+ left.set(t, left.get(t) - n);
59
+ };
60
+ // Greedy seed: innermost pool first, its lowest territories first.
61
+ ps.forEach((p, i) => {
62
+ for (const t of p.territoryIds) {
63
+ const take = Math.min(left.get(t) ?? 0, room[i]);
64
+ if (take > 0)
65
+ add(i, t, take);
66
+ }
67
+ });
68
+ const members = ps.map((p) => new Set(p.territoryIds));
69
+ // Augment: from a territory with armies left, through pools (forward: any pool holding
70
+ // the territory) and back (a territory already charged to that pool), to a pool with room.
71
+ for (;;) {
72
+ const start = [...left].filter(([, n]) => n > 0).map(([t]) => t);
73
+ if (!start.length || room.every((r) => r <= 0))
74
+ break;
75
+ const viaPool = new Map(); // pool → territory it was reached from
76
+ const viaTerr = new Map(); // territory → pool it was reached from (-1: a start)
77
+ for (const t of start)
78
+ viaTerr.set(t, -1);
79
+ const queue = [...start];
80
+ let end = -1;
81
+ while (queue.length && end < 0) {
82
+ const t = queue.shift();
83
+ for (let i = 0; i < ps.length && end < 0; i++) {
84
+ if (viaPool.has(i) || !members[i].has(t))
85
+ continue;
86
+ viaPool.set(i, t);
87
+ if (room[i] > 0) {
88
+ end = i;
89
+ break;
90
+ }
91
+ for (const u of [...flow[i].keys()].sort((a, b) => a - b)) {
92
+ if (viaTerr.has(u))
93
+ continue;
94
+ viaTerr.set(u, i);
95
+ queue.push(u);
96
+ }
97
+ }
98
+ }
99
+ if (end < 0)
100
+ break;
101
+ // Walk the path back from the pool with room to its start; the bottleneck is the
102
+ // pool's room, the start's armies left, and each reversed charge.
103
+ const path = [];
104
+ for (let i = end;;) {
105
+ const t = viaPool.get(i);
106
+ path.push([i, t]);
107
+ const back = viaTerr.get(t);
108
+ if (back < 0)
109
+ break;
110
+ i = back;
111
+ }
112
+ let n = Math.min(room[end], left.get(path[path.length - 1][1]));
113
+ for (let k = 0; k < path.length - 1; k++)
114
+ n = Math.min(n, flow[path[k + 1][0]].get(path[k][1]));
115
+ // Each step charges `terr` to `pool`; each earlier pool on the path releases the same territory.
116
+ for (let k = 0; k < path.length; k++) {
117
+ const [i, t] = path[k];
118
+ add(i, t, n);
119
+ if (k + 1 < path.length)
120
+ add(path[k + 1][0], t, -n);
121
+ }
122
+ }
123
+ const used = new Map();
124
+ ps.forEach((p, i) => used.set(p.bonusId, p.value - room[i]));
125
+ let anywhereUsed = 0;
126
+ for (const n of left.values())
127
+ anywhereUsed += n;
128
+ return { anywhereUsed, used };
129
+ }
130
+ /**
131
+ * An opponent's deploy under Local Deployment (#180), as the planner bounds it (#128): a bonus it
132
+ * visibly holds in full pays only into that bonus's territories, so on `on` it may deploy its
133
+ * estimate less the pools it counts (income in the fog counts as deployable anywhere), plus the
134
+ * pools that contain one of `on`, never above the estimate. Only what it holds above its free
135
+ * floor — max(`floor`, its base income) — is taken as pooled: the free base always lands anywhere.
136
+ * `pools` are the values and members of the bonuses it holds; with none the whole estimate reaches.
137
+ */
138
+ export function enemyDeployReaching(estimate, base, floor, pools, on) {
139
+ if (!pools.length)
140
+ return estimate;
141
+ const pooled = pools.reduce((n, q) => n + q.value, 0);
142
+ const here = pools.reduce((n, q) => n + (on.some((t) => q.members.has(t)) ? q.value : 0), 0);
143
+ const free = Math.min(estimate, Math.max(floor, base));
144
+ return Math.min(estimate, Math.max(free, estimate - pooled) + here);
145
+ }
146
+ /** Each player's bonuses (value above 0) whose every territory it is shown to own: its Local Deployment pools. */
147
+ export function heldBonusPools(g, ownerOf) {
148
+ const out = new Map();
149
+ for (const b of g.map.bonuses) {
150
+ if (b.value <= 0)
151
+ continue;
152
+ const ts = bonusTerritories(g, b.id);
153
+ const p = ts.length ? ownerOf(ts[0]) : undefined;
154
+ if (p === undefined || !ts.every((t) => ownerOf(t) === p))
155
+ continue;
156
+ out.set(p, [...(out.get(p) ?? []), { bonusId: b.id, value: b.value, members: new Set(ts) }]);
157
+ }
158
+ return out;
159
+ }