@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,1405 @@
1
+ import { bonusTerritories } from '../bonuses.js';
2
+ import { armiesForChance, armiesToTake, DEFAULT_DEFENSIVE_KILL_RATE, DEFAULT_OFFENSIVE_KILL_RATE, fewestAttackersToKill, fewestAttackersToTake, luckFraction, specialUnitStrength, straightKills, } from '../combat.js';
3
+ import { neighborsOf } from '../graph.js';
4
+ import { armyCapIncome, boardIncome, DEFAULT_BASE_INCOME, incomeRules, territoryIncome } from '../player.js';
5
+ import { byNum } from './util.js';
6
+ /** A bonus is uneconomic when its remaining capture cost exceeds this many turns of its value… */
7
+ export const PAYBACK_TURNS = 10;
8
+ /**
9
+ * #275 (pattern 2): with the guard off, the share of a breach's income (`breachBehind`, src/analysis/breach.ts) a
10
+ * border's protected value counts. Half: the bonuses behind fall only if the breaching stack walks on
11
+ * next turn, and a border may still be retaken or the stack turned elsewhere.
12
+ */
13
+ export const BREACH_WEIGHT = 0.5;
14
+ /** #201: the shortest payback horizon once the game is decided. */
15
+ export const DECIDED_PAYBACK_MIN = 3;
16
+ /** …or when one remaining territory alone costs more than this many times its value (a wasteland). */
17
+ export const WASTELAND_FACTOR = 5;
18
+ /**
19
+ * Plain expansion (pass 3, #125): a capture that adds no income and is in no bonus worth
20
+ * completing is made only when it loses at most this many armies (a 2- or 3-army neutral at the
21
+ * default rates): a cheap step still widens my reach, a 10-army one throws 7 armies away.
22
+ */
23
+ export const PLAIN_EXPANSION_LOSS = 2;
24
+ /**
25
+ * The fewest armies an order out of a conceded border must carry before the plan spends an Order
26
+ * Priority card on it (#127): a base income's worth (war.app's default MinimumArmyBonus). A
27
+ * 1-army withdrawal from a +0 border is not worth a card.
28
+ */
29
+ export const ORDER_PRIORITY_MIN_ARMIES = DEFAULT_BASE_INCOME;
30
+ /** Floor of the default enemy deploy estimate (a player's base income). */
31
+ export const MIN_ENEMY_DEPLOY = DEFAULT_BASE_INCOME;
32
+ /**
33
+ * Observed turns an opponent track needs before the planner uses its income in place of the
34
+ * single-turn observed figure (S3).
35
+ */
36
+ export const TRACKED_MIN_TURNS = 2;
37
+ /**
38
+ * #235: how much evidence halves the fog prior's lead over an opponent's own figure: the prior keeps
39
+ * PRIOR_EVIDENCE_TURNS / (PRIOR_EVIDENCE_TURNS + observed turns × the visible share of its edge) of
40
+ * the gap. Unmeasured: four observed turns with its whole edge in view meet half-way.
41
+ */
42
+ export const PRIOR_EVIDENCE_TURNS = 4;
43
+ /**
44
+ * #294: an opponent's tracked income was read from less than this share of its frontier
45
+ * ({@link frontierCoverage}, over its income window): it is read as low, and the estimate never
46
+ * falls below the tracked figure × {@link LOW_COVERAGE_FACTOR}. Unmeasured.
47
+ */
48
+ export const LOW_COVERAGE = 0.5;
49
+ /**
50
+ * #294: while coverage is under {@link LOW_COVERAGE}, the estimate is at least the tracked figure ×
51
+ * this (at most what it could earn). Unmeasured: the play session's long fogged games tracked a half
52
+ * to a quarter of the income later seen, so 1.5 is a cautious floor, not a correction.
53
+ */
54
+ export const LOW_COVERAGE_FACTOR = 1.5;
55
+ /** Fog reveals named in the observed-deploy rationale before "and N more". */
56
+ export const MAX_NAMED_REVEALS = 6;
57
+ /**
58
+ * #164: a stack the fog hides (Dense / Heavy fog) moves at most this many turns of its owner's
59
+ * income beyond the guard, however many armies the tracker cannot account for: those are spread
60
+ * over its hidden territories, and its income under fog that shows every owner is exact. A larger
61
+ * bank on one border is possible and the fog cannot show it; the cap is a judgement, said in the
62
+ * warning.
63
+ */
64
+ export const HIDDEN_POOL_INCOMES = 2;
65
+ /** A border is conceded when holding it costs more than this many times the income it protects. */
66
+ export const CONCEDE_FACTOR = 3;
67
+ /** A held border is comfortable once taking it needs more than this many times its threat. */
68
+ export const COMFORT_MARGIN = 1.25;
69
+ /**
70
+ * A held bonus whose threatened borders are short of a sure hold by at most this share of
71
+ * the hold they need (or {@link NEAR_MISS_ARMIES}, whichever is larger) is a near miss:
72
+ * funded with everything available rather than conceded (issue #59).
73
+ */
74
+ export const NEAR_MISS = 0.15;
75
+ /** The near-miss margin is never below this many armies. */
76
+ export const NEAR_MISS_ARMIES = 2;
77
+ /** The most a held bonus's hold `need` may be short and still be a near miss. */
78
+ export function nearMissMargin(need) {
79
+ return Math.max(NEAR_MISS_ARMIES, NEAR_MISS * need);
80
+ }
81
+ /**
82
+ * An opponent next to the fog (it may hold unseen territories) is still pressured — all its
83
+ * visible territories attacked, each sized for its full estimated deploy plus
84
+ * {@link pressureMargin} — when each of those margin-sized captures costs at most this many
85
+ * times a typical expansion capture (the median capture cost of the visible neutrals next to
86
+ * me; issue #60), or is paid outright from idle armies next to it (#120: it then displaces no
87
+ * expansion). All or nothing: one visible territory over it blocks the pressure on all.
88
+ * Not tuned to admit #60: at ~6 its 0-army territory costs 15 with the margin, five 2-army
89
+ * neutrals — "more than the expansion it displaces" (the owner's live calibration) — so it is
90
+ * not attempted; at ~4 it costs 10 and is.
91
+ */
92
+ export const PRESSURE_FACTOR = 4;
93
+ /**
94
+ * A pressure attack is sized for its target's armies + the full estimated deploy + this share
95
+ * of that deploy (at least {@link PRESSURE_MARGIN_ARMIES}): the opponent's income is unseen
96
+ * under fog, and live (#60) an attack sized for exactly its ~6 deploy failed.
97
+ */
98
+ export const PRESSURE_MARGIN = 0.5;
99
+ /** The pressure margin is never below this many armies. */
100
+ export const PRESSURE_MARGIN_ARMIES = 2;
101
+ /** The extra defenders a pressure attack is sized for, over an estimated `deploy`. */
102
+ export function pressureMargin(deploy) {
103
+ return Math.max(PRESSURE_MARGIN_ARMIES, Math.ceil(PRESSURE_MARGIN * deploy));
104
+ }
105
+ /**
106
+ * Ahead in a 1v1 under the game profile (rule 0p): pressure on an opponent next to the fog is
107
+ * allowed when each margin-sized capture costs at most this many typical expansion captures
108
+ * (instead of {@link PRESSURE_FACTOR}) — a lead is pressed, not left to sit.
109
+ */
110
+ export const AHEAD_PRESSURE_FACTOR = 8;
111
+ /**
112
+ * FFA with two or more opponents left (rule 0p): a break against a player that threatens no
113
+ * bonus of mine is skipped when a neutral capture scores at least this share of it per army.
114
+ */
115
+ export const SECOND_FRONT_SIMILAR = 0.5;
116
+ /**
117
+ * #167: rule 0p.2 scales with my army lead — my visible armies over the largest opponent's in view
118
+ * (special units included). Up to this many times, the neutral needs SECOND_FRONT_SIMILAR × the lead
119
+ * (at least 1×) of a break's score to skip it; above it the rule is off: idle stacks beside weak
120
+ * enemy territories are a lever, not a risk, and (adapting) they attack them (the lead strikes).
121
+ */
122
+ export const SECOND_FRONT_LEAD = 3;
123
+ /** Denying +V to the opponent is worth this many times gaining +V yourself (per opponent: divided among them). */
124
+ export const BREAK_WEIGHT = 1.0;
125
+ /** Under `balanced`, at least this share of income goes to expansion/breaking before holds protecting less than it. */
126
+ export const MIN_EXPANSION_SHARE = 0.3;
127
+ /** #167: how many enemy territories the "Not attacking … next to mine" line gives a reason for; the rest are named. */
128
+ export const NOT_ATTACKING_REASONS = 6;
129
+ /**
130
+ * Under `balanced`/`defend` a bonus's score is value / (capture cost + this × the
131
+ * deploys its frontier needs next turn to hold), so a defensible smaller bonus can
132
+ * beat an indefensible big one.
133
+ */
134
+ export const DEFENSE_DISCOUNT = 1;
135
+ /**
136
+ * Every capture pays for the frontier it adds (#71): each border it opens costs this many armies
137
+ * in its score (one it closes saves as much), plus, when the border faces a visible enemy, the
138
+ * deploys it needs next turn to hold. Small, so borders facing only neutrals barely matter.
139
+ */
140
+ export const NEUTRAL_BORDER_COST = 0.25;
141
+ /** Move orders under which the award order carries into the turns (GameFeed's `MoveOrder`). */
142
+ const CYCLIC_ORDERS = new Set(['Cycle', 'NoLuckCycle']);
143
+ /** A cyclic move order (GameFeed's `MoveOrder`): the order reverses every turn. */
144
+ export const isCyclicMoveOrder = (moveOrder) => moveOrder !== undefined && CYCLIC_ORDERS.has(moveOrder);
145
+ /**
146
+ * #293 review: an opponent's free income under Local Deployment on the turn read (`turn`), for
147
+ * {@link ObserveContext.localFree}: its base (never below `floor`) plus a Reinforcement card's armies
148
+ * when the clock says one can be in hand by then (unknown turn: yes, when one is in play). A card
149
+ * play is income it may deploy anywhere.
150
+ */
151
+ export function localFreeOn(base, floor, clock, turn) {
152
+ const card = clock && clock.armies > 0 && (turn === null || turn === undefined || turn >= clock.firstTurn) ? clock.armies : 0;
153
+ return Math.max(floor, base) + card;
154
+ }
155
+ /** #271 review: whether an opponent may have played a Bomb on `turn` (unknown turn: yes, when one is in play). */
156
+ export function bombPossibleOn(settings, turn) {
157
+ return settings.bombFrom !== undefined && (turn === null || turn === undefined || turn >= settings.bombFrom);
158
+ }
159
+ /** #164: GameFeed fog levels that show every territory's owner (No, Light and Dense fog): income is exact. */
160
+ export const OWNERS_SHOWN_FOG = new Set(['NoFog', 'LightFog', 'ModerateFog']);
161
+ /** An opponent with at most this many visible territories has its exits listed (#179). */
162
+ export const FEW_TERRITORIES = 3;
163
+ /** The most turns {@link EliminateEta} looks ahead. */
164
+ export const ETA_HORIZON = 30;
165
+ export const SLOT_NAMES = ['protected', 'early', 'sure', 'filler', 'last'];
166
+ /**
167
+ * The positive bonuses complete over `after` (the holdings after a plan) with at least one
168
+ * member in `conceded`, sorted by id (#109): what the plan's concessions put at risk.
169
+ */
170
+ export function bonusesAtRisk(g, after, conceded) {
171
+ if (!conceded.size)
172
+ return [];
173
+ return g.map.bonuses
174
+ .filter((b) => b.value > 0)
175
+ .map((b) => ({ b, ts: bonusTerritories(g, b.id) }))
176
+ .filter(({ ts }) => ts.length > 0 && ts.every((t) => after.has(t)) && ts.some((t) => conceded.has(t)))
177
+ .sort((x, y) => x.b.id - y.b.id)
178
+ .map(({ b, ts }) => ({
179
+ bonusId: b.id,
180
+ name: b.name,
181
+ value: b.value,
182
+ conceded: ts.filter((t) => conceded.has(t)).sort(byNum),
183
+ }));
184
+ }
185
+ /** A probability as a whole percent, for the rationale. */
186
+ /** The combat model's view of the planner settings. */
187
+ export function combatSettings(settings = {}) {
188
+ return {
189
+ offensiveKillRate: settings.offensiveKillRate ?? DEFAULT_OFFENSIVE_KILL_RATE,
190
+ defensiveKillRate: settings.defensiveKillRate ?? DEFAULT_DEFENSIVE_KILL_RATE,
191
+ luck: luckFraction(settings.luckModifier),
192
+ ...(settings.roundingMode !== undefined ? { rounding: settings.roundingMode } : {}),
193
+ };
194
+ }
195
+ /** A `minWinChance` option clamped to [0.5, 1] (default 1). */
196
+ export function minWinChanceOf(v) {
197
+ if (v === undefined || !Number.isFinite(v))
198
+ return 1;
199
+ return Math.min(1, Math.max(0.5, v));
200
+ }
201
+ /**
202
+ * The win chance an ordinary capture is sized for when `minWinChance` is not given (#126): with
203
+ * luck on, certainty can cost several times a likely win (a 2-army neutral needs 14 armies to be
204
+ * certain at 75% luck, 5 for 95%), so {@link LUCK_WIN_CHANCE}; with no luck certainty is cheap
205
+ * (weighted-random rounding: one army more than straight rounding), so 1.
206
+ */
207
+ export const LUCK_WIN_CHANCE = 0.95;
208
+ /**
209
+ * The most a hold may fall to the attack it is sized against (#126): with luck or weighted-random
210
+ * rounding a stack falls to an attack below its exact `armiesToTake` some of the time, so a hold
211
+ * is judged against the fewest attackers that win more often than this.
212
+ */
213
+ export const HOLD_FALL_CHANCE = 0.05;
214
+ /**
215
+ * Marks around a rationale clause citing a two-step hold (#172): `OPEN <territory> SEP <clause>
216
+ * SEP <fallback> CLOSE`, resolved at the end of the plan (the clause if the hold still applies, the
217
+ * fallback if not).
218
+ */
219
+ export const CITE_OPEN = '\u0001';
220
+ export const CITE_SEP = '\u0002';
221
+ export const CITE_CLOSE = '\u0003';
222
+ export const CITE_RE = /\u0001(\d+)\u0002([^\u0002\u0003]*)\u0002([^\u0003]*)\u0003/g;
223
+ export function defaultMinWinChance(settings = {}) {
224
+ return luckFraction(settings.luckModifier) > 0 ? LUCK_WIN_CHANCE : 1;
225
+ }
226
+ /** Certain sizes by settings and defenders: each is a search over the exact model. */
227
+ const certainMemo = new Map();
228
+ /**
229
+ * Armies to send at a territory held by `defenders`; `null` when it cannot be taken. With
230
+ * `minWinChance` 1 (default) the certain sizing (#126): the fewest armies whose exact
231
+ * {@link winChance} is 1 — every roll and every rounding takes it (`armiesToTake` at 0% luck under
232
+ * straight rounding; one army more under weighted-random rounding; the kills the luck-free share
233
+ * guarantees, {@link guaranteedKills}, with luck). Below 1, the fewest armies whose
234
+ * {@link winChance} reaches it.
235
+ */
236
+ export function captureCost(defenders, settings = {}, minWinChance = 1) {
237
+ const combat = combatSettings(settings);
238
+ if (minWinChance < 1)
239
+ return armiesForChance(defenders, minWinChanceOf(minWinChance), combat);
240
+ if (!combat.luck && combat.rounding !== 'WeightedRandom')
241
+ return armiesToTake(defenders, combat);
242
+ const key = `${combat.offensiveKillRate}|${combat.defensiveKillRate}|${combat.luck}|${combat.rounding}|${defenders}`;
243
+ if (!certainMemo.has(key)) {
244
+ if (certainMemo.size > 50_000)
245
+ certainMemo.clear();
246
+ certainMemo.set(key, armiesForChance(defenders, 1, combat));
247
+ }
248
+ return certainMemo.get(key);
249
+ }
250
+ /**
251
+ * How many attacked territories fall for sure when their owner answers with its best
252
+ * response: one deploy budget `deploy`, split over its territories to save as many as it
253
+ * can. `saveCosts[i]` is the deploys target i needs to survive its attack (the most
254
+ * defenders the attack takes, minus its armies, plus one; 0 when it survives unreinforced).
255
+ * Saving the cheapest first is optimal: any j saved targets cost at least the j cheapest
256
+ * save costs, so j can be saved exactly when those fit the budget.
257
+ */
258
+ export function guaranteedFalls(saveCosts, deploy) {
259
+ let left = deploy;
260
+ let saved = 0;
261
+ for (const c of [...saveCosts].sort((a, b) => a - b)) {
262
+ if (c > left)
263
+ break;
264
+ left -= c;
265
+ saved++;
266
+ }
267
+ return saveCosts.length - saved;
268
+ }
269
+ /**
270
+ * {@link guaranteedFalls} when not all of the owner's deploy can reach every target (#179: Local
271
+ * Deployment pays a bonus only into its own territories): `reaches[i]` is the most it can deploy on
272
+ * target i. A target whose save costs more than that falls for sure; the rest share the one budget
273
+ * `deploy`, cheapest first. An upper bound on what it saves (its pools may not cover the cheapest
274
+ * set together), so the falls stay sure.
275
+ */
276
+ export function guaranteedFallsReaching(saveCosts, reaches, deploy) {
277
+ const savable = saveCosts.filter((c, i) => c <= (reaches[i] ?? deploy));
278
+ return saveCosts.length - savable.length + guaranteedFalls(savable, deploy);
279
+ }
280
+ /**
281
+ * Fog levels that hide a territory's armies. The live board names war.app's StandingFogLevel
282
+ * (1 You, 2 Visible, 3 OwnerOnly, 4 Fogged; the client refuses a deploy on 3 or 4 as "fogged");
283
+ * a GameFeed standing may spell it as a word or as the raw number (every GameFeed scalar is a
284
+ * string).
285
+ */
286
+ const HIDDEN_FOG = /fog|owneronly|^\s*[34]\s*$/i;
287
+ /** Fog levels that hide a territory's owner too (StandingFogLevel 4, Fogged). */
288
+ const OWNER_HIDDEN_FOG = /fog|^\s*4\s*$/i;
289
+ /**
290
+ * `t` when a board shows both its owner (a player or a neutral) and its armies, else
291
+ * `undefined`: a fogged territory (owner unknown, armies `null`), or one whose fog level hides
292
+ * its armies even if a placeholder owner or count came with it (issue #69).
293
+ *
294
+ * One exception: an entry named `"OwnerOnly"` that still carries a count is fog level 2
295
+ * (Visible) from a board cache written before #69, which misnamed it; every current board nulls
296
+ * an owner-only territory's armies, and the old cache left level 3 unnamed (`"3"`).
297
+ */
298
+ export function visibleState(t) {
299
+ if (!t || t.armies === null)
300
+ return undefined;
301
+ if (t.owner.kind !== 'player' && t.owner.kind !== 'neutral')
302
+ return undefined;
303
+ if (t.fogLevel !== undefined && HIDDEN_FOG.test(t.fogLevel) && !/^\s*owneronly\s*$/i.test(t.fogLevel))
304
+ return undefined;
305
+ return t;
306
+ }
307
+ /**
308
+ * `t` when a board shows its owner (a player or a neutral), whatever its armies: visible, or
309
+ * owner-only (light fog); `undefined` when fogged, even under a placeholder owner.
310
+ */
311
+ export function ownerShown(t) {
312
+ if (!t || (t.owner.kind !== 'player' && t.owner.kind !== 'neutral'))
313
+ return undefined;
314
+ if (t.fogLevel !== undefined && OWNER_HIDDEN_FOG.test(t.fogLevel))
315
+ return undefined;
316
+ return t;
317
+ }
318
+ /** #294: {@link FrontierCoverage} of one opponent on one observed turn. Pure. */
319
+ export function frontierCoverage(g, board, previous, playerId) {
320
+ const now = new Map(board.territories.map((t) => [t.territoryId, t]));
321
+ const before = new Map(previous.territories.map((t) => [t.territoryId, t]));
322
+ const its = (id) => {
323
+ const st = ownerShown(now.get(id));
324
+ return st?.owner.kind === 'player' && st.owner.playerId === playerId;
325
+ };
326
+ const shownIts = [...g.territoryById.keys()].filter(its);
327
+ const frontier = new Set();
328
+ let inView = 0;
329
+ for (const t of shownIts) {
330
+ const ns = neighborsOf(g, t);
331
+ if (ns.every(its))
332
+ continue;
333
+ frontier.add(t);
334
+ const a = visibleState(now.get(t));
335
+ const b = visibleState(before.get(t));
336
+ if (a && b)
337
+ inView++;
338
+ for (const n of ns)
339
+ if (!ownerShown(now.get(n)))
340
+ frontier.add(n);
341
+ }
342
+ let hiddenBonuses = 0;
343
+ for (const bonus of g.map.bonuses) {
344
+ const ts = bonusTerritories(g, bonus.id);
345
+ if (bonus.value <= 0 || !ts.length)
346
+ continue;
347
+ const taken = ts.some((t) => {
348
+ const st = ownerShown(now.get(t));
349
+ return st !== undefined && !(st.owner.kind === 'player' && st.owner.playerId === playerId);
350
+ });
351
+ if (!taken && ts.some((t) => !ownerShown(now.get(t))))
352
+ hiddenBonuses++;
353
+ }
354
+ const share = frontier.size ? inView / frontier.size : shownIts.length ? 1 : 0;
355
+ return { inView, frontier: frontier.size, share, hiddenBonuses };
356
+ }
357
+ /** #294: {@link TrackCoverage} over `turns` (those carrying a coverage); `null` when none does. */
358
+ export function trackCoverage(turns) {
359
+ const withIt = turns.filter((x) => x.coverage !== undefined);
360
+ if (!withIt.length)
361
+ return null;
362
+ const inView = withIt.reduce((n, x) => n + x.coverage.inView, 0);
363
+ const frontier = withIt.reduce((n, x) => n + x.coverage.frontier, 0);
364
+ const range = (xs) => ({ min: Math.min(...xs), max: Math.max(...xs) });
365
+ return {
366
+ turns: withIt.map((x) => x.from),
367
+ inView: range(withIt.map((x) => x.coverage.inView)),
368
+ frontier: range(withIt.map((x) => x.coverage.frontier)),
369
+ share: frontier ? inView / frontier : withIt.reduce((n, x) => n + x.coverage.share, 0) / withIt.length,
370
+ hiddenBonuses: withIt.at(-1).coverage.hiddenBonuses,
371
+ };
372
+ }
373
+ /**
374
+ * #294: "1 of ~4 frontier territories (25%)" (a range, "1–2 of ~4–5", when the turns differ; the share
375
+ * is Σ read ÷ Σ frontier), and ", N bonus(es) it could hold out of view" when any: the words beside a
376
+ * tracked figure.
377
+ */
378
+ export function coverageText(c) {
379
+ const b = c.hiddenBonuses;
380
+ const range = (r) => (r.min === r.max ? `${r.min}` : `${r.min}–${r.max}`);
381
+ return `${range(c.inView)} of ~${range(c.frontier)} frontier territories (${Math.round(c.share * 100)}%)${b ? `, ${b} ${b === 1 ? 'bonus' : 'bonuses'} it could hold out of view` : ''}`;
382
+ }
383
+ /**
384
+ * #226: what my failed attacks on `playerId` killed, by target, on the turn `before` → `after`: each
385
+ * move of mine onto a territory it holds on both boards (shown with armies both times), from a
386
+ * source mine on both (one that fell may have been taken before my attack ran), kills
387
+ * round(armies × the offensive kill rate) — a straight-rounded expectation, which luck can move.
388
+ * The board reads that loss as a shrink. The opponent tracker's `measureOrders` counts the same.
389
+ */
390
+ export function failedAttackKills(g, before, after, me, playerId, orders, rates = {}) {
391
+ const offensive = rates.offensiveKillRate ?? DEFAULT_OFFENSIVE_KILL_RATE;
392
+ const out = new Map();
393
+ for (const m of failedAttackMoves(g, before, after, me, playerId, orders))
394
+ out.set(m.to, (out.get(m.to) ?? 0) + straightKills(Math.max(0, m.armies), offensive));
395
+ return out;
396
+ }
397
+ /**
398
+ * The moves {@link failedAttackKills} counts: each move of mine onto a territory `playerId` holds on
399
+ * both boards (shown with armies both times), from a source mine on both. #240 review: the armies
400
+ * {@link repulsedAttacks} reports are these moves' too, so they match the kills.
401
+ */
402
+ function failedAttackMoves(g, before, after, me, playerId, orders) {
403
+ const was = new Map(before.territories.map((t) => [t.territoryId, t]));
404
+ const now = new Map(after.territories.map((t) => [t.territoryId, t]));
405
+ const owns = (t, p) => {
406
+ const v = visibleState(t);
407
+ return v?.owner.kind === 'player' && v.owner.playerId === p;
408
+ };
409
+ return orders.moves.filter((m) => g.territoryById.has(m.to) &&
410
+ owns(was.get(m.from), me) &&
411
+ owns(now.get(m.from), me) &&
412
+ owns(was.get(m.to), playerId) &&
413
+ owns(now.get(m.to), playerId));
414
+ }
415
+ /**
416
+ * #271 review: the territories an order of mine touched that `orders.moves` does not carry, so what
417
+ * they held after my orders is not known: a move order in `sent` beyond the plain ones `moves` keeps on
418
+ * the same pair (#165 leaves out Transfer Only, Attack Only and percentage orders), both its ends; and
419
+ * each territory a card play names (an Airlift's `from` and `to`, a card's `target`).
420
+ */
421
+ function ordersNotInMoves(orders) {
422
+ const out = new Set();
423
+ const key = (from, to) => `${from}>${to}`;
424
+ const carried = new Map();
425
+ for (const m of orders.moves)
426
+ carried.set(key(m.from, m.to), (carried.get(key(m.from, m.to)) ?? 0) + 1);
427
+ for (const o of orders.sent ?? []) {
428
+ const left = carried.get(key(o.from, o.to)) ?? 0;
429
+ if (left > 0)
430
+ carried.set(key(o.from, o.to), left - 1);
431
+ else
432
+ out.add(o.from).add(o.to);
433
+ }
434
+ for (const c of orders.cards ?? [])
435
+ for (const id of [c.from, c.to, c.target])
436
+ if (id !== undefined)
437
+ out.add(id);
438
+ return out;
439
+ }
440
+ /**
441
+ * My holds (mine, with armies, on both boards) that lost armies my orders do not explain, by id: the
442
+ * defenders were my armies there plus what I deployed there, less what I sent out; what the later
443
+ * board shows less (what I moved in from a territory mine on the earlier board counted on top) is what
444
+ * an attack on it that failed killed. A hold I attacked out of and failed is skipped: the survivors of
445
+ * my own attack came back to it, so its loss is not known. So is a hold an order `moves` does not carry
446
+ * touched (#271 review, {@link ordersNotInMoves}: a Transfer Only, Attack Only or percentage order, a
447
+ * card play), and a transfer from a source one touched is not surely whole. The opponent tracker's attacks on my holds
448
+ * and the #271 bound ({@link repelledFloor}) both read these.
449
+ */
450
+ export function holdLosses(g, before, after, me, orders, guard = 1) {
451
+ const was = new Map(before.territories.map((t) => [t.territoryId, t]));
452
+ const now = new Map(after.territories.map((t) => [t.territoryId, t]));
453
+ const owns = (t, p) => t?.owner.kind === 'player' && t.owner.playerId === p;
454
+ const held = (id) => owns(visibleState(was.get(id)), me) && owns(visibleState(now.get(id)), me);
455
+ const deployed = new Map();
456
+ for (const d of orders.deploys)
457
+ deployed.set(d.territoryId, (deployed.get(d.territoryId) ?? 0) + Math.max(0, d.armies));
458
+ const sent = new Map();
459
+ const came = new Map();
460
+ /** The sources of what `came`, by the hold they sent to. */
461
+ const cameFrom = new Map();
462
+ const failedFrom = new Set();
463
+ const untracked = ordersNotInMoves(orders);
464
+ for (const m of orders.moves) {
465
+ const armies = Math.max(0, m.armies);
466
+ sent.set(m.from, (sent.get(m.from) ?? 0) + armies);
467
+ if (held(m.to) && owns(visibleState(was.get(m.from)), me)) {
468
+ came.set(m.to, (came.get(m.to) ?? 0) + armies);
469
+ if (armies > 0)
470
+ cameFrom.set(m.to, (cameFrom.get(m.to) ?? new Set()).add(m.from));
471
+ }
472
+ if (!owns(visibleState(was.get(m.to)), me) && !owns(visibleState(now.get(m.to)), me))
473
+ failedFrom.add(m.from);
474
+ }
475
+ /**
476
+ * #271 review: a source that surely sent all ordered from it ({@link HoldLoss.inflowSure}): mine on
477
+ * both boards, no failed attack of mine out of it, nothing moved into it (when that arrived is not
478
+ * known), and it shows exactly what my orders leave there. An order sends what is left down to the
479
+ * guard, so a loss before it shows only when my orders leave more than the guard there; else only
480
+ * when no other player (nor the fog) was beside it to attack or bomb it.
481
+ */
482
+ const sentWhole = (id) => {
483
+ if (!held(id) || failedFrom.has(id) || came.has(id) || untracked.has(id))
484
+ return false;
485
+ const left = visibleState(was.get(id)).armies + (deployed.get(id) ?? 0) - (sent.get(id) ?? 0);
486
+ if (left < 0 || visibleState(now.get(id)).armies !== left)
487
+ return false;
488
+ if (left > guard)
489
+ return true;
490
+ return neighborsOf(g, id).every((n) => {
491
+ const o = ownerShown(was.get(n))?.owner;
492
+ return o !== undefined && (o.kind === 'neutral' || (o.kind === 'player' && o.playerId === me));
493
+ });
494
+ };
495
+ const out = [];
496
+ for (const id of [...new Set(after.territories.map((t) => t.territoryId))].sort(byNum)) {
497
+ if (!g.territoryById.has(id) || !held(id) || failedFrom.has(id) || untracked.has(id))
498
+ continue;
499
+ const standing = visibleState(was.get(id)).armies + (deployed.get(id) ?? 0);
500
+ const defenders = Math.max(0, standing - (sent.get(id) ?? 0));
501
+ const loss = defenders + (came.get(id) ?? 0) - visibleState(now.get(id)).armies;
502
+ const inflowSure = [...(cameFrom.get(id) ?? [])].every(sentWhole);
503
+ if (loss > 0)
504
+ out.push({ territoryId: id, defenders, loss, standing, inflowSure });
505
+ }
506
+ return out;
507
+ }
508
+ /**
509
+ * #271: a failed attack on a hold of mine is a measurement, the mirror of #226. My loss there
510
+ * ({@link holdLosses}: what my orders do not explain) needed at least {@link fewestAttackersToKill}
511
+ * attackers (every attacker killing its most, luck included), and without Multi-Attack each army
512
+ * moves once, so they all came from its territories beside the hold at the start of the turn: their
513
+ * armies then (less the guard) plus what it deployed there. A hold counts only when every neighbour
514
+ * showed its owner on the earlier board, every territory of `playerId` beside it showed its armies,
515
+ * and `playerId` is the only other player beside it. Over every such hold the bound is the larger of
516
+ * the best single hold and all of them together (the attackers summed against the stacks beside any
517
+ * of them, each counted once).
518
+ * #271 review: a hold reads only when what I moved in surely arrived whole ({@link HoldLoss.inflowSure}),
519
+ * so the bound uses the least my orders can have brought. On a turn an opponent may have played a Bomb
520
+ * card (`bomb`, {@link bombPossibleOn}), which halves a territory of mine beside the bomber after the
521
+ * deploys and reads as an attack, the most it could take (half the stack before any move, rounded up)
522
+ * is left out of the loss first. Orders cached without `sent` or `cards` (before they were kept) bound
523
+ * nothing: an order `moves` leaves out, or a card play, may have moved armies out of a hold.
524
+ */
525
+ export function repelledFloor(g, before, after, me, playerId, orders, settings = {}, guard = (settings.oneArmyStandsGuard ?? true) ? 1 : 0, bomb = false) {
526
+ const none = { territories: [], attackers: 0, supply: 0, floor: 0 };
527
+ // #271 review: orders cached before `sent` and `cards` were kept may have left out an order or a card
528
+ // play that moved armies out of a hold: what ran is unknown, so they bound nothing.
529
+ if (settings.multiAttack || !orders.sent || !orders.cards)
530
+ return none;
531
+ const was = new Map(before.territories.map((t) => [t.territoryId, t]));
532
+ const sendable = (id) => {
533
+ const st = visibleState(was.get(id));
534
+ return Math.max(0, st.armies - guard) + specialUnitStrength(st.specialUnits?.filter((u) => u.playerId === playerId));
535
+ };
536
+ const holds = [];
537
+ for (const h of holdLosses(g, before, after, me, orders, guard)) {
538
+ if (!h.inflowSure)
539
+ continue;
540
+ const loss = h.loss - (bomb ? Math.ceil(h.standing / 2) : 0);
541
+ if (loss <= 0)
542
+ continue;
543
+ const ns = neighborsOf(g, h.territoryId);
544
+ if (ns.some((n) => !ownerShown(was.get(n))))
545
+ continue;
546
+ const others = new Set();
547
+ const beside = [];
548
+ let hidden = false;
549
+ for (const n of ns) {
550
+ const o = ownerShown(was.get(n)).owner;
551
+ if (o.kind !== 'player' || o.playerId === me)
552
+ continue;
553
+ others.add(o.playerId);
554
+ if (o.playerId === playerId) {
555
+ if (!visibleState(was.get(n)))
556
+ hidden = true;
557
+ beside.push(n);
558
+ }
559
+ }
560
+ if (hidden || others.size !== 1 || !others.has(playerId))
561
+ continue;
562
+ const attackers = fewestAttackersToKill(loss, settings, settings.luckModifier, settings.roundingMode);
563
+ if (attackers === null)
564
+ continue;
565
+ holds.push({ id: h.territoryId, attackers, beside });
566
+ }
567
+ if (!holds.length)
568
+ return none;
569
+ const supplyOf = (ids) => [...new Set(ids)].reduce((n, id) => n + sendable(id), 0);
570
+ let best = { ...none, territories: holds.map((h) => h.id) };
571
+ const all = {
572
+ attackers: holds.reduce((n, h) => n + h.attackers, 0),
573
+ supply: supplyOf(holds.flatMap((h) => h.beside)),
574
+ };
575
+ best = { ...best, ...all, floor: Math.max(0, all.attackers - all.supply) };
576
+ for (const h of holds) {
577
+ const supply = supplyOf(h.beside);
578
+ if (h.attackers - supply > best.floor)
579
+ best = { ...best, attackers: h.attackers, supply, floor: h.attackers - supply };
580
+ }
581
+ return best;
582
+ }
583
+ /** #240: the turns {@link repulsedAttacks} looks back over, ending on the board being planned. */
584
+ export const REPULSE_WINDOW = 3;
585
+ /** #240: failed, reinforced attacks on one territory within the window that make it repulsed. */
586
+ export const REPULSE_MIN = 2;
587
+ /**
588
+ * #240: repeated failure is evidence. Over my board history (`boards`, the newest being the board
589
+ * being planned; consecutive turns only, each with my cached orders — `TurnBoard.orders`, what
590
+ * warapp_submit_turn sent), a failed attack of mine on a territory — its owner the same player on
591
+ * both boards, my source mine on both ({@link failedAttackKills}) — whose owner reinforced it: its
592
+ * armies after plus what my attack killed exceed its armies before (after = before + deploys and
593
+ * transfers in − kills). A territory with such an attack on {@link REPULSE_MIN} or more of the last
594
+ * {@link REPULSE_WINDOW} turns, still that player's on the newest board, is reported, by id. Kill
595
+ * counts are straight-rounded expectations: luck can move them. Pure; unknown orders give nothing.
596
+ */
597
+ export function repulsedAttacks(g, boards, me, rates = {}) {
598
+ const sorted = [...boards].sort((a, b) => a.turn - b.turn);
599
+ const newest = sorted[sorted.length - 1];
600
+ if (!newest)
601
+ return [];
602
+ // #240 review: kept per territory and owner, so failed attacks on a territory under an earlier
603
+ // owner never hide those under its newest one (the filter below keeps the newest owner's only).
604
+ const found = new Map();
605
+ for (let i = 0; i + 1 < sorted.length; i++) {
606
+ const was = sorted[i];
607
+ const now = sorted[i + 1];
608
+ if (!was.orders || now.turn !== was.turn + 1 || was.turn < newest.turn - REPULSE_WINDOW)
609
+ continue;
610
+ const orders = was.orders;
611
+ const before = new Map(was.board.territories.map((t) => [t.territoryId, t]));
612
+ const after = new Map(now.board.territories.map((t) => [t.territoryId, t]));
613
+ const owners = new Set();
614
+ for (const m of orders.moves) {
615
+ const o = visibleState(before.get(m.to))?.owner;
616
+ if (o?.kind === 'player' && o.playerId !== me)
617
+ owners.add(o.playerId);
618
+ }
619
+ for (const p of [...owners].sort(byNum)) {
620
+ for (const [t, kills] of [...failedAttackKills(g, was.board, now.board, me, p, orders, rates)].sort(([a], [b]) => a - b)) {
621
+ const b = visibleState(before.get(t)).armies;
622
+ const a = visibleState(after.get(t)).armies;
623
+ if (kills <= 0 || a + kills <= b)
624
+ continue;
625
+ const armies = failedAttackMoves(g, was.board, now.board, me, p, orders)
626
+ .filter((m) => m.to === t)
627
+ .reduce((n, m) => n + Math.max(0, m.armies), 0);
628
+ const attack = { turn: was.turn, armies, before: b, after: a, kills };
629
+ const key = `${t}:${p}`;
630
+ const entry = found.get(key);
631
+ if (!entry)
632
+ found.set(key, { territoryId: t, playerId: p, attacks: [attack] });
633
+ else
634
+ entry.attacks.push(attack);
635
+ }
636
+ }
637
+ }
638
+ const latest = new Map(newest.board.territories.map((t) => [t.territoryId, t]));
639
+ return [...found.values()]
640
+ .filter((r) => {
641
+ const o = visibleState(latest.get(r.territoryId))?.owner;
642
+ return r.attacks.length >= REPULSE_MIN && o?.kind === 'player' && o.playerId === r.playerId;
643
+ })
644
+ .sort((a, b) => a.territoryId - b.territoryId);
645
+ }
646
+ /**
647
+ * One opponent's deploy last turn as seen across two boards (issues #57, #69): the *net*
648
+ * change of its visible armies plus what it visibly lost attacking, floored at 0. Only
649
+ * territories visible on both boards count ({@link visibleState}): one hidden last time
650
+ * (fogged, or under a fog level that hid its armies) only came into view, so it is a fog
651
+ * reveal whoever holds it now — never growth, never a capture.
652
+ * - under it both times: armies now − armies then, shrinks included — a transfer between
653
+ * its own territories nets to zero, so it is never read as deploy;
654
+ * - taken from another visible owner (another player, me included, or a visible neutral): what
655
+ * the capture cost it — the attackers the previous defenders killed at the game's defensive
656
+ * kill rate (`straightKills`, as in `armiesToTake`); taken from me (given `context.me`), the
657
+ * defenders are the guard I may have left, not my stack last turn (#123, `emptied`: I may have
658
+ * attacked out of it) — plus the armies now on it up to what its territories next to it, shown
659
+ * on both boards, visibly sent away (their total shrink, each army claimed by one capture only):
660
+ * those moved in from a visible source, whose shrink they cancel, so source shrink + destination
661
+ * gain nets to the attrition (issue #86). An unchanged visible neighbour sent nothing, so it
662
+ * explains nothing. The rest, when a neighbour was hidden on either board, is ambiguous (#123):
663
+ * a deploy on a visible source that shrank into it (`reinforced`), or a move out of the fog —
664
+ * never income (`fromFog`), still a threat to the borders next to it. With every neighbour in
665
+ * view it can only be a deploy on the source.
666
+ * - growth on its territory next to a hidden one is ambiguous the same way (`grewFromFog`).
667
+ * Ambiguous armies count as deploy while the turn's total stays within {@link ambiguousBound}
668
+ * (twice `context.expected`, never past `context.most`); the rest are moves. Without `expected`,
669
+ * growth is all deploy and a capture's surplus counts up to `most` (none without it, #86).
670
+ * `low` and `high` read every ambiguous army one way or the other (fog moves and the guard, or
671
+ * deploys and my stack standing there).
672
+ * Not counted: armies it lost on a territory it attacked but did not take. The defender's
673
+ * count there also moves with the defender's own deploys and transfers (mine included —
674
+ * this board says nothing about my orders), so the loss cannot be read off it; leaving it
675
+ * out keeps the figure a lower bound (the failed attack's losses still shrink its source). The
676
+ * opponent tracker adds it back when my orders that turn are known (#119, `measureOrders`).
677
+ * Given those orders here (`context.myOrders`, #226), the defenders my failed attack killed on a
678
+ * territory that stayed its count back into its growth there (`attacked`, `attackKills`): after =
679
+ * before + deploy + transfers in − kills, so deploy ≥ after + kills − before — beside the fog an
680
+ * ambiguous growth like any other, read as deploy up to the turn's bound. #271: given those orders,
681
+ * a failed attack on a hold of mine bounds the deploy from below ({@link repelledFloor}: `deploy`,
682
+ * `low` and `high` never below it). A capture also claims, after the visible sources, what its stacks
683
+ * in view last turn and hidden now could have sent (`arrivals`: no figure counts them but `high`); a
684
+ * capture of a neutral beside the fog that no visible source sent into reads the attackers it needed
685
+ * beyond its cost ({@link fewestAttackersToTake}) as ambiguous, deploy up to the bound
686
+ * (`unseenAttackers`; the tracker reads a pattern of them as income), the rest a move out of the fog.
687
+ * One turn only, not smoothed (the tracker reads a history). Transfers in from (or out to) the
688
+ * fog still bias it — income in the fog is unseen anyway.
689
+ */
690
+ export function observeDeploy(g, board, previous, playerId, rates = {}, context = {}) {
691
+ const { signed: _signed, ...o } = observeSigned(g, board, previous, playerId, rates, context);
692
+ return o;
693
+ }
694
+ /**
695
+ * {@link observeDeploy} with its total before the floor at 0 (`signed`): the opponent tracker
696
+ * adds what my own orders measure (#119) to it before flooring.
697
+ */
698
+ export function observeSigned(g, board, previous, playerId, rates = {}, context = {}) {
699
+ const before = new Map(previous.territories.map((t) => [t.territoryId, t]));
700
+ let total = 0;
701
+ /** What `low` and `high` differ from `total` by. */
702
+ let lowExtra = 0;
703
+ let highExtra = 0;
704
+ const counted = [];
705
+ const captured = [];
706
+ const fromFog = [];
707
+ let fogArmies = 0;
708
+ const reveals = [];
709
+ const reinforced = [];
710
+ const emptied = [];
711
+ let emptiedHigh = 0;
712
+ /**
713
+ * The ambiguous armies (#123): growth on its held territories next to a hidden one (a stack
714
+ * may have walked in) and a capture's surplus over what a visible source that shrank into it
715
+ * sent (deploy-then-capture, or a stack out of the fog joined). Read after the loop against
716
+ * one bound, the same for both ({@link ambiguousBound}).
717
+ */
718
+ const ambiguous = [];
719
+ const now = new Map(board.territories.map((t) => [t.territoryId, t]));
720
+ const defensive = rates.defensiveKillRate ?? DEFAULT_DEFENSIVE_KILL_RATE;
721
+ const guard = Math.max(0, context.guard ?? 1);
722
+ // #226: my failed attacks' kills, by target: they count back into its growth there.
723
+ const kills = context.me !== undefined && context.myOrders
724
+ ? failedAttackKills(g, previous, board, context.me, playerId, context.myOrders, rates)
725
+ : new Map();
726
+ const killsAt = (id) => kills.get(id) ?? 0;
727
+ /** Held by the observed player (`playerId`, not me) and shown with armies on both boards. */
728
+ const heldBothTimes = (id) => {
729
+ const a = visibleState(now.get(id));
730
+ const b = visibleState(before.get(id));
731
+ return a?.owner.kind === 'player' && a.owner.playerId === playerId && b?.owner.kind === 'player' && b.owner.playerId === playerId;
732
+ };
733
+ /**
734
+ * What each of its territories shown with armies on both boards visibly sent away (its
735
+ * shrink): the most a capture next to it can have received from it. A capture draws on it
736
+ * (ascending ids), so two captures never both claim the same armies. What my failed attack killed
737
+ * there (#226: these are exactly {@link failedAttackKills}' targets) is a loss, not armies sent
738
+ * away, so it is taken out of the shrink.
739
+ */
740
+ const shrinkLeft = new Map();
741
+ for (const t of board.territories)
742
+ if (g.territoryById.has(t.territoryId) && heldBothTimes(t.territoryId))
743
+ shrinkLeft.set(t.territoryId, Math.max(0, visibleState(before.get(t.territoryId)).armies - t.armies - killsAt(t.territoryId)));
744
+ /** Not shown with armies on both boards: armies could have left it unseen. */
745
+ const hidden = (id) => !visibleState(now.get(id)) || !visibleState(before.get(id));
746
+ // #294: each grown stack's growth split, against its own copy of the shrinks (captures claim theirs below).
747
+ // The stacks with no hidden neighbour claim first (what they leave can only be deploy, so a shrink
748
+ // taken by a stack beside the fog would turn a move into a false "can only be deploy"), then those
749
+ // beside the fog; each in id order, and reported in id order.
750
+ const stacks = [];
751
+ const shrinkForSplit = new Map(shrinkLeft);
752
+ const grown = [...shrinkLeft.keys()]
753
+ .sort(byNum)
754
+ .map((id) => ({
755
+ id,
756
+ growth: visibleState(now.get(id)).armies - visibleState(before.get(id)).armies + killsAt(id),
757
+ beside: neighborsOf(g, id).some(hidden),
758
+ }))
759
+ .filter((x) => x.growth > 0);
760
+ for (const { id, growth, beside } of [...grown.filter((x) => !x.beside), ...grown.filter((x) => x.beside)]) {
761
+ let left = growth;
762
+ const moved = [];
763
+ for (const n of [...neighborsOf(g, id)].sort(byNum)) {
764
+ const can = shrinkForSplit.get(n);
765
+ if (!can || !left)
766
+ continue;
767
+ const take = Math.min(can, left);
768
+ shrinkForSplit.set(n, can - take);
769
+ left -= take;
770
+ moved.push({ from: n, armies: take });
771
+ }
772
+ stacks.push({ territoryId: id, growth, moved, fog: beside ? left : 0, deploy: beside ? 0 : left });
773
+ }
774
+ stacks.sort((a, b) => a.territoryId - b.territoryId);
775
+ /**
776
+ * #271 (3): its territories shown with armies on the earlier board and hidden on the later one: what
777
+ * each could have sent (its armies less the guard), the most a capture beside it can have received
778
+ * from it. Claimed after `shrinkLeft`, in ascending ids, each army once.
779
+ * #271 review, a known under-read: a stack hidden now is claimed whether or not it emptied, and it is
780
+ * usually hidden because the capture took my territory and my sight of it with it. So a real
781
+ * deploy-then-capture beside a source in view both times and such a stack reads its surplus as an
782
+ * arrival (counted only in `high`), not deploy. Accepted: a merge read as deploy once read +45.
783
+ */
784
+ const hiddenLeft = new Map();
785
+ for (const t of previous.territories) {
786
+ const b = visibleState(t);
787
+ if (!g.territoryById.has(t.territoryId) || b?.owner.kind !== 'player' || b.owner.playerId !== playerId)
788
+ continue;
789
+ if (!visibleState(now.get(t.territoryId)))
790
+ hiddenLeft.set(t.territoryId, Math.max(0, b.armies - guard));
791
+ }
792
+ let arrivals = 0;
793
+ const unseenAttackers = [];
794
+ let unseenAttackerArmies = 0;
795
+ for (const t of [...board.territories].sort((a, b) => a.territoryId - b.territoryId)) {
796
+ if (!g.territoryById.has(t.territoryId) || !visibleState(t))
797
+ continue;
798
+ if (t.owner.kind !== 'player' || t.owner.playerId !== playerId)
799
+ continue;
800
+ const was = visibleState(before.get(t.territoryId));
801
+ if (!was) {
802
+ reveals.push(t.territoryId);
803
+ continue;
804
+ }
805
+ counted.push(t.territoryId);
806
+ const ns = [...neighborsOf(g, t.territoryId)].sort((a, b) => a - b);
807
+ if (was.owner.kind === 'player' && was.owner.playerId === playerId) {
808
+ // #226: what my failed attack killed there stood there too: defenders after = before + deploy
809
+ // + transfers in − kills.
810
+ const growth = t.armies - was.armies + killsAt(t.territoryId);
811
+ if (growth > 0 && ns.some(hidden))
812
+ ambiguous.push({ id: t.territoryId, armies: growth, kind: 'growth' });
813
+ else
814
+ total += growth;
815
+ }
816
+ else {
817
+ captured.push(t.territoryId);
818
+ // What the capture cost it, always. Taken from me (#123), the defenders were what I left
819
+ // there, which this board cannot tell (I may have attacked out of it): priced at the guard,
820
+ // my stack last turn the high reading.
821
+ if (context.me !== undefined && was.owner.kind === 'player' && was.owner.playerId === context.me) {
822
+ const least = straightKills(Math.min(was.armies, guard), defensive);
823
+ total += least;
824
+ highExtra += straightKills(was.armies, defensive) - least;
825
+ emptiedHigh += straightKills(was.armies, defensive) - least;
826
+ emptied.push(t.territoryId);
827
+ }
828
+ else
829
+ total += straightKills(was.armies, defensive);
830
+ // The armies standing there only as far as a visible source's shrink accounts for them
831
+ // (it cancels them). Beyond that, with a neighbour that was hidden on either board: when a
832
+ // visible source did shrink into it, the attack came from that stack and the rest was
833
+ // deployed on it first (deploy-then-capture, #123); when none did, the rest arrived from
834
+ // the fog — a move, not income (#86). With no hidden neighbour, the rest can only be a
835
+ // deploy on a visible source before it attacked.
836
+ let arrived = t.armies;
837
+ let claimed = 0;
838
+ for (const n of ns) {
839
+ const left = shrinkLeft.get(n);
840
+ if (!left || !arrived)
841
+ continue;
842
+ const take = Math.min(left, arrived);
843
+ shrinkLeft.set(n, left - take);
844
+ arrived -= take;
845
+ claimed += take;
846
+ total += take;
847
+ }
848
+ // #271 (3): its stacks in view last turn beside it, hidden now, may have moved in: arrivals.
849
+ let came = 0;
850
+ for (const n of ns) {
851
+ const left = hiddenLeft.get(n);
852
+ if (!left || !arrived)
853
+ continue;
854
+ const take = Math.min(left, arrived);
855
+ hiddenLeft.set(n, left - take);
856
+ arrived -= take;
857
+ came += take;
858
+ }
859
+ arrivals += came;
860
+ // Had its source stayed put (hidden now, it may have), they were deployed: the high reading.
861
+ highExtra += came;
862
+ if (arrived > 0 && ns.some(hidden)) {
863
+ // #271 (2): a neutral in view needed attackers; what stands there beyond what its stacks in
864
+ // view sent, up to what that need leaves standing, came from out of sight.
865
+ let unseen = 0;
866
+ if (was.owner.kind === 'neutral') {
867
+ const need = fewestAttackersToTake(was.armies, rates, rates.luckModifier, rates.roundingMode);
868
+ const cost = straightKills(was.armies, defensive);
869
+ unseen = need === null ? 0 : Math.min(arrived, Math.max(0, need - cost - claimed - came));
870
+ if (unseen > 0) {
871
+ unseenAttackers.push(t.territoryId);
872
+ // The attackers out of sight: what the capture needed less what came from view
873
+ // (need − claimed − came), within what stands there.
874
+ unseenAttackerArmies += unseen + cost;
875
+ }
876
+ }
877
+ if (claimed > 0)
878
+ ambiguous.push({ id: t.territoryId, armies: arrived, kind: 'capture' });
879
+ else {
880
+ if (unseen > 0)
881
+ ambiguous.push({ id: t.territoryId, armies: unseen, kind: 'needed' });
882
+ const rest = arrived - unseen;
883
+ if (rest > 0) {
884
+ fromFog.push(t.territoryId);
885
+ fogArmies += rest;
886
+ highExtra += rest;
887
+ }
888
+ }
889
+ }
890
+ else
891
+ total += arrived;
892
+ }
893
+ }
894
+ // #123: the ambiguous armies, read as deploy up to one bound on the turn's deploy — the same
895
+ // bound for growth beside the fog and a reinforced capture's surplus, shared in id order —
896
+ // and the rest as moves out of the fog. The low reading takes all of them out, the high one
897
+ // counts all of them.
898
+ const grewFromFog = [];
899
+ let fogGrowth = 0;
900
+ const bound = ambiguousBound(context);
901
+ // Without an expected deploy (a board-only reading), growth is all deploy, as before #123.
902
+ if (bound === null)
903
+ for (const x of ambiguous)
904
+ if (x.kind === 'growth')
905
+ total += x.armies;
906
+ // A board-only reading (neither `expected` nor `most`) has no room at all: a negative total (a
907
+ // stack of its own that shrank into the fog) must not make room for a capture's surplus.
908
+ let room = bound === null && context.most === undefined ? 0 : Math.max(0, (bound ?? Math.max(0, context.most)) - total);
909
+ // #293: under Local Deployment, the territories a bonus pool could have paid into on the turn read
910
+ // (the bonuses it could hold on the earlier board); growth beside the fog elsewhere draws on `freeLeft`.
911
+ const local = rates.localDeployments === true && bound !== null && context.localFree !== undefined;
912
+ const pooledOn = new Set();
913
+ if (local)
914
+ for (const b of g.map.bonuses) {
915
+ if (b.value <= 0)
916
+ continue;
917
+ const ts = bonusTerritories(g, b.id);
918
+ const possible = ts.every((t) => {
919
+ const o = ownerShown(before.get(t))?.owner;
920
+ return o === undefined || (o.kind === 'player' && o.playerId === playerId);
921
+ });
922
+ if (possible)
923
+ for (const t of ts)
924
+ pooledOn.add(t);
925
+ }
926
+ let freeLeft = Math.max(0, context.localFree ?? 0);
927
+ const localCut = [];
928
+ // #293 review: a walled growth's walk draws on the shrink the captures left (`shrinkLeft`, after
929
+ // the capture loop), less what the other grown stacks' splits took (their growth already nets it),
930
+ // in ascending ids: one claim pass, so one neighbour's shrink never offsets a capture and a walk both.
931
+ const walled = (x) => local && x.kind === 'growth' && !pooledOn.has(x.id);
932
+ const walkLeft = new Map(shrinkLeft);
933
+ if (local) {
934
+ const walledIds = new Set(ambiguous.filter(walled).map((x) => x.id));
935
+ for (const st of stacks)
936
+ if (!walledIds.has(st.territoryId))
937
+ for (const m of st.moved)
938
+ walkLeft.set(m.from, Math.max(0, (walkLeft.get(m.from) ?? 0) - m.armies));
939
+ }
940
+ for (const x of [...ambiguous].sort((a, b) => a.id - b.id)) {
941
+ if (bound === null && x.kind === 'growth') {
942
+ lowExtra -= x.armies;
943
+ continue;
944
+ }
945
+ // #293: a walk from a neighbour in view (the growth split) nets its shrink; the rest is deploy only
946
+ // as far as the free income still reaches.
947
+ const isWalled = walled(x);
948
+ let walk = 0;
949
+ if (isWalled)
950
+ for (const n of [...neighborsOf(g, x.id)].sort(byNum)) {
951
+ const can = walkLeft.get(n);
952
+ if (!can || walk >= x.armies)
953
+ continue;
954
+ const take = Math.min(can, x.armies - walk);
955
+ walkLeft.set(n, can - take);
956
+ walk += take;
957
+ }
958
+ total += walk;
959
+ room = Math.max(0, room - walk);
960
+ const deployed = Math.min(x.armies - walk, room, isWalled ? freeLeft : Infinity);
961
+ if (isWalled)
962
+ freeLeft -= deployed;
963
+ room -= deployed;
964
+ total += deployed;
965
+ lowExtra -= deployed;
966
+ const moved = x.armies - walk - deployed;
967
+ if (isWalled && moved > 0)
968
+ localCut.push(x.id);
969
+ highExtra += moved;
970
+ if (x.kind === 'capture') {
971
+ if (deployed > 0)
972
+ reinforced.push(x.id);
973
+ if (moved > 0)
974
+ fromFog.push(x.id);
975
+ }
976
+ else if (x.kind === 'needed') {
977
+ if (moved > 0 && !fromFog.includes(x.id))
978
+ fromFog.push(x.id);
979
+ }
980
+ else if (moved > 0) {
981
+ grewFromFog.push(x.id);
982
+ fogGrowth += moved;
983
+ }
984
+ fogArmies += moved;
985
+ }
986
+ fromFog.sort((a, b) => a - b);
987
+ // #271 (1): a failed attack on a hold of mine bounds its deploy from below, fog or not.
988
+ const repelled = context.me !== undefined && context.myOrders
989
+ ? repelledFloor(g, previous, board, context.me, playerId, context.myOrders, rates, guard, context.bomb === true)
990
+ : { territories: [], floor: 0 };
991
+ const floor = repelled.floor;
992
+ return {
993
+ stacks,
994
+ deploy: Math.max(0, total, floor),
995
+ signed: total,
996
+ counted,
997
+ captured,
998
+ fromFog,
999
+ fogArmies,
1000
+ reveals,
1001
+ reinforced,
1002
+ grewFromFog,
1003
+ fogGrowth,
1004
+ ...(localCut.length ? { localCut: { free: Math.max(0, context.localFree ?? 0), territories: localCut } } : {}),
1005
+ expected: context.expected ?? null,
1006
+ attacked: [...kills.keys()].sort(byNum),
1007
+ attackKills: [...kills.values()].reduce((n, k) => n + k, 0),
1008
+ emptied,
1009
+ emptiedHigh,
1010
+ arrivals,
1011
+ unseenAttackers,
1012
+ unseenAttackerArmies,
1013
+ repelled: repelled.territories,
1014
+ repelledFloor: floor,
1015
+ low: Math.max(0, total + lowExtra, floor),
1016
+ high: Math.max(0, total + highExtra, floor),
1017
+ };
1018
+ }
1019
+ /**
1020
+ * How much more than it was expected to deploy an opponent may earn unseen (#123 review): under
1021
+ * fog the visible income reads 2–3× low (#119), so ambiguous armies count as deploy up to twice
1022
+ * the expected figure. A one-off stack out of the fog is not read as a phantom income; a steady
1023
+ * hidden bonus (as large as the visible income) still is, and the tracker, which raises the
1024
+ * expected figure to its carried income, learns a larger one over a few turns.
1025
+ */
1026
+ export const HIDDEN_INCOME_FACTOR = 2;
1027
+ /**
1028
+ * The most an opponent's deploy may total once ambiguous armies are counted (#123): twice what
1029
+ * it was expected to deploy ({@link HIDDEN_INCOME_FACTOR}), never more than it could earn
1030
+ * (`most`). Null without an expected figure: then growth is all deploy and a capture's surplus
1031
+ * counts up to `most` (none without it, #86).
1032
+ */
1033
+ function ambiguousBound(context) {
1034
+ if (context.expected === undefined)
1035
+ return null;
1036
+ const twice = HIDDEN_INCOME_FACTOR * Math.max(0, context.expected);
1037
+ return context.most !== undefined ? Math.min(Math.max(0, context.most), twice) : twice;
1038
+ }
1039
+ /** {@link observeDeploy}'s deploy figure alone. */
1040
+ export function observedDeploy(g, board, previous, playerId, rates = {}) {
1041
+ return observeDeploy(g, board, previous, playerId, rates).deploy;
1042
+ }
1043
+ /**
1044
+ * The army count every visible player territory holds, when they all hold the same one (the
1045
+ * initial allotment). Neutrals are left out (#128): their stacks are not the starting stacks on
1046
+ * ordinary maps, so counting them meant this never fired. Only the first turn can be the opening
1047
+ * board (#128): with a previous board, or a known turn past the first, equal stacks are a
1048
+ * coincidence of the mid-game, and reading them as the opening would drop visible bonuses.
1049
+ */
1050
+ export function openingArmies(g, board, when = {}) {
1051
+ if (when.previous !== undefined || (when.turn !== null && when.turn !== undefined && when.turn > 1))
1052
+ return null;
1053
+ const counts = new Set();
1054
+ for (const t of board.territories)
1055
+ if (g.territoryById.has(t.territoryId) && t.armies !== null && t.owner.kind === 'player')
1056
+ counts.add(t.armies);
1057
+ return counts.size === 1 ? [...counts][0] : null;
1058
+ }
1059
+ /**
1060
+ * Per-opponent enemy deploy estimates, one per visible enemy player (sorted by
1061
+ * id): base income plus the bonuses that player visibly holds in full, never
1062
+ * below max({@link MIN_ENEMY_DEPLOY}, base income). Its stack next to me does not
1063
+ * limit it — income held in plain view can all be deployed on my border, however
1064
+ * small the stack there. Bonuses in the fog are unseen, so this is what the
1065
+ * visible board supports. On the opening board (every visible player territory holds
1066
+ * the same count, with no previous board and `when.turn` unknown or the first) every
1067
+ * opponent gets the floor.
1068
+ */
1069
+ export function enemyDeployEstimates(g, board, me, settings = {}, previous, tracks, prior, when = {}) {
1070
+ const owner = new Map();
1071
+ const armies = new Map();
1072
+ const seenNow = new Map();
1073
+ for (const t of board.territories)
1074
+ if (g.territoryById.has(t.territoryId))
1075
+ seenNow.set(t.territoryId, t);
1076
+ // Owners count whatever the armies: an owner-only territory (light fog) is visibly held, so
1077
+ // it counts toward base income and the bonuses held in full. Only stacks need the armies.
1078
+ for (const t of board.territories) {
1079
+ if (!g.territoryById.has(t.territoryId) || t.owner.kind !== 'player')
1080
+ continue;
1081
+ owner.set(t.territoryId, t.owner.playerId);
1082
+ if (t.armies !== null)
1083
+ armies.set(t.territoryId, t.armies);
1084
+ }
1085
+ const players = [...new Set([...owner.values()].filter((p) => p !== me))].sort(byNum);
1086
+ const opening = openingArmies(g, board, { turn: when.turn, previous }) !== null;
1087
+ // #164: under No, Light and Dense fog every owner shows, so income is exact — when this board
1088
+ // shows every territory's owner too (the setting is a name, never compared by position).
1089
+ const ownersAll = when.fog !== undefined &&
1090
+ OWNERS_SHOWN_FOG.has(when.fog) &&
1091
+ g.map.territories.every((t) => ownerShown(seenNow.get(t.id)) !== undefined);
1092
+ const minimum = Math.max(0, Math.floor(settings.baseIncome ?? DEFAULT_BASE_INCOME));
1093
+ const per = settings.bonusArmyPer ?? 0;
1094
+ return players.map((playerId) => {
1095
+ // Its visible territories are a lower bound on what it holds, so on its
1096
+ // per-territory income too.
1097
+ const theirs = new Set();
1098
+ for (const [t, p] of owner)
1099
+ if (p === playerId)
1100
+ theirs.add(t);
1101
+ const held = theirs.size;
1102
+ const base = territoryIncome(held, minimum, per);
1103
+ // The one income rule (#85) over what it visibly holds; `bonusIncome` is what it adds to the base.
1104
+ const bonusIncome = boardIncome(g, theirs, { base: minimum, per }).total - base;
1105
+ let adjacent = 0;
1106
+ let any = 0;
1107
+ for (const [t, p] of owner) {
1108
+ if (p !== playerId)
1109
+ continue;
1110
+ const a = armies.get(t);
1111
+ if (a === undefined)
1112
+ continue;
1113
+ any = Math.max(any, a);
1114
+ if (neighborsOf(g, t).some((n) => owner.get(n) === me))
1115
+ adjacent = Math.max(adjacent, a);
1116
+ }
1117
+ const largestStack = adjacent || any;
1118
+ // Every opponent earns at least the game's base income (never below the 5 minimum), and
1119
+ // never less than the bonuses it visibly holds: its stack next to me limits neither.
1120
+ const floor = Math.max(MIN_ENEMY_DEPLOY, base);
1121
+ const visible = opening ? floor : Math.max(floor, base + bonusIncome);
1122
+ // What it was seen to deploy is cut only by what it could earn
1123
+ // (#69): its base plus every bonus none of whose territories someone else visibly holds
1124
+ // (an owner-only territory is visibly held: its owner shows). Both come from this board,
1125
+ // so a bonus it lost since last turn is out, though it may have paid for that deploy.
1126
+ let possible = 0;
1127
+ /** #235: of `possible`, the bonuses it visibly holds in full (no share of them goes to another). */
1128
+ let possibleOwn = 0;
1129
+ for (const b of g.map.bonuses) {
1130
+ const ts = bonusTerritories(g, b.id);
1131
+ if (b.value <= 0 || !ts.length)
1132
+ continue;
1133
+ const taken = ts.some((t) => {
1134
+ const st = ownerShown(seenNow.get(t));
1135
+ return st !== undefined && !(st.owner.kind === 'player' && st.owner.playerId === playerId);
1136
+ });
1137
+ if (!taken)
1138
+ possible += b.value;
1139
+ if (!taken && ts.every((t) => theirs.has(t)))
1140
+ possibleOwn += b.value;
1141
+ }
1142
+ // #226: with per-territory income, the territories it could hold pay at the rate: its visible
1143
+ // ones and every one whose owner this board hides (it may hold any of them).
1144
+ const couldHold = per > 0
1145
+ ? g.map.territories.filter((t) => {
1146
+ const st = ownerShown(seenNow.get(t.id));
1147
+ return st === undefined || (st.owner.kind === 'player' && st.owner.playerId === playerId) || theirs.has(t.id);
1148
+ }).length
1149
+ : held;
1150
+ const couldEarn = territoryIncome(couldHold, minimum, per) + possible;
1151
+ // #119: the fog prior. In a symmetric-start 1v1 an opponent bordering the fog earns at least
1152
+ // what I earn, capped at what it could earn on this board. It only ever raises the figure.
1153
+ const fogBeside = [...theirs].some((t) => neighborsOf(g, t).some((n) => !ownerShown(seenNow.get(n))));
1154
+ // #166: with its starts proven, its opening simulated from them raises the prior when it earns
1155
+ // more than I do; never lowers it (the simulation is a simple player, and #119's evidence read low).
1156
+ const priorBase = Math.max(prior?.myIncome ?? 0, prior?.opening?.get(playerId) ?? 0);
1157
+ // #235: in a free-for-all the hidden part of the board is shared: an even share of the hidden
1158
+ // territories and of the bonuses it could still hold (its own in full), never above couldEarn.
1159
+ const k = prior?.format === 'ffa' && (prior.opponents ?? 0) > 1 ? prior.opponents : 0;
1160
+ const priorCap = prior && k > 0
1161
+ ? Math.min(couldEarn, territoryIncome(held + Math.ceil((couldHold - held) / k), minimum, per) + possibleOwn + Math.ceil((possible - possibleOwn) / k))
1162
+ : null;
1163
+ const priorFigure = prior && fogBeside ? Math.min(Math.max(0, Math.floor(priorBase)), priorCap ?? couldEarn) : null;
1164
+ // A track over enough turns replaces the single-turn observed figure (S3).
1165
+ const track = tracks?.find((t) => t.playerId === playerId);
1166
+ const usable = track && track.income !== null && track.turns.length >= TRACKED_MIN_TURNS ? track : undefined;
1167
+ const tracked = usable ? usable.income : null;
1168
+ // #235 review: does the track end on this board? Its newest observed turn then ends at the turn
1169
+ // being planned (the newest board's turn, when that is not given: tracks end on `board`).
1170
+ const newestTurn = when.turn ?? usable?.lastTurn ?? null;
1171
+ const newest = usable?.turns.at(-1);
1172
+ const trackEndsNow = newest !== undefined && newest.to === newestTurn;
1173
+ // #123: what it was expected to deploy before this observation (its visible income, and its
1174
+ // tracked income when it has a usable track, else the prior): ambiguous armies beyond twice that
1175
+ // are moves out of the fog ({@link ambiguousBound}); a capture from me is priced at the guard.
1176
+ // With a track the prior stays out of the bound, and the reading is no part of the estimate
1177
+ // (#235 1c): the track replaces it. A track that ends on this board has read the newest turn
1178
+ // already, so the turn is read with that track's own bound (`ObservedTurn.expected`), and the
1179
+ // rationale's observed line agrees with the tracker and with the label below.
1180
+ const trackBound = trackEndsNow ? newest.expected : undefined;
1181
+ const observation = previous
1182
+ ? observeDeploy(g, board, previous, playerId, settings, {
1183
+ me,
1184
+ guard: (settings.oneArmyStandsGuard ?? true) ? 1 : 0,
1185
+ expected: Math.max(visible, trackBound ?? tracked ?? priorFigure ?? 0),
1186
+ most: couldEarn,
1187
+ // #293: under Local Deployment, growth beside the fog outside every bonus it could hold is
1188
+ // deploy only up to its free income.
1189
+ ...(settings.localDeployments
1190
+ ? { localFree: localFreeOn(base, MIN_ENEMY_DEPLOY, when.reinforcement ?? settings.opponentReinforcement, when.turn == null ? null : when.turn - 1) }
1191
+ : {}),
1192
+ ...(when.previousOrders ? { myOrders: when.previousOrders } : {}),
1193
+ // #271 review: the turn read is the one before the turn planned.
1194
+ ...(bombPossibleOn(settings, when.turn == null ? null : when.turn - 1) ? { bomb: true } : {}),
1195
+ })
1196
+ : null;
1197
+ // #235 1c: the track's newest turn, when it ends on this board and its bound cut armies that
1198
+ // arrived beside the fog (or joined a capture): what that turn reads with them all as deploys.
1199
+ // A label only: a stack walking in is not income (#123 lesson 5), so the estimate stays.
1200
+ const newestCut = trackEndsNow && newest.high > newest.raw && (newest.grewFromFog.length > 0 || newest.reinforced.length > 0)
1201
+ ? {
1202
+ from: newest.from,
1203
+ to: newest.to,
1204
+ observed: newest.observed,
1205
+ reading: Math.min(newest.high, newest.cap),
1206
+ expected: newest.expected ?? null,
1207
+ }
1208
+ : null;
1209
+ const observedCap = observation ? couldEarn : null;
1210
+ const observedRaw = observation?.deploy ?? null;
1211
+ const observed = observation ? Math.min(observation.deploy, observedCap) : null;
1212
+ // A usable track replaces the single-turn observed figure (S3; #235 1c: its newest reading too).
1213
+ const seenSource = tracked !== null
1214
+ ? tracked > visible
1215
+ ? 'tracked'
1216
+ : 'visible'
1217
+ : observed !== null && observed > visible
1218
+ ? 'observed'
1219
+ : 'visible';
1220
+ const seen = seenSource === 'tracked' ? tracked : seenSource === 'observed' ? observed : visible;
1221
+ // #235: the prior shrinks toward that evidence: the more consecutive observed turns, and the more
1222
+ // of its edge in view, the less of its lead it keeps.
1223
+ let priorBlend = null;
1224
+ if (priorFigure !== null && usable) {
1225
+ const toward = Math.max(tracked, visible);
1226
+ if (priorFigure > toward) {
1227
+ // The consecutive observed turns up to the newest board; a run that stopped earlier is none.
1228
+ let turns = trackEndsNow ? 1 : 0;
1229
+ const run = usable.turns;
1230
+ for (let i = run.length - 1; turns > 0 && i > 0 && run[i - 1].from === run[i].from - 1; i--)
1231
+ turns++;
1232
+ const edge = new Set();
1233
+ for (const t of theirs)
1234
+ for (const n of neighborsOf(g, t))
1235
+ if (!theirs.has(n))
1236
+ edge.add(n);
1237
+ const edgeShare = edge.size ? [...edge].filter((n) => ownerShown(seenNow.get(n)) !== undefined).length / edge.size : 0;
1238
+ // #294: each turn of the run weighs what it read of its frontier (this board's edge for a turn
1239
+ // that carries no coverage).
1240
+ const evidence = run.slice(run.length - turns).reduce((n, x) => n + (x.coverage?.share ?? edgeShare), 0);
1241
+ const share = turns ? evidence / turns : edgeShare;
1242
+ const weight = PRIOR_EVIDENCE_TURNS / (PRIOR_EVIDENCE_TURNS + evidence);
1243
+ const figure = toward + Math.ceil(weight * (priorFigure - toward) - 1e-9);
1244
+ priorBlend = { prior: priorFigure, toward, turns, share, weight, figure };
1245
+ }
1246
+ }
1247
+ const priorUsed = priorBlend ? priorBlend.figure : priorFigure;
1248
+ // #164: with every owner shown, its income is base + held bonuses exactly; a deploy above it was
1249
+ // a card (or armies the board misread), never income.
1250
+ const exact = ownersAll && !opening ? Math.max(0, base + bonusIncome) : null;
1251
+ const source = exact !== null ? 'exact' : priorUsed !== null && priorUsed > seen ? 'prior' : seenSource;
1252
+ // #294: what its tracked figure was read from; while that is little, the estimate never falls below
1253
+ // the tracked figure × LOW_COVERAGE_FACTOR (the fog hid most of where it deploys).
1254
+ const coverage = usable ? trackCoverage(usable.turns.filter((x) => usable.incomeTurns.includes(x.from))) : null;
1255
+ const chosen = source === 'exact' ? exact : source === 'prior' ? priorUsed : seen;
1256
+ const lowFloor = source !== 'exact' && tracked !== null && tracked > visible && coverage !== null && coverage.share < LOW_COVERAGE
1257
+ ? Math.min(couldEarn, Math.ceil(tracked * LOW_COVERAGE_FACTOR - 1e-9))
1258
+ : null;
1259
+ const coverageFloor = lowFloor !== null && lowFloor > chosen ? { tracked: tracked, share: coverage.share, factor: LOW_COVERAGE_FACTOR, figure: lowFloor } : null;
1260
+ const income = coverageFloor ? coverageFloor.figure : chosen;
1261
+ // #164: a Reinforcement card, from the turn the clock says one can be in hand, until a deployment
1262
+ // above its income is seen; the next card is due a card's capturing turns after the last one
1263
+ // (pieces carry over while a card is held), never before the turn after the play.
1264
+ // A play is seen as a deploy (its low reading) above the income that turn: exactly, when every
1265
+ // owner shows; under fog only a jump of the card's armies over its visible income counts (a
1266
+ // smaller excess may be a bonus the fog hides — and the tracked income then carries the jump).
1267
+ const played = [];
1268
+ if (when.reinforcement) {
1269
+ const above = (low, income) => (exact !== null ? low > income : low >= income + when.reinforcement.armies);
1270
+ for (const x of track?.turns ?? [])
1271
+ if (above(x.low, x.visibleIncome))
1272
+ played.push(x.from);
1273
+ // Last turn's deploy was paid by last turn's income: what it held on the previous board (a
1274
+ // bonus it lost since paid for it), never below this board's figure.
1275
+ if (observation && previous && when.turn !== null && when.turn !== undefined) {
1276
+ const before = new Set();
1277
+ for (const t of previous.territories)
1278
+ if (g.territoryById.has(t.territoryId) && t.owner.kind === 'player' && t.owner.playerId === playerId)
1279
+ before.add(t.territoryId);
1280
+ const paid = boardIncome(g, before, { base: minimum, per }).total;
1281
+ if (above(observation.low, Math.max(exact ?? visible, paid)))
1282
+ played.push(when.turn - 1);
1283
+ }
1284
+ }
1285
+ let card = null;
1286
+ let cardPlayed = null;
1287
+ if (when.reinforcement && when.turn !== null && when.turn !== undefined) {
1288
+ const r = when.reinforcement;
1289
+ let due = r.firstTurn;
1290
+ let cards = 0;
1291
+ for (const t of [...new Set(played)].sort(byNum)) {
1292
+ if (t < due || t >= when.turn)
1293
+ continue;
1294
+ cards++;
1295
+ cardPlayed = t;
1296
+ due = r.turnsPerCard === null ? Infinity : Math.max(t + 1, r.firstTurn + cards * Math.max(1, r.turnsPerCard));
1297
+ }
1298
+ if (when.turn >= due && r.armies > 0)
1299
+ card = { armies: r.armies, due };
1300
+ }
1301
+ const estimate = income + (card?.armies ?? 0);
1302
+ return {
1303
+ playerId,
1304
+ estimate,
1305
+ held,
1306
+ base,
1307
+ bonusIncome,
1308
+ largestStack,
1309
+ opening,
1310
+ observed,
1311
+ observedRaw,
1312
+ observedCap,
1313
+ couldEarn,
1314
+ couldHold,
1315
+ observation,
1316
+ tracked,
1317
+ newestCut,
1318
+ trackedTurns: usable ? usable.incomeTurns : [],
1319
+ prior: priorFigure,
1320
+ priorBlend,
1321
+ coverage,
1322
+ coverageFloor,
1323
+ priorCap,
1324
+ fogBeside,
1325
+ source,
1326
+ exact,
1327
+ card,
1328
+ cardPlayed,
1329
+ };
1330
+ });
1331
+ }
1332
+ /**
1333
+ * Default enemy deploy: the largest {@link enemyDeployEstimates} figure among the
1334
+ * players with a stack next to me — visible, or its owner shown and its armies hidden (#164) —
1335
+ * at least {@link MIN_ENEMY_DEPLOY}. Pass the turn, fog setting and Reinforcement clock (`when`)
1336
+ * and the fog prior {@link planEnemyEstimates} uses, or a mid-game board of equal stacks reads as
1337
+ * the opening board (#128), an opponent's card is left out (#164), and the figure disagrees with
1338
+ * the planner's. Unlike the planner's, it does not know the teams: a teammate counts.
1339
+ */
1340
+ export function defaultEnemyDeploy(g, board, me, settings = {}, previous, tracks, prior, when = {}) {
1341
+ const mineIds = new Set(board.territories.flatMap((t) => (t.owner.kind === 'player' && t.owner.playerId === me ? [t.territoryId] : [])));
1342
+ const next = new Set();
1343
+ for (const t of board.territories) {
1344
+ if (t.owner.kind !== 'player' || t.owner.playerId === me)
1345
+ continue;
1346
+ if (t.armies === null && (ownerShown(t) === undefined || visibleState(t)))
1347
+ continue;
1348
+ if (!g.territoryById.has(t.territoryId))
1349
+ continue;
1350
+ if (neighborsOf(g, t.territoryId).some((n) => mineIds.has(n)))
1351
+ next.add(t.owner.playerId);
1352
+ }
1353
+ return enemyDeployEstimates(g, board, me, settings, previous, tracks, prior, when).reduce((m, e) => (next.has(e.playerId) ? Math.max(m, e.estimate) : m), MIN_ENEMY_DEPLOY);
1354
+ }
1355
+ /**
1356
+ * This turn's income on the board, cards aside: {@link boardIncome} over the territories `me`
1357
+ * holds, cut by the game's army cap (#253, {@link armyCapIncome}: min(income, round(cap × income)
1358
+ * − my armies on the board)). warapp_plan_turn and warapp_submit_turn both use it (plus the armies
1359
+ * of the card plays in their orders, which the cap leaves alone), so the plan's deploy total is the
1360
+ * total the submit check requires.
1361
+ */
1362
+ export function incomeFor(g, board, me, settings) {
1363
+ return incomeDetail(g, board, me, settings).income;
1364
+ }
1365
+ /**
1366
+ * Another player's income from what the board shows, before any army cap: base, bonuses and cities
1367
+ * over the territories it visibly holds. The cap is not applied (#253): its fogged armies are
1368
+ * unknown, so a cut from its visible armies alone would depend on the fog. My own income is
1369
+ * {@link incomeFor}.
1370
+ */
1371
+ export function visibleIncomeFor(g, board, player, settings) {
1372
+ const held = new Set();
1373
+ for (const t of board.territories)
1374
+ if (g.territoryById.has(t.territoryId) && t.owner.kind === 'player' && t.owner.playerId === player)
1375
+ held.add(t.territoryId);
1376
+ return boardIncome(g, held, incomeRules(settings)).total;
1377
+ }
1378
+ /**
1379
+ * {@link incomeFor} with the army cap's arithmetic: `cap` when the game has one and every territory
1380
+ * of mine shows its armies (my own always should); `capUnknown` when one does not, and the income is
1381
+ * then left uncut. The cap reads my armies from the start-of-turn standing as war.app showed it:
1382
+ * callers may pass a board with the award or a prior merged in (livePlanSetup's `board`), which must
1383
+ * never change my own territories' armies — a merge that did would move the cap's cut.
1384
+ */
1385
+ export function incomeDetail(g, board, me, settings) {
1386
+ const held = new Set();
1387
+ let armies = 0;
1388
+ let unread = false;
1389
+ for (const t of board.territories) {
1390
+ if (!g.territoryById.has(t.territoryId) || t.owner.kind !== 'player' || t.owner.playerId !== me)
1391
+ continue;
1392
+ held.add(t.territoryId);
1393
+ if (t.armies === null)
1394
+ unread = true;
1395
+ else
1396
+ armies += t.armies;
1397
+ }
1398
+ const income = boardIncome(g, held, incomeRules(settings)).total;
1399
+ if (settings?.armyCap === undefined || settings.armyCap === null || !(settings.armyCap > 0))
1400
+ return { income };
1401
+ if (unread)
1402
+ return { income, capUnknown: true };
1403
+ const cap = armyCapIncome(income, settings.armyCap, armies);
1404
+ return { income: cap.received, cap };
1405
+ }