@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,130 @@
1
+ // PLAN-TEAMS D3: the cards in effect the planner may rely on. `readActiveCards` (src/cards.ts) decodes
2
+ // the current standing's ActiveCards loosely and UNVERIFIED live (#163); this module decides which of
3
+ // them are sure enough to change a plan, and why the others are not. Pure and deterministic.
4
+ //
5
+ // What the client bundle says (read-only, never vendored):
6
+ // - an ActiveCard is created when its play order is applied, with ExpiresAfterTurn = the card's
7
+ // Duration (`ActiveOrderDuration`) + the turn number + 1, and is removed at the end of the turn
8
+ // processing that reaches it (Diplomacy and Sanctions expire `EndOfTurn`). So a card still in the
9
+ // current standing is in effect for the whole of the turn being ordered, and gone by its
10
+ // `untilTurn` (src/cards.ts) — never more than Duration turns ahead;
11
+ // - Diplomacy stops its two players attacking each other;
12
+ // - a Sanctions card on a player multiplies that player's income by (1 − Percentage), rounded to
13
+ // the nearest with .5 up, once per active card, after the army cap, capped at 10000 (a negative
14
+ // Percentage raises it). How the cut is taken from Local Deployment pools is not simple, so the
15
+ // tool does not apply it there.
16
+ //
17
+ // "Sure" means every one of: the turn is known; the card is in play in the game's settings with a
18
+ // Duration (and, for Sanctions, a Percentage of at most 1); the decoded expiry is after this turn and
19
+ // no later than Duration turns ahead; every player it names is a distinct player of this game still
20
+ // playing; and a Diplomacy names me and an opponent (not a teammate). Anything else is reported in
21
+ // `unsure` and changes nothing.
22
+ import { carriesTeam } from '../teams.js';
23
+ /** The most a sanctioned income can be (the client bundle's cap). */
24
+ export const SANCTIONED_INCOME_CAP = 10000;
25
+ /** Round to the nearest, .5 away from zero (the client bundle's rounding of a sanctioned income). */
26
+ const roundHalfUp = (x) => (x < 0 ? -Math.round(-x) : Math.round(x));
27
+ /**
28
+ * An income under the Sanctions cards in effect on its player, as the client bundle computes it:
29
+ * per card, round((1 − percentage) × income), capped at {@link SANCTIONED_INCOME_CAP}.
30
+ */
31
+ export function sanctionedIncome(income, percentages) {
32
+ let out = income;
33
+ for (const p of percentages) {
34
+ const r = roundHalfUp((1 - p) * out);
35
+ out = r < 0 || r > SANCTIONED_INCOME_CAP ? SANCTIONED_INCOME_CAP : r;
36
+ }
37
+ return out;
38
+ }
39
+ function cardSettings(settings, card) {
40
+ if (!settings?.cards.includes(card))
41
+ return undefined;
42
+ const raw = settings.raw?.[`${card}Card`];
43
+ return typeof raw === 'object' && raw !== null && !Array.isArray(raw) ? raw : undefined;
44
+ }
45
+ const durationOf = (s) => {
46
+ const d = s?.Duration;
47
+ return typeof d === 'number' && Number.isInteger(d) && d >= 1 ? d : undefined;
48
+ };
49
+ /** Why a card's timing is not sure this turn, or `undefined` when it is. */
50
+ function timingDoubt(card, turn, duration, name) {
51
+ if (turn === null)
52
+ return 'the turn is not known';
53
+ if (duration === undefined)
54
+ return `the game's settings give no ${name} duration`;
55
+ if (card.untilTurn === undefined)
56
+ return 'its expiry was not read';
57
+ if (card.untilTurn <= turn)
58
+ return `it reads as already over (until turn ${card.untilTurn}, this is turn ${turn})`;
59
+ if (card.untilTurn > turn + duration)
60
+ return `it reads as lasting until turn ${card.untilTurn}, longer than the game's ${name} duration (${duration}) allows from turn ${turn}`;
61
+ return undefined;
62
+ }
63
+ const playing = (p) => (p.state ?? 'Playing') === 'Playing';
64
+ /**
65
+ * PLAN-TEAMS D3: which decoded active cards the planner may rely on. Only a Diplomacy that names me
66
+ * and Sanctions on me are reasoned about in `unsure`; cards between other players are left out.
67
+ */
68
+ export function cardsInEffect(input) {
69
+ const { players, me, turn, settings } = input;
70
+ const mine = [...players].find(([, p]) => p.id === me);
71
+ const myInGame = mine?.[0];
72
+ const myTeam = mine && carriesTeam(mine[1].team) ? mine[1].team : undefined;
73
+ const diplomacy = new Map();
74
+ const sanctionsOnMe = [];
75
+ const sanctionsOnOthers = [];
76
+ const unsure = [];
77
+ const dipSettings = cardSettings(settings, 'Diplomacy');
78
+ const sanSettings = cardSettings(settings, 'Sanctions');
79
+ for (const a of input.active) {
80
+ if (a.card === 'Diplomacy' && a.players) {
81
+ const [x, y] = a.players;
82
+ if (myInGame === undefined || (x !== myInGame && y !== myInGame))
83
+ continue;
84
+ if (x === y)
85
+ continue;
86
+ const otherIn = x === myInGame ? y : x;
87
+ const other = players.get(otherIn);
88
+ const label = `Diplomacy with player ${other?.id ?? `(in-game ${otherIn})`}`;
89
+ const doubt = !settings?.cards.includes('Diplomacy')
90
+ ? 'the game does not have the Diplomacy card in play'
91
+ : !other
92
+ ? `in-game id ${otherIn} is not a player of this game`
93
+ : myTeam !== undefined && other.team === myTeam
94
+ ? 'it names a teammate'
95
+ : !playing(other)
96
+ ? 'that player is no longer playing'
97
+ : timingDoubt(a, turn, durationOf(dipSettings), 'Diplomacy');
98
+ if (doubt) {
99
+ unsure.push(`${label} was read from the board, but the plan does not rely on it: ${doubt}.`);
100
+ continue;
101
+ }
102
+ diplomacy.set(other.id, Math.max(diplomacy.get(other.id) ?? 0, a.untilTurn));
103
+ }
104
+ if (a.card === 'Sanctions' && a.target !== undefined) {
105
+ const target = players.get(a.target);
106
+ const onMe = a.target === myInGame;
107
+ const pct = sanSettings?.Percentage;
108
+ const doubt = !settings?.cards.includes('Sanctions')
109
+ ? 'the game does not have the Sanctions card in play'
110
+ : !target
111
+ ? `in-game id ${a.target} is not a player of this game`
112
+ : typeof pct !== 'number' || !Number.isFinite(pct) || pct > 1
113
+ ? "the game's settings give no usable Sanctions percentage"
114
+ : timingDoubt(a, turn, durationOf(sanSettings), 'Sanctions');
115
+ if (doubt) {
116
+ if (onMe)
117
+ unsure.push(`Sanctions on you were read from the board, but the plan's income does not apply them: ${doubt}.`);
118
+ continue;
119
+ }
120
+ const s = { player: target.id, percentage: pct, untilTurn: a.untilTurn };
121
+ (onMe ? sanctionsOnMe : sanctionsOnOthers).push(s);
122
+ }
123
+ }
124
+ return {
125
+ diplomacy: [...diplomacy].sort((p, q) => p[0] - q[0]).map(([player, untilTurn]) => ({ player, untilTurn })),
126
+ sanctionsOnMe,
127
+ sanctionsOnOthers,
128
+ unsure,
129
+ };
130
+ }
@@ -0,0 +1,59 @@
1
+ // Multi-Attack chains (#180, #199): under Multi-Attack a stack's survivors carry on — after a
2
+ // capture they attack again from the territory taken, less the guard. This searches the chains
3
+ // out of one stack on the exact luck-free combat model, depth first in ascending neighbour ids,
4
+ // at most `maxSteps` attacks deep and `maxNodes` attacks tried. It reports every attack tried; the
5
+ // caller picks what matters (stress.ts the most damaging chain, the planner the armies a chain
6
+ // lands on each territory of mine). Pure and deterministic.
7
+ import { COMMANDER_STRENGTH, DEFAULT_DEFENSIVE_KILL_RATE, DEFAULT_OFFENSIVE_KILL_RATE, straightKills } from './combat.js';
8
+ import { neighborsOf } from './graph.js';
9
+ /** The most attacks one chain is searched to (#180). */
10
+ export const CHAIN_MAX_STEPS = 6;
11
+ /** The most attacks tried while searching one stack's chains (#180). */
12
+ export const CHAIN_MAX_NODES = 4000;
13
+ /** Luck-free: `sent` armies (and a commander, when it goes along) take `t` as it stands. */
14
+ export function breaksLuckFree(sent, withCommander, t, rates = {}) {
15
+ if (!t || t.owner === 'unknown' || sent < 0)
16
+ return false;
17
+ const off = rates.offensiveKillRate ?? DEFAULT_OFFENSIVE_KILL_RATE;
18
+ const def = rates.defensiveKillRate ?? DEFAULT_DEFENSIVE_KILL_RATE;
19
+ const power = sent + (withCommander ? COMMANDER_STRENGTH : 0);
20
+ const defPower = t.armies + (t.commander !== undefined ? COMMANDER_STRENGTH : 0);
21
+ const kills = straightKills(power, off);
22
+ const defenceGone = kills >= t.armies && (t.commander === undefined || kills - t.armies >= COMMANDER_STRENGTH);
23
+ const losses = straightKills(defPower, def);
24
+ const lives = sent - Math.min(sent, losses) > 0 || (withCommander && losses - sent < COMMANDER_STRENGTH);
25
+ return defenceGone && lives;
26
+ }
27
+ /** Search the chains out of one stack (see the header). */
28
+ export function searchChains(o) {
29
+ if (o.sending <= 0)
30
+ return;
31
+ const def = o.defensiveKillRate ?? DEFAULT_DEFENSIVE_KILL_RATE;
32
+ const maxSteps = o.maxSteps ?? CHAIN_MAX_STEPS;
33
+ const maxNodes = o.maxNodes ?? CHAIN_MAX_NODES;
34
+ let nodes = 0;
35
+ const visit = (at, sending, path, sends) => {
36
+ for (const n of neighborsOf(o.graph, at)) {
37
+ if (nodes >= maxNodes)
38
+ return;
39
+ if (path.includes(n))
40
+ continue;
41
+ const t = o.territories.get(n);
42
+ if (!t || !o.hostile(n, t))
43
+ continue;
44
+ nodes++;
45
+ const captured = breaksLuckFree(sending, false, t, o);
46
+ const defPower = t.armies + (t.commander !== undefined ? COMMANDER_STRENGTH : 0);
47
+ const survivors = sending - Math.min(sending, straightKills(defPower, def));
48
+ const p = [...path, n];
49
+ const sd = [...sends, sending];
50
+ o.onAttack({ path: p, sends: sd, sending, captured, survivors });
51
+ if (!captured)
52
+ continue;
53
+ const next = survivors - o.guard;
54
+ if (next > 0 && p.length <= maxSteps && (o.goOn?.(n) ?? true))
55
+ visit(n, next, p, sd);
56
+ }
57
+ };
58
+ visit(o.from, o.sending, [o.from], []);
59
+ }
@@ -0,0 +1,140 @@
1
+ // Chokepoints: articulation points, bridge edges between bonus clusters, and
2
+ // low-degree territories that connect clusters. Pure and deterministic.
3
+ import { bonusTerritories } from './bonuses.js';
4
+ import { neighborsOf } from './graph.js';
5
+ const byNum = (a, b) => a - b;
6
+ // Iterative Tarjan (no recursion: real maps run to thousands of territories).
7
+ function cuts(g) {
8
+ const disc = new Map();
9
+ const low = new Map();
10
+ const points = new Set();
11
+ const bridges = [];
12
+ let time = 0;
13
+ const roots = [...g.territoryById.keys()].sort(byNum);
14
+ for (const root of roots) {
15
+ if (disc.has(root))
16
+ continue;
17
+ disc.set(root, time);
18
+ low.set(root, time++);
19
+ let rootChildren = 0;
20
+ const stack = [{ v: root, parent: null, i: 0 }];
21
+ while (stack.length) {
22
+ const f = stack[stack.length - 1];
23
+ const ns = neighborsOf(g, f.v);
24
+ if (f.i < ns.length) {
25
+ const w = ns[f.i++];
26
+ if (!disc.has(w)) {
27
+ disc.set(w, time);
28
+ low.set(w, time++);
29
+ if (f.v === root)
30
+ rootChildren++;
31
+ stack.push({ v: w, parent: f.v, i: 0 });
32
+ }
33
+ else if (w !== f.parent) {
34
+ low.set(f.v, Math.min(low.get(f.v), disc.get(w)));
35
+ }
36
+ continue;
37
+ }
38
+ stack.pop();
39
+ const p = stack[stack.length - 1];
40
+ if (!p)
41
+ continue;
42
+ low.set(p.v, Math.min(low.get(p.v), low.get(f.v)));
43
+ if (p.parent !== null && low.get(f.v) >= disc.get(p.v))
44
+ points.add(p.v);
45
+ if (low.get(f.v) > disc.get(p.v))
46
+ bridges.push(p.v < f.v ? [p.v, f.v] : [f.v, p.v]);
47
+ }
48
+ if (rootChildren > 1)
49
+ points.add(root);
50
+ }
51
+ bridges.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
52
+ return { points: [...points].sort(byNum), bridges };
53
+ }
54
+ /** Territories whose removal disconnects the map, sorted. */
55
+ export function articulationPoints(g) {
56
+ return cuts(g).points;
57
+ }
58
+ /** Edges whose removal disconnects the map, as sorted `[low, high]` pairs. */
59
+ export function findBridges(g) {
60
+ return cuts(g).bridges;
61
+ }
62
+ const primaryCache = new WeakMap();
63
+ /**
64
+ * A territory's cluster: the smallest bonus (by flattened size, then id) that
65
+ * contains it, or `null` when it is in none. Bonuses overlap heavily on real
66
+ * maps, so the smallest one is the meaningful "home" region.
67
+ */
68
+ export function primaryBonusOf(g, territoryId) {
69
+ let index = primaryCache.get(g);
70
+ if (!index) {
71
+ index = new Map();
72
+ const sizes = new Map();
73
+ for (const b of [...g.map.bonuses].sort((a, b) => a.id - b.id)) {
74
+ const ts = bonusTerritories(g, b.id);
75
+ for (const t of ts) {
76
+ const cur = index.get(t);
77
+ if (cur === undefined || ts.length < sizes.get(cur))
78
+ index.set(t, b.id);
79
+ }
80
+ sizes.set(b.id, ts.length);
81
+ }
82
+ primaryCache.set(g, index);
83
+ }
84
+ return index.get(territoryId) ?? null;
85
+ }
86
+ /**
87
+ * Chokepoints: articulation points; endpoints of bridge edges whose two ends
88
+ * lie in different clusters; and territories of degree ≤ `maxConnectorDegree`
89
+ * touching at least two distinct clusters (their own included). A dead end (one
90
+ * neighbour or none) is never one: nothing passes through it, so holding it blocks
91
+ * nothing. True cut points (articulation) come first — a route cannot go around
92
+ * them — then by number of reasons desc, degree asc, id asc.
93
+ */
94
+ export function findChokepoints(g, opts = {}) {
95
+ const maxDeg = opts.maxConnectorDegree ?? 2;
96
+ const { points, bridges } = cuts(g);
97
+ const art = new Set(points);
98
+ const bridgeEnds = new Set();
99
+ for (const [a, b] of bridges) {
100
+ const ca = primaryBonusOf(g, a);
101
+ const cb = primaryBonusOf(g, b);
102
+ if (ca !== null && cb !== null && ca !== cb) {
103
+ bridgeEnds.add(a);
104
+ bridgeEnds.add(b);
105
+ }
106
+ }
107
+ const out = [];
108
+ for (const id of [...g.territoryById.keys()].sort(byNum)) {
109
+ const ns = neighborsOf(g, id);
110
+ if (ns.length < 2)
111
+ continue;
112
+ const own = primaryBonusOf(g, id);
113
+ const others = new Set();
114
+ for (const n of ns) {
115
+ const c = primaryBonusOf(g, n);
116
+ if (c !== null && c !== own)
117
+ others.add(c);
118
+ }
119
+ const clusters = others.size + (own !== null ? 1 : 0);
120
+ const reasons = [];
121
+ if (art.has(id))
122
+ reasons.push('articulation');
123
+ if (bridgeEnds.has(id))
124
+ reasons.push('bridge');
125
+ if (ns.length <= maxDeg && clusters >= 2)
126
+ reasons.push('low-degree-connector');
127
+ if (!reasons.length)
128
+ continue;
129
+ out.push({
130
+ territoryId: id,
131
+ name: g.territoryById.get(id).name,
132
+ degree: ns.length,
133
+ reasons,
134
+ bonusId: own,
135
+ connectsBonusIds: [...others].sort(byNum),
136
+ });
137
+ }
138
+ const cut = (c) => Number(c.reasons[0] === 'articulation');
139
+ return out.sort((a, b) => cut(b) - cut(a) || b.reasons.length - a.reasons.length || a.degree - b.degree || a.territoryId - b.territoryId);
140
+ }
@@ -0,0 +1,231 @@
1
+ // Attack arithmetic under straight rounding and no luck.
2
+ export const DEFAULT_OFFENSIVE_KILL_RATE = 60;
3
+ export const DEFAULT_DEFENSIVE_KILL_RATE = 70;
4
+ /**
5
+ * Fewest attacking armies that take a territory held by `defenders` armies,
6
+ * assuming straight rounding and 0% luck: enough to kill every defender
7
+ * (`round(a·off) ≥ d`) with at least one survivor to move in
8
+ * (`a − round(d·def) ≥ 1`). `null` when attackers cannot kill at all.
9
+ */
10
+ export function armiesToTake(defenders, rates = {}) {
11
+ // Both terms are the luck-free share `expectedKills` rounded half up, solved for exactly.
12
+ const off = rates.offensiveKillRate ?? DEFAULT_OFFENSIVE_KILL_RATE;
13
+ const def = rates.defensiveKillRate ?? DEFAULT_DEFENSIVE_KILL_RATE;
14
+ if (defenders <= 0)
15
+ return 1;
16
+ if (off <= 0)
17
+ return null;
18
+ // round(a·off/100) ≥ d ⇔ a·off ≥ 100d − 50 (integer-exact for integer rates).
19
+ const toKill = Math.ceil((100 * defenders - 50) / off);
20
+ const lost = straightKills(defenders, def);
21
+ return Math.max(toKill, lost + 1);
22
+ }
23
+ /**
24
+ * The luck-free kill share of `n` armies at `ratePct`%: `n·rate/100`, computed in that order
25
+ * so a share that is exactly .5 stays .5 (`n * (rate / 100)` reads 45 at 70% as
26
+ * 31.499999999999996 and rounds it down). Every kill count — {@link armiesToTake},
27
+ * {@link winChance}, {@link guaranteedKills} — starts from this, so they always agree.
28
+ */
29
+ export function expectedKills(n, ratePct) {
30
+ return (n * ratePct) / 100;
31
+ }
32
+ /** {@link expectedKills} rounded half up: the kills of a luck-free straight-rounded round. */
33
+ export function straightKills(n, ratePct) {
34
+ return Math.round(expectedKills(n, ratePct));
35
+ }
36
+ /**
37
+ * A commander fights as this many armies, attacking and defending (the client bundle's
38
+ * `Commander`: attack and defence power `a + 7`). It is never partially damaged — it dies
39
+ * only to 7 damage left over after the armies with it are all killed (armies take damage
40
+ * first; its combat order is last) — so a stack of `d` armies plus a commander falls to
41
+ * exactly the attack that takes `d + 7` armies.
42
+ */
43
+ export const COMMANDER_STRENGTH = 7;
44
+ /**
45
+ * The armies the special units on a territory fight as: {@link COMMANDER_STRENGTH} per
46
+ * commander. Bosses and custom units are not counted (their strength is per-unit data the
47
+ * board does not carry).
48
+ */
49
+ export function specialUnitStrength(units) {
50
+ return (units ?? []).reduce((n, u) => n + (u.kind === 'commander' ? COMMANDER_STRENGTH : 0), 0);
51
+ }
52
+ /** A luck modifier as a fraction in [0, 0.95] (a value above 1 is read as a percent). */
53
+ export function luckFraction(v) {
54
+ if (!v || v <= 0)
55
+ return 0;
56
+ const f = v > 1 ? v / 100 : v;
57
+ return Math.min(f, 0.95);
58
+ }
59
+ const weighted = (rounding) => rounding === 'WeightedRandom';
60
+ /** ln(k!) for k = 0..n, memoised. */
61
+ const logFact = [0];
62
+ function lnFact(k) {
63
+ for (let i = logFact.length; i <= k; i++)
64
+ logFact.push(logFact[i - 1] + Math.log(i));
65
+ return logFact[k];
66
+ }
67
+ function binomial(n, k, p) {
68
+ if (p <= 0)
69
+ return k === 0 ? 1 : 0;
70
+ if (p >= 1)
71
+ return k === n ? 1 : 0;
72
+ return Math.exp(lnFact(n) - lnFact(k) - lnFact(n - k) + k * Math.log(p) + (n - k) * Math.log(1 - p));
73
+ }
74
+ /**
75
+ * The probability that `n` armies at `ratePct`% kill at least `k` (`atLeast`) or at most `k`
76
+ * (`!atLeast`). Summed over the binomial outcomes as 1 − (the failing mass), so a certain
77
+ * outcome is exactly 1 and an impossible one exactly 0.
78
+ */
79
+ function killProbability(n, ratePct, luck, rounding, k, atLeast) {
80
+ const r = ratePct / 100;
81
+ const f = expectedKills(n, ratePct);
82
+ /** P(the kills meet the bound | the expected-plus-random share is x). */
83
+ const meets = (x) => {
84
+ if (weighted(rounding)) {
85
+ const lo = Math.floor(x);
86
+ const frac = x - lo;
87
+ // biome-ignore lint/complexity/useMathMinMax: a NaN fraction must give 0, which Math.max would not.
88
+ const pUp = frac > 0 ? frac : 0;
89
+ // kills = lo + 1 with pUp, else lo.
90
+ const okLo = atLeast ? lo >= k : lo <= k;
91
+ const okHi = atLeast ? lo + 1 >= k : lo + 1 <= k;
92
+ return (okLo ? 1 - pUp : 0) + (okHi ? pUp : 0);
93
+ }
94
+ const kills = Math.round(x);
95
+ return (atLeast ? kills >= k : kills <= k) ? 1 : 0;
96
+ };
97
+ if (luck === 0)
98
+ return meets(f);
99
+ let fail = 0;
100
+ let pass = 0;
101
+ for (let g = 0; g <= n; g++) {
102
+ const m = meets(f + (g - f) * luck);
103
+ const p = binomial(n, g, r);
104
+ if (m < 1)
105
+ fail += p * (1 - m);
106
+ if (m > 0)
107
+ pass += p * m;
108
+ }
109
+ if (fail === 0)
110
+ return 1;
111
+ if (pass === 0)
112
+ return 0;
113
+ return Math.min(1, Math.max(0, 1 - fail));
114
+ }
115
+ /**
116
+ * The exact probability that `attackers` armies capture a territory held by `defenders`:
117
+ * every defender dies and at least one attacker survives. Summed over the binomial
118
+ * distributions — no simulation, no randomness. Exactly 1 when the capture is certain
119
+ * (0% luck under straight rounding is always 0 or 1).
120
+ */
121
+ export function winChance(attackers, defenders, settings = {}) {
122
+ if (attackers <= 0)
123
+ return 0;
124
+ if (defenders <= 0)
125
+ return 1;
126
+ const off = settings.offensiveKillRate ?? DEFAULT_OFFENSIVE_KILL_RATE;
127
+ const def = settings.defensiveKillRate ?? DEFAULT_DEFENSIVE_KILL_RATE;
128
+ if (off <= 0)
129
+ return 0;
130
+ const luck = luckFraction(settings.luck);
131
+ const kill = killProbability(attackers, off, luck, settings.rounding, defenders, true);
132
+ if (kill === 0)
133
+ return 0;
134
+ const survive = killProbability(defenders, def, luck, settings.rounding, attackers - 1, false);
135
+ return kill * survive;
136
+ }
137
+ /**
138
+ * The kills `n` armies at `ratePct`% make whatever the dice: the expected share
139
+ * `(1 − luck)·n·rate` alone, rounded half up (straight) or down (weighted-random, which only
140
+ * guarantees the floor).
141
+ */
142
+ export function guaranteedKills(n, ratePct, luck = 0, rounding = 'StraightRound') {
143
+ if (n <= 0 || ratePct <= 0)
144
+ return 0;
145
+ const x = (1 - luckFraction(luck)) * expectedKills(n, ratePct);
146
+ return weighted(rounding) ? Math.floor(x) : Math.round(x);
147
+ }
148
+ /**
149
+ * The smallest attack larger than `n` that guarantees one more kill at `ratePct`%;
150
+ * `null` when no size ever kills (a zero rate).
151
+ */
152
+ export function nextBreakpoint(n, ratePct, luck = 0, rounding = 'StraightRound') {
153
+ if (ratePct <= 0 || luckFraction(luck) >= 1)
154
+ return null;
155
+ const now = guaranteedKills(Math.max(0, n), ratePct, luck, rounding);
156
+ let m = Math.max(0, n) + 1;
157
+ while (guaranteedKills(m, ratePct, luck, rounding) <= now)
158
+ m++;
159
+ return m;
160
+ }
161
+ /**
162
+ * The efficient attack sizes up to `upTo`: each size that guarantees one more kill than the
163
+ * size below it (e.g. 1, 3, 5, 6, 8, 10, 11, 13 at 60%). Any size between two of them kills
164
+ * no more than the smaller one.
165
+ */
166
+ export function killBreakpoints(ratePct, upTo, luck = 0, rounding = 'StraightRound') {
167
+ const out = [];
168
+ for (let m = 1; m <= upTo; m++)
169
+ if (guaranteedKills(m, ratePct, luck, rounding) > guaranteedKills(m - 1, ratePct, luck, rounding))
170
+ out.push(m);
171
+ return out;
172
+ }
173
+ /**
174
+ * #271: the fewest attackers that can have killed `kills` defenders, at the most every attacker may
175
+ * kill: the offensive rate plus luck's share of the rest (luck L lets each army kill with
176
+ * probability r on top of the (1 − L)·r it always kills, so at most r + L·(1 − r) of a defender
177
+ * each). Straight rounding rounds the share half up; weighted-random rounding may round any
178
+ * fraction up. A lower bound on an attack seen only by what it killed; `null` when attackers
179
+ * cannot kill at all.
180
+ */
181
+ export function fewestAttackersToKill(kills, rates = {}, luck = 0, rounding = 'StraightRound') {
182
+ if (kills <= 0)
183
+ return 0;
184
+ const off = rates.offensiveKillRate ?? DEFAULT_OFFENSIVE_KILL_RATE;
185
+ const best = off + luckFraction(luck) * (100 - off);
186
+ if (best <= 0)
187
+ return null;
188
+ // round(a·best/100) ≥ k ⇔ a·best ≥ 100k − 50; weighted: a·best/100 > k − 1.
189
+ return weighted(rounding) ? Math.floor((100 * (kills - 1)) / best) + 1 : Math.ceil((100 * kills - 50) / best);
190
+ }
191
+ /**
192
+ * #271: the fewest attackers that can have taken a territory held by `defenders`: enough to kill
193
+ * every defender ({@link fewestAttackersToKill}) and one more than the defenders surely kill
194
+ * ({@link guaranteedKills}), so one survives to move in. {@link armiesToTake} when luck is off under
195
+ * straight rounding; `null` when attackers cannot kill at all.
196
+ */
197
+ export function fewestAttackersToTake(defenders, rates = {}, luck = 0, rounding = 'StraightRound') {
198
+ if (defenders <= 0)
199
+ return 1;
200
+ const kill = fewestAttackersToKill(defenders, rates, luck, rounding);
201
+ if (kill === null)
202
+ return null;
203
+ return Math.max(kill, guaranteedKills(defenders, rates.defensiveKillRate ?? DEFAULT_DEFENSIVE_KILL_RATE, luck, rounding) + 1);
204
+ }
205
+ /**
206
+ * The fewest attackers whose {@link winChance} reaches `minChance` against `defenders`;
207
+ * `null` when attackers cannot kill at all.
208
+ */
209
+ export function armiesForChance(defenders, minChance, settings = {}) {
210
+ if (defenders <= 0)
211
+ return 1;
212
+ if ((settings.offensiveKillRate ?? DEFAULT_OFFENSIVE_KILL_RATE) <= 0)
213
+ return null;
214
+ const ok = (n) => winChance(n, defenders, settings) >= minChance;
215
+ // winChance is monotone in the attackers: double, then bisect.
216
+ let hi = Math.max(1, defenders);
217
+ while (!ok(hi)) {
218
+ hi *= 2;
219
+ if (hi > 1_000_000)
220
+ return null;
221
+ }
222
+ let lo = 0;
223
+ while (hi - lo > 1) {
224
+ const mid = (lo + hi) >> 1;
225
+ if (ok(mid))
226
+ hi = mid;
227
+ else
228
+ lo = mid;
229
+ }
230
+ return hi;
231
+ }