@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,552 @@
1
+ import { luckFraction, straightKills, armiesToTake, specialUnitStrength, DEFAULT_DEFENSIVE_KILL_RATE, DEFAULT_OFFENSIVE_KILL_RATE } from './combat.js';
2
+ import { neighborsOf } from './graph.js';
3
+ import { ownerShown, visibleState } from './plan/shared.js';
4
+ import { holdsSeat } from '../player-states.js';
5
+ import { isTeamGame } from '../teams.js';
6
+ const byNum = (a, b) => a - b;
7
+ const ownerOf = (t) => (t?.owner.kind === 'player' ? t.owner.playerId : undefined);
8
+ /** The owner when the board shows it (visible or owner-only). */
9
+ const shownOwner = (t) => ownerOf(ownerShown(t));
10
+ /** The owner and armies when the board shows both. */
11
+ const seen = (t) => {
12
+ const v = visibleState(t);
13
+ return v ? { owner: ownerOf(v), armies: v.armies } : undefined;
14
+ };
15
+ /**
16
+ * Whether combat is exact (0% luck, straight rounding): the only games where an attack's result
17
+ * says how many defenders it met.
18
+ */
19
+ export function exactCombat(s) {
20
+ return luckFraction(s.luckModifier) === 0 && s.roundingMode !== 'WeightedRandom';
21
+ }
22
+ /** The least defenders, from `from` up, an attack of `armies` fails against (exact combat); `from` when none is found within the bound. */
23
+ function leastFailing(armies, from, off, def) {
24
+ for (let d = Math.max(0, from); d < from + 10_000; d++) {
25
+ const need = armiesToTake(d, { offensiveKillRate: off, defensiveKillRate: def });
26
+ if (need === null || armies < need)
27
+ return d;
28
+ }
29
+ return from;
30
+ }
31
+ /**
32
+ * One primitive record per opponent for turn T, keyed by player id (opponents ascending).
33
+ *
34
+ * - `attackedMe`: a territory mine on T is its on T+1; or (orders known) a territory mine on both
35
+ * boards, next to a visible stack of its and of no other player, holds fewer armies than T's count
36
+ * + my deploys − my moves out + my transfers in (a transfer in counts only from a source next to no
37
+ * other player's territory, which nobody could have hit first). Survivors of a move out that did
38
+ * not surely land (its target not mine on T+1, as after a failed attack or a transfer that met a
39
+ * territory taken first, or entered by another order of mine too, which may have retaken it after
40
+ * this move failed) may come back and cover a hit, so such a border still reads yes on a drop but never tests a "no";
41
+ * nor does one a move of mine enters from a territory not mine on T (a Multi-Attack chain through
42
+ * a territory I took this turn: armies the figure leaves out), nor one whose moves out leave it at
43
+ * the guard or less (war.app sends what is left, so a hit landing first shrinks the move, not the
44
+ * border: a withdrawal of every movable army).
45
+ * Under Multi-Attack (or when the settings do not say) a border is read only when every territory
46
+ * within two steps has its owner shown on T and none is another player's: a third player may have
47
+ * chained through the shown neighbour (or a neutral) into mine, and the drop would be blamed on it.
48
+ * A longer chain is not ruled out. Without orders only a capture says
49
+ * so, else `null`; with orders and no testable territory, `null` too.
50
+ * - `reinforce`: one opportunity per attack of mine onto X (its, with D armies on T) when combat is
51
+ * exact, it is my only move onto X, X carries no special unit, no move of mine leaves X, X shows its
52
+ * armies on T+1 (still its, or mine), and my source S is mine on both boards with no transfer in,
53
+ * affordable orders out, every other move out of it surely landed (as above), no special unit of mine on it (a
54
+ * commander going along fights as 7, which the move's armies do not count), and exactly the armies
55
+ * my orders leave (on a capture), or those plus at most the A armies sent (on a failure: an X
56
+ * weaker than D kills fewer, so more come back). An event when X stood stronger than D: captured
57
+ * with fewer survivors than the exact result, or not captured with more defenders left than the
58
+ * exact result against D (which covers an attack big enough to take D that failed); an X weaker
59
+ * than D is an opportunity without an event. `extra` is the least defenders above D explaining it.
60
+ * - `stack`: over its territories visible on both boards, growth = max(0, now − then).
61
+ * - `tookFromMe` / `lostToMe`: ownership changes between it and me, owners shown on both boards;
62
+ * `tookFromMe` is `null` (cannot tell) when a Gift of mine may have gone unrecorded, and then a
63
+ * quiet border never makes `attackedMe` false (only a drop makes it true).
64
+ *
65
+ * Assumed for `reinforce`: on a failure, the armies back on S are the exact result against the
66
+ * defenders X's survivors imply (else no reading: a capture it took back later in the turn returns
67
+ * none). On a capture, a later fight that thins my survivors on X is not told apart from defenders
68
+ * above D, and reads as an event.
69
+ *
70
+ * My orders as cached (`MyOrders`): `moves` holds only plain orders; a percentage, Attack Only or
71
+ * Transfer Only order is in `sent` alone, and card plays in `cards`. A territory such an order leaves
72
+ * or enters, or one of my Airlifts touches, is never tested for `attackedMe` and gives no `reinforce`
73
+ * reading (its armies are not known); `iAttacked` counts every non-transfer order of `sent`. When the
74
+ * orders do not record card plays (`cards` absent: a cache written before they were) and the game may
75
+ * have Airlift, nothing is tested from armies at all, and when it may have Gift — orders unknown
76
+ * included — captures cannot be told (`tookFromMe: null`; it may have been my gift), so a game with
77
+ * Gift and no orders of mine never reads one, nor counts a turn as one without. A territory recorded as my Gift is no capture
78
+ * either. Not filtered: its own Gift of a territory to me reads as `lostToMe` (my orders cannot say).
79
+ */
80
+ export function observeTurn(input) {
81
+ const { graph, me, previous, current, orders, settings } = input;
82
+ const was = new Map(previous.territories.map((t) => [t.territoryId, t]));
83
+ const now = new Map(current.territories.map((t) => [t.territoryId, t]));
84
+ const off = settings.offensiveKillRate ?? DEFAULT_OFFENSIVE_KILL_RATE;
85
+ const def = settings.defensiveKillRate ?? DEFAULT_DEFENSIVE_KILL_RATE;
86
+ const guard = settings.oneArmyStandsGuard === false ? 0 : 1;
87
+ const exact = exactCombat(settings);
88
+ const ids = [...new Set(previous.territories.map((t) => t.territoryId))].sort(byNum);
89
+ const mineWas = (id) => shownOwner(was.get(id)) === me;
90
+ const mineNow = (id) => shownOwner(now.get(id)) === me;
91
+ const deploys = new Map();
92
+ for (const d of orders?.deploys ?? [])
93
+ deploys.set(d.territoryId, (deploys.get(d.territoryId) ?? 0) + d.armies);
94
+ const moves = orders?.moves ?? [];
95
+ const sent = orders?.sent ?? [];
96
+ const transferOnly = new Set(sent.filter((m) => m.transferOnly).map((m) => `${m.from}:${m.to}`));
97
+ // Card plays my orders may not record (A1): absent from the cache, in a game that may have the card.
98
+ const mayHave = (card) => input.cards === undefined || input.cards.includes(card);
99
+ const cardsUnknown = orders?.cards === undefined;
100
+ const airliftUnknown = cardsUnknown && mayHave('Airlift');
101
+ const giftUnknown = cardsUnknown && mayHave('Gift');
102
+ const gifted = new Set((orders?.cards ?? []).flatMap((c) => (c.card === 'Gift' && c.target !== undefined ? [c.target] : [])));
103
+ // Territories whose armies my plain moves do not account for: an order only `sent` holds, or an Airlift.
104
+ const untested = new Set();
105
+ const plain = (a) => moves.filter((m) => m.from === a.from && m.to === a.to).length;
106
+ const sentCount = (a) => sent.filter((m) => m.from === a.from && m.to === a.to).length;
107
+ for (const m of sent)
108
+ if (sentCount(m) > plain(m)) {
109
+ untested.add(m.from);
110
+ untested.add(m.to);
111
+ }
112
+ for (const c of orders?.cards ?? [])
113
+ if (c.card === 'Airlift')
114
+ for (const t of [c.from, c.to])
115
+ if (t !== undefined)
116
+ untested.add(t);
117
+ /** Every neighbour of `id` has its owner shown on board T (no hidden player could have hit it). */
118
+ const allShown = (id) => neighborsOf(graph, id).every((n) => ownerShown(was.get(n)) !== undefined);
119
+ // Multi-Attack (or unstated, so maybe on): a player can chain captures in one turn.
120
+ const multiAttack = settings.multiAttack !== false;
121
+ /** The territories within two steps of `id`, itself left out. */
122
+ const twoSteps = (id) => {
123
+ const out = new Set();
124
+ for (const n of neighborsOf(graph, id)) {
125
+ out.add(n);
126
+ for (const m of neighborsOf(graph, n))
127
+ out.add(m);
128
+ }
129
+ out.delete(id);
130
+ return [...out];
131
+ };
132
+ const outOf = (id) => moves.filter((m) => m.from === id);
133
+ const into = (id) => moves.filter((m) => m.to === id);
134
+ const sum = (ms) => ms.reduce((n, m) => n + Math.max(0, m.armies), 0);
135
+ /** A move of mine that surely ended on its target: the target is mine after the turn and no other
136
+ * order of mine entered it (another could have failed first and been retaken, or retaken it after
137
+ * this one met it taken), so none of its survivors can have gone back to the source. */
138
+ const landed = (m) => mineNow(m.to) && into(m.to).length === 1 && !untested.has(m.to);
139
+ /** A player's territory next to `id` on board T, other than me. */
140
+ const enemiesNext = (id) => {
141
+ const out = new Set();
142
+ for (const n of neighborsOf(graph, id)) {
143
+ const o = shownOwner(was.get(n));
144
+ if (o !== undefined && o !== me)
145
+ out.add(o);
146
+ }
147
+ return out;
148
+ };
149
+ const result = new Map();
150
+ for (const p of [...input.opponents].sort(byNum)) {
151
+ if (p === me)
152
+ continue;
153
+ const ownsWas = (id) => shownOwner(was.get(id)) === p;
154
+ const ownsNow = (id) => shownOwner(now.get(id)) === p;
155
+ const contact = ids.some((id) => ownsWas(id) && neighborsOf(graph, id).some(mineWas));
156
+ const tookFromMe = giftUnknown ? null : ids.filter((id) => mineWas(id) && ownsNow(id) && !gifted.has(id));
157
+ const lostToMe = ids.filter((id) => ownsWas(id) && mineNow(id));
158
+ const iAttacked = moves.some((m) => ownsWas(m.to) && m.armies > 0 && !transferOnly.has(`${m.from}:${m.to}`)) ||
159
+ sent.some((m) => ownsWas(m.to) && !m.transferOnly && sentCount(m) > plain(m));
160
+ // attackedMe
161
+ let attackedMe = tookFromMe?.length ? true : null;
162
+ if (attackedMe === null && orders && !airliftUnknown) {
163
+ let tested = false;
164
+ for (const id of ids) {
165
+ if (untested.has(id))
166
+ continue;
167
+ const a = seen(was.get(id));
168
+ const b = seen(now.get(id));
169
+ if (a?.owner !== me || b?.owner !== me)
170
+ continue;
171
+ const stacks = neighborsOf(graph, id).filter((n) => {
172
+ const s = seen(was.get(n));
173
+ return s !== undefined && s.owner === p && s.armies > 0;
174
+ });
175
+ if (!stacks.length)
176
+ continue;
177
+ const others = enemiesNext(id);
178
+ if (others.size !== 1 || !allShown(id))
179
+ continue;
180
+ // Under Multi-Attack a third player may have chained through its territory (or a neutral) into
181
+ // mine and the drop would be blamed on it: only a border with every territory within two steps
182
+ // shown, none another player's, is read (a longer chain is not ruled out).
183
+ if (multiAttack &&
184
+ twoSteps(id).some((t) => {
185
+ const o = shownOwner(was.get(t));
186
+ return ownerShown(was.get(t)) === undefined || (o !== undefined && o !== me && o !== p);
187
+ }))
188
+ continue;
189
+ const transfersIn = into(id).filter((m) => mineWas(m.from));
190
+ if (transfersIn.some((m) => enemiesNext(m.from).size > 0 || !allShown(m.from)))
191
+ continue;
192
+ const expected = a.armies + (deploys.get(id) ?? 0) - sum(outOf(id)) + sum(transfersIn);
193
+ if (b.armies < expected) {
194
+ attackedMe = true;
195
+ break;
196
+ }
197
+ // A move out that did not surely land (a failed attack, a transfer that met a territory taken
198
+ // first, or a move into a territory another order of mine also entered, which may have been
199
+ // taken or retaken in between) may send survivors back, which can cover a hit: no "no" here.
200
+ // A move out that drains it to the guard sends only what is left: a hit landing first shrinks
201
+ // the move, not the border, which still ends at `expected`: no "no" from here either.
202
+ const drained = outOf(id).some((m) => m.armies > 0) && expected <= guard;
203
+ // A move in from a territory not mine on T (one I took this turn: a Multi-Attack chain) brings
204
+ // armies the figure leaves out, which can cover a hit: a drop is still a yes, never a "no".
205
+ const chainedIn = into(id).some((m) => m.armies > 0 && !mineWas(m.from));
206
+ if (!drained && !chainedIn && !outOf(id).some((m) => m.armies > 0 && !landed(m)))
207
+ tested = true;
208
+ }
209
+ // A quiet border is a "no" only when captures can be told too (a capture elsewhere would be a yes).
210
+ if (attackedMe === null && tested && tookFromMe !== null)
211
+ attackedMe = false;
212
+ }
213
+ // reinforce
214
+ const reinforce = { n: 0, e: 0, extra: 0 };
215
+ if (exact && orders && !airliftUnknown) {
216
+ for (const m of moves) {
217
+ const x = seen(was.get(m.to));
218
+ if (!x || x.owner !== p || m.armies <= 0)
219
+ continue;
220
+ if (untested.has(m.from) || untested.has(m.to))
221
+ continue;
222
+ if (transferOnly.has(`${m.from}:${m.to}`))
223
+ continue;
224
+ if (into(m.to).length !== 1 || outOf(m.to).length)
225
+ continue;
226
+ if (specialUnitStrength(visibleState(was.get(m.to))?.specialUnits) > 0)
227
+ continue;
228
+ const xNow = seen(now.get(m.to));
229
+ if (!xNow || (xNow.owner !== p && xNow.owner !== me))
230
+ continue;
231
+ const captured = xNow.owner === me;
232
+ // The source: mine on both boards, not hit first.
233
+ const sWas = seen(was.get(m.from));
234
+ const sNow = seen(now.get(m.from));
235
+ if (sWas?.owner !== me || sNow?.owner !== me)
236
+ continue;
237
+ // A commander of mine may go with the attack (fighting as 7): its kills are not `m.armies`'.
238
+ if (visibleState(was.get(m.from))?.specialUnits?.some((u) => u.playerId === me))
239
+ continue;
240
+ if (into(m.from).length)
241
+ continue;
242
+ const sent = outOf(m.from);
243
+ const available = sWas.armies + (deploys.get(m.from) ?? 0);
244
+ if (sum(sent) > available - guard)
245
+ continue;
246
+ if (sent.some((o) => o !== m && !landed(o)))
247
+ continue;
248
+ const base = available - sum(sent);
249
+ const A = m.armies;
250
+ const D = x.armies;
251
+ const K = straightKills(A, off);
252
+ let d;
253
+ if (captured) {
254
+ if (sNow.armies !== base)
255
+ continue;
256
+ // The least defenders from D up whose kills leave what stands on X: D itself when more
257
+ // survived than the exact result (X weaker than shown: an opportunity, not an event).
258
+ d = D;
259
+ while (d < D + 10_000 && A - straightKills(d, def) > xNow.armies)
260
+ d++;
261
+ }
262
+ else {
263
+ // At most A come back (fewer defenders than D kill fewer of mine); less than none: S was hit.
264
+ const returned = sNow.armies - base;
265
+ if (returned < 0 || returned > A)
266
+ continue;
267
+ d = Math.max(leastFailing(A, D, off, def), xNow.armies > 0 ? xNow.armies + K : 0);
268
+ // What comes back must be the exact result against the defenders X's survivors imply: a
269
+ // capture it took back later in the turn (none back, X its again) or another fight on X
270
+ // does not match and is no reading.
271
+ const met = xNow.armies > 0 ? xNow.armies + K : d;
272
+ if (A - Math.min(A, straightKills(met, def)) !== returned)
273
+ continue;
274
+ }
275
+ reinforce.n++;
276
+ if (d > D) {
277
+ reinforce.e++;
278
+ reinforce.extra += d - D;
279
+ }
280
+ }
281
+ }
282
+ // stack
283
+ let top = 0;
284
+ let total = 0;
285
+ let both = 0;
286
+ for (const id of ids) {
287
+ const a = seen(was.get(id));
288
+ const b = seen(now.get(id));
289
+ if (a?.owner !== p || b?.owner !== p)
290
+ continue;
291
+ both++;
292
+ const g = Math.max(0, b.armies - a.armies);
293
+ total += g;
294
+ top = Math.max(top, g);
295
+ }
296
+ const stack = both >= 2 && total >= 1 ? { top, total } : null;
297
+ result.set(p, { contact, attackedMe, iAttacked, reinforce, stack, tookFromMe, lostToMe });
298
+ }
299
+ return result;
300
+ }
301
+ export const HABIT_NAMES = ['reinforce', 'attack', 'firstStrike', 'stacking', 'retaliate', 'retake'];
302
+ /**
303
+ * The habits of one opponent from its observed turns (any order; each turn once). Habits that span
304
+ * turns are recomputed from the whole list, so re-deriving never double-counts:
305
+ * - `reinforce`: Σ events ÷ Σ opportunities;
306
+ * - `attack`: turns in contact where it attacked me ÷ turns in contact where that could be told;
307
+ * - `firstStrike`: its first contact with me (the turn before observed without contact, or turn 1)
308
+ * that lasted two turns, an event when it attacked me on either; counted only when both turns
309
+ * could be told or one says it did;
310
+ * - `stacking`: the mean of `top ÷ total` over turns with a stack;
311
+ * - `retaliate`: turns I attacked it, an event when it attacked me on one of the next two turns;
312
+ * counted only when both are observed and told, or one says it did;
313
+ * - `retake`: territories I took from it, an event when it took them back within two turns;
314
+ * counted only when both turns are observed with their captures told, or it did.
315
+ */
316
+ export function habitsOf(turns) {
317
+ const by = new Map();
318
+ for (const t of turns)
319
+ by.set(t.turn, t.primitives);
320
+ const order = [...by.keys()].sort(byNum);
321
+ const h = {
322
+ reinforce: { e: 0, n: 0 },
323
+ reinforceExtra: { n: 0, sum: 0 },
324
+ attack: { e: 0, n: 0 },
325
+ firstStrike: { e: 0, n: 0 },
326
+ stacking: { n: 0, sum: 0, sq: 0 },
327
+ retaliate: { e: 0, n: 0 },
328
+ retake: { e: 0, n: 0 },
329
+ turns: order.length,
330
+ };
331
+ /** Whether either of the next two turns says yes (`true`), both say no (`false`), or it cannot be told (`null`). */
332
+ const within2 = (t, test) => {
333
+ const a = by.get(t + 1);
334
+ const b = by.get(t + 2);
335
+ const ra = a ? test(a) : null;
336
+ const rb = b ? test(b) : null;
337
+ if (ra === true || rb === true)
338
+ return true;
339
+ return ra === false && rb === false ? false : null;
340
+ };
341
+ const count = (r, v) => {
342
+ if (v === null)
343
+ return;
344
+ r.n++;
345
+ if (v)
346
+ r.e++;
347
+ };
348
+ for (const t of order) {
349
+ const p = by.get(t);
350
+ h.reinforce.e += p.reinforce.e;
351
+ h.reinforce.n += p.reinforce.n;
352
+ h.reinforceExtra.n += p.reinforce.e;
353
+ h.reinforceExtra.sum += p.reinforce.extra;
354
+ if (p.contact && p.attackedMe !== null)
355
+ count(h.attack, p.attackedMe);
356
+ if (p.stack && p.stack.total > 0) {
357
+ const share = p.stack.top / p.stack.total;
358
+ h.stacking.n++;
359
+ h.stacking.sum += share;
360
+ h.stacking.sq += share * share;
361
+ }
362
+ if (p.iAttacked)
363
+ count(h.retaliate, within2(t, (q) => q.attackedMe));
364
+ for (const id of p.lostToMe)
365
+ count(h.retake, within2(t, (q) => (q.tookFromMe === null ? null : q.tookFromMe.includes(id))));
366
+ }
367
+ // The first contact: the earliest turn in contact.
368
+ const first = order.find((t) => by.get(t).contact);
369
+ if (first !== undefined) {
370
+ const before = by.get(first - 1);
371
+ const fresh = first <= 1 || (before !== undefined && !before.contact);
372
+ const next = by.get(first + 1);
373
+ if (fresh && next?.contact) {
374
+ const a = by.get(first).attackedMe;
375
+ const b = next.attackedMe;
376
+ if (a === true || b === true)
377
+ count(h.firstStrike, true);
378
+ else if (a === false && b === false)
379
+ count(h.firstStrike, false);
380
+ }
381
+ }
382
+ return h;
383
+ }
384
+ // ---- the estimate (B1): this game pooled with past games, shrunk toward the population or a default ----
385
+ /** How many opportunities the prior weighs as (docs/PLAN-PROFILES.md B1). */
386
+ export const PROFILE_PRIOR_WEIGHT = 4;
387
+ /** The least confidence at which a habit gives a label. */
388
+ export const PROFILE_MIN_CONFIDENCE = 0.5;
389
+ /** The neutral prior per habit, until part 0's pooled rates replace them. */
390
+ export const HABIT_DEFAULTS = {
391
+ reinforce: 0.5,
392
+ attack: 0.4,
393
+ firstStrike: 0.3,
394
+ stacking: 0.7,
395
+ retaliate: 0.5,
396
+ retake: 0.4,
397
+ };
398
+ /**
399
+ * The least opportunities (readings, for a size) a population pool needs for one habit before its
400
+ * rate replaces the constant default as that habit's prior: fewer, and the next pool (or the default)
401
+ * is used. A pool of a handful would swing the prior on one game.
402
+ */
403
+ export const POPULATION_MIN_OPPORTUNITIES = 10;
404
+ /** A player's totals from earlier games are multiplied by this when a game new to it is folded (B2). */
405
+ export const PROFILE_DECAY = 0.9;
406
+ /** The formats profiles are pooled by. */
407
+ export const PROFILE_FORMATS = ['1v1', 'ffa', 'team'];
408
+ /** A game's format for pooling: a team game, else `1v1` with two seats held, else `ffa`. */
409
+ export function profileFormatOf(players) {
410
+ if (isTeamGame(players))
411
+ return 'team';
412
+ return players.filter((p) => holdsSeat(p.state)).length <= 2 ? '1v1' : 'ffa';
413
+ }
414
+ /** No counts at all. */
415
+ export function emptyHabits() {
416
+ return {
417
+ reinforce: { e: 0, n: 0 },
418
+ reinforceExtra: { n: 0, sum: 0 },
419
+ attack: { e: 0, n: 0 },
420
+ firstStrike: { e: 0, n: 0 },
421
+ stacking: { n: 0, sum: 0, sq: 0 },
422
+ retaliate: { e: 0, n: 0 },
423
+ retake: { e: 0, n: 0 },
424
+ turns: 0,
425
+ };
426
+ }
427
+ /** Rounded to 1e-6, so faded totals do not drift with float noise (and a cancelled count is 0). */
428
+ const tidy = (v) => {
429
+ const r = Math.round(v * 1e6) / 1e6;
430
+ return r === 0 ? 0 : r;
431
+ };
432
+ /** `a + scale × b`, count by count (`scale` −1 takes `b` back out). */
433
+ export function addHabits(a, b, scale = 1) {
434
+ const rate = (x, y) => ({ e: tidy(x.e + scale * y.e), n: tidy(x.n + scale * y.n) });
435
+ return {
436
+ reinforce: rate(a.reinforce, b.reinforce),
437
+ reinforceExtra: { n: tidy(a.reinforceExtra.n + scale * b.reinforceExtra.n), sum: tidy(a.reinforceExtra.sum + scale * b.reinforceExtra.sum) },
438
+ attack: rate(a.attack, b.attack),
439
+ firstStrike: rate(a.firstStrike, b.firstStrike),
440
+ stacking: { n: tidy(a.stacking.n + scale * b.stacking.n), sum: tidy(a.stacking.sum + scale * b.stacking.sum), sq: tidy(a.stacking.sq + scale * b.stacking.sq) },
441
+ retaliate: rate(a.retaliate, b.retaliate),
442
+ retake: rate(a.retake, b.retake),
443
+ turns: tidy(a.turns + scale * b.turns),
444
+ };
445
+ }
446
+ /** Every count × `f` (the fade). */
447
+ export const scaleHabits = (h, f) => addHabits(emptyHabits(), h, f);
448
+ const round2 = (v) => Math.round(v * 100) / 100;
449
+ /** `(p0 × K + e) ÷ (K + n)` from this game's counts alone, its confidence and basis. */
450
+ export function estimate(events, n, p0, k = PROFILE_PRIOR_WEIGHT) {
451
+ return blend({ e: events, n }, { e: 0, n: 0 }, p0, 'default', k);
452
+ }
453
+ /**
454
+ * `(p0 × K + e) ÷ (K + n)` with `e` and `n` this game's and the past's together. The basis is the
455
+ * largest weight of this game's `n`, the past's `n` and the prior's K; the prior wins a tie, then
456
+ * this game. A past basis reads `history` when `fromHistory` (the part of the past folded from
457
+ * finished games' histories) holds at least half of the past's `n` (#312 E3); the value never changes.
458
+ */
459
+ function blend(game, past, p0, prior, k = PROFILE_PRIOR_WEIGHT, fromHistory) {
460
+ const e = game.e + past.e;
461
+ const n = game.n + past.n;
462
+ let basis = prior;
463
+ let weight = k;
464
+ if (game.n > weight) {
465
+ basis = 'this-game';
466
+ weight = game.n;
467
+ }
468
+ if (past.n > weight)
469
+ basis = fromHistory && fromHistory.n > 0 && 2 * fromHistory.n >= past.n ? 'history' : 'past-games';
470
+ return { value: round2((p0 * k + e) / (k + n)), n: round2(n), confidence: round2(n / (n + k)), basis };
471
+ }
472
+ /** Every habit's estimate from a game's counts, pooled with the past and shrunk toward the prior (B1). */
473
+ export function estimateHabits(h, priors = {}) {
474
+ const past = priors.past ?? emptyHabits();
475
+ const pools = priors.pools ?? [];
476
+ const prior = (name, pick) => {
477
+ for (const pool of pools) {
478
+ const r = pick(pool);
479
+ if (r.n >= POPULATION_MIN_OPPORTUNITIES)
480
+ return { p0: r.e / r.n, from: 'population' };
481
+ }
482
+ return { p0: HABIT_DEFAULTS[name], from: 'default' };
483
+ };
484
+ const rate = (name) => {
485
+ const p = prior(name, (x) => x[name]);
486
+ return blend(h[name], past[name], p.p0, p.from, PROFILE_PRIOR_WEIGHT, priors.pastHistory?.[name]);
487
+ };
488
+ const size = (x) => ({ e: x.stacking.sum, n: x.stacking.n });
489
+ const s = prior('stacking', size);
490
+ return {
491
+ reinforce: rate('reinforce'),
492
+ attack: rate('attack'),
493
+ firstStrike: rate('firstStrike'),
494
+ stacking: blend(size(h), size(past), s.p0, s.from, PROFILE_PRIOR_WEIGHT, priors.pastHistory ? size(priors.pastHistory) : undefined),
495
+ retaliate: rate('retaliate'),
496
+ retake: rate('retake'),
497
+ };
498
+ }
499
+ export const PROFILE_LABELS = ['reinforcer', 'rarely-reinforces', 'stacker', 'spreader', 'rusher', 'turtle', 'avenger', 'retakes'];
500
+ /** One fixed counter-play line per label the plan gives one (docs/PLAN-PROFILES.md B1; `spreader` has none). */
501
+ export const COUNTER_PLAY = {
502
+ reinforcer: 'Attack two of its territories in one turn (it deploys on one), or size for its deploy.',
503
+ 'rarely-reinforces': 'Attack at the bare cost; spend the saving elsewhere.',
504
+ stacker: 'Hold in full where its stack is; expect one push.',
505
+ rusher: 'Garrison at first contact; no leftover on expansion.',
506
+ turtle: 'Out-expand it; a quiet border with it tends to stay quiet.',
507
+ avenger: 'Do not poke; strike only to cripple, and garrison the source.',
508
+ retakes: 'A capture from it needs a garrison that survives its counter.',
509
+ };
510
+ /** Turns back from the one being played within which an attack on me withholds `turtle` (#264). */
511
+ export const TURTLE_QUIET_TURNS = 2;
512
+ const attackedRecently = (r) => r.lastAttackTurn != null && r.turn != null && r.lastAttackTurn >= r.turn - TURTLE_QUIET_TURNS;
513
+ /**
514
+ * The last turn an opponent attacked me (#264): the latest observed turn whose primitives say it did
515
+ * (`attackedMe`, or a territory it took from me); `null` when none does. A turn T is what happened
516
+ * between my boards of T and T + 1, so on turn N an attack on N − 1 or N − 2 is "the last two turns".
517
+ */
518
+ export function lastAttackTurn(turns) {
519
+ let last = null;
520
+ for (const t of turns)
521
+ if ((t.primitives.attackedMe === true || (t.primitives.tookFromMe?.length ?? 0) > 0) && (last === null || t.turn > last))
522
+ last = t.turn;
523
+ return last;
524
+ }
525
+ /**
526
+ * The labels the estimates earn, each only at {@link PROFILE_MIN_CONFIDENCE} or more, in a fixed order.
527
+ *
528
+ * Withheld until the second part-0 report (review of the first, 2026-11-15):
529
+ * - `stacker` / `spreader`: the pooled stacking mean is ~0.74, so a fixed 0.75 bar labels most
530
+ * opponents and 0.45 none; and a stack that stays put is board state as much as habit.
531
+ * - `rusher`: `firstStrike` counts once per opponent-game, so its confidence bar needs about a fifth
532
+ * meeting with the same player; it cannot fire in practice.
533
+ * `turtle` is given only on this game's counts: the first report could not separate a quiet player
534
+ * from a quiet game, so a quiet past is not carried into a label. Nor is it given when it attacked me
535
+ * within the last {@link TURTLE_QUIET_TURNS} turns (`recent`, #264): a quiet rate beside a fresh
536
+ * attack gives the wrong picture of that border.
537
+ */
538
+ export function labelsOf(e, recent = {}) {
539
+ const sure = (x) => x.confidence >= PROFILE_MIN_CONFIDENCE;
540
+ const out = [];
541
+ if (sure(e.reinforce) && e.reinforce.value >= 0.6)
542
+ out.push('reinforcer');
543
+ if (sure(e.reinforce) && e.reinforce.value <= 0.3)
544
+ out.push('rarely-reinforces');
545
+ if (sure(e.attack) && e.attack.basis === 'this-game' && e.attack.value <= 0.2 && !attackedRecently(recent))
546
+ out.push('turtle');
547
+ if (sure(e.retaliate) && e.retaliate.value >= 0.6)
548
+ out.push('avenger');
549
+ if (sure(e.retake) && e.retake.value >= 0.6)
550
+ out.push('retakes');
551
+ return out;
552
+ }