@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
+ // How a lost game was lost (#274 item 5), read from the boards this server cached while it played.
2
+ // Pure and deterministic; no I/O.
3
+ //
4
+ // The board cached for turn T is the board turn T was planned on, before it resolved, and a player
5
+ // eliminated on turn T has no board after it. So the newest cached board on which I hold anything is
6
+ // the turn I was most likely eliminated on: certain only when that is the newest completed turn
7
+ // (`turnsCompleted === T`: the game ended on it, or, #283, the others play on and it just resolved),
8
+ // since otherwise this server may simply have stopped planning. The cause
9
+ // is read from that board:
10
+ // - `commander`: my commander stands on it. Losing the commander eliminates a player, and losing every
11
+ // territory at once on a board where I held more is far less likely, so the commander's territory is
12
+ // taken to be what fell (an inference, never seen). Given my cached orders for the turn, what stood
13
+ // there is a range: `low` = armies + my deploys − my moves out (the attack after they left, before my
14
+ // moves in landed), `high` = armies + my deploys + my moves in (after they landed, before any left); the attack that took it needed at least
15
+ // `armiesToTake(low + COMMANDER_STRENGTH)` at the game's kill rates (exact only at 0% luck under
16
+ // straight rounding; with luck an expectation). `held.uncertain` marks a range my orders cannot pin:
17
+ // an order `moves` leaves out (a percentage, Attack Only or Transfer Only one, kept only in `sent`) or
18
+ // an Airlift or other card play touches the territory.
19
+ // When that turn's orders walk the commander (a move flagged `commander`), it is read at the walk's
20
+ // destination, `territoryCertain: false` (it may have fallen on its start before the walk ran): the
21
+ // range there is from after the walk landed (its armies in `low`), and the neighbours are both
22
+ // territories'. A walk known only from `sent` (a percentage order) has no army count and no range.
23
+ // - `last-territories`: no commander of mine on the board (and the game was not known to have
24
+ // commanders): the territories I still held, which all fell.
25
+ // - `unknown`: the game had commanders but the board shows none of mine (a board cached before
26
+ // special units were decoded).
27
+ // Who: the players on the territories next to what fell (by the map's adjacency; a fogged neighbour
28
+ // is `playerId: null`). `by` names a taker only when exactly one player borders it and no neighbour
29
+ // is fogged. Ids only: names are the tool's business.
30
+ import { armiesToTake, COMMANDER_STRENGTH, luckFraction } from './combat.js';
31
+ export const MAX_LAST_TERRITORIES = 5;
32
+ const ownerId = (t) => t.owner.kind === 'player' ? t.owner.playerId : t.owner.kind === 'unknown' ? null : undefined;
33
+ function neighboursOf(board, me, fallen, adjacency) {
34
+ const byId = new Map(board.territories.map((t) => [t.territoryId, t]));
35
+ const fallenSet = new Set(fallen);
36
+ const seen = new Set();
37
+ const groups = new Map();
38
+ for (const f of fallen)
39
+ for (const n of adjacency.get(f) ?? []) {
40
+ if (fallenSet.has(n) || seen.has(n))
41
+ continue;
42
+ seen.add(n);
43
+ const t = byId.get(n);
44
+ // Not on the board, mine, neutral or pickable: no attacker there.
45
+ if (!t)
46
+ continue;
47
+ const owner = ownerId(t);
48
+ if (owner === undefined || owner === me)
49
+ continue;
50
+ const g = groups.get(owner) ?? { territories: 0, armies: null };
51
+ g.territories++;
52
+ if (owner !== null && t.armies !== null)
53
+ g.armies = (g.armies ?? 0) + t.armies;
54
+ groups.set(owner, g);
55
+ }
56
+ return [...groups.entries()]
57
+ .sort(([a], [b]) => (a === null ? 1 : b === null ? -1 : a - b))
58
+ .map(([playerId, g]) => ({ playerId, ...g }));
59
+ }
60
+ /** How the game was lost, from the newest cached board on which I hold a territory; `undefined` without one. */
61
+ export function howLost(input) {
62
+ const { me } = input;
63
+ const mineOn = (b) => b.territories.filter((t) => t.owner.kind === 'player' && t.owner.playerId === me);
64
+ const last = [...input.boards].sort((a, b) => b.turn - a.turn).find((b) => mineOn(b.board).length > 0);
65
+ if (!last)
66
+ return undefined;
67
+ const { turn, board } = last;
68
+ const mine = mineOn(board);
69
+ const cmd = mine.find((t) => t.specialUnits?.some((u) => u.kind === 'commander' && u.playerId === me));
70
+ const cause = cmd ? 'commander' : input.commanders ? 'unknown' : 'last-territories';
71
+ const out = {
72
+ turn,
73
+ turnCertain: input.turnsCompleted === turn,
74
+ cause,
75
+ territoriesHeld: mine.length,
76
+ neighbours: null,
77
+ by: null,
78
+ };
79
+ let fallen = [];
80
+ if (cmd) {
81
+ const orders = input.orders.get(turn);
82
+ const start = cmd.territoryId;
83
+ const walkMove = orders?.moves.find((m) => m.commander && m.from === start);
84
+ const walkSent = orders?.sent?.find((m) => m.commander && m.from === start);
85
+ const walk = walkMove
86
+ ? { from: start, to: walkMove.to, armies: walkMove.armies }
87
+ : walkSent
88
+ ? { from: start, to: walkSent.to, armies: null }
89
+ : undefined;
90
+ const id = walk ? walk.to : start;
91
+ const at = walk ? board.territories.find((t) => t.territoryId === id) : cmd;
92
+ const armies = at && ownerId(at) === me ? (at.armies ?? 0) : 0;
93
+ const sum = (xs) => xs.reduce((s, x) => s + x.armies, 0);
94
+ const deployed = orders ? sum(orders.deploys.filter((d) => d.territoryId === id)) : null;
95
+ const movedOut = orders ? sum(orders.moves.filter((m) => m.from === id)) : null;
96
+ const movedIn = orders ? sum(orders.moves.filter((m) => m.to === id)) : null;
97
+ // An order `moves` leaves out (kept only in `sent`), or a card play, touching it: the count is a bound.
98
+ const touches = (m) => m.from === id || m.to === id || m.target === id;
99
+ const uncertain = !!orders && ((orders.sent?.filter(touches).length ?? 0) > orders.moves.filter(touches).length || (orders.cards ?? []).some(touches));
100
+ // At a walk's destination the commander stands only once the walk has landed: its armies are in `low`.
101
+ const walkIn = walk ? walk.armies : 0;
102
+ const held = deployed !== null && movedOut !== null && movedIn !== null && walkIn !== null && (!walk || (at && ownerId(at) === me))
103
+ ? { low: Math.max(0, armies + deployed - movedOut + walkIn), high: armies + deployed + movedIn, uncertain }
104
+ : null;
105
+ out.commander = {
106
+ territoryId: id,
107
+ territoryCertain: !walk,
108
+ ...(walk ? { walk } : {}),
109
+ armies,
110
+ deployed,
111
+ movedOut,
112
+ movedIn,
113
+ held,
114
+ attackersNeeded: held ? armiesToTake(held.low + COMMANDER_STRENGTH, input.rates) : null,
115
+ exact: luckFraction(input.rates.luck) === 0 && input.rates.rounding !== 'WeightedRandom',
116
+ };
117
+ fallen = walk ? [start, id] : [id];
118
+ }
119
+ else if (cause === 'last-territories') {
120
+ const sorted = [...mine].sort((a, b) => a.territoryId - b.territoryId);
121
+ out.lastTerritories = sorted.slice(0, MAX_LAST_TERRITORIES).map((t) => ({ territoryId: t.territoryId, armies: t.armies }));
122
+ fallen = sorted.map((t) => t.territoryId);
123
+ }
124
+ if (input.adjacency && fallen.length) {
125
+ out.neighbours = neighboursOf(board, me, fallen, input.adjacency);
126
+ const players = out.neighbours.filter((n) => n.playerId !== null);
127
+ out.by = players.length === 1 && players.length === out.neighbours.length ? players[0].playerId : null;
128
+ }
129
+ return out;
130
+ }
@@ -0,0 +1,14 @@
1
+ // Map + board analysis core. Pure and deterministic; no I/O.
2
+ export * from './graph.js';
3
+ export * from './bonuses.js';
4
+ export * from './chokepoints.js';
5
+ export * from './combat.js';
6
+ export * from './player.js';
7
+ export * from './planner.js';
8
+ export * from './local-deploy.js';
9
+ export * from './picks.js';
10
+ export * from './overrides.js';
11
+ export * from './profile.js';
12
+ export * from './exchange.js';
13
+ export * from './opponents.js';
14
+ export * from './guess.js';
@@ -0,0 +1,179 @@
1
+ // Local Deployment (GameFeed `LocalDeployments`): armies earned from a bonus may
2
+ // only be deployed on that bonus's territories; the rest of the income (base
3
+ // income, per-territory income, card armies) may go anywhere. Which income is
4
+ // "anywhere" is UNVERIFIED beyond the bonus rule itself — see docs/WARAPP-API.md.
5
+ // Pure and deterministic.
6
+ import { bonusTerritories } from './bonuses.js';
7
+ /**
8
+ * The deploy pools for a player holding `held` with this turn's `income`: one per
9
+ * fully held bonus of positive value (a superbonus gets its own pool over all its
10
+ * territories, beside its member bonuses' pools), and the rest anywhere.
11
+ */
12
+ export function deployPools(g, held, income) {
13
+ const bonuses = [];
14
+ for (const b of g.map.bonuses) {
15
+ if (b.value <= 0)
16
+ continue;
17
+ const ts = bonusTerritories(g, b.id);
18
+ if (!ts.length || !ts.every((t) => held.has(t)))
19
+ continue;
20
+ bonuses.push({ bonusId: b.id, name: b.name, value: b.value, territoryIds: [...ts] });
21
+ }
22
+ bonuses.sort((a, b) => a.territoryIds.length - b.territoryIds.length || a.bonusId - b.bonusId);
23
+ const total = bonuses.reduce((s, p) => s + p.value, 0);
24
+ let trimmed = 0;
25
+ // Never more pooled armies than the income: trim the outermost pools first.
26
+ for (let i = bonuses.length - 1, over = total - Math.max(0, income); i >= 0 && over > 0; i--) {
27
+ const cut = Math.min(over, bonuses[i].value);
28
+ bonuses[i].value -= cut;
29
+ over -= cut;
30
+ trimmed += cut;
31
+ }
32
+ return { anywhere: Math.max(0, income - (total - trimmed)), bonuses, trimmed };
33
+ }
34
+ /**
35
+ * Charge deploys (armies by territory) to the pools so that as few armies as possible
36
+ * draw on the anywhere pool: a maximum flow from the deployed territories to the bonus
37
+ * pools that contain them (each pool capped at its value). The deploys are valid
38
+ * exactly when `anywhereUsed ≤ anywhere`.
39
+ *
40
+ * Exact for any bonus layout — nested (member bonuses inside a superbonus) or
41
+ * overlapping without nesting. A greedy pass (innermost pool first, lowest territory
42
+ * first) seeds the flow; augmenting paths then move armies between pools until no
43
+ * more can be absorbed (Ford–Fulkerson; deterministic: BFS in pool and id order).
44
+ */
45
+ export function chargeDeploys(pools, deploys) {
46
+ const ps = pools.bonuses;
47
+ const left = new Map([...deploys].filter(([, n]) => n > 0).sort(([a], [b]) => a - b));
48
+ /** flow[i]: armies from each territory charged to pool i. */
49
+ const flow = ps.map(() => new Map());
50
+ const room = ps.map((p) => p.value);
51
+ const add = (i, t, n) => {
52
+ const f = (flow[i].get(t) ?? 0) + n;
53
+ if (f)
54
+ flow[i].set(t, f);
55
+ else
56
+ flow[i].delete(t);
57
+ room[i] -= n;
58
+ left.set(t, left.get(t) - n);
59
+ };
60
+ // Greedy seed: innermost pool first, its lowest territories first.
61
+ ps.forEach((p, i) => {
62
+ for (const t of p.territoryIds) {
63
+ const take = Math.min(left.get(t) ?? 0, room[i]);
64
+ if (take > 0)
65
+ add(i, t, take);
66
+ }
67
+ });
68
+ const members = ps.map((p) => new Set(p.territoryIds));
69
+ // Augment: from a territory with armies left, through pools (forward: any pool holding
70
+ // the territory) and back (a territory already charged to that pool), to a pool with room.
71
+ for (;;) {
72
+ const start = [...left].filter(([, n]) => n > 0).map(([t]) => t);
73
+ if (!start.length || room.every((r) => r <= 0))
74
+ break;
75
+ const viaPool = new Map(); // pool → territory it was reached from
76
+ const viaTerr = new Map(); // territory → pool it was reached from (-1: a start)
77
+ for (const t of start)
78
+ viaTerr.set(t, -1);
79
+ const queue = [...start];
80
+ let end = -1;
81
+ while (queue.length && end < 0) {
82
+ const t = queue.shift();
83
+ for (let i = 0; i < ps.length && end < 0; i++) {
84
+ if (viaPool.has(i) || !members[i].has(t))
85
+ continue;
86
+ viaPool.set(i, t);
87
+ if (room[i] > 0) {
88
+ end = i;
89
+ break;
90
+ }
91
+ for (const u of [...flow[i].keys()].sort((a, b) => a - b)) {
92
+ if (viaTerr.has(u))
93
+ continue;
94
+ viaTerr.set(u, i);
95
+ queue.push(u);
96
+ }
97
+ }
98
+ }
99
+ if (end < 0)
100
+ break;
101
+ // Walk the path back from the pool with room to its start; the bottleneck is the
102
+ // pool's room, the start's armies left, and each reversed charge.
103
+ const path = [];
104
+ for (let i = end;;) {
105
+ const t = viaPool.get(i);
106
+ path.push([i, t]);
107
+ const back = viaTerr.get(t);
108
+ if (back < 0)
109
+ break;
110
+ i = back;
111
+ }
112
+ let n = Math.min(room[end], left.get(path[path.length - 1][1]));
113
+ for (let k = 0; k < path.length - 1; k++)
114
+ n = Math.min(n, flow[path[k + 1][0]].get(path[k][1]));
115
+ // Each step charges `terr` to `pool`; each earlier pool on the path releases the same territory.
116
+ for (let k = 0; k < path.length; k++) {
117
+ const [i, t] = path[k];
118
+ add(i, t, n);
119
+ if (k + 1 < path.length)
120
+ add(path[k + 1][0], t, -n);
121
+ }
122
+ }
123
+ const used = new Map();
124
+ ps.forEach((p, i) => used.set(p.bonusId, p.value - room[i]));
125
+ let anywhereUsed = 0;
126
+ for (const n of left.values())
127
+ anywhereUsed += n;
128
+ return { anywhereUsed, used };
129
+ }
130
+ /**
131
+ * What an opponent may deploy anywhere under Local Deployment (#293): its free income — its base
132
+ * income (never below `floor`) plus the Reinforcement card armies its estimate counts. Bonus armies
133
+ * land only in their own bonus.
134
+ */
135
+ export function freeIncome(base, floor, card = 0) {
136
+ return Math.max(floor, base) + Math.max(0, card);
137
+ }
138
+ /**
139
+ * An opponent's deploy under Local Deployment on `on` (#180, #293), as the planner bounds it (#128)
140
+ * and warapp_check_plan's stress test does: its free income ({@link freeIncome}) plus the pools of the
141
+ * bonuses it could hold ({@link couldHoldBonusPools}) that contain one of `on`, never above the
142
+ * estimate. A total read above that (a tracked figure, the fog prior) never lands on one border.
143
+ * With per-territory income (`perTerritory`) the income no pool can carry (per-territory income on
144
+ * territories the fog hides) may land anywhere too: what the estimate holds beyond every bonus it
145
+ * could hold together counts as free (with no pools, the whole estimate reaches). Without it, nothing
146
+ * beyond the free income and those pools does.
147
+ */
148
+ export function enemyDeployReaching(estimate, free, pools, on, perTerritory) {
149
+ const pooled = pools.reduce((n, q) => n + q.value, 0);
150
+ const here = pools.reduce((n, q) => n + (on.some((t) => q.members.has(t)) ? q.value : 0), 0);
151
+ const anywhere = perTerritory ? Math.max(Math.min(estimate, free), estimate - pooled) : free;
152
+ return Math.min(estimate, anywhere + here);
153
+ }
154
+ /**
155
+ * Each player's Local Deployment pools as far as the board can tell (#293): the bonuses (value above 0)
156
+ * it could hold — none of their territories shown with another owner (`ownerOf` gives a player id, `null`
157
+ * for an owner shown that is no player, `undefined` when the board hides the owner). For each of
158
+ * `players`, sorted by bonus id. A bonus it visibly holds in full is one of them; so is one the fog hides.
159
+ */
160
+ export function couldHoldBonusPools(g, players, ownerOf) {
161
+ const out = new Map();
162
+ for (const p of players)
163
+ out.set(p, []);
164
+ for (const b of [...g.map.bonuses].sort((x, y) => x.id - y.id)) {
165
+ if (b.value <= 0)
166
+ continue;
167
+ const ts = bonusTerritories(g, b.id);
168
+ if (!ts.length)
169
+ continue;
170
+ const members = new Set(ts);
171
+ for (const p of players)
172
+ if (ts.every((t) => {
173
+ const o = ownerOf(t);
174
+ return o === undefined || o === p;
175
+ }))
176
+ out.get(p).push({ bonusId: b.id, value: b.value, members });
177
+ }
178
+ return out;
179
+ }
@@ -0,0 +1,108 @@
1
+ // One turn ahead (#156, #172): a territory of mine that no enemy stack touches today can be a
2
+ // border tomorrow. For each stack, each territory beside it that it can take this turn (mine or
3
+ // neutral), and each territory of mine beyond that one, the two turns are carried out: the stack
4
+ // takes the one in between with its deploy (under whichever move order leaves it strongest
5
+ // there), then attacks on with the survivors and its next deploy. I am taken to add nothing next
6
+ // turn. Each step is a simulated turn under the game's settings, so with One Army Must Stand Guard
7
+ // off the stack moves every army both times and arrives whole (#276); with it on, one stays behind
8
+ // at each step. Pure and deterministic; the reaches come out in a fixed order (opponents, stacks and
9
+ // territories ascending, as the graph lists neighbours).
10
+ //
11
+ // The one computation behind `warapp_check_plan`'s `exposedNextTurn` (stress.ts, which keeps
12
+ // only the reaches that take the territory) and the planner's two-step hold (planner.ts rule 6,
13
+ // which keeps what the territory needs against them). `needs` is luck-free (check_plan's measure);
14
+ // the planner measures its hold from `power` as its one-step holds are, never below `needs`.
15
+ import { COMMANDER_STRENGTH, DEFAULT_OFFENSIVE_KILL_RATE, straightKills } from './combat.js';
16
+ import { neighborsOf } from './graph.js';
17
+ import { simTerritories, simulateTurn } from './turn-sim.js';
18
+ const byNum = (a, b) => a - b;
19
+ export function twoStepReaches(input) {
20
+ const { graph, board, me, teams } = input;
21
+ const start = simTerritories(board);
22
+ const friendly = (owner) => owner === me || (typeof owner === 'number' && teams !== undefined && teams.get(owner) !== undefined && teams.get(owner) === teams.get(me));
23
+ const myDeploys = (input.deploys ?? []).map((d) => ({ player: me, territoryId: d.territoryId, armies: d.armies }));
24
+ const myOrders = (input.moves ?? []).map((m) => ({ ...m }));
25
+ const simulate = (deploys, theirs, moveOrder) => simulateTurn({
26
+ graph,
27
+ board,
28
+ deploys: [...myDeploys, ...deploys],
29
+ orders: [{ player: me, orders: myOrders }, ...(theirs ? [theirs] : [])],
30
+ moveOrder,
31
+ ...(input.settings ? { settings: input.settings } : {}),
32
+ ...(teams ? { teams } : {}),
33
+ ...(input.orderPriority ? { orderPriority: [me] } : {}),
34
+ });
35
+ const baseline = simulate([], undefined, [me]);
36
+ const mineAfter = new Set([...baseline.territories].filter(([, t]) => t.owner === me).map(([id]) => id));
37
+ const only = input.only ?? (() => true);
38
+ const off = input.settings?.offensiveKillRate ?? DEFAULT_OFFENSIVE_KILL_RATE;
39
+ const firsts = input.firstMover !== undefined ? [input.firstMover] : ['me', 'opponent'];
40
+ const out = [];
41
+ for (const opp of [...input.opponents].sort((a, b) => a.id - b.id)) {
42
+ if (opp.id === me || friendly(opp.id))
43
+ continue;
44
+ const deploy = Math.max(0, Math.floor(opp.deploy));
45
+ const theirDeploy = (territoryId) => (deploy > 0 ? [{ player: opp.id, territoryId, armies: deploy }] : []);
46
+ const stacks = [...start].filter(([, t]) => t.owner === opp.id).map(([id]) => id).sort(byNum);
47
+ for (const from of stacks) {
48
+ const beside = new Set(neighborsOf(graph, from));
49
+ for (const via of beside) {
50
+ const between = start.get(via);
51
+ // The territory in between must be one it can attack and whose defenders are known.
52
+ if (!between || between.owner === 'unknown' || between.owner === opp.id)
53
+ continue;
54
+ if (typeof between.owner === 'number' && between.owner !== me && teams?.get(between.owner) !== undefined && teams.get(between.owner) === teams.get(opp.id))
55
+ continue;
56
+ // Beyond it: territories I hold after my orders that this stack does not touch today.
57
+ const beyond = neighborsOf(graph, via).filter((t) => t !== from && mineAfter.has(t) && !beside.has(t) && only(t));
58
+ if (!beyond.length)
59
+ continue;
60
+ // This turn: the stack takes it, under whichever move order leaves it strongest there.
61
+ let first;
62
+ for (const order1 of firsts) {
63
+ const r = simulate(theirDeploy(from), { player: opp.id, orders: [{ from, to: via, armies: (start.get(from)?.armies ?? 0) + deploy, withCommander: true }] }, order1 === 'me' ? [me, opp.id] : [opp.id, me]);
64
+ const held = r.territories.get(via);
65
+ if (held?.owner !== opp.id)
66
+ continue;
67
+ if (!first || held.armies > (first.territories.get(via)?.armies ?? 0))
68
+ first = r;
69
+ }
70
+ if (!first)
71
+ continue;
72
+ for (const territory of beyond) {
73
+ const there = first.territories.get(territory);
74
+ if (!there || there.owner !== me)
75
+ continue;
76
+ // Next turn: it deploys there again and attacks on; I add nothing.
77
+ const second = simulateTurn({
78
+ graph,
79
+ board,
80
+ start: first.territories,
81
+ deploys: theirDeploy(via),
82
+ orders: [{ player: opp.id, orders: [{ from: via, to: territory, armies: (first.territories.get(via)?.armies ?? 0) + deploy, withCommander: true }] }],
83
+ moveOrder: [opp.id],
84
+ ...(input.settings ? { settings: input.settings } : {}),
85
+ ...(teams ? { teams } : {}),
86
+ });
87
+ const blow = second.log[0];
88
+ if (!blow)
89
+ continue;
90
+ const attackers = blow.sent;
91
+ const power = attackers + (first.territories.get(via)?.commander === opp.id ? COMMANDER_STRENGTH : 0);
92
+ out.push({
93
+ territory,
94
+ armies: there.armies,
95
+ opponent: opp.id,
96
+ from,
97
+ via,
98
+ attackers,
99
+ power,
100
+ needs: straightKills(power, off) + 1,
101
+ falls: second.territories.get(territory)?.owner !== me,
102
+ });
103
+ }
104
+ }
105
+ }
106
+ }
107
+ return out;
108
+ }