@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,1109 @@
1
+ import { carriesTeam } from '../teams.js';
2
+ import { bonusTerritories } from './bonuses.js';
3
+ import { armiesToTake, specialUnitStrength } from './combat.js';
4
+ import { bfsDistances, neighborsOf } from './graph.js';
5
+ import { DEFAULT_NEUTRALS_IN_DISTRIBUTION, DEFAULT_NON_DISTRIBUTION_ARMIES, DEFAULT_PICK_ARMIES } from './picks.js';
6
+ import { captureCost, ownerShown, visibleState } from './planner.js';
7
+ import { DEFAULT_BASE_INCOME, territoryIncome } from './player.js';
8
+ /** Captures along one path that {@link reach} looks ahead, and turns {@link growth} is run for. */
9
+ const REACH_HORIZON = 12;
10
+ /** Start sets enumerated before the candidates are weighed one by one. */
11
+ export const MAX_START_SETS = 5000;
12
+ /** How well a start explains a sighting it could only reach at the earliest (1: the growth model holds it; 0: not in time). */
13
+ export const EXPLAINS_EARLIEST = 0.3;
14
+ /** No guess is surer than this. */
15
+ export const PRESENCE_CAP = 0.95;
16
+ /**
17
+ * Presence on a territory last seen as the opponent's: `duel` in a two-player game (only I could
18
+ * have taken it, and I would know); with more players `first` minus `perTurn` for each turn since,
19
+ * never below `floor`.
20
+ */
21
+ export const LAST_SEEN = { duel: 0.95, first: 0.9, perTurn: 0.1, floor: 0.4 };
22
+ /** Presence the growth model gives a territory, as a share of its start's likelihood. */
23
+ export const GROWTH_WEIGHT = 0.6;
24
+ /** Presence on the hidden members of a bonus that is in every combination explaining a tracked income. */
25
+ export const INCOME_WEIGHT = 0.7;
26
+ /** The least likelihood at which a bonus is listed as probably held, or a missing member of mine as contested. */
27
+ const LIKELY_BONUS = 0.3;
28
+ /** The least presence at which a hidden territory counts as a place it could attack from. */
29
+ const SOURCE_PRESENCE = 0.5;
30
+ /** Presence that could go either way: worth a look. */
31
+ const SCOUT_RANGE = { min: 0.25, max: 0.75 };
32
+ /** How far ahead `prepare` looks: this turn and the next. */
33
+ export const PREPARE_TURNS = 2;
34
+ export const MAX_APPROACHES = 10;
35
+ export const MAX_PREPARE = 10;
36
+ /** Sentences one `doing` rule gives per opponent. */
37
+ const MAX_DOING_PER_RULE = 3;
38
+ /** Territories one `can-attack` sentence names before it gives the rest as a count. */
39
+ const MAX_TARGETS_NAMED = 5;
40
+ /**
41
+ * A bonus I hold part of is `contested` only when finishing it (the capture cost of its missing
42
+ * territories, as shown now) is at most this many turns of its value.
43
+ */
44
+ const CONTEST_PAYBACK_TURNS = 10;
45
+ const PRESENCE_ORDER = ['last-seen', 'start', 'corridor', 'growth', 'income'];
46
+ /** Sources that all come from one start likelihood: never added up as if independent. */
47
+ const FROM_STARTS = new Set(['start', 'corridor', 'growth']);
48
+ /**
49
+ * A territory's presence from its sources. Start, corridor and growth all rest on the same start
50
+ * likelihoods, so they count once (the strongest of them); that and the independent sources
51
+ * (last-seen, income) are combined by noisy-OR, capped at {@link PRESENCE_CAP}.
52
+ */
53
+ export function combinePresence(parts) {
54
+ let fromStarts = 0;
55
+ let p = 0;
56
+ for (const s of PRESENCE_ORDER) {
57
+ const v = parts.get(s) ?? 0;
58
+ if (FROM_STARTS.has(s))
59
+ fromStarts = Math.max(fromStarts, v);
60
+ else
61
+ p = either(p, v);
62
+ }
63
+ return Math.min(PRESENCE_CAP, either(p, fromStarts));
64
+ }
65
+ const byNum = (a, b) => a - b;
66
+ const round2 = (n) => Math.round(n * 100) / 100;
67
+ const plural = (n, one, many) => (n === 1 ? one : many);
68
+ /** 1 − (1 − a)(1 − b), exact when one of them is 0. */
69
+ const either = (a, b) => (a <= 0 ? b : b <= 0 ? a : 1 - (1 - a) * (1 - b));
70
+ function reachCore(field, sources, budget, horizon) {
71
+ const g = field.graph;
72
+ const armies = Math.max(0, budget.armies);
73
+ const income = Math.max(0, budget.income);
74
+ /** max(captures, the turns of income the cost needs); Infinity when it is never paid. */
75
+ const turnsFor = (cost, captures) => {
76
+ if (cost <= armies)
77
+ return captures;
78
+ if (income <= 0)
79
+ return Infinity;
80
+ return Math.max(captures, Math.ceil((cost - armies) / income));
81
+ };
82
+ const cost = new Map();
83
+ const best = new Map();
84
+ // steps[h]: the territories whose cheapest way in at most h captures is new at h → the one before.
85
+ const steps = [new Map()];
86
+ let frontier = [];
87
+ for (const s of [...new Set(sources)].sort(byNum)) {
88
+ if (!g.territoryById.has(s))
89
+ continue;
90
+ cost.set(s, 0);
91
+ best.set(s, { turns: 0, captures: 0, cost: 0 });
92
+ frontier.push(s);
93
+ }
94
+ const isSource = new Set(frontier);
95
+ for (let h = 1; h <= horizon && frontier.length; h++) {
96
+ const cheaper = new Map();
97
+ const from = new Map();
98
+ for (const u of frontier) {
99
+ if (field.targets?.has(u) && !isSource.has(u))
100
+ continue;
101
+ const cu = cost.get(u);
102
+ for (const n of neighborsOf(g, u)) {
103
+ const c = field.cost(n);
104
+ if (c === null)
105
+ continue;
106
+ const nc = cu + c;
107
+ if (nc < (cheaper.get(n) ?? cost.get(n) ?? Infinity)) {
108
+ cheaper.set(n, nc);
109
+ from.set(n, u);
110
+ }
111
+ }
112
+ }
113
+ frontier = [...cheaper.keys()].sort(byNum);
114
+ for (const v of frontier) {
115
+ const nc = cheaper.get(v);
116
+ cost.set(v, nc);
117
+ const turns = turnsFor(nc, h);
118
+ if (turns < (best.get(v)?.turns ?? Infinity))
119
+ best.set(v, { turns, captures: h, cost: nc });
120
+ }
121
+ steps.push(from);
122
+ }
123
+ const pathTo = (territoryId) => {
124
+ const b = best.get(territoryId);
125
+ if (!b)
126
+ return [];
127
+ const path = [territoryId];
128
+ let at = territoryId;
129
+ for (let j = b.captures; j > 0; j--) {
130
+ while (j > 0 && !steps[j].has(at))
131
+ j--;
132
+ if (j === 0)
133
+ break;
134
+ at = steps[j].get(at);
135
+ path.push(at);
136
+ }
137
+ return path.reverse();
138
+ };
139
+ return { best, pathTo };
140
+ }
141
+ /**
142
+ * For a player standing on `sources`: the earliest number of turns after which it can hold each
143
+ * territory, taking one capture per turn along a path and paying each capture's cost out of
144
+ * `budget.armies` plus `budget.income` per turn. For a path of h captures costing C in total that
145
+ * is max(h, ceil((C − armies) / income)); the least over h up to `horizon` is kept (fewest
146
+ * captures on a tie). Territories of `field.targets` are reached, never passed through.
147
+ */
148
+ export function reach(field, sources, budget, horizon = REACH_HORIZON) {
149
+ const core = reachCore(field, sources, budget, horizon);
150
+ const out = new Map();
151
+ for (const id of [...core.best.keys()].sort(byNum))
152
+ out.set(id, { ...core.best.get(id), path: core.pathTo(id) });
153
+ return out;
154
+ }
155
+ /** Territory → the bonuses it is in (superbonus members flattened), ascending; per graph. */
156
+ const bonusIndexes = new WeakMap();
157
+ function bonusesOf(g) {
158
+ let index = bonusIndexes.get(g);
159
+ if (index)
160
+ return index;
161
+ index = new Map();
162
+ for (const b of [...g.map.bonuses].sort((x, y) => x.id - y.id)) {
163
+ for (const t of bonusTerritories(g, b.id)) {
164
+ const list = index.get(t);
165
+ if (list)
166
+ list.push(b.id);
167
+ else
168
+ index.set(t, [b.id]);
169
+ }
170
+ }
171
+ bonusIndexes.set(g, index);
172
+ return index;
173
+ }
174
+ /**
175
+ * What a player starting on `start` could plausibly hold after `turns` turns (at most
176
+ * {@link REACH_HORIZON}): territory → the turn it is first held (0: the start). Each turn it
177
+ * adds its income (the base, plus the bonuses it holds in full) to one pool of armies and spends
178
+ * it on the bonus with the best value per remaining capture cost among those with a member next
179
+ * to what it held when the turn began, cheapest such member first, until a capture cannot be
180
+ * paid. Territories of `field.targets` and of `never` are not taken (and are left out of a
181
+ * bonus's remaining cost). Generous on purpose: the armies are pooled and nothing is kept back.
182
+ */
183
+ export function growth(field, start, turns, economy, never = new Set()) {
184
+ const g = field.graph;
185
+ const held = new Map();
186
+ if (!g.territoryById.has(start))
187
+ return held;
188
+ held.set(start, 0);
189
+ const index = bonusesOf(g);
190
+ const takeable = (t) => !held.has(t) && !never.has(t) && !field.targets?.has(t) && field.cost(t) !== null;
191
+ const income = () => {
192
+ let bonuses = 0;
193
+ const checked = new Set();
194
+ for (const t of held.keys()) {
195
+ for (const b of index.get(t) ?? []) {
196
+ if (checked.has(b))
197
+ continue;
198
+ checked.add(b);
199
+ if (bonusTerritories(g, b).every((m) => held.has(m)))
200
+ bonuses += g.bonusById.get(b).value;
201
+ }
202
+ }
203
+ return Math.max(0, territoryIncome(held.size, economy.baseIncome, economy.bonusArmyPer ?? 0) + bonuses);
204
+ };
205
+ let pool = Math.max(0, economy.armies);
206
+ for (let turn = 1; turn <= Math.min(turns, REACH_HORIZON); turn++) {
207
+ pool += income();
208
+ // One capture per turn along a path: only what borders the holdings the turn began with.
209
+ const edge = new Set();
210
+ for (const t of held.keys())
211
+ for (const n of neighborsOf(g, t))
212
+ if (takeable(n))
213
+ edge.add(n);
214
+ while (edge.size) {
215
+ let choice;
216
+ const checked = new Set();
217
+ for (const e of edge) {
218
+ for (const b of index.get(e) ?? []) {
219
+ if (checked.has(b))
220
+ continue;
221
+ checked.add(b);
222
+ const value = g.bonusById.get(b).value;
223
+ if (value <= 0)
224
+ continue;
225
+ let remaining = 0;
226
+ let member;
227
+ let memberCost = Infinity;
228
+ for (const m of bonusTerritories(g, b)) {
229
+ if (!takeable(m))
230
+ continue;
231
+ const c = field.cost(m);
232
+ remaining += c;
233
+ if (edge.has(m) && c < memberCost) {
234
+ member = m;
235
+ memberCost = c;
236
+ }
237
+ }
238
+ if (member === undefined)
239
+ continue;
240
+ const score = remaining > 0 ? value / remaining : Infinity;
241
+ if (!choice || score > choice.score || (score === choice.score && b < choice.bonusId))
242
+ choice = { bonusId: b, score, member, cost: memberCost };
243
+ }
244
+ }
245
+ if (!choice || choice.cost > pool)
246
+ break;
247
+ pool -= choice.cost;
248
+ held.set(choice.member, turn);
249
+ edge.delete(choice.member);
250
+ }
251
+ }
252
+ return held;
253
+ }
254
+ // ---- the board as the model reads it ----
255
+ /** The owner a board shows: a player id, `neutral`, or `undefined` when hidden. */
256
+ function shownOwner(t) {
257
+ const s = ownerShown(t);
258
+ if (!s)
259
+ return undefined;
260
+ return s.owner.kind === 'player' ? s.owner.playerId : 'neutral';
261
+ }
262
+ /** The armies a territory defends with: its count plus its special units (a commander as 7). */
263
+ const defenders = (t) => (t.armies ?? 0) + specialUnitStrength(t.specialUnits);
264
+ function worldOf(input) {
265
+ const g = input.graph;
266
+ const byTurn = new Map();
267
+ for (const b of input.boards)
268
+ byTurn.set(b.turn, b.board);
269
+ const turns = [...byTurn.keys()].sort(byNum);
270
+ const turn = turns.at(-1) ?? null;
271
+ const now = new Map();
272
+ if (turn !== null)
273
+ for (const t of byTurn.get(turn).territories)
274
+ if (g.territoryById.has(t.territoryId))
275
+ now.set(t.territoryId, t);
276
+ const mine = new Set();
277
+ const wall = new Set();
278
+ for (const [id, t] of now) {
279
+ const owner = shownOwner(t);
280
+ if (owner === input.me)
281
+ mine.add(id);
282
+ if (owner === input.me || owner === 'neutral')
283
+ wall.add(id);
284
+ }
285
+ const lastShown = new Map();
286
+ const neutralSeen = new Map();
287
+ const everNeutral = new Set();
288
+ for (const n of [...turns].reverse()) {
289
+ for (const t of byTurn.get(n).territories) {
290
+ const id = t.territoryId;
291
+ if (!g.territoryById.has(id) || !ownerShown(t))
292
+ continue;
293
+ if (t.owner.kind === 'neutral') {
294
+ everNeutral.add(id);
295
+ const v = visibleState(t);
296
+ if (v && !neutralSeen.has(id))
297
+ neutralSeen.set(id, v.armies);
298
+ }
299
+ if (!lastShown.has(id))
300
+ lastShown.set(id, { turn: n, state: t });
301
+ }
302
+ }
303
+ const s = input.settings;
304
+ const candidates = new Set((input.candidates?.territories ?? []).filter((t) => g.territoryById.has(t)));
305
+ const neutral = Math.max(0, s.neutralArmies ?? DEFAULT_NON_DISTRIBUTION_ARMIES);
306
+ const inDistribution = Math.max(0, s.distributionNeutralArmies ?? DEFAULT_NEUTRALS_IN_DISTRIBUTION);
307
+ const costs = new Map();
308
+ return {
309
+ g,
310
+ me: input.me,
311
+ turn,
312
+ turns,
313
+ byTurn,
314
+ now,
315
+ mine,
316
+ wall,
317
+ lastShown,
318
+ everNeutral,
319
+ candidates,
320
+ base: Math.max(0, Math.floor(s.baseIncome ?? DEFAULT_BASE_INCOME)),
321
+ starting: Math.max(0, s.startingArmies ?? DEFAULT_PICK_ARMIES),
322
+ guard: s.oneArmyStandsGuard === false ? 0 : 1,
323
+ settings: s,
324
+ neutralSize: (id) => neutralSeen.get(id) ?? (candidates.has(id) ? inDistribution : neutral),
325
+ costOf: (defending) => {
326
+ let c = costs.get(defending);
327
+ if (c === undefined)
328
+ costs.set(defending, (c = captureCost(defending, s)));
329
+ return c;
330
+ },
331
+ };
332
+ }
333
+ /**
334
+ * The board as `mover` crosses it from now on: its own territories in view are free, a neutral
335
+ * costs the attack that takes its armies (those shown, else those last shown, else the settings'
336
+ * size — the in-distribution size for a start candidate nobody is known to have taken), another
337
+ * player's what its stack costs, and mine are targets. With no `mover` it is the board as anyone
338
+ * crossed it since the game began: every territory not mine costs what a neutral there would.
339
+ */
340
+ function fieldFor(w, mover) {
341
+ const memo = new Map();
342
+ const compute = (id) => {
343
+ const t = w.now.get(id);
344
+ const owner = shownOwner(t);
345
+ if (owner === w.me)
346
+ return w.costOf(defenders(t));
347
+ if (mover !== undefined && owner === mover)
348
+ return 0;
349
+ if (owner === 'neutral')
350
+ return w.costOf(t.armies ?? w.neutralSize(id));
351
+ if (mover !== undefined && owner !== undefined)
352
+ return w.costOf((t.armies ?? w.neutralSize(id)) + specialUnitStrength(t.specialUnits));
353
+ return w.costOf(w.neutralSize(id));
354
+ };
355
+ return {
356
+ graph: w.g,
357
+ cost: (id) => {
358
+ let c = memo.get(id);
359
+ if (c === undefined)
360
+ memo.set(id, (c = compute(id)));
361
+ return c;
362
+ },
363
+ targets: w.mine,
364
+ };
365
+ }
366
+ /** The {@link ReachField} of the newest board: for `mover` from now on, or (none given) for anyone since the game began. */
367
+ export function boardField(input, mover) {
368
+ return fieldFor(worldOf(input), mover);
369
+ }
370
+ // ---- starts ----
371
+ /** n choose k, or `limit + 1` once it passes `limit`. */
372
+ function choose(n, k, limit) {
373
+ if (k < 0 || k > n)
374
+ return 0;
375
+ const r = Math.min(k, n - k);
376
+ let c = 1;
377
+ for (let i = 1; i <= r; i++) {
378
+ // C(n − r + i, i): whole at every step, and growing, so passing the limit is final.
379
+ c = (c * (n - r + i)) / i;
380
+ if (c > limit)
381
+ return limit + 1;
382
+ }
383
+ return Math.round(c);
384
+ }
385
+ /** Every k-subset of 0..n−1 (as ascending indices), in lexicographic order. */
386
+ function forEachCombination(n, k, visit) {
387
+ if (k > n)
388
+ return;
389
+ const idx = Array.from({ length: k }, (_, i) => i);
390
+ for (;;) {
391
+ visit(idx);
392
+ let i = k - 1;
393
+ while (i >= 0 && idx[i] === n - k + i)
394
+ i--;
395
+ if (i < 0)
396
+ return;
397
+ idx[i]++;
398
+ for (let j = i + 1; j < k; j++)
399
+ idx[j] = idx[j - 1] + 1;
400
+ }
401
+ }
402
+ /** Scale weights to sum to `total`, none above 1 (what is cut off goes to the rest). */
403
+ function shareOut(weights, total) {
404
+ const out = weights.map(() => 0);
405
+ const open = new Set(weights.map((_, i) => i).filter((i) => weights[i] > 0));
406
+ let left = Math.min(total, open.size);
407
+ for (;;) {
408
+ const sum = [...open].reduce((s, i) => s + weights[i], 0);
409
+ if (sum <= 0 || left <= 0)
410
+ break;
411
+ const over = [...open].filter((i) => (weights[i] * left) / sum >= 1);
412
+ if (!over.length) {
413
+ for (const i of open)
414
+ out[i] = (weights[i] * left) / sum;
415
+ break;
416
+ }
417
+ for (const i of over) {
418
+ out[i] = 1;
419
+ open.delete(i);
420
+ left -= 1;
421
+ }
422
+ }
423
+ return out;
424
+ }
425
+ /**
426
+ * Where each opponent is and what it is doing, as far as my boards, the map, the settings and the
427
+ * start candidates say. See the module comment for the model; `seen` is fact, the rest is guessed.
428
+ */
429
+ export function locateOpponents(input) {
430
+ const w = worldOf(input);
431
+ const g = w.g;
432
+ const assumptions = baseAssumptions(input, w);
433
+ if (w.turn === null)
434
+ return { turn: null, opponents: [], prepare: [], assumptions };
435
+ const turn = w.turn;
436
+ // Who is an opponent: not me, not a teammate; still playing, or still holding territory in view.
437
+ const players = input.players;
438
+ const myTeam = players.find((p) => p.id === w.me)?.team;
439
+ const friend = (id) => id === w.me || (carriesTeam(myTeam) && players.find((p) => p.id === id)?.team === myTeam);
440
+ const inView = new Set();
441
+ for (const t of w.now.values()) {
442
+ const owner = shownOwner(t);
443
+ if (typeof owner === 'number')
444
+ inView.add(owner);
445
+ }
446
+ const ids = new Set(inView);
447
+ for (const p of players)
448
+ if ((p.state ?? 'Playing') === 'Playing')
449
+ ids.add(p.id);
450
+ const opponents = [...ids].filter((id) => !friend(id)).sort(byNum);
451
+ const duel = opponents.length === 1 && !players.some((p) => p.id !== w.me && friend(p.id));
452
+ // What my side holds and values.
453
+ const index = bonusesOf(g);
454
+ const fullBonusOf = new Map();
455
+ const mine = fieldFor(w, w.me);
456
+ /** Finishing a bonus pays within {@link CONTEST_PAYBACK_TURNS} of its value. */
457
+ const worthFinishing = (value, missing) => {
458
+ let cost = 0;
459
+ for (const t of missing) {
460
+ const c = mine.cost(t);
461
+ if (c === null)
462
+ return false;
463
+ cost += c;
464
+ }
465
+ return cost <= CONTEST_PAYBACK_TURNS * value;
466
+ };
467
+ const partial = [];
468
+ for (const b of [...g.map.bonuses].sort((x, y) => x.id - y.id)) {
469
+ const members = bonusTerritories(g, b.id);
470
+ if (b.value <= 0 || !members.length)
471
+ continue;
472
+ const missing = members.filter((t) => !w.mine.has(t));
473
+ if (!missing.length) {
474
+ for (const t of members)
475
+ if (!fullBonusOf.has(t))
476
+ fullBonusOf.set(t, b.id);
477
+ }
478
+ else if (missing.length < members.length && worthFinishing(b.value, missing)) {
479
+ partial.push({ bonusId: b.id, value: b.value, size: members.length, held: members.length - missing.length, missing });
480
+ }
481
+ }
482
+ const wanted = new Set(partial.flatMap((p) => p.missing));
483
+ const commanderOn = new Set();
484
+ for (const id of w.mine)
485
+ if (w.now.get(id).specialUnits?.some((u) => u.kind === 'commander' && u.playerId === w.me))
486
+ commanderOn.add(id);
487
+ const valued = (id) => fullBonusOf.has(id) || commanderOn.has(id);
488
+ const borders = [...w.mine].sort(byNum).filter((id) => neighborsOf(g, id).some((n) => !w.mine.has(n)));
489
+ const hidden = (id) => shownOwner(w.now.get(id)) === undefined;
490
+ // From a candidate start, for anyone: shared by every opponent.
491
+ const past = fieldFor(w);
492
+ const elapsed = Math.min(Math.max(0, turn - 1), REACH_HORIZON);
493
+ const grown = new Map();
494
+ const growthFrom = (c) => {
495
+ let m = grown.get(c);
496
+ if (!m)
497
+ grown.set(c, (m = growth(past, c, elapsed, { armies: w.starting, baseIncome: w.base, bonusArmyPer: w.settings.bonusArmyPer ?? 0 }, w.wall)));
498
+ return m;
499
+ };
500
+ const reached = new Map();
501
+ const reachFrom = (c) => {
502
+ let m = reached.get(c);
503
+ if (!m)
504
+ reached.set(c, (m = reachCore(past, [c], { armies: w.starting, income: w.base }, REACH_HORIZON).best));
505
+ return m;
506
+ };
507
+ const distances = new Map();
508
+ const distFrom = (c) => {
509
+ let m = distances.get(c);
510
+ if (!m)
511
+ distances.set(c, (m = bfsDistances(g, [c], { passable: (id) => !w.wall.has(id) })));
512
+ return m;
513
+ };
514
+ /** How well a start on `c` explains its owner being on `e` by the board of turn `firstSeen`. */
515
+ const explains = (c, e, firstSeen) => {
516
+ const by = firstSeen - 1;
517
+ const held = growthFrom(c).get(e);
518
+ if (held !== undefined && held <= by)
519
+ return 1;
520
+ const r = reachFrom(c).get(e);
521
+ if (r ? r.turns <= by : by > REACH_HORIZON)
522
+ return EXPLAINS_EARLIEST;
523
+ return 0;
524
+ };
525
+ const startsPerPlayer = w.settings.startsPerPlayer !== undefined && w.settings.startsPerPlayer > 0 ? Math.floor(w.settings.startsPerPlayer) : null;
526
+ const oldest = w.byTurn.get(w.turns[0]);
527
+ const oldestOwner = new Map();
528
+ for (const t of oldest.territories) {
529
+ const owner = shownOwner(t);
530
+ if (owner !== undefined && g.territoryById.has(t.territoryId))
531
+ oldestOwner.set(t.territoryId, owner);
532
+ }
533
+ // Certain starts: the award's, and whatever the turn-1 board shows (nobody has moved).
534
+ const provenOf = new Map();
535
+ for (const o of opponents)
536
+ provenOf.set(o, new Set((input.proven?.get(o) ?? []).filter((t) => g.territoryById.has(t))));
537
+ const first = w.byTurn.get(1);
538
+ if (first) {
539
+ for (const t of first.territories) {
540
+ const owner = shownOwner(t);
541
+ if (typeof owner === 'number' && provenOf.has(owner) && g.territoryById.has(t.territoryId))
542
+ provenOf.get(owner).add(t.territoryId);
543
+ }
544
+ }
545
+ const locate = (o) => {
546
+ const track = input.tracks?.find((t) => t.playerId === o);
547
+ // 1. Facts.
548
+ const own = [...w.now.values()].filter((t) => shownOwner(t) === o).sort((a, b) => a.territoryId - b.territoryId);
549
+ const ownIds = new Set(own.map((t) => t.territoryId));
550
+ const seenInView = own.map((t) => ({ territoryId: t.territoryId, armies: visibleState(t)?.armies ?? null }));
551
+ const lastSeen = [...w.lastShown]
552
+ .filter(([, s]) => s.turn < turn && shownOwner(s.state) === o)
553
+ .map(([id, s]) => ({ territoryId: id, armies: visibleState(s.state)?.armies ?? null, turn: s.turn }))
554
+ .sort((a, b) => a.territoryId - b.territoryId);
555
+ /** Every territory of it ever shown → the first turn whose board showed it. */
556
+ const sightings = new Map();
557
+ let lastSight = 0;
558
+ for (const n of w.turns) {
559
+ for (const t of w.byTurn.get(n).territories) {
560
+ if (shownOwner(t) !== o || !g.territoryById.has(t.territoryId))
561
+ continue;
562
+ lastSight = n;
563
+ if (!sightings.has(t.territoryId))
564
+ sightings.set(t.territoryId, n);
565
+ }
566
+ }
567
+ const seenIds = [...sightings.keys()].sort(byNum);
568
+ // 2. Starts.
569
+ const proven = [...provenOf.get(o)].sort(byNum);
570
+ const provenElsewhere = new Set(opponents.filter((x) => x !== o).flatMap((x) => [...provenOf.get(x)]));
571
+ const ruledOut = [];
572
+ const open = [];
573
+ for (const c of [...w.candidates].sort(byNum)) {
574
+ if (provenOf.get(o).has(c))
575
+ continue;
576
+ const then = oldestOwner.get(c);
577
+ const notIts = (then !== undefined && then !== o) || provenElsewhere.has(c);
578
+ if (w.everNeutral.has(c) || notIts)
579
+ ruledOut.push(c);
580
+ else
581
+ open.push(c);
582
+ }
583
+ const unknown = startsPerPlayer === null ? null : Math.max(0, startsPerPlayer - proven.length);
584
+ const priorOf = (c) => {
585
+ const v = input.prior?.weights.get(c) ?? 1;
586
+ return Number.isFinite(v) && v > 0 ? v : 0;
587
+ };
588
+ const likelihood = new Map(proven.map((c) => [c, 1]));
589
+ let method = 'none';
590
+ let priorOnly = false;
591
+ const k = Math.min(unknown ?? 0, open.length);
592
+ /** [candidate][sighting]: how well the candidate explains it. */
593
+ const fit = new Map();
594
+ for (const c of [...proven, ...(k > 0 ? open : [])])
595
+ fit.set(c, seenIds.map((e) => explains(c, e, sightings.get(e))));
596
+ const provenFit = seenIds.map((_, j) => Math.max(0, ...proven.map((c) => fit.get(c)[j])));
597
+ if (k > 0) {
598
+ const prior = open.map(priorOf);
599
+ const rows = open.map((c) => fit.get(c));
600
+ let marginals;
601
+ if (choose(open.length, k, MAX_START_SETS) <= MAX_START_SETS) {
602
+ method = 'enumerated';
603
+ const weigh = (explained) => {
604
+ const sums = open.map(() => 0);
605
+ let total = 0;
606
+ forEachCombination(open.length, k, (set) => {
607
+ let weight = 1;
608
+ for (const i of set)
609
+ weight *= prior[i];
610
+ if (explained) {
611
+ for (let j = 0; j < seenIds.length && weight > 0; j++) {
612
+ let best = provenFit[j];
613
+ for (const i of set)
614
+ if (rows[i][j] > best)
615
+ best = rows[i][j];
616
+ weight *= best;
617
+ }
618
+ }
619
+ if (weight <= 0)
620
+ return;
621
+ total += weight;
622
+ for (const i of set)
623
+ sums[i] += weight;
624
+ });
625
+ return { sums, total };
626
+ };
627
+ let r = weigh(true);
628
+ if (r.total <= 0) {
629
+ priorOnly = seenIds.length > 0;
630
+ r = weigh(false);
631
+ }
632
+ marginals = r.total > 0 ? r.sums.map((s) => s / r.total) : open.map(() => k / open.length);
633
+ }
634
+ else {
635
+ method = 'independent';
636
+ // Each candidate alone, against what the other k − 1 starts are expected to explain.
637
+ const priorSum = prior.reduce((s, p) => s + p, 0);
638
+ const others = seenIds.map((_, j) => {
639
+ if (priorSum <= 0)
640
+ return 0;
641
+ const q = rows.reduce((s, row, i) => s + prior[i] * row[j], 0) / priorSum;
642
+ return 1 - (1 - q) ** (k - 1);
643
+ });
644
+ let weights = open.map((_, i) => seenIds.reduce((x, _e, j) => x * Math.max(rows[i][j], provenFit[j], others[j]), prior[i]));
645
+ if (!weights.some((x) => x > 0)) {
646
+ priorOnly = seenIds.length > 0;
647
+ weights = prior.some((p) => p > 0) ? prior : open.map(() => 1);
648
+ }
649
+ marginals = shareOut(weights, k);
650
+ }
651
+ open.forEach((c, i) => likelihood.set(c, marginals[i]));
652
+ }
653
+ const likely = open
654
+ .filter((c) => (likelihood.get(c) ?? 0) > 0)
655
+ .map((c) => ({ territoryId: c, likelihood: likelihood.get(c) }))
656
+ .sort((a, b) => b.likelihood - a.likelihood || a.territoryId - b.territoryId);
657
+ const starts = {
658
+ source: input.candidates ? input.candidates.source : 'none',
659
+ proven,
660
+ likely,
661
+ ruledOut,
662
+ unknown,
663
+ method,
664
+ priorOnly,
665
+ prior: input.prior
666
+ ? { source: input.prior.source, sample: input.prior.sample, weak: input.prior.weak === true }
667
+ : { source: 'uniform', sample: null, weak: false },
668
+ };
669
+ if (priorOnly)
670
+ assumptions.push(`Player ${o}: no start set explains where it was seen (the candidates may be wrong, or it moved faster than the model allows), so its start likelihoods are the prior alone.`);
671
+ if (method === 'independent')
672
+ assumptions.push(`Player ${o}: more than ${MAX_START_SETS} start sets, so its candidates were weighed one by one, each against what its other starts are expected to explain.`);
673
+ if (unknown !== null && unknown > open.length && input.candidates)
674
+ assumptions.push(`Player ${o}: ${unknown} ${plural(unknown, 'start is', 'starts are')} unknown and only ${open.length} ${plural(open.length, 'candidate is', 'candidates are')} left, so the candidates are incomplete.`);
675
+ // 5. Presence on what is hidden now.
676
+ const parts = new Map();
677
+ const add = (id, source, x) => {
678
+ if (x <= 0 || !hidden(id))
679
+ return;
680
+ let m = parts.get(id);
681
+ if (!m)
682
+ parts.set(id, (m = new Map()));
683
+ m.set(source, either(m.get(source) ?? 0, x));
684
+ };
685
+ for (const s of lastSeen)
686
+ add(s.territoryId, 'last-seen', duel ? LAST_SEEN.duel : Math.max(LAST_SEEN.floor, LAST_SEEN.first - LAST_SEEN.perTurn * (turn - s.turn)));
687
+ const startsByLikelihood = [...likelihood].filter(([, x]) => x > 0).sort(([a], [b]) => a - b);
688
+ for (const [c, x] of startsByLikelihood) {
689
+ add(c, 'start', x);
690
+ for (const [t, heldOn] of growthFrom(c))
691
+ if (t !== c && heldOn <= elapsed)
692
+ add(t, 'growth', x * GROWTH_WEIGHT);
693
+ // The shortest ways from the start to each sighting it explains: per territory, the largest
694
+ // share any one sighting gives (they are one walk from one start, not independent ones).
695
+ const share = new Map();
696
+ const dist = distFrom(c);
697
+ seenIds.forEach((e, j) => {
698
+ if (e === c || fit.get(c)[j] <= 0)
699
+ return;
700
+ const far = dist.get(e) ?? Math.min(Infinity, ...neighborsOf(g, e).map((n) => (dist.get(n) ?? Infinity) + 1));
701
+ if (!Number.isFinite(far))
702
+ return;
703
+ let level = [e];
704
+ for (let d = far - 1; d >= 1; d--) {
705
+ const before = new Set();
706
+ for (const v of level)
707
+ for (const n of neighborsOf(g, v))
708
+ if (dist.get(n) === d)
709
+ before.add(n);
710
+ level = [...before];
711
+ for (const v of level)
712
+ share.set(v, Math.max(share.get(v) ?? 0, 1 / level.length));
713
+ }
714
+ });
715
+ for (const [t, s] of [...share].sort(([a], [b]) => a - b))
716
+ add(t, 'corridor', x * s);
717
+ }
718
+ const combinations = track?.inferred?.candidates ?? [];
719
+ if (combinations.length) {
720
+ // Combinations that fit as well but are not listed count too, as holding none of these.
721
+ const fits = combinations.length + (track?.inferred?.more ?? 0);
722
+ const inHowMany = new Map();
723
+ for (const c of combinations)
724
+ for (const b of new Set(c.bonusIds))
725
+ inHowMany.set(b, (inHowMany.get(b) ?? 0) + 1);
726
+ for (const [b, n] of [...inHowMany].sort(([a], [x]) => a - x))
727
+ for (const t of bonusTerritories(g, b))
728
+ add(t, 'income', (n / fits) * INCOME_WEIGHT);
729
+ }
730
+ const presence = new Map();
731
+ const basisOf = new Map();
732
+ for (const [id, m] of parts) {
733
+ presence.set(id, combinePresence(m));
734
+ basisOf.set(id, PRESENCE_ORDER.filter((s) => m.has(s)));
735
+ }
736
+ const presenceList = [...presence]
737
+ .map(([id, x]) => ({ territoryId: id, likelihood: x, basis: basisOf.get(id) }))
738
+ .sort((a, b) => b.likelihood - a.likelihood || a.territoryId - b.territoryId);
739
+ // 6. Bonuses: held in full in view (fact), or probably (guess).
740
+ const seenBonuses = [];
741
+ const bonusGuesses = [];
742
+ const touched = new Set();
743
+ for (const id of ownIds)
744
+ for (const b of index.get(id) ?? [])
745
+ touched.add(b);
746
+ for (const [id, x] of presence)
747
+ if (x >= LIKELY_BONUS)
748
+ for (const b of index.get(id) ?? [])
749
+ touched.add(b);
750
+ for (const b of [...touched].sort(byNum)) {
751
+ if (g.bonusById.get(b).value <= 0)
752
+ continue;
753
+ let least = 1;
754
+ let view = 0;
755
+ let unseen = 0;
756
+ const basis = new Set();
757
+ for (const t of bonusTerritories(g, b)) {
758
+ if (ownIds.has(t))
759
+ view++;
760
+ else if (hidden(t)) {
761
+ unseen++;
762
+ least = Math.min(least, presence.get(t) ?? 0);
763
+ for (const s of basisOf.get(t) ?? [])
764
+ basis.add(s);
765
+ }
766
+ else
767
+ least = 0;
768
+ if (least <= 0)
769
+ break;
770
+ }
771
+ if (least <= 0)
772
+ continue;
773
+ if (!unseen)
774
+ seenBonuses.push(b);
775
+ else if (least >= LIKELY_BONUS)
776
+ bonusGuesses.push({ bonusId: b, likelihood: least, basis: PRESENCE_ORDER.filter((s) => basis.has(s)), inView: view, hidden: unseen });
777
+ }
778
+ bonusGuesses.sort((a, b) => b.likelihood - a.likelihood || g.bonusById.get(b.bonusId).value - g.bonusById.get(a.bonusId).value || a.bonusId - b.bonusId);
779
+ // 7. Approaches: from each stack in view, and from each hidden territory it probably holds.
780
+ const income = track?.income ?? track?.visibleIncome ?? w.base;
781
+ const field = fieldFor(w, o);
782
+ const sources = [
783
+ ...own.map((t) => {
784
+ const shown = visibleState(t);
785
+ const units = specialUnitStrength(t.specialUnits?.filter((u) => u.playerId === o));
786
+ return shown
787
+ ? { id: t.territoryId, kind: 'seen', armies: Math.max(0, shown.armies - w.guard) + units, counted: true }
788
+ : { id: t.territoryId, kind: 'seen', armies: w.starting, counted: false };
789
+ }),
790
+ ...presenceList
791
+ .filter((p) => p.likelihood >= SOURCE_PRESENCE)
792
+ .map((p) => ({ id: p.territoryId, kind: 'guessed', armies: w.starting, counted: false }))
793
+ .sort((a, b) => a.id - b.id),
794
+ ];
795
+ const sooner = (a, b) => {
796
+ if (!b)
797
+ return true;
798
+ if (a.inTurns !== b.inTurns)
799
+ return a.inTurns < b.inTurns;
800
+ if (a.source.kind !== b.source.kind)
801
+ return a.source.kind === 'seen';
802
+ if (a.source.counted !== b.source.counted)
803
+ return a.source.counted;
804
+ if (a.arriving !== b.arriving)
805
+ return a.arriving > b.arriving;
806
+ if (a.source.id !== b.source.id)
807
+ return a.source.id < b.source.id;
808
+ return a.via < b.via;
809
+ };
810
+ const ways = new Map();
811
+ const threats = new Map();
812
+ const takings = new Map();
813
+ for (const s of sources) {
814
+ const r = reachCore(field, [s.id], { armies: s.armies, income }, REACH_HORIZON);
815
+ for (const m of borders) {
816
+ for (const via of neighborsOf(g, m)) {
817
+ const e = w.mine.has(via) ? undefined : r.best.get(via);
818
+ if (!e)
819
+ continue;
820
+ const way = {
821
+ inTurns: e.turns,
822
+ arriving: Math.max(0, s.armies + income * (e.turns + 1) - e.cost),
823
+ via,
824
+ source: s,
825
+ path: () => [...r.pathTo(via), m],
826
+ };
827
+ if (sooner(way, ways.get(m)))
828
+ ways.set(m, way);
829
+ if (s.counted && way.inTurns < PREPARE_TURNS) {
830
+ const t = threats.get(m);
831
+ // The soonest attack is the one to prepare for; among equally soon ones, the largest.
832
+ if (!t || way.inTurns < t.inTurns || (way.inTurns === t.inTurns && way.arriving > t.armies))
833
+ threats.set(m, { armies: way.arriving, inTurns: way.inTurns, from: s.id });
834
+ }
835
+ }
836
+ }
837
+ for (const t of wanted) {
838
+ const e = r.best.get(t);
839
+ if (!e || e.turns < 1)
840
+ continue;
841
+ const had = takings.get(t);
842
+ if (!had || e.turns < had.turns)
843
+ takings.set(t, { turns: e.turns, from: s.id, guessed: s.kind === 'guessed' });
844
+ }
845
+ }
846
+ const approaches = [...ways]
847
+ .map(([target, way]) => ({
848
+ target,
849
+ turn: turn + way.inTurns,
850
+ inTurns: way.inTurns,
851
+ source: way.source.kind,
852
+ from: way.source.id,
853
+ path: way.path(),
854
+ armies: way.source.counted ? way.arriving : null,
855
+ valued: valued(target),
856
+ }))
857
+ .sort((a, b) => a.inTurns - b.inTurns || Number(b.valued) - Number(a.valued) || a.target - b.target)
858
+ .slice(0, MAX_APPROACHES);
859
+ // 8. Doing.
860
+ const doing = [];
861
+ const received = track?.earnedAtLeast
862
+ ? `; it has received at least ${track.earnedAtLeast.total} armies since the game started (received, not held).`
863
+ : '.';
864
+ if (!seenIds.length)
865
+ doing.push({ rule: 'unseen', text: `Player ${o} has not been seen on any board of yours${received}`, territoryIds: [] });
866
+ else if (!own.length)
867
+ doing.push({ rule: 'out-of-sight', text: `Player ${o} has nothing in view (last seen on turn ${lastSight})${received}`, territoryIds: [] });
868
+ // One sentence per stack, naming the territories of mine it can attack this turn.
869
+ const stacks = new Map();
870
+ for (const [target, way] of ways) {
871
+ if (way.inTurns !== 0 || !way.source.counted)
872
+ continue;
873
+ const s = stacks.get(way.source.id) ?? { arriving: 0, targets: [] };
874
+ s.arriving = Math.max(s.arriving, way.arriving);
875
+ s.targets.push(target);
876
+ stacks.set(way.source.id, s);
877
+ }
878
+ const attacks = [...stacks].sort(([a, x], [b, y]) => y.arriving - x.arriving || a - b).slice(0, MAX_DOING_PER_RULE);
879
+ for (const [from, { arriving, targets }] of attacks) {
880
+ targets.sort(byNum);
881
+ const named = targets.slice(0, MAX_TARGETS_NAMED);
882
+ const rest = targets.length - named.length;
883
+ const list = targets.length === 1
884
+ ? `territory ${named[0]}`
885
+ : rest > 0
886
+ ? `territories ${named.join(', ')} and ${rest} more`
887
+ : `territories ${named.slice(0, -1).join(', ')} and ${named[named.length - 1]}`;
888
+ doing.push({
889
+ rule: 'can-attack',
890
+ text: `Player ${o} can attack ${list} this turn with up to ${arriving} armies from territory ${from} (what its stack can move plus a deploy of ${income}).`,
891
+ territoryIds: [...targets, from],
892
+ });
893
+ }
894
+ const before = w.byTurn.get(turn - 1);
895
+ if (before) {
896
+ const was = new Map(before.territories.map((t) => [t.territoryId, t]));
897
+ const grew = own
898
+ .flatMap((t) => {
899
+ const a = visibleState(t);
900
+ const b = visibleState(was.get(t.territoryId));
901
+ const next = neighborsOf(g, t.territoryId).find((n) => w.mine.has(n));
902
+ if (!a || !b || shownOwner(b) !== o || next === undefined || a.armies <= b.armies)
903
+ return [];
904
+ return [{ id: t.territoryId, by: a.armies - b.armies, to: a.armies, next }];
905
+ })
906
+ .sort((a, b) => b.by - a.by || a.id - b.id)
907
+ .slice(0, MAX_DOING_PER_RULE);
908
+ for (const s of grew)
909
+ doing.push({
910
+ rule: 'stack-grew',
911
+ text: `Player ${o}'s stack on territory ${s.id}, next to your territory ${s.next}, grew by ${s.by} to ${s.to} since turn ${turn - 1}.`,
912
+ territoryIds: [s.id, s.next],
913
+ });
914
+ }
915
+ const near = [];
916
+ const ownBonuses = new Set();
917
+ for (const id of ownIds)
918
+ for (const b of index.get(id) ?? [])
919
+ ownBonuses.add(b);
920
+ for (const b of [...ownBonuses].sort(byNum)) {
921
+ const value = g.bonusById.get(b).value;
922
+ const members = bonusTerritories(g, b);
923
+ if (value <= 0 || members.some(hidden))
924
+ continue;
925
+ const missing = members.filter((t) => !ownIds.has(t));
926
+ if (missing.length >= 1 && missing.length <= 2)
927
+ near.push({ bonusId: b, value, held: members.length - missing.length, size: members.length, missing });
928
+ }
929
+ near.sort((a, b) => a.missing.length - b.missing.length || b.value - a.value || a.bonusId - b.bonusId);
930
+ for (const n of near.slice(0, MAX_DOING_PER_RULE)) {
931
+ const yours = n.missing.filter((t) => w.mine.has(t));
932
+ doing.push({
933
+ rule: 'near-bonus',
934
+ text: `Player ${o} holds ${n.held} of the ${n.size} territories of bonus ${n.bonusId} (+${n.value}): ${n.missing.length} ` +
935
+ `${plural(n.missing.length, 'capture', 'captures')} from completing it (${plural(n.missing.length, 'territory', 'territories')} ${n.missing.join(', ')}` +
936
+ `${yours.length ? `; ${yours.join(', ')} ${plural(yours.length, 'is', 'are')} yours` : ''}).`,
937
+ territoryIds: n.missing,
938
+ bonusId: n.bonusId,
939
+ });
940
+ }
941
+ if (track?.unexplained !== null && track?.unexplained !== undefined && track.income !== null && track.unexplained > track.income)
942
+ doing.push({
943
+ rule: 'hidden-armies',
944
+ text: `About ${track.unexplained} of player ${o}'s armies are out of sight or were spent there (earned since it was first seen, and neither on the board nor lost in view), more than its income of ${track.income} a turn.`,
945
+ territoryIds: [],
946
+ });
947
+ const where = own.length ? `${own.length} ${plural(own.length, 'territory', 'territories')} in view` : 'nothing in view';
948
+ const startText = proven.length
949
+ ? `${plural(proven.length, 'start', 'starts')} ${proven.join(', ')} proven`
950
+ : likely[0]
951
+ ? `likeliest start ${likely[0].territoryId} (${round2(likely[0].likelihood)})`
952
+ : 'no start guess';
953
+ const soonest = approaches[0];
954
+ const next = soonest
955
+ ? `soonest attack on territory ${soonest.target} on turn ${soonest.turn}${soonest.armies !== null ? ` with up to ${soonest.armies}` : ''} (${soonest.source})`
956
+ : 'no attack on you within reach';
957
+ return {
958
+ out: {
959
+ playerId: o,
960
+ seen: { inView: seenInView, lastSeen, bonuses: seenBonuses },
961
+ starts,
962
+ presence: presenceList,
963
+ bonuses: bonusGuesses,
964
+ income: track && track.income !== null ? { estimate: track.income, method: track.incomeMethod } : null,
965
+ hiddenArmies: track?.unexplained ?? null,
966
+ approaches,
967
+ doing,
968
+ summary: `Player ${o}: ${where}${lastSeen.length ? `, ${lastSeen.length} last seen` : ''}; ${startText}; ${next}.`,
969
+ },
970
+ presence,
971
+ threats,
972
+ takings,
973
+ };
974
+ };
975
+ const located = opponents.map(locate);
976
+ const rateArgs = {
977
+ ...(w.settings.offensiveKillRate !== undefined ? { offensiveKillRate: w.settings.offensiveKillRate } : {}),
978
+ ...(w.settings.defensiveKillRate !== undefined ? { defensiveKillRate: w.settings.defensiveKillRate } : {}),
979
+ };
980
+ /** The fewest defenders that `attackers` armies cannot take. */
981
+ const defendersToHold = (attackers) => {
982
+ let d = 0;
983
+ while (d <= attackers && (armiesToTake(d, rateArgs) ?? Infinity) <= attackers)
984
+ d++;
985
+ return d;
986
+ };
987
+ const ranked = [];
988
+ for (const { out, presence, threats, takings } of located) {
989
+ const o = out.playerId;
990
+ for (const [m, threat] of [...threats].sort(([a], [b]) => a - b)) {
991
+ if (!valued(m))
992
+ continue;
993
+ const need = defendersToHold(threat.armies);
994
+ const have = defenders(w.now.get(m));
995
+ if (need <= have)
996
+ continue;
997
+ const bonusId = fullBonusOf.get(m);
998
+ const why = bonusId !== undefined ? `in bonus ${bonusId}, which you hold in full` : 'your commander is there';
999
+ ranked.push({
1000
+ kind: 'hold',
1001
+ opponent: o,
1002
+ turn: turn + threat.inTurns,
1003
+ territory: m,
1004
+ ...(bonusId !== undefined ? { bonusId } : {}),
1005
+ need,
1006
+ have,
1007
+ armies: threat.armies,
1008
+ from: threat.from,
1009
+ text: `Territory ${m} (${why}) can be attacked by player ${o} on turn ${turn + threat.inTurns} with up to ${threat.armies} armies from territory ${threat.from}: it needs ${need} armies to hold and has ${have}.`,
1010
+ weight: need - have,
1011
+ });
1012
+ }
1013
+ for (const p of partial) {
1014
+ const head = `Bonus ${p.bonusId} (+${p.value}): you hold ${p.held} of ${p.size}; player ${o}`;
1015
+ const base = { kind: 'contested', opponent: o, bonusId: p.bonusId, weight: p.value };
1016
+ const holds = p.missing.find((t) => shownOwner(w.now.get(t)) === o);
1017
+ if (holds !== undefined) {
1018
+ ranked.push({ ...base, turn, territory: holds, text: `${head} holds territory ${holds}.` });
1019
+ continue;
1020
+ }
1021
+ const guess = p.missing
1022
+ .filter((t) => (presence.get(t) ?? 0) >= LIKELY_BONUS)
1023
+ .sort((a, b) => presence.get(b) - presence.get(a) || a - b)[0];
1024
+ if (guess !== undefined) {
1025
+ const x = presence.get(guess);
1026
+ ranked.push({ ...base, turn, territory: guess, likelihood: x, text: `${head} may hold territory ${guess} (likelihood ${round2(x)}).` });
1027
+ continue;
1028
+ }
1029
+ const taken = p.missing
1030
+ .filter((t) => (takings.get(t)?.turns ?? Infinity) <= PREPARE_TURNS)
1031
+ .sort((a, b) => takings.get(a).turns - takings.get(b).turns || a - b)[0];
1032
+ if (taken !== undefined) {
1033
+ const t = takings.get(taken);
1034
+ const by = turn + t.turns - 1;
1035
+ ranked.push({ ...base, turn: by, territory: taken, from: t.from, text: `${head} could take territory ${taken} by turn ${by} from territory ${t.from}${t.guessed ? ' (guessed)' : ''}.` });
1036
+ }
1037
+ }
1038
+ // One look per opponent: the territory next to mine that shows the most of the fog, among
1039
+ // those that would settle a guess that could go either way.
1040
+ const unsure = (id) => hidden(id) && (presence.get(id) ?? 0) >= SCOUT_RANGE.min && (presence.get(id) ?? 0) <= SCOUT_RANGE.max;
1041
+ let look;
1042
+ const tried = new Set();
1043
+ for (const m of borders) {
1044
+ for (const at of neighborsOf(g, m)) {
1045
+ if (w.mine.has(at) || tried.has(at))
1046
+ continue;
1047
+ tried.add(at);
1048
+ const around = [at, ...neighborsOf(g, at)].filter(hidden);
1049
+ const shows = around.filter(unsure);
1050
+ if (!shows.length)
1051
+ continue;
1052
+ if (!look || around.length > look.fog || (around.length === look.fog && at < look.at))
1053
+ look = { at, next: m, shows, fog: around.length };
1054
+ }
1055
+ }
1056
+ if (look) {
1057
+ const best = [...look.shows].sort((a, b) => presence.get(b) - presence.get(a) || a - b)[0];
1058
+ const x = presence.get(best);
1059
+ const text = hidden(look.at)
1060
+ ? `Territory ${look.at} borders your territory ${look.next} and is hidden: player ${o} may be there (likelihood ${round2(presence.get(look.at) ?? x)}); taking or seeing it would settle that.`
1061
+ : `Taking territory ${look.at} (it borders your territory ${look.next}) would show ${plural(look.shows.length, 'territory', 'territories')} ${look.shows.join(', ')}, where player ${o} may be (likelihood ${round2(x)}); it borders ${look.fog} hidden ${plural(look.fog, 'territory', 'territories')}.`;
1062
+ ranked.push({ kind: 'scout', opponent: o, turn, territory: look.at, reveals: look.shows, likelihood: x, text, weight: look.fog });
1063
+ }
1064
+ }
1065
+ const kindOrder = { hold: 0, contested: 1, scout: 2 };
1066
+ const prepare = ranked
1067
+ .sort((a, b) => kindOrder[a.kind] - kindOrder[b.kind] ||
1068
+ a.turn - b.turn ||
1069
+ b.weight - a.weight ||
1070
+ a.territory - b.territory ||
1071
+ a.opponent - b.opponent ||
1072
+ (a.bonusId ?? 0) - (b.bonusId ?? 0))
1073
+ .slice(0, MAX_PREPARE)
1074
+ .map(({ weight: _weight, ...p }) => p);
1075
+ return { turn, opponents: located.map((l) => l.out), prepare, assumptions };
1076
+ }
1077
+ /** What the model assumes whatever the opponent. */
1078
+ function baseAssumptions(input, w) {
1079
+ const out = [
1080
+ 'Only `seen` is fact (what your boards showed). The likelihoods are a simple model\'s estimates, not measured probabilities.',
1081
+ 'Growth pools armies: a start\'s armies and its whole income (the base, plus the bonuses it completes) are spent on the bonus with the best value per capture cost. It says what a player could plausibly hold, which is more than it probably does.',
1082
+ 'Movement is one capture per turn along a path, each capture paying its whole attack out of the armies at hand plus the income per turn; Multi-Attack, Airlift and every other card are ignored.',
1083
+ 'A start is never abandoned and a captured territory never turns neutral again (Blockade is ignored).',
1084
+ 'An opponent\'s income is its tracked estimate when it has one, else what it visibly earns (the base plus the bonuses it holds in view). The armies that could arrive count that income every turn on the way and one stack only.',
1085
+ ];
1086
+ if (input.settings.multiAttack)
1087
+ out.push('This game has Multi-Attack on: a stack can take several territories in one turn, so every turn given here may come sooner.');
1088
+ const c = input.candidates;
1089
+ const n = w.candidates.size;
1090
+ if (!c)
1091
+ out.push('No start candidates are known (no pickable territories were kept, and no statistics are in use), so no start is guessed: the rest works from what was seen.');
1092
+ else if (c.source === 'pickable')
1093
+ out.push(`Start candidates: the ${n} ${plural(n, 'territory', 'territories')} the live board showed as pickable during distribution.`);
1094
+ else
1095
+ out.push(`Start candidates: the ${n} ${plural(n, 'territory', 'territories')} players started on in the finished games cached for this map; a start nobody used there is missed.`);
1096
+ if (c) {
1097
+ if (input.prior)
1098
+ out.push(`The start prior weighs a candidate by the players who started on it in ${input.prior.sample} finished ${plural(input.prior.sample, 'game', 'games')} on this map, plus one` +
1099
+ `${input.prior.weak ? ': a small sample, so a weak prior' : ''}.`);
1100
+ else
1101
+ out.push('The start prior is uniform: every candidate weighs the same.');
1102
+ if (input.settings.startsPerPlayer === undefined || input.settings.startsPerPlayer <= 0)
1103
+ out.push('The settings do not say how many territories a player started on, so no start is guessed.');
1104
+ }
1105
+ const oldest = w.turns[0];
1106
+ if (oldest !== undefined && oldest > 1 && c)
1107
+ out.push(`Your oldest board is turn ${oldest}: what it shows as yours or as another player's is taken as no start of anyone else, though it may have been captured before.`);
1108
+ return out;
1109
+ }