@chrischall/warapp-mcp 0.0.0-stage → 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 (179) hide show
  1. package/.claude-plugin/marketplace.json +34 -0
  2. package/.claude-plugin/plugin.json +21 -0
  3. package/.mcp.json +11 -0
  4. package/LICENSE +21 -0
  5. package/README.md +264 -2
  6. package/dist/analysis/award.js +159 -0
  7. package/dist/analysis/bonuses.js +98 -0
  8. package/dist/analysis/breach.js +62 -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/graph.js +82 -0
  19. package/dist/analysis/guard-off.js +54 -0
  20. package/dist/analysis/guess.js +351 -0
  21. package/dist/analysis/headroom.js +241 -0
  22. package/dist/analysis/hold-diff.js +64 -0
  23. package/dist/analysis/how-lost.js +130 -0
  24. package/dist/analysis/index.js +14 -0
  25. package/dist/analysis/local-deploy.js +159 -0
  26. package/dist/analysis/lookahead.js +108 -0
  27. package/dist/analysis/opponent-profile.js +551 -0
  28. package/dist/analysis/opponents.js +1245 -0
  29. package/dist/analysis/outlook.js +633 -0
  30. package/dist/analysis/overrides.js +60 -0
  31. package/dist/analysis/picks.js +1879 -0
  32. package/dist/analysis/plan/after-leftover.js +140 -0
  33. package/dist/analysis/plan/cap-spend.js +242 -0
  34. package/dist/analysis/plan/captures.js +1195 -0
  35. package/dist/analysis/plan/commander.js +236 -0
  36. package/dist/analysis/plan/completed.js +29 -0
  37. package/dist/analysis/plan/conceded-out.js +131 -0
  38. package/dist/analysis/plan/estimates.js +715 -0
  39. package/dist/analysis/plan/guard-off.js +232 -0
  40. package/dist/analysis/plan/holds.js +1631 -0
  41. package/dist/analysis/plan/leftover.js +760 -0
  42. package/dist/analysis/plan/move-order.js +319 -0
  43. package/dist/analysis/plan/orders.js +317 -0
  44. package/dist/analysis/plan/relations.js +702 -0
  45. package/dist/analysis/plan/report.js +672 -0
  46. package/dist/analysis/plan/shared.js +1218 -0
  47. package/dist/analysis/plan/stand-still.js +823 -0
  48. package/dist/analysis/plan/state.js +44 -0
  49. package/dist/analysis/plan/strike.js +1416 -0
  50. package/dist/analysis/plan/targets.js +651 -0
  51. package/dist/analysis/plan/team.js +299 -0
  52. package/dist/analysis/plan/threats.js +927 -0
  53. package/dist/analysis/plan/transfers.js +328 -0
  54. package/dist/analysis/plan/util.js +5 -0
  55. package/dist/analysis/plan/vacated.js +285 -0
  56. package/dist/analysis/planner.js +2922 -0
  57. package/dist/analysis/player-record.js +144 -0
  58. package/dist/analysis/player.js +268 -0
  59. package/dist/analysis/profile.js +347 -0
  60. package/dist/analysis/relations.js +1030 -0
  61. package/dist/analysis/schedule.js +88 -0
  62. package/dist/analysis/since-last.js +50 -0
  63. package/dist/analysis/static-seats.js +71 -0
  64. package/dist/analysis/stress.js +577 -0
  65. package/dist/analysis/team-brief.js +151 -0
  66. package/dist/analysis/tripwire.js +644 -0
  67. package/dist/analysis/turn-sim.js +259 -0
  68. package/dist/analysis/whereabouts.js +1109 -0
  69. package/dist/board.js +105 -0
  70. package/dist/bundle.js +143479 -0
  71. package/dist/cards.js +435 -0
  72. package/dist/chat-cursor.js +135 -0
  73. package/dist/chat.js +192 -0
  74. package/dist/client.js +361 -0
  75. package/dist/config.js +62 -0
  76. package/dist/direct/link.js +102 -0
  77. package/dist/direct/session.js +267 -0
  78. package/dist/direct/transport.js +424 -0
  79. package/dist/guess-salt.js +65 -0
  80. package/dist/hosted.js +24 -0
  81. package/dist/index.js +33 -0
  82. package/dist/join-color.js +140 -0
  83. package/dist/live.js +278 -0
  84. package/dist/map-stats.js +152 -0
  85. package/dist/map-store.js +204 -0
  86. package/dist/move-order.js +141 -0
  87. package/dist/my-games.js +180 -0
  88. package/dist/normalize.js +411 -0
  89. package/dist/open-games.js +537 -0
  90. package/dist/outlook-log.js +138 -0
  91. package/dist/path-lock.js +22 -0
  92. package/dist/pick-list.js +193 -0
  93. package/dist/player-record-store.js +229 -0
  94. package/dist/player-states.js +31 -0
  95. package/dist/profile-store.js +677 -0
  96. package/dist/protocol/bundle.js +375 -0
  97. package/dist/protocol/codec.js +556 -0
  98. package/dist/protocol/decoded.js +12 -0
  99. package/dist/protocol/interp.js +1904 -0
  100. package/dist/protocol/methods.js +531 -0
  101. package/dist/protocol/rpc.js +202 -0
  102. package/dist/push/listener.js +393 -0
  103. package/dist/push/packets.js +66 -0
  104. package/dist/push/socketio.js +333 -0
  105. package/dist/push/websocket.js +179 -0
  106. package/dist/redact.js +62 -0
  107. package/dist/relations-store.js +242 -0
  108. package/dist/replay.js +215 -0
  109. package/dist/scalars.js +28 -0
  110. package/dist/scout.js +346 -0
  111. package/dist/stats.js +269 -0
  112. package/dist/strategy/card-clock.js +185 -0
  113. package/dist/strategy/map-notes.js +128 -0
  114. package/dist/strategy/notes.js +2168 -0
  115. package/dist/team-cards.js +84 -0
  116. package/dist/team-orders.js +150 -0
  117. package/dist/teams.js +19 -0
  118. package/dist/tools/award.js +206 -0
  119. package/dist/tools/begin-turn.js +162 -0
  120. package/dist/tools/board.js +77 -0
  121. package/dist/tools/card-advice.js +256 -0
  122. package/dist/tools/card-effects.js +49 -0
  123. package/dist/tools/card-plays.js +434 -0
  124. package/dist/tools/card-support-advice.js +140 -0
  125. package/dist/tools/chat-inbox.js +146 -0
  126. package/dist/tools/chat.js +483 -0
  127. package/dist/tools/check-plan.js +688 -0
  128. package/dist/tools/commander-check.js +102 -0
  129. package/dist/tools/commitments.js +216 -0
  130. package/dist/tools/common.js +143 -0
  131. package/dist/tools/diplomacy.js +342 -0
  132. package/dist/tools/game.js +126 -0
  133. package/dist/tools/guess-view.js +56 -0
  134. package/dist/tools/healthcheck.js +90 -0
  135. package/dist/tools/hints.js +34 -0
  136. package/dist/tools/how-lost.js +154 -0
  137. package/dist/tools/index.js +142 -0
  138. package/dist/tools/join-game.js +327 -0
  139. package/dist/tools/leave-game.js +181 -0
  140. package/dist/tools/live-context.js +339 -0
  141. package/dist/tools/live.js +404 -0
  142. package/dist/tools/map-stats.js +117 -0
  143. package/dist/tools/map.js +133 -0
  144. package/dist/tools/my-games.js +123 -0
  145. package/dist/tools/open-games.js +104 -0
  146. package/dist/tools/opponents.js +151 -0
  147. package/dist/tools/order-options.js +135 -0
  148. package/dist/tools/picks.js +292 -0
  149. package/dist/tools/profile-hook.js +156 -0
  150. package/dist/tools/profile-opponents.js +121 -0
  151. package/dist/tools/profile-reads.js +99 -0
  152. package/dist/tools/push.js +385 -0
  153. package/dist/tools/relations.js +611 -0
  154. package/dist/tools/resolve.js +45 -0
  155. package/dist/tools/route.js +36 -0
  156. package/dist/tools/scout.js +87 -0
  157. package/dist/tools/session.js +163 -0
  158. package/dist/tools/strategy.js +200 -0
  159. package/dist/tools/stress-opponents.js +83 -0
  160. package/dist/tools/surrender.js +240 -0
  161. package/dist/tools/survival.js +189 -0
  162. package/dist/tools/team-brief.js +266 -0
  163. package/dist/tools/team-source.js +222 -0
  164. package/dist/tools/team.js +182 -0
  165. package/dist/tools/turn.js +2761 -0
  166. package/dist/tools/uncommit.js +160 -0
  167. package/dist/tools/where.js +275 -0
  168. package/dist/tools/write-kit.js +158 -0
  169. package/dist/transport-bridge.js +33 -0
  170. package/dist/trend.js +452 -0
  171. package/dist/version.js +4 -0
  172. package/manifest.json +247 -0
  173. package/mint.yaml +140 -0
  174. package/package.json +68 -4
  175. package/server.json +72 -0
  176. package/skills/warapp-api/SKILL.md +226 -0
  177. package/skills/warapp-api/references/scout.mjs +348 -0
  178. package/skills/warapp-api/scripts/warapp.sh +228 -0
  179. package/skills/warapp-mcp/SKILL.md +1011 -0
@@ -0,0 +1,234 @@
1
+ // Cards the planner does not play, read against its plan (#163): my Bomb (where halving a stack
2
+ // changes a hold, a capture or a commander kill, else hold it), an opponent's Bomb (borders that
3
+ // hold only while unbombed), an opponent's Emergency Blockade (attacks that would die against the
4
+ // wall) and my own (a conceded border where the wall kills more than I give up). Pure and
5
+ // deterministic (ties on ascending territory id); no I/O.
6
+ //
7
+ // Rules (the wiki's Bomb_Card, Turn_phases, Emergency Blockade; docs/STRATEGY.md): a Bomb hits a
8
+ // territory next to one of mine after the deployments and before every move, and kills half its
9
+ // armies — a commander is reported unharmed. An Emergency Blockade turns a territory into a
10
+ // neutral of its armies (that turn's deploy included) times the multiplier, before the attacks;
11
+ // special units count for nothing on it. UNVERIFIED: how war.app rounds the half (each side is
12
+ // read in its worst case: a bombed enemy keeps the larger half, a bombed stack of mine the
13
+ // smaller) and the wall (rounded to the nearest army here).
14
+ import { armiesToTake, COMMANDER_STRENGTH, DEFAULT_DEFENSIVE_KILL_RATE, straightKills } from './combat.js';
15
+ import { neighborsOf } from './graph.js';
16
+ import { bonusTerritories } from './bonuses.js';
17
+ /** The common reads over the board and the plan (shared with card-support.ts). */
18
+ export function reader(cb) {
19
+ const state = new Map(cb.board.territories.map((t) => [t.territoryId, t]));
20
+ const guard = cb.settings?.oneArmyStandsGuard === false ? 0 : 1;
21
+ const rates = {
22
+ ...(cb.settings?.offensiveKillRate !== undefined ? { offensiveKillRate: cb.settings.offensiveKillRate } : {}),
23
+ ...(cb.settings?.defensiveKillRate !== undefined ? { defensiveKillRate: cb.settings.defensiveKillRate } : {}),
24
+ };
25
+ const ownerOf = (t) => {
26
+ const o = state.get(t)?.owner;
27
+ return o?.kind === 'player' ? o.playerId : undefined;
28
+ };
29
+ const isMine = (t) => ownerOf(t) === cb.me;
30
+ const foe = (p) => p !== undefined && p !== cb.me && !cb.friends?.has(p);
31
+ const armiesOf = (t) => state.get(t)?.armies ?? 0;
32
+ const commanderOf = (t, who) => (state.get(t)?.specialUnits ?? []).some((u) => u.kind === 'commander' && who(u.playerId));
33
+ const deployAt = (t) => cb.deploys.filter((d) => d.territoryId === t).reduce((a, d) => a + d.armies, 0);
34
+ const outOf = (t) => cb.moves.filter((m) => m.from === t).reduce((a, m) => a + m.armies, 0);
35
+ const transfersInto = (t) => cb.moves.filter((m) => m.to === t && m.kind === 'transfer' && isMine(m.from)).reduce((a, m) => a + m.armies, 0);
36
+ const attacksOn = (t) => cb.moves.filter((m) => m.to === t && m.kind === 'attack').reduce((a, m) => a + m.armies, 0);
37
+ /** My armies on `t` once the plan's deploys and moves have run (captures not counted). */
38
+ const after = (t) => armiesOf(t) + deployAt(t) - outOf(t) + transfersInto(t);
39
+ const toTake = (d) => armiesToTake(d, rates) ?? Infinity;
40
+ const ids = [...state.keys()].sort((a, b) => a - b);
41
+ /**
42
+ * Each opponent's stacks next to `t` plus its deploy (the strongest one), with `bombed` halved by
43
+ * a bomb. The bomb lands after the deploys, so the worst case is taken: an owner with another
44
+ * stack next to `t` deploys there, unhalved (d + ⌈a/2⌉ + the other stacks, less the guards); one
45
+ * whose only stack next to `t` is the bombed one deploys on it, and the deploy is halved with it
46
+ * (⌈(a + d)/2⌉ less the guard).
47
+ */
48
+ const reachOf = (t, bombed) => {
49
+ const by = new Map();
50
+ for (const n of neighborsOf(cb.graph, t)) {
51
+ const p = ownerOf(n);
52
+ if (!foe(p) || state.get(n)?.armies === null)
53
+ continue;
54
+ const e = by.get(p) ?? { others: 0, hasOther: false };
55
+ if (n === bombed)
56
+ e.bombed = armiesOf(n);
57
+ else {
58
+ e.others += Math.max(0, armiesOf(n) - guard);
59
+ e.hasOther = true;
60
+ }
61
+ by.set(p, e);
62
+ }
63
+ const d = cb.enemyDeploy;
64
+ let best;
65
+ for (const [player, e] of [...by].sort((a, b) => a[0] - b[0])) {
66
+ const reach = e.bombed === undefined
67
+ ? d + e.others
68
+ : e.hasOther
69
+ ? d + e.others + Math.max(0, Math.ceil(e.bombed / 2) - guard)
70
+ : Math.max(0, Math.ceil((e.bombed + d) / 2) - guard);
71
+ if (!best || reach > best.reach)
72
+ best = { player, reach };
73
+ }
74
+ return best;
75
+ };
76
+ /** Each opponent's reach at `t` alone (its movable stacks next to `t` plus its deploy), by player. */
77
+ const reachByPlayer = (t) => {
78
+ const by = new Map();
79
+ for (const n of neighborsOf(cb.graph, t)) {
80
+ const p = ownerOf(n);
81
+ if (!foe(p) || state.get(n)?.armies === null)
82
+ continue;
83
+ by.set(p, (by.get(p) ?? cb.enemyDeploy) + Math.max(0, armiesOf(n) - guard));
84
+ }
85
+ return by;
86
+ };
87
+ /** The fewest armies on `t` (its commander there counted apart) that `reach` cannot take. */
88
+ const holdNeed = (reach, commander) => {
89
+ const extra = commander ? COMMANDER_STRENGTH : 0;
90
+ let h = 0;
91
+ while (toTake(h + extra) <= reach)
92
+ h++;
93
+ return h;
94
+ };
95
+ return { state, guard, rates, ownerOf, isMine, foe, armiesOf, commanderOf, deployAt, outOf, transfersInto, attacksOn, after, toTake, ids, reachOf, reachByPlayer, holdNeed };
96
+ }
97
+ const KIND_RANK = { commander: 0, hold: 1, capture: 2 };
98
+ /**
99
+ * Where to play my Bomb this turn: an opponent's territory next to mine where halving its armies
100
+ * plus the owner's deploy (a commander unharmed) makes a commander kill, a hold or a capture that
101
+ * fails without it — in that order, then the bigger stack. Else hold the card: the threat of it
102
+ * keeps the opponent from stacking, and is worth more than a blast that changes nothing.
103
+ */
104
+ export function bombAdvice(cb) {
105
+ const r = reader(cb);
106
+ const best = [];
107
+ for (const t of r.ids) {
108
+ const p = r.ownerOf(t);
109
+ if (!r.foe(p) || r.state.get(t)?.armies === null)
110
+ continue;
111
+ if (cb.noBomb?.has(t))
112
+ continue;
113
+ const borders = neighborsOf(cb.graph, t).filter(r.isMine);
114
+ if (!borders.length)
115
+ continue;
116
+ const n = r.armiesOf(t) + cb.enemyDeploy;
117
+ const left = Math.ceil(n / 2);
118
+ const cmd = r.commanderOf(t, (q) => q === p) ? COMMANDER_STRENGTH : 0;
119
+ const planned = r.attacksOn(t);
120
+ const free = planned + borders.reduce((a, b) => a + Math.max(0, r.after(b) - r.guard), 0);
121
+ const label = `player ${p}'s ${r.armiesOf(t)} + its deploy of ${cb.enemyDeploy} on ${t}`;
122
+ if (cmd > 0 && r.toTake(left + cmd) <= free && r.toTake(n + cmd) > free) {
123
+ best.push({ target: t, kind: 'commander', stake: n, why: `halving ${label} leaves ${left} with its commander, which my ${free} next to it can kill (not the whole ${n})` });
124
+ continue;
125
+ }
126
+ const held = borders.filter((b) => {
127
+ const reach = r.reachOf(b)?.reach ?? 0;
128
+ const bombed = r.reachOf(b, t)?.reach ?? 0;
129
+ const need = r.toTake(r.after(b) + (r.commanderOf(b, (q) => q === cb.me) ? COMMANDER_STRENGTH : 0));
130
+ return need <= reach && need > bombed;
131
+ });
132
+ if (held.length) {
133
+ best.push({ target: t, kind: 'hold', stake: n, why: `halving ${label} leaves too few to take ${held.join(', ')}, which fall${held.length === 1 ? 's' : ''} to it unbombed` });
134
+ continue;
135
+ }
136
+ if (planned > 0 ? r.toTake(n + cmd) > planned && r.toTake(left + cmd) <= planned : r.toTake(left + cmd) <= free && r.toTake(n + cmd) > free) {
137
+ const sent = planned > 0 ? planned : free;
138
+ best.push({ target: t, kind: 'capture', stake: n, why: `halving ${label} lets my ${sent} take it even if the owner deploys there (it needs ${r.toTake(n + cmd)} unbombed)` });
139
+ }
140
+ }
141
+ best.sort((a, b) => KIND_RANK[a.kind] - KIND_RANK[b.kind] || b.stake - a.stake || a.target - b.target);
142
+ const top = best[0];
143
+ if (!top) {
144
+ return {
145
+ why: 'Hold the Bomb: halving no stack next to me changes a hold, a capture or a commander kill this turn, and while I hold it the opponent cannot safely stack.',
146
+ };
147
+ }
148
+ return { target: top.target, kind: top.kind, why: `Bomb ${top.target}: ${top.why}.` };
149
+ }
150
+ /**
151
+ * My borders (after the plan) that hold against the opponent's reach unbombed but fall once a
152
+ * bomb halves them: the bomb lands after my deploys and before every move, so it halves what
153
+ * stands there (moves out are cut from what is left; transfers in still arrive). Ascending id.
154
+ */
155
+ export function bombExposure(cb) {
156
+ const r = reader(cb);
157
+ const out = [];
158
+ for (const b of r.ids) {
159
+ if (!r.isMine(b))
160
+ continue;
161
+ const reach = r.reachOf(b);
162
+ if (!reach)
163
+ continue;
164
+ const cmd = r.commanderOf(b, (q) => q === cb.me);
165
+ const extra = cmd ? COMMANDER_STRENGTH : 0;
166
+ const armies = r.after(b);
167
+ const kept = Math.floor((r.armiesOf(b) + r.deployAt(b)) / 2);
168
+ const bombed = Math.max(0, kept - r.outOf(b)) + r.transfersInto(b);
169
+ if (r.toTake(armies + extra) > reach.reach && r.toTake(bombed + extra) <= reach.reach) {
170
+ out.push({ territory: b, armies, bombed, reach: reach.reach, player: reach.player, commander: cmd });
171
+ }
172
+ }
173
+ return out;
174
+ }
175
+ /** The wall an Emergency Blockade makes of `armies` at `multiplier` (rounded: unverified). */
176
+ const wallOf = (armies, multiplier) => Math.round(Math.max(0, armies) * multiplier);
177
+ /**
178
+ * The planned attacks on an opponent's territory that its Emergency Blockade would stop: the
179
+ * owner turns it into a neutral of (its armies + its deploy) × the multiplier before the attacks,
180
+ * and what I send cannot take that. Ascending target id.
181
+ */
182
+ export function wallThreats(cb, multiplier) {
183
+ const r = reader(cb);
184
+ const out = [];
185
+ for (const t of r.ids) {
186
+ const p = r.ownerOf(t);
187
+ if (!r.foe(p))
188
+ continue;
189
+ const attackers = r.attacksOn(t);
190
+ if (attackers <= 0)
191
+ continue;
192
+ const wall = wallOf(r.armiesOf(t) + cb.enemyDeploy, multiplier);
193
+ if (r.toTake(wall) > attackers)
194
+ out.push({ target: t, player: p, attackers, wall });
195
+ }
196
+ return out;
197
+ }
198
+ /**
199
+ * Where my Emergency Blockade pays: a border the plan concedes, where the wall of my armies there
200
+ * (this turn's deploy included) times the multiplier kills more of the stack that can reach it
201
+ * than the armies I give up — never on my commander's territory (it would be lost with it),
202
+ * never on one the plan moves armies out of (they would be lost with it: the wall comes before the
203
+ * moves) and never on a member of a bonus I hold whole at the start of the turn (I need it). The best by
204
+ * kills over armies given up, then ascending id; `undefined` when none pays.
205
+ */
206
+ export function wallOffer(cb, multiplier, conceded) {
207
+ const r = reader(cb);
208
+ const defence = cb.settings?.defensiveKillRate ?? DEFAULT_DEFENSIVE_KILL_RATE;
209
+ const held = (id) => cb.graph.map.bonuses.some((bonus) => {
210
+ if (bonus.value <= 0)
211
+ return false;
212
+ const members = bonusTerritories(cb.graph, bonus.id);
213
+ return members.includes(id) && members.every(r.isMine);
214
+ });
215
+ let best;
216
+ for (const c of [...conceded].sort((a, b) => a - b)) {
217
+ // A border the plan withdraws from is skipped: the wall turns it neutral before the moves, so
218
+ // the armies the plan moves out of it would be lost with it.
219
+ if (!r.isMine(c) || r.commanderOf(c, (q) => q === cb.me) || held(c) || r.outOf(c) > 0)
220
+ continue;
221
+ const reach = r.reachOf(c);
222
+ if (!reach)
223
+ continue;
224
+ const givesUp = r.armiesOf(c) + r.deployAt(c);
225
+ const wall = wallOf(givesUp, multiplier);
226
+ const kills = Math.min(reach.reach, straightKills(wall, defence));
227
+ if (kills <= givesUp)
228
+ continue;
229
+ const offer = { territory: c, givesUp, wall, player: reach.player, reach: reach.reach, kills };
230
+ if (!best || kills - givesUp > best.kills - best.givesUp)
231
+ best = offer;
232
+ }
233
+ return best;
234
+ }
@@ -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
+ }