@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,351 @@
1
+ // The border guess: a randomized deploy split for when no fixed split holds.
2
+ //
3
+ // One opponent touches two or more of my borders. The deploys the plan spends on those borders
4
+ // cannot hold all of them against "its stacks + its whole deploy", so the opponent picks which
5
+ // border to hit: a fixed (predictable) split loses the border it always leaves short. A split
6
+ // drawn at random, weighted by what each border is worth, cuts the expected loss (the security
7
+ // game of docs/STRATEGY.md "Guessing at a border").
8
+ //
9
+ // The model: the opponent attacks every border with the stacks beside it, and lands its whole
10
+ // deploy next to one border (its choice). I fund each border at one of its threshold levels: what
11
+ // planned moves out of it need, what holds the stacks alone, what holds the stacks plus the
12
+ // deploy (anything between two levels is wasted under exact combat). A border that falls costs
13
+ // its worth: 1, plus the value of every bonus I hold in full that contains it, plus 100 when my
14
+ // commander stands there. The best fixed split is the maximin; the mixed value is the exact
15
+ // value of the matrix game (a small simplex over the allocations × targets matrix).
16
+ //
17
+ // Only the deploys the plan puts on these borders are redistributed (`budget`): expansion and
18
+ // every other order of the plan are untouched. #274: the territory my commander stands on, and any a
19
+ // commander move of the plan walks it to, keep at least the plan's deploy in every allocation: the
20
+ // planner sizes that hold at my income and every stack within two moves, more than this model's one
21
+ // deploy, and warapp_submit_turn refuses orders that leave the commander takeable. Pure and deterministic (ties on ascending id),
22
+ // no I/O; the sample is drawn from a caller's seed with mulberry32.
23
+ // No guess against an opponent whose estimate the #275 tripwire marked untrusted (`untrusted`): the
24
+ // plan sized its held-bonus borders above the estimate, and a split drawn from the estimate would undo it.
25
+ import { bonusTerritories } from './bonuses.js';
26
+ import { armiesToTake, DEFAULT_DEFENSIVE_KILL_RATE, DEFAULT_OFFENSIVE_KILL_RATE, luckFraction, specialUnitStrength } from './combat.js';
27
+ import { neighborsOf } from './graph.js';
28
+ import { alliesOf } from './planner.js';
29
+ /** A guess is emitted only when the mix beats the best fixed split by this share of the worth at stake. */
30
+ export const MIN_GUESS_GAIN = 0.05;
31
+ /** A border with my commander on it is worth this much more (losing it can lose the game). */
32
+ const COMMANDER_WORTH = 100;
33
+ /** At most this many borders (the allocations grow as 3^borders). */
34
+ const MAX_GUESS_BORDERS = 7;
35
+ const byNum = (a, b) => a - b;
36
+ const skip = (reason, message) => ({ kind: 'skipped', reason, message });
37
+ const round = (x) => Math.round(x * 1e6) / 1e6;
38
+ /** A 32-bit seed from a game id and a turn (FNV-1a): re-planning a turn draws the same sample. */
39
+ export function guessSeed(gameId, turn, salt = '') {
40
+ // The salt is a local secret (src/guess-salt.ts): without it, anyone who reads this public code
41
+ // could reproduce the draw from the game id and turn.
42
+ const text = `warapp-guess:${salt}:${gameId}:${turn ?? 'none'}`;
43
+ let h = 0x811c9dc5;
44
+ for (let i = 0; i < text.length; i++)
45
+ h = Math.imul(h ^ text.charCodeAt(i), 0x01000193);
46
+ return h >>> 0;
47
+ }
48
+ /** mulberry32: a small deterministic PRNG, one draw in [0, 1). */
49
+ function mulberry32(seed) {
50
+ let a = seed >>> 0;
51
+ return () => {
52
+ a = (a + 0x6d2b79f5) >>> 0;
53
+ let t = a;
54
+ t = Math.imul(t ^ (t >>> 15), t | 1);
55
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
56
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
57
+ };
58
+ }
59
+ /**
60
+ * The exact value of a zero-sum matrix game where the row player minimises `loss[a][j]`:
61
+ * its optimal mix `x`, the column player's optimal mix `q` and the value. Solved as the LP
62
+ * max Σw s.t. (C − loss)·w ≤ 1, w ≥ 0 (C makes every payoff positive) by a dense tableau simplex
63
+ * with Bland's rule; the row mix is read from the slacks' reduced costs.
64
+ */
65
+ export function solveLossGame(loss) {
66
+ const n = loss.length;
67
+ const k = loss[0]?.length ?? 0;
68
+ if (n === 0 || k === 0)
69
+ return { value: 0, x: [], q: [] };
70
+ const C = Math.max(...loss.flat()) + 1;
71
+ const width = k + n + 1;
72
+ const rhs = k + n;
73
+ const T = [];
74
+ for (let a = 0; a < n; a++) {
75
+ const row = new Float64Array(width);
76
+ for (let j = 0; j < k; j++)
77
+ row[j] = C - loss[a][j];
78
+ row[k + a] = 1;
79
+ row[rhs] = 1;
80
+ T.push(row);
81
+ }
82
+ const obj = new Float64Array(width);
83
+ for (let j = 0; j < k; j++)
84
+ obj[j] = -1;
85
+ const basis = Array.from({ length: n }, (_, a) => k + a);
86
+ const EPS = 1e-12;
87
+ for (let iter = 0; iter < 10_000; iter++) {
88
+ let e = -1;
89
+ for (let c = 0; c < rhs; c++)
90
+ if (obj[c] < -EPS) {
91
+ e = c;
92
+ break;
93
+ }
94
+ if (e < 0)
95
+ break;
96
+ let r = -1;
97
+ let best = Infinity;
98
+ for (let i = 0; i < n; i++) {
99
+ const v = T[i][e];
100
+ if (v <= EPS)
101
+ continue;
102
+ const ratio = T[i][rhs] / v;
103
+ if (ratio < best - EPS || (Math.abs(ratio - best) <= EPS && basis[i] < basis[r])) {
104
+ best = ratio;
105
+ r = i;
106
+ }
107
+ }
108
+ if (r < 0)
109
+ break; // unbounded: impossible with positive payoffs
110
+ const pr = T[r];
111
+ const pv = pr[e];
112
+ for (let c = 0; c < width; c++)
113
+ pr[c] = pr[c] / pv;
114
+ for (let i = 0; i < n; i++) {
115
+ if (i === r)
116
+ continue;
117
+ const row = T[i];
118
+ const f = row[e];
119
+ if (f !== 0)
120
+ for (let c = 0; c < width; c++)
121
+ row[c] = row[c] - f * pr[c];
122
+ }
123
+ const f = obj[e];
124
+ for (let c = 0; c < width; c++)
125
+ obj[c] = obj[c] - f * pr[c];
126
+ basis[r] = e;
127
+ }
128
+ const V = obj[rhs];
129
+ const vB = 1 / V;
130
+ const w = new Array(k).fill(0);
131
+ basis.forEach((b, i) => {
132
+ if (b < k)
133
+ w[b] = T[i][rhs];
134
+ });
135
+ const clean = (xs) => {
136
+ const ys = xs.map((v) => (v > 1e-9 ? v : 0));
137
+ const s = ys.reduce((a, b) => a + b, 0);
138
+ return ys.map((v) => v / s);
139
+ };
140
+ const x = clean(Array.from({ length: n }, (_, a) => obj[k + a] * vB));
141
+ const q = clean(w.map((v) => v * vB));
142
+ // The value of the cleaned mix against the best reply (never below the LP's).
143
+ const value = Math.max(...Array.from({ length: k }, (_, j) => x.reduce((acc, p, a) => acc + p * loss[a][j], 0)));
144
+ return { value, x, q };
145
+ }
146
+ /**
147
+ * The border guess for a planned turn, or why there is none. See the file header for the model.
148
+ */
149
+ export function borderGuess(input) {
150
+ const { graph: g, board, me, plan } = input;
151
+ const s = input.settings ?? {};
152
+ if (luckFraction(s.luckModifier) > 0 || s.roundingMode === 'WeightedRandom')
153
+ return skip('luck', 'Battles have luck or weighted rounding here, so hold levels are not exact.');
154
+ if (s.localDeployments === true)
155
+ return skip('local-deployment', 'Local Deployment is on: deploys cannot move freely between these borders.');
156
+ const rates = { offensiveKillRate: s.offensiveKillRate ?? DEFAULT_OFFENSIVE_KILL_RATE, defensiveKillRate: s.defensiveKillRate ?? DEFAULT_DEFENSIVE_KILL_RATE };
157
+ const guard = (s.oneArmyStandsGuard ?? true) ? 1 : 0;
158
+ const allies = alliesOf(me, input.players);
159
+ const state = new Map();
160
+ for (const t of board.territories)
161
+ if (g.territoryById.has(t.territoryId))
162
+ state.set(t.territoryId, t);
163
+ const ownerOf = (id) => {
164
+ const t = state.get(id);
165
+ return t?.owner.kind === 'player' ? t.owner.playerId : null;
166
+ };
167
+ const foe = (p) => p !== null && p !== me && !allies.has(p);
168
+ /** A foe's territory with its armies shown. */
169
+ const foeStack = (id) => foe(ownerOf(id)) && state.get(id).armies !== null;
170
+ const mine = [...state.values()].filter((t) => ownerOf(t.territoryId) === me).map((t) => t.territoryId).sort(byNum);
171
+ const mineSet = new Set(mine);
172
+ const opponents = new Set();
173
+ for (const t of mine)
174
+ for (const n of neighborsOf(g, t))
175
+ if (foeStack(n))
176
+ opponents.add(ownerOf(n));
177
+ if (opponents.size === 0)
178
+ return skip('no-contact', 'No opponent stack is in sight next to my territories.');
179
+ if (opponents.size > 1)
180
+ return skip('several-opponents', `${opponents.size} opponents touch my borders: the guess models one opponent with one deploy.`);
181
+ const opp = [...opponents][0];
182
+ if (input.enemyDeploy === undefined && input.untrusted?.includes(opp))
183
+ return skip('untrusted', `Player ${opp}'s deploy estimate is untrusted (#275): the plan sized its borders above it, and a guess drawn from the estimate would undo that.`);
184
+ const D = Math.max(0, Math.floor(input.enemyDeploy ?? input.estimates?.find((e) => e.playerId === opp)?.estimate ?? plan.enemyDeploy));
185
+ const ids = mine.filter((t) => neighborsOf(g, t).some((n) => foeStack(n) && ownerOf(n) === opp));
186
+ if (ids.length < 2)
187
+ return skip('one-border', 'The opponent touches only one of my territories: there is nothing to guess between.');
188
+ if (ids.length > MAX_GUESS_BORDERS)
189
+ return skip('too-many-borders', `The opponent touches ${ids.length} of my territories (at most ${MAX_GUESS_BORDERS} are modelled).`);
190
+ const held = g.map.bonuses.filter((b) => {
191
+ if (b.value <= 0)
192
+ return false;
193
+ const ts = bonusTerritories(g, b.id);
194
+ return ts.length > 0 && ts.every((t) => mineSet.has(t));
195
+ });
196
+ const planDeploy = new Map();
197
+ for (const d of plan.deploys)
198
+ planDeploy.set(d.territoryId, (planDeploy.get(d.territoryId) ?? 0) + d.armies);
199
+ if (s.noSplit === true && plan.moves.some((m) => ids.includes(m.from)))
200
+ return skip('no-split', 'No-Split is on and the plan moves a whole stack out of one of these borders.');
201
+ /** Least defenders (armies + unit strength) that `attack` armies cannot take. */
202
+ const need = (attack) => {
203
+ let d = 0;
204
+ while ((armiesToTake(d, rates) ?? Infinity) <= attack)
205
+ d++;
206
+ return d;
207
+ };
208
+ /** #274: where my commander stands or walks to this turn. */
209
+ const commanderAt = new Set([
210
+ ...mine.filter((id) => (state.get(id).specialUnits ?? []).some((u) => u.kind === 'commander' && u.playerId === me)),
211
+ ...plan.moves.filter((m) => m.commander).map((m) => m.to),
212
+ ]);
213
+ const borders = ids.map((id) => {
214
+ const t = state.get(id);
215
+ const armies = t.armies ?? 0;
216
+ const myUnits = (t.specialUnits ?? []).filter((u) => u.playerId === me);
217
+ const strength = specialUnitStrength(myUnits);
218
+ const stack = neighborsOf(g, id)
219
+ .filter((n) => foeStack(n) && ownerOf(n) === opp)
220
+ .reduce((a, n) => {
221
+ const nt = state.get(n);
222
+ const units = (nt.specialUnits ?? []).filter((u) => u.playerId === opp);
223
+ return a + Math.max(0, (nt.armies ?? 0) - guard) + specialUnitStrength(units);
224
+ }, 0);
225
+ const worth = 1 +
226
+ held.filter((b) => bonusTerritories(g, b.id).includes(id)).reduce((a, b) => a + b.value, 0) +
227
+ (myUnits.some((u) => u.kind === 'commander') ? COMMANDER_WORTH : 0);
228
+ // The least deploy that keeps every planned move out of it valid (each move counting the
229
+ // armies moved in earlier in the list, as warapp_submit_turn checks it).
230
+ let running = armies;
231
+ let minDeploy = 0;
232
+ let movedOut = 0;
233
+ for (const m of plan.moves) {
234
+ if (m.to === id)
235
+ running += m.armies;
236
+ if (m.from === id) {
237
+ running -= m.armies;
238
+ movedOut += m.armies;
239
+ minDeploy = Math.max(minDeploy, guard - running);
240
+ }
241
+ }
242
+ return {
243
+ id,
244
+ worth,
245
+ armies,
246
+ movedOut,
247
+ base: armies - movedOut,
248
+ minDeploy,
249
+ holdAlone: Math.max(0, need(stack) - strength),
250
+ holdFull: Math.max(0, need(stack + D) - strength),
251
+ planDeploy: planDeploy.get(id) ?? 0,
252
+ ...(commanderAt.has(id) ? { pinned: true } : {}),
253
+ };
254
+ });
255
+ const k = borders.length;
256
+ const budget = borders.reduce((a, b) => a + b.planDeploy, 0);
257
+ const richest = borders.reduce((best, b, i) => (b.worth > borders[best].worth ? i : best), 0);
258
+ // Allocations: each border at one of its distinct levels within the budget, the rest on the richest;
259
+ // a pinned border (#274) at the plan's deploy only.
260
+ const levels = borders.map((b) => b.pinned
261
+ ? [Math.max(b.minDeploy, b.planDeploy)]
262
+ : [...new Set([b.minDeploy, Math.max(b.minDeploy, b.holdAlone - b.base), Math.max(b.minDeploy, b.holdFull - b.base)])].sort(byNum));
263
+ const seen = new Set();
264
+ const allocs = [];
265
+ const rec = (i, acc, spent) => {
266
+ if (i === k) {
267
+ const a = [...acc];
268
+ a[richest] = a[richest] + (budget - spent);
269
+ const key = a.join(',');
270
+ if (!seen.has(key)) {
271
+ seen.add(key);
272
+ allocs.push(a);
273
+ }
274
+ return;
275
+ }
276
+ for (const c of levels[i])
277
+ if (spent + c <= budget)
278
+ rec(i + 1, [...acc, c], spent + c);
279
+ };
280
+ rec(0, [], 0);
281
+ const lossOf = (alloc, j) => borders.reduce((a, b, i) => a + (b.base + alloc[i] < (i === j ? b.holdFull : b.holdAlone) ? b.worth : 0), 0);
282
+ const worst = (alloc) => Math.max(...borders.map((_, j) => lossOf(alloc, j)));
283
+ const planAlloc = borders.map((b) => b.planDeploy);
284
+ const planLoss = worst(planAlloc);
285
+ if (allocs.length === 0)
286
+ allocs.push(planAlloc);
287
+ const M = allocs.map((a) => borders.map((_, j) => lossOf(a, j)));
288
+ const fixedLoss = Math.min(...M.map((row) => Math.max(...row)));
289
+ if (fixedLoss === 0)
290
+ return skip('fixed-split-holds', 'A fixed split of the deploys on these borders holds every one of them: no need to guess.');
291
+ // Drop dominated allocations (another loses no more against every target); the first of equals stays.
292
+ const keep = [];
293
+ for (let a = 0; a < M.length; a++) {
294
+ const dominated = M.some((row, b) => b !== a && row.every((v, j) => v <= M[a][j]) && (row.some((v, j) => v < M[a][j]) || b < a));
295
+ if (!dominated)
296
+ keep.push(a);
297
+ }
298
+ const { value, x, q } = solveLossGame(keep.map((a) => M[a]));
299
+ const worthAtStake = borders.reduce((a, b) => a + b.worth, 0);
300
+ if (fixedLoss - value < MIN_GUESS_GAIN * worthAtStake)
301
+ return skip('small-gain', `Mixing would cut the expected loss only from ${fixedLoss} to ${round(value)} of ${worthAtStake} at stake: the fixed split is as good.`);
302
+ const mix = keep.map((a, i) => ({ allocation: allocs[a], probability: round(x[i]) })).filter((m) => m.probability > 0);
303
+ const draw = mulberry32(input.seed)();
304
+ let acc = 0;
305
+ let pick = mix[mix.length - 1];
306
+ const totalP = mix.reduce((a, m) => a + m.probability, 0);
307
+ for (const m of mix) {
308
+ acc += m.probability / totalP;
309
+ if (draw < acc) {
310
+ pick = m;
311
+ break;
312
+ }
313
+ }
314
+ const allocation = pick.allocation;
315
+ const prob = (test, i) => round(mix.reduce((a, m) => a + (test(m.allocation, i) ? m.probability : 0), 0) / totalP);
316
+ const onBorders = new Set(ids);
317
+ const deploys = new Map();
318
+ for (const d of plan.deploys)
319
+ if (!onBorders.has(d.territoryId))
320
+ deploys.set(d.territoryId, (deploys.get(d.territoryId) ?? 0) + d.armies);
321
+ borders.forEach((b, i) => {
322
+ if (allocation[i] > 0)
323
+ deploys.set(b.id, allocation[i]);
324
+ });
325
+ return {
326
+ kind: 'guess',
327
+ opponent: opp,
328
+ enemyDeploy: D,
329
+ budget,
330
+ borders: borders.map((b, i) => ({
331
+ id: b.id,
332
+ worth: b.worth,
333
+ armies: b.armies,
334
+ movedOut: b.movedOut,
335
+ holdAlone: b.holdAlone,
336
+ holdFull: b.holdFull,
337
+ planDeploy: b.planDeploy,
338
+ guessDeploy: allocation[i],
339
+ holdProbability: prob((a, j) => b.base + a[j] >= b.holdFull, i),
340
+ holdAloneProbability: prob((a, j) => b.base + a[j] >= b.holdAlone, i),
341
+ })),
342
+ worthAtStake,
343
+ fixedLoss,
344
+ mixedLoss: round(value),
345
+ planLoss,
346
+ targets: borders.map((b, j) => ({ id: b.id, probability: round(q[j] ?? 0) })),
347
+ mix,
348
+ allocation,
349
+ deploys: [...deploys].sort((a, b) => a[0] - b[0]).map(([territoryId, armies]) => ({ territoryId, armies })),
350
+ };
351
+ }
@@ -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
+ }