@chrischall/warapp-mcp 0.0.0 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (177) hide show
  1. package/.claude-plugin/marketplace.json +4 -4
  2. package/.claude-plugin/plugin.json +2 -2
  3. package/README.md +199 -8
  4. package/dist/analysis/award.js +159 -0
  5. package/dist/analysis/bonuses.js +98 -0
  6. package/dist/analysis/breach.js +62 -0
  7. package/dist/analysis/card-support.js +329 -0
  8. package/dist/analysis/card-threats.js +234 -0
  9. package/dist/analysis/cards-in-effect.js +130 -0
  10. package/dist/analysis/chains.js +59 -0
  11. package/dist/analysis/chokepoints.js +140 -0
  12. package/dist/analysis/combat.js +231 -0
  13. package/dist/analysis/commander-safety.js +149 -0
  14. package/dist/analysis/commitments.js +338 -0
  15. package/dist/analysis/exchange.js +155 -0
  16. package/dist/analysis/graph.js +82 -0
  17. package/dist/analysis/guard-off.js +54 -0
  18. package/dist/analysis/guess.js +351 -0
  19. package/dist/analysis/headroom.js +241 -0
  20. package/dist/analysis/hold-diff.js +64 -0
  21. package/dist/analysis/how-lost.js +130 -0
  22. package/dist/analysis/index.js +14 -0
  23. package/dist/analysis/local-deploy.js +159 -0
  24. package/dist/analysis/lookahead.js +108 -0
  25. package/dist/analysis/opponent-profile.js +551 -0
  26. package/dist/analysis/opponents.js +1245 -0
  27. package/dist/analysis/outlook.js +633 -0
  28. package/dist/analysis/overrides.js +60 -0
  29. package/dist/analysis/picks.js +1879 -0
  30. package/dist/analysis/plan/after-leftover.js +140 -0
  31. package/dist/analysis/plan/cap-spend.js +242 -0
  32. package/dist/analysis/plan/captures.js +1195 -0
  33. package/dist/analysis/plan/commander.js +236 -0
  34. package/dist/analysis/plan/completed.js +29 -0
  35. package/dist/analysis/plan/conceded-out.js +131 -0
  36. package/dist/analysis/plan/estimates.js +715 -0
  37. package/dist/analysis/plan/guard-off.js +232 -0
  38. package/dist/analysis/plan/holds.js +1631 -0
  39. package/dist/analysis/plan/leftover.js +760 -0
  40. package/dist/analysis/plan/move-order.js +319 -0
  41. package/dist/analysis/plan/orders.js +317 -0
  42. package/dist/analysis/plan/relations.js +702 -0
  43. package/dist/analysis/plan/report.js +672 -0
  44. package/dist/analysis/plan/shared.js +1218 -0
  45. package/dist/analysis/plan/stand-still.js +823 -0
  46. package/dist/analysis/plan/state.js +44 -0
  47. package/dist/analysis/plan/strike.js +1416 -0
  48. package/dist/analysis/plan/targets.js +651 -0
  49. package/dist/analysis/plan/team.js +299 -0
  50. package/dist/analysis/plan/threats.js +927 -0
  51. package/dist/analysis/plan/transfers.js +328 -0
  52. package/dist/analysis/plan/util.js +5 -0
  53. package/dist/analysis/plan/vacated.js +285 -0
  54. package/dist/analysis/planner.js +2922 -0
  55. package/dist/analysis/player-record.js +144 -0
  56. package/dist/analysis/player.js +268 -0
  57. package/dist/analysis/profile.js +347 -0
  58. package/dist/analysis/relations.js +1030 -0
  59. package/dist/analysis/schedule.js +88 -0
  60. package/dist/analysis/since-last.js +50 -0
  61. package/dist/analysis/static-seats.js +71 -0
  62. package/dist/analysis/stress.js +577 -0
  63. package/dist/analysis/team-brief.js +151 -0
  64. package/dist/analysis/tripwire.js +644 -0
  65. package/dist/analysis/turn-sim.js +259 -0
  66. package/dist/analysis/whereabouts.js +1109 -0
  67. package/dist/board.js +105 -0
  68. package/dist/bundle.js +117959 -36172
  69. package/dist/cards.js +435 -0
  70. package/dist/chat-cursor.js +135 -0
  71. package/dist/chat.js +192 -0
  72. package/dist/client.js +361 -0
  73. package/dist/config.js +62 -0
  74. package/dist/direct/link.js +102 -0
  75. package/dist/direct/session.js +267 -0
  76. package/dist/direct/transport.js +424 -0
  77. package/dist/guess-salt.js +65 -0
  78. package/dist/hosted.js +24 -0
  79. package/dist/index.js +33 -0
  80. package/dist/join-color.js +140 -0
  81. package/dist/live.js +278 -0
  82. package/dist/map-stats.js +152 -0
  83. package/dist/map-store.js +204 -0
  84. package/dist/move-order.js +141 -0
  85. package/dist/my-games.js +180 -0
  86. package/dist/normalize.js +411 -0
  87. package/dist/open-games.js +537 -0
  88. package/dist/outlook-log.js +138 -0
  89. package/dist/path-lock.js +22 -0
  90. package/dist/pick-list.js +193 -0
  91. package/dist/player-record-store.js +229 -0
  92. package/dist/player-states.js +31 -0
  93. package/dist/profile-store.js +677 -0
  94. package/dist/protocol/bundle.js +375 -0
  95. package/dist/protocol/codec.js +556 -0
  96. package/dist/protocol/decoded.js +12 -0
  97. package/dist/protocol/interp.js +1904 -0
  98. package/dist/protocol/methods.js +531 -0
  99. package/dist/protocol/rpc.js +202 -0
  100. package/dist/push/listener.js +393 -0
  101. package/dist/push/packets.js +66 -0
  102. package/dist/push/socketio.js +333 -0
  103. package/dist/push/websocket.js +179 -0
  104. package/dist/redact.js +62 -0
  105. package/dist/relations-store.js +242 -0
  106. package/dist/replay.js +215 -0
  107. package/dist/scalars.js +28 -0
  108. package/dist/scout.js +346 -0
  109. package/dist/stats.js +269 -0
  110. package/dist/strategy/card-clock.js +185 -0
  111. package/dist/strategy/map-notes.js +128 -0
  112. package/dist/strategy/notes.js +2168 -0
  113. package/dist/team-cards.js +84 -0
  114. package/dist/team-orders.js +150 -0
  115. package/dist/teams.js +19 -0
  116. package/dist/tools/award.js +206 -0
  117. package/dist/tools/begin-turn.js +162 -0
  118. package/dist/tools/board.js +77 -0
  119. package/dist/tools/card-advice.js +256 -0
  120. package/dist/tools/card-effects.js +49 -0
  121. package/dist/tools/card-plays.js +434 -0
  122. package/dist/tools/card-support-advice.js +140 -0
  123. package/dist/tools/chat-inbox.js +146 -0
  124. package/dist/tools/chat.js +483 -0
  125. package/dist/tools/check-plan.js +688 -0
  126. package/dist/tools/commander-check.js +102 -0
  127. package/dist/tools/commitments.js +216 -0
  128. package/dist/tools/common.js +143 -0
  129. package/dist/tools/diplomacy.js +342 -0
  130. package/dist/tools/game.js +126 -0
  131. package/dist/tools/guess-view.js +56 -0
  132. package/dist/tools/healthcheck.js +90 -0
  133. package/dist/tools/hints.js +34 -0
  134. package/dist/tools/how-lost.js +154 -0
  135. package/dist/tools/index.js +142 -0
  136. package/dist/tools/join-game.js +327 -0
  137. package/dist/tools/leave-game.js +181 -0
  138. package/dist/tools/live-context.js +339 -0
  139. package/dist/tools/live.js +404 -0
  140. package/dist/tools/map-stats.js +117 -0
  141. package/dist/tools/map.js +133 -0
  142. package/dist/tools/my-games.js +123 -0
  143. package/dist/tools/open-games.js +104 -0
  144. package/dist/tools/opponents.js +151 -0
  145. package/dist/tools/order-options.js +135 -0
  146. package/dist/tools/picks.js +292 -0
  147. package/dist/tools/profile-hook.js +156 -0
  148. package/dist/tools/profile-opponents.js +121 -0
  149. package/dist/tools/profile-reads.js +99 -0
  150. package/dist/tools/push.js +385 -0
  151. package/dist/tools/relations.js +611 -0
  152. package/dist/tools/resolve.js +45 -0
  153. package/dist/tools/route.js +36 -0
  154. package/dist/tools/scout.js +87 -0
  155. package/dist/tools/session.js +163 -0
  156. package/dist/tools/strategy.js +200 -0
  157. package/dist/tools/stress-opponents.js +83 -0
  158. package/dist/tools/surrender.js +240 -0
  159. package/dist/tools/survival.js +189 -0
  160. package/dist/tools/team-brief.js +266 -0
  161. package/dist/tools/team-source.js +222 -0
  162. package/dist/tools/team.js +182 -0
  163. package/dist/tools/turn.js +2761 -0
  164. package/dist/tools/uncommit.js +160 -0
  165. package/dist/tools/where.js +275 -0
  166. package/dist/tools/write-kit.js +158 -0
  167. package/dist/transport-bridge.js +33 -0
  168. package/dist/trend.js +452 -0
  169. package/dist/version.js +4 -0
  170. package/manifest.json +174 -4
  171. package/mint.yaml +101 -14
  172. package/package.json +11 -6
  173. package/server.json +40 -3
  174. package/skills/warapp-api/SKILL.md +95 -4
  175. package/skills/warapp-api/references/scout.mjs +348 -0
  176. package/skills/warapp-api/scripts/warapp.sh +69 -8
  177. package/skills/warapp-mcp/SKILL.md +969 -21
@@ -0,0 +1,644 @@
1
+ // The broken-estimate tripwire (#275 b). Pure and deterministic.
2
+ //
3
+ // An opponent's deploy estimate is a floor: what the board proves it earns. Five of eighteen lost
4
+ // games were lost to holds sized for one (an estimate of 15 met 70–120; 41 met about 170). One
5
+ // observation that the estimate cannot explain is enough to stop trusting it: when what an opponent
6
+ // did needed TRIP_RATIO (1.5) × or more of what its estimate allowed, and at least TRIP_MIN_EXCESS
7
+ // armies more, its estimate is marked untrusted for UNTRUSTED_TURNS turns (`activeTripwires`; the
8
+ // tools keep the marks in the board cache, src/trend.ts, by player id only).
9
+ //
10
+ // The observations, each read off two consecutive boards of mine (the previous turn's and this one's):
11
+ // fog-stack a stack of its comes out of the fog (visible now, not on the previous board) larger
12
+ // than the armies last seen there (when it held it then) plus its estimate for every
13
+ // turn since that board. When no board here shows it, since turn 1 and with its whole
14
+ // start credited (`start`: territories × armies each — every start may have walked in
15
+ // there); with its start unknown such a stack is not read. When a board showed it and the
16
+ // start is known, never below its whole stock (every start plus its estimate for every turn
17
+ // so far) less its armies in view elsewhere now: armies banked under the fog since early on
18
+ // walk in unseen, and no sighting credits them. The stock is known only when every turn's
19
+ // estimate is the one kept from that turn's plan (`estimateKept`): a stand-in may under-count
20
+ // an opponent whose estimate a bonus break has lowered since, so the start then counts as
21
+ // unknown. With the start known, a stack walking in is not
22
+ // income (#123 lesson 5): its armies that left view or shrank are credited too: for each other
23
+ // territory, every drop of its movable armies between two consecutive sightings since the
24
+ // stack's own, and from the latest sighting to now (all of them when hidden now or another's),
25
+ // each when within reach (graph distance at most the turns from the earlier sighting to now).
26
+ // With the start unknown there is no stock, and a drop in view is net (a stack may walk in
27
+ // while another fills in behind it), so the bound is every army that could reach it: from a
28
+ // board on which every territory within reach (distance at most the turns left) is in view,
29
+ // what stood on it then, its movable armies within reach and its estimates since, boards
30
+ // chained for the least (`reachBound`); with no such chain (a territory within reach hidden
31
+ // on the turn a stack passed it, or a board missing from the cache) it is not read.
32
+ // Not read when Gift may be in play (`gift`) and the territory was last seen another player's:
33
+ // that player (a third one in a free-for-all) may have gifted it with its stack; nor, with a
34
+ // third player in the game (`players`), when no board showed it its own (never seen, last
35
+ // seen neutral): that player may have taken it out of view and gifted it, armies no stock or
36
+ // sighting counts.
37
+ // Under Multi-Attack,
38
+ // or when the settings do not say, a chain covers many hops in one turn: every such
39
+ // territory is within reach, whatever its distance;
40
+ // capture it took a territory of mine or a visible neutral that needed more attackers
41
+ // (`armiesToTake` of the defenders) than its stacks beside it could move (a commander of
42
+ // its counted as COMMANDER_STRENGTH, 7) plus its estimate. With no luck and straight rounding only
43
+ // (a lucky roll takes it with fewer). Never when a territory beside it was hidden on the previous board (a
44
+ // stack of its could have stood there), when a third player stood beside it, under
45
+ // Multi-Attack or when the settings do not say (a chain lands from further), or when my
46
+ // orders that turn are unknown
47
+ // and could have moved armies out of mine (or attacked the neutral) first. My orders are
48
+ // known only with `sent` (an older cache is unknown): a Transfer Only, Attack Only or
49
+ // percentage order, which `sent` lists and `moves` leaves out, sends an unknown count, so
50
+ // none may leave the territory of mine nor go into the neutral. A territory my Gift card gave
51
+ // it (`orders.cards`) is no capture, and with my card plays not recorded (`cards` absent) no
52
+ // capture of mine is read when Gift may be in play (`gift`). My cached orders count only when
53
+ // the board agrees they ran (`ordersLanded`, shared with the held attack): orders modified in the
54
+ // web client after this server cached them (a deploy that never landed, a transfer dropped or
55
+ // rerouted, an attack added into a neutral) read no capture of mine, nor one of a neutral beside
56
+ // mine. A deploy on a territory of mine it took never counts: once lost, the board cannot confirm
57
+ // it; nor is one read beside a neutral that shrank with no attack of mine cached into it;
58
+ // held-attack an attack of mine (my cached orders) failed on a territory of its that held: the
59
+ // defenders it took to hold (one more than my attackers kill) beyond the armies there
60
+ // (its commander there counted as 7, as on its stacks beside it),
61
+ // its estimate and its stacks beside it that could move in. With no luck and straight
62
+ // rounding only, not under Multi-Attack or when the settings do not say (a chain brings
63
+ // armies from beyond its stacks beside it), and not when a territory beside it was hidden.
64
+ // An order sends what is
65
+ // left, so not from a source another stack could have hit first (a territory beside the
66
+ // source, the target aside, hidden or holding a movable stack or a commander not mine on
67
+ // the previous board), nor from one that ended with fewer armies than my orders left it; and only what
68
+ // the source had left after its earlier orders in list order, so not from a source an
69
+ // order outside `moves` (Transfer Only, Attack Only, percentage) left too, nor with my
70
+ // orders cached before `sent` existed, nor when the board disagrees with them (`ordersLanded`).
71
+ // A Transfer Only order
72
+ // (flagged in `sent`) attacks nothing, and a player a Diplomacy card may have kept at
73
+ // peace with me (`peace`) is not read, nor anyone while a Diplomacy card may have been in
74
+ // force on the turn the attack ran (`diplomacy`: the cards in effect now do not say). A
75
+ // source that lost nothing (it ended at or above what my orders left it plus the armies
76
+ // the attack sent) did not fight: a failed attack on a defender always costs attackers, so
77
+ // the attack never ran (a Diplomacy card, or orders withdrawn in the web client after this
78
+ // server cached them); one that lost fewer than the defenders it needed kill (every attacker,
79
+ // or round(defensive kill rate × defenders)) sent less than the cache says. The target's own
80
+ // stack attacking my source cannot
81
+ // fake a trip: what it sends leaves the defence.
82
+ // A board from GameFeed's GetHistory (`source: 'history'`, unverified and parsed loosely, as the
83
+ // opponent-profile observer treats it) may show less than war.app did: nothing is read when the previous
84
+ // board is one, a fog-stack's last sighting never comes from one, and with one since that sighting only
85
+ // the stock bound reads the stack (none without the start).
86
+ // Cards: nothing is read when an opponent may hold an Airlift (`airlift`, the caller's card clock): one
87
+ // lands armies on any territory it holds, into a target, a fogged stack or one beside a capture, and
88
+ // reads as income. No capture and no held attack is read when an opponent may hold a Bomb (`bomb`): one
89
+ // runs before the attacks (phase 30) and halves my attack's source (beside the target by definition: the
90
+ // source still ends at the guard plus survivors, so the check on it misses it) or a territory of mine it
91
+ // then takes (half the defenders counted). A Bomb only kills, so a stack out of the fog is still read.
92
+ // Players: a player out of the game whose seat no AI plays (`staticSeats`, #270) is never read, nor one
93
+ // the caller has no estimate for (`estimateAt` undefined: never compared against 0). Another player's
94
+ // armies are never credited to it: a held attack is not read with any player but it beside the target
95
+ // (its teammate may have sent armies in; a third may have moved), and a fog stack is not read for a player
96
+ // with a teammate (`teams`), whose armies may have walked in. A Reinforcement card is income: the estimate compared carries it from the turn the
97
+ // card clock says one can be in hand (#164).
98
+ // It carries one card at most, and an opponent may bank several (up to MaxCardsHold) and play them in one
99
+ // turn: a capture, a held attack and a stack out of the fog with its start unknown allow every card it may
100
+ // hold (`banked`, the caller's card clock), and are not read at all when those cannot be counted. With the
101
+ // start known a stack out of the fog is bounded by its stock, which credits a card every turn so far.
102
+ // `implied` is the deploy per turn the observation needs: what the estimate should have been.
103
+ // The estimate compared is the one the plan used that turn (`estimateAt`), the caller's to supply.
104
+ import { armiesToTake, COMMANDER_STRENGTH, luckFraction, straightKills } from './combat.js';
105
+ import { bfsDistances, neighborsOf } from './graph.js';
106
+ import { visibleState } from './plan/shared.js';
107
+ /** An observation trips when it needs at least this many times what the estimate allows. */
108
+ export const TRIP_RATIO = 1.5;
109
+ /** …and at least this many armies more (small numbers are noise). */
110
+ export const TRIP_MIN_EXCESS = 5;
111
+ /** Turns an opponent's estimate stays untrusted, the turn of the observation included. */
112
+ export const UNTRUSTED_TURNS = 3;
113
+ const byNum = (a, b) => a - b;
114
+ export function brokenEstimates(input) {
115
+ const { graph, me, boards } = input;
116
+ const now = boards.at(-1);
117
+ const prev = boards.at(-2);
118
+ if (!now || !prev || prev.turn !== now.turn - 1 || input.airlift)
119
+ return [];
120
+ // A history board may show less than war.app did: stacks would look out of the fog.
121
+ if (now.source === 'history' || prev.source === 'history')
122
+ return [];
123
+ const T = now.turn;
124
+ const s = input.settings ?? {};
125
+ // Multi-Attack on, or the settings do not say: a chain moves armies many hops in one turn.
126
+ const chains = s.multiAttack !== false;
127
+ const rates = { offensiveKillRate: s.offensiveKillRate, defensiveKillRate: s.defensiveKillRate };
128
+ const guard = s.oneArmyStandsGuard === false ? 0 : 1;
129
+ const exact = luckFraction(s.luckModifier) === 0 && (s.roundingMode === undefined || s.roundingMode === 'StraightRound');
130
+ const teams = input.teams;
131
+ const friend = (p) => p === me || (teams !== undefined && teams.get(p) !== undefined && teams.get(p) === teams.get(me));
132
+ const index = (b) => new Map(b.territories.map((t) => [t.territoryId, t]));
133
+ const cur = index(now.board);
134
+ const before = index(prev.board);
135
+ const playerOf = (t) => (t?.owner.kind === 'player' ? t.owner.playerId : undefined);
136
+ const est = (p, turn) => Math.max(0, input.estimateAt(p, turn) ?? 0);
137
+ /** `p` has a teammate in the game: another player's armies may stand for its own. */
138
+ const hasMate = (p) => {
139
+ const team = teams?.get(p);
140
+ return team !== undefined && team >= 0 && [...teams].some(([q, t]) => q !== p && t === team);
141
+ };
142
+ /** Another player than me and `p` may be in the game (`players` unknown: one may). */
143
+ const thirdParty = (p) => input.players === undefined || input.players.some((q) => q !== me && q !== p);
144
+ /** Every turn before this one has `p`'s estimate as that turn's plan kept it. */
145
+ const stockKept = (p) => {
146
+ if (!input.estimateKept)
147
+ return true;
148
+ for (let k = 1; k < T; k++)
149
+ if (!input.estimateKept(p, k))
150
+ return false;
151
+ return true;
152
+ };
153
+ // My Gift card plays that turn: a territory I gave away is no capture. Unknown when my card plays were
154
+ // not recorded and Gift may be in play.
155
+ const gifted = new Set((prev.orders?.cards ?? []).flatMap((c) => (c.card === 'Gift' && c.target !== undefined ? [c.target] : [])));
156
+ const giftUnknown = input.gift === true && prev.orders?.cards === undefined;
157
+ // Reinforcement cards banked and played at once: the estimate carries at most one.
158
+ const bank = Math.max(0, input.banked ?? 0);
159
+ const out = [];
160
+ const trip = (o) => {
161
+ if (o.observed >= TRIP_RATIO * o.allowed && o.observed - o.allowed >= TRIP_MIN_EXCESS)
162
+ out.push({ ...o, turn: T });
163
+ };
164
+ /** Every neighbour of `id` was in view on the previous board. */
165
+ const clearAround = (id) => neighborsOf(graph, id).every((n) => visibleState(before.get(n)) !== undefined);
166
+ /** `p`'s commanders on `t`, each fighting as {@link COMMANDER_STRENGTH}. */
167
+ const commanders = (t, p) => (t?.specialUnits ?? []).filter((u) => u.kind === 'commander' && u.playerId === p).length * COMMANDER_STRENGTH;
168
+ /** What `p` could move from its stacks beside `id` on the previous board, a commander counted as 7. */
169
+ const stacksBeside = (id, p) => neighborsOf(graph, id).reduce((n, x) => {
170
+ const t = visibleState(before.get(x));
171
+ return n + (playerOf(t) === p ? Math.max(0, t.armies - guard) + commanders(t, p) : 0);
172
+ }, 0);
173
+ // My orders, known only with `sent`: `moves` leaves out Transfer Only, Attack Only and percentage
174
+ // orders (`myOrdersOf`), which `sent` lists. Orders cached before `sent` existed are unknown.
175
+ const myOrders = prev.orders?.sent ? prev.orders : undefined;
176
+ /** An order of mine matching `match` that `sent` lists but `moves` lacks: its armies are unknown. */
177
+ const unlisted = (match) => myOrders !== undefined && myOrders.sent.filter(match).length > myOrders.moves.filter(match).length;
178
+ /** My cached deploys on `x`. */
179
+ const deployedOn = (x) => (myOrders?.deploys ?? []).filter((d) => d.territoryId === x).reduce((n, d) => n + d.armies, 0);
180
+ /**
181
+ * What each of my orders out of `f` sends, in list order: an order sends what is left (transfers in are
182
+ * not counted: armies move once a turn). Exact when nothing hit `f` first; else an upper bound.
183
+ */
184
+ const sentFrom = (f) => {
185
+ let left = Math.max(0, (visibleState(before.get(f))?.armies ?? 0) + deployedOn(f) - guard);
186
+ return (myOrders?.moves ?? [])
187
+ .filter((m) => m.from === f)
188
+ .map((m) => {
189
+ const took = Math.min(m.armies, left);
190
+ left -= took;
191
+ return { to: m.to, armies: took };
192
+ });
193
+ };
194
+ const isMine = (t) => playerOf(visibleState(t)) === me;
195
+ /** Mine on both boards, and nothing but my territories and neutrals, all in view, beside it on the previous one. */
196
+ const quiet = (x) => isMine(before.get(x)) &&
197
+ isMine(cur.get(x)) &&
198
+ neighborsOf(graph, x).every((n) => {
199
+ const t = visibleState(before.get(n));
200
+ return t !== undefined && (t.owner.kind === 'neutral' || playerOf(t) === me);
201
+ });
202
+ /**
203
+ * #275 review: whether the board agrees with my cached orders, so they are the orders war.app ran (orders
204
+ * modified in the web client after this server cached them are not). Every territory of mine on both
205
+ * boards with no card play or order in outside `moves` touching it, borders included, ends at most at what
206
+ * it had plus my deploys there plus what my orders in could send, less what its transfers out into
207
+ * territories mine on both boards sent (none with an order out outside `moves`); every territory newly
208
+ * mine, at most at what my orders in could send; every neutral in view on both boards beside nothing but
209
+ * my territories and neutrals, at least at what it had less what my cached attacks into it could kill.
210
+ * Each one that stayed mine with no other
211
+ * player or fog beside it, no card play or order outside `moves` touching it, and only transfers out of it
212
+ * into territories that stayed mine, must end at what it had plus my deploys there, less what went out,
213
+ * plus what came in (an order in from a territory that may have been hit first: up to what it sends).
214
+ * Needs one such territory: with none, nothing agrees. Shared by the capture and the held attack, which
215
+ * both read my cached orders; neither trusts a cached figure the board cannot confirm (a deploy on a
216
+ * territory I lost; an attack its source's losses do not fit).
217
+ * What no board shows: a failed attack the edit added out of a territory I then lost into a territory of
218
+ * the player that took it (its losses fell with the territory; the defenders it met are that player's to
219
+ * count). Into a neutral it shows as the neutral shrinking: here when nothing but mine is beside it, and the
220
+ * capture skips one beside the territory lost whoever else is beside it. Only called without Multi-Attack
221
+ * (both callers need it): a chain carries armies an order out of a territory entered earlier sends, which
222
+ * `sentFrom` does not count.
223
+ */
224
+ let landed;
225
+ const ordersLanded = () => {
226
+ if (landed !== undefined)
227
+ return landed;
228
+ landed = false;
229
+ if (!myOrders)
230
+ return false;
231
+ const carded = new Set((myOrders.cards ?? []).flatMap((c) => [c.from, c.to, c.target].filter((x) => x !== undefined)));
232
+ /** What my cached orders into `x` could send it: each up to what its source had left. */
233
+ const sentInto = (x) => [...new Set(myOrders.moves.filter((m) => m.to === x).map((m) => m.from))]
234
+ .sort(byNum)
235
+ .map((f) => ({ f, into: sentFrom(f).filter((o) => o.to === x).reduce((n, o) => n + o.armies, 0) }));
236
+ // Every territory of mine on both boards, borders included: nothing but my deploys and my moves in adds
237
+ // armies (an attack on it only kills, a failed attack's survivors stay where they were), so it ends at
238
+ // most at what it had plus my deploys there plus what each order in could send. A deploy or a move the
239
+ // web-client edit put there instead shows above that (#275 review: borders are never quiet).
240
+ // Less what its transfers out sent into territories mine on both boards (#275 review: a web-client edit
241
+ // that dropped or rerouted a transfer between two borders left its source above this): a transfer between
242
+ // my territories cannot fail, and each order sends no more than `sentFrom` says, the shortfall of them all
243
+ // at most what a hit on x took first, which x lost too. Not with an order out of x outside `moves`: it
244
+ // may have taken any share first, so the transfers listed may have sent nothing.
245
+ const transferredOut = (x) => unlisted((m) => m.from === x)
246
+ ? 0
247
+ : sentFrom(x)
248
+ .filter((o) => isMine(before.get(o.to)) && isMine(cur.get(o.to)))
249
+ .reduce((n, o) => n + o.armies, 0);
250
+ for (const x of [...before.keys()].sort(byNum)) {
251
+ if (!isMine(before.get(x)) || !isMine(cur.get(x)) || carded.has(x) || unlisted((m) => m.to === x))
252
+ continue;
253
+ const most = before.get(x).armies + deployedOn(x) + sentInto(x).reduce((n, i) => n + i.into, 0) - transferredOut(x);
254
+ if (visibleState(cur.get(x)).armies > most)
255
+ return false;
256
+ }
257
+ // Every territory newly mine (a neutral, another player's or one the fog hid): only my orders into it
258
+ // put armies there, so it ends at most at what they could send (#275 review: a web-client edit that sent
259
+ // armies into a neutral instead, from an attack source or a territory I later lost, shows here; both
260
+ // loops above and below skip a territory that was not mine on the previous board).
261
+ for (const x of [...cur.keys()].sort(byNum)) {
262
+ if (isMine(before.get(x)) || !isMine(cur.get(x)) || carded.has(x) || unlisted((m) => m.to === x))
263
+ continue;
264
+ const most = sentInto(x).reduce((n, i) => n + i.into, 0);
265
+ if (visibleState(cur.get(x)).armies > most)
266
+ return false;
267
+ }
268
+ // Every neutral in view on both boards with nothing but my territories and neutrals, all in view, beside
269
+ // it on the previous board: only my attacks wear it down, each killing at most its luck-free share of what
270
+ // it sends (#275 review: a web-client edit that added a failed attack into it, from a border I then lost,
271
+ // shows here). Not with an order into it outside `moves` or a card play on it.
272
+ for (const x of [...before.keys()].sort(byNum)) {
273
+ const was = visibleState(before.get(x));
274
+ const is = visibleState(cur.get(x));
275
+ if (was?.owner.kind !== 'neutral' || is?.owner.kind !== 'neutral' || carded.has(x) || unlisted((m) => m.to === x))
276
+ continue;
277
+ const alone = neighborsOf(graph, x).every((n) => {
278
+ const t = visibleState(before.get(n));
279
+ return t !== undefined && (t.owner.kind === 'neutral' || playerOf(t) === me);
280
+ });
281
+ if (!alone)
282
+ continue;
283
+ const kills = sentInto(x).reduce((n, { f }) => n +
284
+ sentFrom(f)
285
+ .filter((o) => o.to === x)
286
+ .reduce((k, o) => k + straightKills(o.armies, s.offensiveKillRate ?? 60), 0), 0);
287
+ if (is.armies < was.armies - kills)
288
+ return false;
289
+ }
290
+ let checked = 0;
291
+ for (const x of [...before.keys()].sort(byNum)) {
292
+ if (!quiet(x) || carded.has(x) || unlisted((m) => m.from === x || m.to === x))
293
+ continue;
294
+ const outs = sentFrom(x);
295
+ if (outs.some((o) => !isMine(before.get(o.to)) || !isMine(cur.get(o.to))))
296
+ continue;
297
+ let low = before.get(x).armies + deployedOn(x) - outs.reduce((n, o) => n + o.armies, 0);
298
+ let high = low;
299
+ for (const { f, into } of sentInto(x)) {
300
+ if (quiet(f) && !unlisted((m) => m.from === f))
301
+ low += into;
302
+ high += into;
303
+ }
304
+ high = Math.max(high, low);
305
+ const end = visibleState(cur.get(x)).armies;
306
+ if (end < low || end > high)
307
+ return false;
308
+ checked++;
309
+ }
310
+ landed = checked > 0;
311
+ return landed;
312
+ };
313
+ /**
314
+ * #123 lesson 5: the armies of `p` that could have walked into `id` since `since[0]`: per other territory,
315
+ * every drop of its movable armies between consecutive sightings among `since`, and from the latest to now
316
+ * (all of them when hidden now or not its), each within reach (graph distance at most the turns from the
317
+ * earlier sighting to now). A stack seen in two places, or one that left and came back, may be counted
318
+ * twice: generous, never a false alarm.
319
+ */
320
+ const walkIn = (id, p, since) => {
321
+ const dist = bfsDistances(graph, [id]);
322
+ // Every sighting of each other territory, in turn order: its movable armies of `p` then.
323
+ const sightings = new Map();
324
+ for (const b of since) {
325
+ for (const t of b.board.territories) {
326
+ const v = visibleState(t);
327
+ if (!v || t.territoryId === id)
328
+ continue;
329
+ const list = sightings.get(t.territoryId) ?? [];
330
+ list.push({ turn: b.turn, movable: playerOf(v) === p ? Math.max(0, v.armies - guard) : 0 });
331
+ sightings.set(t.territoryId, list);
332
+ }
333
+ }
334
+ let credit = 0;
335
+ for (const [x, seen] of [...sightings].sort((a, b) => a[0] - b[0])) {
336
+ const d = dist.get(x);
337
+ if (d === undefined)
338
+ continue;
339
+ const v = visibleState(cur.get(x));
340
+ const nowMovable = v && playerOf(v) === p ? Math.max(0, v.armies - guard) : 0;
341
+ // Each drop between consecutive sightings, and from the latest to now: armies that left then had
342
+ // the turns from the earlier sighting to now to walk in (#275 review: a stack seen leaving a
343
+ // territory still in view was lost when only the latest sighting was compared with now).
344
+ const steps = [...seen, { turn: T, movable: nowMovable }];
345
+ for (let i = 0; i + 1 < steps.length; i++) {
346
+ if (!chains && d > T - steps[i].turn)
347
+ continue;
348
+ credit += Math.max(0, steps[i].movable - steps[i + 1].movable);
349
+ }
350
+ }
351
+ return credit;
352
+ };
353
+ /**
354
+ * #275 review, with the start unknown: the most armies of `p` that can stand on `id` now, from its
355
+ * sighting on `since[0]` (`base`). Every army on `id` now stood on `id` or within reach on any earlier
356
+ * board (graph distance at most the turns left: one step a turn; any distance under chains), or was
357
+ * deployed since. So from a board `j` on which every territory within reach of `id` is in view, the
358
+ * armies on `id` at a later turn `h` are at most those on `id` at `j`, plus its movable armies within
359
+ * `h − j` of `id` on `j`, plus its estimates from `j` to `h − 1`; chaining boards keeps the bound tight
360
+ * (a stack still out of reach on a later board counts nothing). Counting every army within reach, not
361
+ * only the drops seen, credits a stack that walked in while another filled in behind it; a territory
362
+ * hidden on the turn a stack passed it (or a board missing from the cache) bounds nothing through that
363
+ * board. Undefined when no chain of boards in view bounds it.
364
+ */
365
+ const reachBound = (id, p, base, since) => {
366
+ const dist = bfsDistances(graph, [id]);
367
+ const views = since.map((b) => ({ turn: b.turn, at: index(b.board) }));
368
+ const bound = new Map([[views[0].turn, base]]);
369
+ const targets = [...views.slice(1).map((v) => v.turn), T];
370
+ for (const h of targets) {
371
+ let best;
372
+ for (const v of views) {
373
+ const from = bound.get(v.turn);
374
+ if (v.turn >= h || from === undefined)
375
+ continue;
376
+ let within = 0;
377
+ let open = true;
378
+ for (const [x, d] of dist) {
379
+ if (x === id || (!chains && d > h - v.turn))
380
+ continue;
381
+ const st = visibleState(v.at.get(x));
382
+ if (!st) {
383
+ open = false;
384
+ break;
385
+ }
386
+ if (playerOf(st) === p)
387
+ within += Math.max(0, st.armies - guard);
388
+ }
389
+ if (!open)
390
+ continue;
391
+ let deploys = 0;
392
+ for (let k = v.turn; k < h; k++)
393
+ deploys += est(p, k);
394
+ const b = from + within + deploys;
395
+ if (best === undefined || b < best)
396
+ best = b;
397
+ }
398
+ if (best !== undefined)
399
+ bound.set(h, best);
400
+ }
401
+ return bound.get(T);
402
+ };
403
+ for (const id of [...cur.keys()].sort(byNum)) {
404
+ const t = visibleState(cur.get(id));
405
+ const p = playerOf(t);
406
+ if (p === undefined || friend(p) || !graph.territoryById.has(id))
407
+ continue;
408
+ // #270: a static seat deploys nothing; a player with no estimate is never compared against 0.
409
+ if (input.staticSeats?.has(p) || input.estimateAt(p, T - 1) === undefined)
410
+ continue;
411
+ const was = visibleState(before.get(id));
412
+ const armies = t.armies;
413
+ // fog-stack: out of the fog this turn.
414
+ if (!was) {
415
+ // Its teammate's armies may have walked in under the fog: they are not its income.
416
+ if (hasMate(p))
417
+ continue;
418
+ // Its stock is known only with its start and every turn's estimate as that turn's plan kept it: a
419
+ // stand-in (today's figure) may under-count what it earned before a bonus break lowered it.
420
+ const start = input.start && stockKept(p) ? input.start : undefined;
421
+ let last;
422
+ for (const b of boards.slice(0, -1))
423
+ if (b.source !== 'history' && visibleState(index(b.board).get(id)))
424
+ last = b;
425
+ // Never seen: its start may have walked in; unknown, nothing is read.
426
+ if (!last && !start)
427
+ continue;
428
+ const since = last ? boards.slice(boards.indexOf(last), -1) : [];
429
+ // A history board since that sighting may have hidden a stack walking in: only the stock bound reads it.
430
+ if (!start && since.some((b) => b.source === 'history'))
431
+ continue;
432
+ const startArmies = start ? start.territories * start.armiesPerTerritory : 0;
433
+ const from = last?.turn ?? 1;
434
+ const seen = last ? visibleState(index(last.board).get(id)) : undefined;
435
+ // Last seen another player's: with Gift in play it may have given the territory with its stack.
436
+ if (input.gift && seen && seen.owner.kind === 'player' && playerOf(seen) !== p)
437
+ continue;
438
+ // Never seen, or last seen neutral, with Gift in play and a third player in the game: that player may
439
+ // have taken it out of view and gifted it, its stack with it; neither the stock nor a sighting counts
440
+ // that player's armies.
441
+ if (input.gift && thirdParty(p) && playerOf(seen) !== p)
442
+ continue;
443
+ // With no stock to bound it, Reinforcement cards banked before the sighting may all land after it.
444
+ if (!start && !Number.isFinite(bank))
445
+ continue;
446
+ const base = seen ? (playerOf(seen) === p ? seen.armies : 0) : startArmies;
447
+ let deploys = 0;
448
+ for (let k = from; k < T; k++)
449
+ deploys += est(p, k);
450
+ const turns = Math.max(1, T - from);
451
+ let walked;
452
+ if (start)
453
+ walked = last ? walkIn(id, p, since.filter((b) => b.source !== 'history')) : 0;
454
+ else {
455
+ // No stock bounds it: only the armies that could reach it from boards in view (#275 review).
456
+ const reach = reachBound(id, p, base, since);
457
+ if (reach === undefined)
458
+ continue;
459
+ walked = reach - base - deploys;
460
+ }
461
+ let allowed = base + deploys + walked + (start ? 0 : bank);
462
+ let implied = Math.ceil((armies - base - walked) / turns);
463
+ if (last && start) {
464
+ // Armies banked under the fog since early on (#123 lesson 5, #250) walk in unseen: its whole
465
+ // stock (every start and every turn's estimate) less its armies in view elsewhere now.
466
+ let stock = startArmies;
467
+ for (let k = 1; k < T; k++)
468
+ stock += est(p, k);
469
+ let elsewhere = 0;
470
+ for (const [x, st] of cur) {
471
+ const v = visibleState(st);
472
+ if (x !== id && v && playerOf(v) === p)
473
+ elsewhere += v.armies;
474
+ }
475
+ if (stock - elsewhere > allowed) {
476
+ allowed = stock - elsewhere;
477
+ implied = Math.ceil((armies + elsewhere - startArmies) / Math.max(1, T - 1));
478
+ }
479
+ }
480
+ trip({ player: p, kind: 'fog-stack', territory: id, observed: armies, allowed, implied });
481
+ continue;
482
+ }
483
+ // capture: it holds what was mine or a visible neutral's.
484
+ const wasOwner = playerOf(was);
485
+ if (wasOwner !== p && (wasOwner === me || was.owner.kind === 'neutral')) {
486
+ // With luck a roll may take it with fewer than the luck-free attackers.
487
+ if (!exact || chains || input.bomb || !Number.isFinite(bank) || !clearAround(id))
488
+ continue;
489
+ const third = neighborsOf(graph, id).some((n) => {
490
+ const o = playerOf(visibleState(before.get(n)));
491
+ return o !== undefined && o !== p && o !== me;
492
+ });
493
+ if (third)
494
+ continue;
495
+ let defenders = was.armies;
496
+ if (wasOwner === me) {
497
+ // The cached moves count only when the board agrees they ran. A deploy on it never counts (#275
498
+ // review): once it is lost the board cannot confirm one, and a web-client edit moving a deploy from
499
+ // it to another border would read as defenders that never stood there.
500
+ if (!myOrders || !ordersLanded() || unlisted((m) => m.from === id) || giftUnknown || gifted.has(id))
501
+ continue;
502
+ // A neutral beside it in view on both boards that shrank with no order of mine cached into it: an
503
+ // attack the cache does not list (a web-client edit) may have spent its armies first. With its owner
504
+ // beside that neutral too the board cannot tell which (`ordersLanded` reads only a neutral beside
505
+ // nobody but me), so the capture is not read (#275 review).
506
+ const worn = neighborsOf(graph, id).some((n) => {
507
+ const a = visibleState(before.get(n));
508
+ const b = visibleState(cur.get(n));
509
+ return a?.owner.kind === 'neutral' && b?.owner.kind === 'neutral' && b.armies < a.armies && !myOrders.sent.some((m) => m.to === n);
510
+ });
511
+ if (worn)
512
+ continue;
513
+ const out = myOrders.moves.filter((m) => m.from === id).reduce((n, m) => n + m.armies, 0);
514
+ defenders = Math.max(guard, defenders - out);
515
+ }
516
+ else {
517
+ // My own attack on the neutral would have worn it down first.
518
+ const mineBeside = neighborsOf(graph, id).some((n) => playerOf(before.get(n)) === me);
519
+ if (mineBeside && (!myOrders || !ordersLanded() || myOrders.sent.some((m) => m.to === id)))
520
+ continue;
521
+ }
522
+ const needed = armiesToTake(defenders, rates);
523
+ if (needed === null)
524
+ continue;
525
+ const stacks = stacksBeside(id, p);
526
+ trip({ player: p, kind: 'capture', territory: id, observed: needed, allowed: stacks + est(p, T - 1) + bank, implied: needed - stacks });
527
+ continue;
528
+ }
529
+ // held-attack: my attack on its territory failed, and it still holds it.
530
+ // Not when another player stood beside the target (its teammate may have sent armies in), nor when a
531
+ // Bomb may have halved my source first.
532
+ const otherBeside = neighborsOf(graph, id).some((n) => {
533
+ const o = playerOf(visibleState(before.get(n)));
534
+ return o !== undefined && o !== p && !friend(o);
535
+ });
536
+ if (wasOwner === p &&
537
+ exact &&
538
+ !chains &&
539
+ !input.bomb &&
540
+ Number.isFinite(bank) &&
541
+ !otherBeside &&
542
+ myOrders &&
543
+ ordersLanded() &&
544
+ clearAround(id) &&
545
+ !input.peace?.has(p) &&
546
+ !input.diplomacy) {
547
+ const transferOnly = new Set(myOrders.sent.filter((m) => m.transferOnly).map((m) => `${m.from}:${m.to}`));
548
+ const fromIds = [...new Set(myOrders.moves.filter((m) => m.to === id && !transferOnly.has(`${m.from}:${id}`)).map((m) => m.from))].sort(byNum);
549
+ let attackers = 0;
550
+ for (const f of fromIds) {
551
+ const src = visibleState(before.get(f));
552
+ const after = visibleState(cur.get(f));
553
+ if (playerOf(src) !== me || playerOf(after) !== me)
554
+ continue;
555
+ // An order out of it that `moves` leaves out took an unknown share first.
556
+ if (unlisted((m) => m.from === f))
557
+ continue;
558
+ const added = deployedOn(f);
559
+ // An order sends what is left: in list order, each order out of the source takes from what the
560
+ // earlier ones left (transfers in are not counted: they may land after it).
561
+ const sent = sentFrom(f).filter((o) => o.to === id).reduce((n, o) => n + o.armies, 0);
562
+ // Another stack beside the source could have shrunk it first: my attack then sent less. An enemy
563
+ // commander there attacks alone as 7 even with nothing movable under the guard (#275 review).
564
+ const exposed = neighborsOf(graph, f).some((n) => {
565
+ if (n === id)
566
+ return false;
567
+ const t = visibleState(before.get(n));
568
+ if (!t)
569
+ return true;
570
+ const o = playerOf(t);
571
+ return o !== undefined && !friend(o) && (t.armies > guard || commanders(t, o) > 0);
572
+ });
573
+ if (exposed)
574
+ continue;
575
+ // …or it ended below what my orders left it (survivors and transfers in only add).
576
+ const outAll = myOrders.moves.filter((m) => m.from === f).reduce((n, m) => n + m.armies, 0);
577
+ const inAll = myOrders.moves.filter((m) => m.to === f).reduce((n, m) => n + m.armies, 0);
578
+ const floor = src.armies + added - outAll + inAll;
579
+ if (after.armies < floor)
580
+ continue;
581
+ // …or it lost nothing: a failed attack on a defender always costs attackers, so it never ran (a
582
+ // Diplomacy card in force then, or orders withdrawn in the web client after this server cached them).
583
+ if (after.armies >= floor + sent)
584
+ continue;
585
+ // …or it lost fewer than the defenders that attack needed would kill (#275 review): the attack that
586
+ // ran was smaller than the cached one (a web-client edit). Its losses are at least what it had and
587
+ // got, less what its orders sent, plus the attackers that came back, less what it ended with
588
+ // (transfers in left out: they only add, so this never over-states a loss).
589
+ const lost = src.armies + added - sentFrom(f).reduce((n, o) => n + o.armies, 0) + sent - after.armies;
590
+ const need = straightKills(sent, s.offensiveKillRate ?? 60) + 1;
591
+ if (lost < Math.min(sent, straightKills(need, s.defensiveKillRate ?? 70)))
592
+ continue;
593
+ attackers = Math.max(attackers, sent);
594
+ }
595
+ if (attackers <= 0)
596
+ continue;
597
+ const defenders = straightKills(attackers, s.offensiveKillRate ?? 60) + 1;
598
+ const stacks = stacksBeside(id, p);
599
+ // Its commander on the target defends as 7 more.
600
+ const standing = was.armies + commanders(was, p);
601
+ trip({
602
+ player: p,
603
+ kind: 'held-attack',
604
+ territory: id,
605
+ observed: defenders,
606
+ allowed: standing + est(p, T - 1) + stacks + bank,
607
+ implied: defenders - standing - stacks,
608
+ });
609
+ }
610
+ }
611
+ return out;
612
+ }
613
+ /**
614
+ * The opponents whose estimates are untrusted on `turn`: the marks kept (`stored`) still running, and
615
+ * a mark from each fresh observation (the one implying most per player). A player marked again starts
616
+ * its {@link UNTRUSTED_TURNS} over, keeping whichever observation implies more. Ascending by player.
617
+ */
618
+ export function activeTripwires(stored, fresh, turn) {
619
+ const by = new Map();
620
+ for (const w of stored)
621
+ if (w.until >= turn && w.since <= turn)
622
+ by.set(w.player, w);
623
+ const newest = new Map();
624
+ for (const o of fresh) {
625
+ const had = newest.get(o.player);
626
+ if (!had || o.implied > had.implied)
627
+ newest.set(o.player, o);
628
+ }
629
+ for (const [p, o] of newest) {
630
+ const had = by.get(p);
631
+ const keep = had && had.implied > o.implied ? had : { ...o };
632
+ by.set(p, {
633
+ player: p,
634
+ since: o.turn,
635
+ until: o.turn + UNTRUSTED_TURNS - 1,
636
+ kind: keep.kind,
637
+ territory: keep.territory,
638
+ observed: keep.observed,
639
+ allowed: keep.allowed,
640
+ implied: keep.implied,
641
+ });
642
+ }
643
+ return [...by.values()].sort((a, b) => a.player - b.player);
644
+ }