@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,1879 @@
1
+ // Pick advisor for manual-distribution games (docs/PLAN-PICKS.md, K1). Pure and
2
+ // deterministic (every choice tie-breaks on ascending id); no I/O. Advisory only —
3
+ // the owner submits with warapp_submit_picks.
4
+ //
5
+ // Model, in order:
6
+ // 1. Neutral sizes. A territory's neutral armies are the live board's count when
7
+ // given (`neutralArmies`: wastelands at their real size), else
8
+ // InitialNeutralsInDistribution for a pickable territory (an unpicked one turns
9
+ // neutral) and InitialNonDistributionArmies for the rest. A capture costs
10
+ // `captureCost` (the planner's: exact at the game's kill rates, 0% luck,
11
+ // straight round; the game's luck is not passed in).
12
+ // 2. Opening simulation (`simulate`), PICK_HORIZON turns from a set of picks, each
13
+ // starting with InitialPlayerArmiesPerTerritory. Armies stay where they stand:
14
+ // each turn's income is max(base income, floor(territories held / BonusArmyPer))
15
+ // (`territoryIncome`: the territory armies replace the base, never add to it, #38)
16
+ // + completed bonuses; with local deployments a bonus's income is deployed only inside
17
+ // that bonus, the rest anywhere (#129: it was pooled). Within a turn it
18
+ // repeatedly picks the bonus (value > 0, not a superbonus, with a member in or next
19
+ // to the territories held) with the best value / remaining capture cost that has a
20
+ // member next to a territory held at the start of the turn, and attacks that bonus's
21
+ // cheapest such member from one bordering start-of-turn territory (the one with the
22
+ // most movable armies, i.e. above the guard), topped up by the turn's unspent income
23
+ // (deployed there). When that cannot afford it, the capture is tried in two orders
24
+ // (#166, only at 0% luck under straight rounding and with No-Split off, where the
25
+ // arithmetic is exact): a first attack of k armies that does not capture — it kills
26
+ // round(k × offence) of the d defenders, leaving at least one, and loses
27
+ // min(k, round(d × defence)) — then one sized for the defenders left; both from one
28
+ // bordering start-of-turn territory, or the first from one (its own movable armies only)
29
+ // and the second from another. The plan committing the fewest armies wins, then one source
30
+ // over two, then the lower ids, then the smaller first attack; the first attack's armies
31
+ // are spent for the turn (its survivors stay on their source), and such captures are
32
+ // reported (`twoOrderCaptures`). At 60/70 a 3-army neutral costs 5 in one order and 4 in
33
+ // two (1, then 3). When that cannot be paid either, the rest of the income is deployed on
34
+ // that source and saved for the next turn, and the next-best bonuses are still tried
35
+ // with the movable armies of other sources alone. A capture's survivors stay on the captured
36
+ // territory and attack from there next turn (captured armies never attack the turn
37
+ // they capture). Nothing is parked (#129): an attacking source's spare movable armies,
38
+ // and the turn's unspent deploys, go with its attack into its most forward capture, so
39
+ // a bonus behind one neutral completes on turn 2 as it does by hand. A bonus held in full by the picks themselves (a single-territory
40
+ // bonus) completes on turn 0; one completed on turn 1 is a first-turn bonus (FTB).
41
+ // (Before #47 every pick's armies and the captured survivors were one pool, so a
42
+ // bonus was "completed" with armies on picks nowhere near it.)
43
+ // 3. Score of a pick set: Σ completed value × (PICK_HORIZON + 1 − turn) — the bonus
44
+ // armies earned through turn PICK_HORIZON + 1 — plus PROGRESS_WEIGHT × value ×
45
+ // share held for bonuses still incomplete, each bonus scaled by its
46
+ // defensibility 1 / (1 + weight × exposure × hardness), where weight is
47
+ // ENTRY_WEIGHT, or ENTRY_WEIGHT_1V1 (twice as much) in a 1v1 — one opponent finds
48
+ // every entry point, so a narrow bonus wins ties against a wide one (#73) —,
49
+ // exposure counts each entry point once per member of the bonus it borders (#166: a
50
+ // double border, one outside territory next to two members, counts twice; with none it
51
+ // is the number of entry points), and hardness is how much dearer an attack is than at
52
+ // the standard 60/70 (at 30/75 a bonus with few entry points is worth more).
53
+ // A completed bonus is also credited by who can reach it (#166): × (1 − THREAT_LOSS × P).
54
+ // A pickable territory q that is not one of the picks threatens a bonus completed on
55
+ // turn T when a lone stack starting on q holds one of the bonus's territories, or a
56
+ // territory next to one, by the end of turn T (it denies the bonus, or attacks it on
57
+ // turn T + 1). The stack: the starting armies on q, the base income deployed on it each
58
+ // turn, and each turn everything but the guard may go into one neighbour whose capture
59
+ // cost it covers, arriving less the armies lost; every other territory is a neutral at
60
+ // its size, so a wasteland in the way delays it. For T = 0 the threats are the pickables
61
+ // next to the bonus. P is the chance an opponent stands on a threat: 1 when a known
62
+ // opponent start (`taken`) is one; otherwise 1 − C(N − k, L) / C(N, L), with N the
63
+ // pickables neither mine nor known, k the threats among them and L the opponent starts
64
+ // still unknown ((players − 1) × the territory limit, less the known ones) — their starts
65
+ // taken as drawn uniformly from the pickables left, a simplification. A pick of mine is
66
+ // never a threat, so also holding the threatening neighbour restores the credit. In a team
67
+ // game (`team`, C2) L counts only the opponents' starts, and a known start may be a teammate's:
68
+ // only the known starts beyond the teammates' count are taken from L (the worst case).
69
+ // A negative bonus held in full costs
70
+ // its value × (PICK_HORIZON + 1 − turn), unscaled, and is listed among the pick's
71
+ // negatives; the simulation never steers for a bonus whose completion would also
72
+ // complete negative bonuses worth as much (its value is counted net of them, #129).
73
+ // 4. Contestedness. A pick's centrality is its mean hop distance to the other
74
+ // pickable territories, normalised over the pickables (1 = most central). Its
75
+ // score is scaled by 1 − contestWeight(players) × centrality: no penalty in a
76
+ // 1v1, growing CONTEST_PER_PLAYER per extra player up to CONTEST_MAX.
77
+ // 5. Groups. The primary group (min(TerritoryLimit, maxPicks) picks) grows from a seed
78
+ // by adding, greedily, the pick with the biggest marginal gain in the joint
79
+ // simulation's score (× its contest factor), among picks within COMPACT_DISTANCE hops
80
+ // (on the map graph warapp_plan_route uses) of a pick already in the group. Ties:
81
+ // individual score, then id. Every seed (the MAX_SEEDS best by score) grows a group and
82
+ // the best-scoring group wins, ties to the better seed (#129: growing only from the best
83
+ // single pick gave a +4 single grown into dead ground over three +3 singles); when none
84
+ // grows a full group, the hop limit relaxes by one, with a warning, until one does. This holds in
85
+ // a 1v1 too (#73): a primary spread over bonuses against a counter-pick meant a
86
+ // frontier on every one of them from turn 1, and the counter-pick is already covered
87
+ // by the fallback. The fallback group is built the same way from the remaining
88
+ // pickables, up to maxPicks in total, but scored — its picks' scores and reasons too —
89
+ // with the primary picks held by someone else, since only then is it granted: a bonus
90
+ // shared with the primary never completes for it (#129).
91
+ // In a two-player game whose primary has 2 to 4 picks (and without `spread`, and with
92
+ // room on the list for as many again), the first fallback tier is not a group (#166):
93
+ // a pick ranked below the primary is granted only when the opponent holds picks above
94
+ // it, so each is chosen for exactly those outcomes. Positions primary + 1 … 2 × primary
95
+ // are filled one at a time. For position p, each outcome of `pickOutcomes` whose last
96
+ // granted position is p is settled by the list so far plus the candidate: I hold the
97
+ // granted set G and the opponent the picks above p that I was not granted, K
98
+ // (`impliedOpponentStarts`). The candidate's value there is
99
+ // simulate(G, K).score − OPPONENT_WEIGHT × simulate(K, G).score: my opening, less a share
100
+ // of the opponent's from the starts the award reveals, in which my picks are known
101
+ // threats to their bonuses — so a pick that reaches the bonus of the pick I lost scores
102
+ // higher, and its own bonus still counts. The best mean over those outcomes wins; ties:
103
+ // its own score with the primary taken, then id. (The opponent's opening is simulated
104
+ // once per outcome for every candidate standing nowhere it looks.) The picks' scores and
105
+ // reasons are still those with the primary taken, plus what each answers.
106
+ // Otherwise in a 1v1 (a primary of one pick, or of five or more), among the equally
107
+ // scored compact fallbacks found at its hop limit, the one farthest from the primary
108
+ // (fewest hops between the two groups, maximised) wins, so one counter-pick cannot reach
109
+ // both. A fallback that still outscores the primary is warned about. A list longer than
110
+ // twice the limit (war.app's client allows players × territories per player,
111
+ // `clientPickLimits`) runs in fallback tiers of the primary's size, each built as a group
112
+ // with the primary and the earlier tiers taken; the fallback group's score, bonuses
113
+ // and spread are its first tier's.
114
+ // Only with `spread: true` in a 1v1 does the old rule apply: a pick may also join
115
+ // when it anchors a bonus no group pick anchors and lies within SPREAD_DISTANCE hops,
116
+ // and the bound gives way, with a warning, at the smallest hop limit where a group
117
+ // scores SPREAD_RELAX_GAIN times the bounded one. Usually worse on large maps.
118
+ // Each group built as a group is listed by score (an answering tier in the order its
119
+ // picks were chosen); its maxHops and the rationale state its real
120
+ // spread (farthest pair, and the longest step linking its picks into one cluster) and
121
+ // call it compact only when that step is at most COMPACT_DISTANCE: one cluster, not
122
+ // merely each pick with a group-mate nearby.
123
+ // 5b. Award order (#129). Picks are awarded round by round in move order, reversing each
124
+ // round, each player getting their highest-ranked territory still free (`pickOutcomes`
125
+ // enumerates the sets a list can yield, other players' lists unknown). The list's worst
126
+ // outcome is scored with the other players on the starts it implies
127
+ // (`impliedOpponentStarts`) and reported; the primary is reordered (up to MAX_REORDER
128
+ // picks) only when another order raises that worst outcome. An answering fallback
129
+ // (item 5) depends on that order: it is chosen for the score order first, and when the
130
+ // award order prefers another, chosen again for it — the new order standing only if the
131
+ // list as it then reads still has a better worst outcome than the list it replaces. A team
132
+ // game's award order is not settled (C2): both the reversing and a repeating order (the same
133
+ // every round) are enumerated, and the worst outcome of either is reported.
134
+ // 5c. Commanders (#129): the first pick awarded carries the commander, so the primary's
135
+ // safest pick (fewest other pickables within COMPACT_DISTANCE hops, then fewest
136
+ // neighbours outside the primary, then score) is listed first; the award reorder keeps it.
137
+ // 6. Reasons. reasons[0] is the bonus the pick anchors (worth most to it alone) and its
138
+ // completion turn and the income it adds, or how much of it is held by the horizon;
139
+ // then the other bonuses it completes or advances. Each such line gives the bonus's entry
140
+ // points and which are double borders, and for a completed bonus who can reach it: no
141
+ // other pickable territory, or the threats by name (three at most) with the score cost,
142
+ // and "safe only if you also hold …" when there are one or two. Then the captures that
143
+ // took two orders; negatives (shortfalls,
144
+ // wastelands — a member other than the pick larger than an ordinary neutral —, contest,
145
+ // negative bonuses held) come last, and after them what a pick of an answering fallback
146
+ // answers: the lost picks whose bonus it reaches by the turn they complete it alone.
147
+ import { analyzeBonus, bonusTerritories, entryTouches } from './bonuses.js';
148
+ import { armiesToTake, DEFAULT_DEFENSIVE_KILL_RATE, DEFAULT_OFFENSIVE_KILL_RATE, luckFraction, straightKills, } from './combat.js';
149
+ import { bfsDistances, neighborsOf } from './graph.js';
150
+ import { captureCost } from './planner.js';
151
+ import { boardIncome, DEFAULT_BASE_INCOME } from './player.js';
152
+ /** Turns the opening simulation runs (income by turn 3). */
153
+ export const PICK_HORIZON = 3;
154
+ /** Share of a still-incomplete bonus's value credited per share of it held at the horizon. */
155
+ const PROGRESS_WEIGHT = 0.5;
156
+ /** Share of a completed bonus's credit lost when an opponent certainly starts where it can be reached in time (#166). */
157
+ export const THREAT_LOSS = 0.5;
158
+ /**
159
+ * In a two-player game a fallback pick is worth its own opening less this share of the
160
+ * opponent's, from the starts the award then reveals (#166).
161
+ */
162
+ export const OPPONENT_WEIGHT = 0.5;
163
+ /** Defensibility penalty per unit of exposure — an entry point, once per member it borders — scaled by attack hardness… */
164
+ const ENTRY_WEIGHT = 0.05;
165
+ /** …and in a 1v1 (twice ENTRY_WEIGHT: the one opponent finds every entry point, #73). */
166
+ const ENTRY_WEIGHT_1V1 = 0.1;
167
+ /** Contest penalty per player beyond two… */
168
+ const CONTEST_PER_PLAYER = 0.06;
169
+ /** …capped here. */
170
+ const CONTEST_MAX = 0.5;
171
+ /** A group pick lies within this many hops of another pick in its group… */
172
+ export const COMPACT_DISTANCE = 2;
173
+ /** With `spread: true` in a 1v1: or within this many when it anchors a bonus no other group pick anchors. */
174
+ export const SPREAD_DISTANCE = 4;
175
+ /** With `spread: true`: a 1v1 group spreads past SPREAD_DISTANCE only when that scores at least this many times as much. */
176
+ const SPREAD_RELAX_GAIN = 1.5;
177
+ /** Defaults when the settings are missing (war.app's usual values). */
178
+ export const DEFAULT_PICK_ARMIES = 5;
179
+ export const DEFAULT_NEUTRALS_IN_DISTRIBUTION = 4;
180
+ export const DEFAULT_NON_DISTRIBUTION_ARMIES = 2;
181
+ /** Seeds (best score first) each group search grows from; every one when the pool is no larger (#129). */
182
+ const MAX_SEEDS = 12;
183
+ /** The primary's order is searched for the best worst outcome only up to this size (#129). */
184
+ const MAX_REORDER = 5;
185
+ /** Neutral size used to compare attack hardness against the standard kill rates. */
186
+ const HARDNESS_PROBE = 10;
187
+ /** Territories a reason names before it says "and n more". */
188
+ const MAX_NAMED = 3;
189
+ const byNum = (a, b) => a - b;
190
+ const NO_TAKEN = new Set();
191
+ const round2 = (x) => Math.round(x * 100) / 100;
192
+ /** `a` sorts before `b`, compared element by element. */
193
+ const lexLess = (a, b) => {
194
+ for (let i = 0; i < Math.min(a.length, b.length); i++)
195
+ if (a[i] !== b[i])
196
+ return a[i] < b[i];
197
+ return a.length < b.length;
198
+ };
199
+ const NO_THREATS = [];
200
+ /**
201
+ * The chance that an opponent starts on one of `threats` (pickables that are not mine). 1 when
202
+ * a known opponent start (`taken`) is among them. Otherwise the opponent starts still unknown
203
+ * — (players − 1) × the territory limit, less the known ones — are taken to be drawn uniformly
204
+ * from the pickables that are neither mine nor known: 1 − C(N − k, L) / C(N, L). In a team game
205
+ * only the opponents' starts count, and a known start may be a teammate's: only the known starts
206
+ * beyond what my teammates hold are taken from the opponents' (the worst case).
207
+ */
208
+ function threatChance(ctx, threats, mine, taken, known) {
209
+ if (!threats.length)
210
+ return 0;
211
+ for (const q of threats)
212
+ if (taken.has(q))
213
+ return 1;
214
+ const n = Math.max(0, ctx.pickCount - mine - known);
215
+ const unknown = Math.min(Math.max(0, ctx.opponentStarts - Math.max(0, known - ctx.teammateStarts)), n);
216
+ const k = threats.length;
217
+ if (unknown <= 0)
218
+ return 0;
219
+ if (n - k < unknown)
220
+ return 1;
221
+ let none = 1;
222
+ for (let i = 0; i < unknown; i++)
223
+ none *= (n - k - i) / (n - i);
224
+ return 1 - none;
225
+ }
226
+ /** The bonuses with a territory in or next to `from`, ascending: the ones an opening from there can touch. */
227
+ function relevantBonuses(ctx, from) {
228
+ const ids = new Set();
229
+ for (const t of from) {
230
+ for (const b of ctx.bonusesOf.get(t) ?? [])
231
+ ids.add(b);
232
+ for (const n of neighborsOf(ctx.g, t))
233
+ for (const b of ctx.bonusesOf.get(n) ?? [])
234
+ ids.add(b);
235
+ }
236
+ return [...ids].sort(byNum);
237
+ }
238
+ /**
239
+ * Every territory whose owner an opening looked at: the members of each bonus it could touch,
240
+ * and the pickables that reach a bonus it completed. Giving any other territory to someone
241
+ * else changes nothing in that opening but the count of known starts.
242
+ */
243
+ function territoriesRead(ctx, sim) {
244
+ const read = new Set();
245
+ for (const id of relevantBonuses(ctx, sim.held))
246
+ for (const m of ctx.bonuses.get(id).members)
247
+ read.add(m);
248
+ for (const reach of sim.threats.values())
249
+ for (const q of reach)
250
+ read.add(q);
251
+ return read;
252
+ }
253
+ /**
254
+ * The opening from `start`. `taken` territories belong to someone else (the primary picks when
255
+ * the fallback is granted, #129): never captured, so a bonus holding one never completes.
256
+ * `known` is how many of the other players' starts are known (all of `taken`, unless the caller
257
+ * knows of one more that this opening never comes near).
258
+ */
259
+ function simulate(ctx, start, taken = NO_TAKEN, known = taken.size) {
260
+ const held = new Set(start);
261
+ // Armies on each held territory: armies attack only from where they stand.
262
+ const armiesOn = new Map(start.map((t) => [t, ctx.pickArmies]));
263
+ const completions = new Map();
264
+ // The bonuses the territories held can touch, worked out again only when more are held.
265
+ let touching = null;
266
+ const relevant = () => (touching ??= relevantBonuses(ctx, held));
267
+ const penalties = new Map();
268
+ const twoOrders = [];
269
+ const incomes = [];
270
+ const checkComplete = (turn) => {
271
+ for (const id of relevant()) {
272
+ if (completions.has(id))
273
+ continue;
274
+ if (ctx.bonuses.get(id).members.every((m) => held.has(m)))
275
+ completions.set(id, turn);
276
+ }
277
+ for (const t of held)
278
+ for (const id of ctx.penaltiesOf.get(t) ?? [])
279
+ if (!penalties.has(id) && ctx.penalties.get(id).members.every((m) => held.has(m)))
280
+ penalties.set(id, turn);
281
+ };
282
+ // A bonus is worth its value less the negative bonuses that completing it would also
283
+ // complete (#129): one worth no more than that is not steered for.
284
+ const netValue = (b) => {
285
+ let v = b.value;
286
+ if (!ctx.penalties.size)
287
+ return v;
288
+ const ids = new Set(b.members.flatMap((m) => ctx.penaltiesOf.get(m) ?? []));
289
+ for (const id of ids) {
290
+ if (penalties.has(id))
291
+ continue;
292
+ const n = ctx.penalties.get(id);
293
+ if (n.members.every((m) => held.has(m) || b.members.includes(m)))
294
+ v += n.value;
295
+ }
296
+ return v;
297
+ };
298
+ checkComplete(0);
299
+ for (let turn = 1; turn <= PICK_HORIZON; turn++) {
300
+ // The one income rule (#85): every bonus held in full counts — negative ones and superbonuses
301
+ // too, not only the anchorable bonuses the simulation steers for. With local deployments
302
+ // (#129) each positive bonus's income is its own pool, deployable only inside the bonus;
303
+ // the rest (base or territory income, less negative bonuses) goes anywhere.
304
+ const income = boardIncome(ctx.g, held, { base: ctx.baseIncome, per: ctx.bonusArmyPer });
305
+ incomes.push(income.total);
306
+ const pools = [];
307
+ if (ctx.localDeployments) {
308
+ const local = income.bonuses.filter((b) => b.value > 0);
309
+ const free = income.total - local.reduce((n, b) => n + b.value, 0);
310
+ for (const b of local)
311
+ pools.push({ cells: new Set(bonusTerritories(ctx.g, b.bonusId)), left: b.value });
312
+ pools.push({ cells: null, left: Math.max(0, free) });
313
+ }
314
+ else
315
+ pools.push({ cells: null, left: income.total });
316
+ const usable = (p, t) => p.cells === null || p.cells.has(t);
317
+ const startHeld = [...held].sort(byNum);
318
+ const startSet = new Set(startHeld);
319
+ // Movable armies of the territories held at the start of the turn (captured ones never attack).
320
+ const avail = new Map(startHeld.map((t) => [t, Math.max(0, armiesOn.get(t) - ctx.guard)]));
321
+ const captured = new Set();
322
+ // Where this turn's unspent deploys go: the source of the attack it is saving for.
323
+ // Once set, the deploys that could go there are reserved for it; other sources still
324
+ // attack with their own armies (and, with local deployments, the pools it cannot use).
325
+ let saveAt = null;
326
+ const reserved = new Set();
327
+ const deployAt = (t) => pools.reduce((n, p) => n + (usable(p, t) && !reserved.has(p) ? p.left : 0), 0);
328
+ const spend = (t, n) => {
329
+ // Bonus-local pools first: the free pool can go elsewhere.
330
+ for (const p of [...pools].sort((a, b) => (a.cells === null ? 1 : 0) - (b.cells === null ? 1 : 0))) {
331
+ if (n <= 0)
332
+ break;
333
+ if (!usable(p, t) || reserved.has(p))
334
+ continue;
335
+ const k = Math.min(p.left, n);
336
+ p.left -= k;
337
+ n -= k;
338
+ }
339
+ };
340
+ // A capture in two orders (#166), for a target no single source can pay for: a first attack
341
+ // of k armies that does not capture (it kills round(k × offence) of the d defenders, leaving
342
+ // at least one, and loses min(k, round(d × defence))), then one sized for the defenders left.
343
+ // Both from one bordering start-of-turn territory (its movable armies and the deploys it may
344
+ // receive), or the first from one using only its own movable armies and the second from
345
+ // another. The fewest armies committed wins, then one source over two, then the lower ids,
346
+ // then the smaller first attack.
347
+ const twoOrderPlan = (target) => {
348
+ const d = ctx.armies.get(target);
349
+ const sources = neighborsOf(ctx.g, target).filter((n) => startSet.has(n) && n !== saveAt);
350
+ if (!ctx.twoOrders || ctx.off <= 0 || d < 2 || !sources.length)
351
+ return null;
352
+ const reach = new Map(sources.map((n) => [n, avail.get(n) + deployAt(n)]));
353
+ const most = Math.max(...reach.values());
354
+ let best = null;
355
+ for (let k = 1; k <= most; k++) {
356
+ const kills = straightKills(k, ctx.off);
357
+ if (kills >= d)
358
+ break;
359
+ if (kills < 1)
360
+ continue;
361
+ const rest = d - kills;
362
+ const then = armiesToTake(rest, { offensiveKillRate: ctx.off, defensiveKillRate: ctx.def });
363
+ for (const first of sources)
364
+ for (const second of sources) {
365
+ const can = first === second ? reach.get(first) >= k + then : avail.get(first) >= k && reach.get(second) >= then;
366
+ if (!can)
367
+ continue;
368
+ const key = [k + then, first === second ? 1 : 2, first, second, k];
369
+ if (!best || lexLess(key, best.key))
370
+ best = { key, first, second, k, rest, then };
371
+ }
372
+ }
373
+ return best;
374
+ };
375
+ // Bonuses whose next capture cannot be paid for this turn.
376
+ const skipped = new Set();
377
+ // This turn's attacks, in order: the armies left over follow them (#129).
378
+ const attacks = [];
379
+ // The bonuses this turn can work on, set up once (the simulation runs very many times): what
380
+ // is left to capture, and the members next to a territory held at the start of the turn,
381
+ // cheapest first (then id). Within the turn only the captures change: `rem` falls, and a
382
+ // captured target is passed over.
383
+ const reachable = new Set();
384
+ for (const t of startHeld)
385
+ for (const n of neighborsOf(ctx.g, t))
386
+ reachable.add(n);
387
+ const open = [];
388
+ const openById = new Map();
389
+ for (const id of relevant()) {
390
+ if (completions.has(id))
391
+ continue;
392
+ const b = ctx.bonuses.get(id);
393
+ let rem = 0;
394
+ let blocked = false;
395
+ const targets = [];
396
+ for (const m of b.members) {
397
+ if (held.has(m))
398
+ continue;
399
+ const c = taken.has(m) || ctx.friendly.has(m) ? null : ctx.cost.get(m);
400
+ if (c === null || c === undefined) {
401
+ blocked = true;
402
+ break;
403
+ }
404
+ rem += c;
405
+ if (reachable.has(m))
406
+ targets.push(m);
407
+ }
408
+ if (blocked || !targets.length || rem === 0)
409
+ continue;
410
+ const net = netValue(b);
411
+ if (net <= 0)
412
+ continue;
413
+ targets.sort((x, y) => ctx.cost.get(x) - ctx.cost.get(y) || x - y);
414
+ const o = { id, net, rem, targets, next: 0 };
415
+ open.push(o);
416
+ openById.set(id, o);
417
+ }
418
+ const capture = (target) => {
419
+ captured.add(target);
420
+ for (const id of ctx.bonusesOf.get(target) ?? []) {
421
+ const o = openById.get(id);
422
+ if (o)
423
+ o.rem -= ctx.cost.get(target);
424
+ }
425
+ };
426
+ for (;;) {
427
+ let best = null;
428
+ for (const o of open) {
429
+ if (skipped.has(o.id))
430
+ continue;
431
+ while (o.next < o.targets.length && captured.has(o.targets[o.next]))
432
+ o.next++;
433
+ if (o.next >= o.targets.length || o.rem === 0)
434
+ continue;
435
+ const { id, rem } = o;
436
+ const ratio = o.net / rem;
437
+ if (!best || ratio > best.ratio || (ratio === best.ratio && (rem < best.rem || (rem === best.rem && id < best.id)))) {
438
+ const target = o.targets[o.next];
439
+ best = { id, ratio, rem, target, cost: ctx.cost.get(target) };
440
+ }
441
+ }
442
+ if (!best)
443
+ break;
444
+ // The attack comes from one bordering territory held at the start of the turn —
445
+ // the one with the most movable armies (then id) — topped up by this turn's deploys
446
+ // unless they are already reserved for an attack saved for next turn.
447
+ let source = -1;
448
+ for (const n of neighborsOf(ctx.g, best.target)) {
449
+ if (!startSet.has(n) || n === saveAt)
450
+ continue;
451
+ if (source < 0 || avail.get(n) > avail.get(source))
452
+ source = n;
453
+ }
454
+ const own = source < 0 ? 0 : avail.get(source);
455
+ const deploy = source < 0 ? 0 : deployAt(source);
456
+ const two = source < 0 || own + deploy < best.cost ? twoOrderPlan(best.target) : null;
457
+ if (two) {
458
+ const { first, second, k, rest, then } = two;
459
+ // The first attack: its armies are spent for the turn, and its survivors stay put.
460
+ const dead = Math.min(k, straightKills(ctx.armies.get(best.target), ctx.def));
461
+ const pay = (t, n) => {
462
+ const fromOwn = Math.min(avail.get(t), n);
463
+ avail.set(t, avail.get(t) - fromOwn);
464
+ armiesOn.set(t, armiesOn.get(t) - fromOwn);
465
+ spend(t, n - fromOwn);
466
+ };
467
+ pay(first, k);
468
+ armiesOn.set(first, armiesOn.get(first) + k - dead);
469
+ pay(second, then);
470
+ capture(best.target);
471
+ attacks.push({ source: second, target: best.target });
472
+ armiesOn.set(best.target, then - straightKills(rest, ctx.def));
473
+ twoOrders.push({
474
+ turn,
475
+ territoryId: best.target,
476
+ orders: [
477
+ { from: first, armies: k },
478
+ { from: second, armies: then },
479
+ ],
480
+ });
481
+ continue;
482
+ }
483
+ if (source < 0 || own + deploy < best.cost) {
484
+ // Save the deploys for the best bonus; try the next one with what else stands idle.
485
+ if (saveAt === null && source >= 0) {
486
+ saveAt = source;
487
+ for (const p of pools)
488
+ if (usable(p, source))
489
+ reserved.add(p);
490
+ }
491
+ skipped.add(best.id);
492
+ continue;
493
+ }
494
+ const fromOwn = Math.min(own, best.cost);
495
+ avail.set(source, own - fromOwn);
496
+ armiesOn.set(source, armiesOn.get(source) - fromOwn);
497
+ spend(source, best.cost - fromOwn);
498
+ capture(best.target);
499
+ attacks.push({ source, target: best.target });
500
+ armiesOn.set(best.target, Math.max(0, best.cost - ctx.lost.get(best.target)));
501
+ }
502
+ // Armies are not parked (#129): what is left goes with the attacks, as a player would
503
+ // send it — each attacking source's spare movable armies, and the unspent deploys (on the
504
+ // first attack's source they may be deployed on), join that source's most forward capture
505
+ // (the most territories next to it neither held nor captured; ties: lowest id). Deploys
506
+ // saved for an attack next turn stay on its source; with no attack they can go with, they
507
+ // go on the start territory (they may be deployed on) with the most unheld neighbours.
508
+ const unheld = (t) => neighborsOf(ctx.g, t).filter((n) => !held.has(n) && !captured.has(n)).length;
509
+ const forward = (ids) => ids.reduce((a, b) => (unheld(b) > unheld(a) || (unheld(b) === unheld(a) && b < a) ? b : a));
510
+ const carry = new Map();
511
+ for (const p of pools) {
512
+ if (p.left <= 0)
513
+ continue;
514
+ if (reserved.has(p)) {
515
+ armiesOn.set(saveAt, armiesOn.get(saveAt) + p.left);
516
+ continue;
517
+ }
518
+ const with_ = attacks.find((a) => usable(p, a.source) && a.source !== saveAt);
519
+ if (with_)
520
+ carry.set(with_.source, (carry.get(with_.source) ?? 0) + p.left);
521
+ else {
522
+ const cells = startHeld.filter((t) => usable(p, t));
523
+ if (!cells.length)
524
+ continue;
525
+ const at = forward(cells);
526
+ armiesOn.set(at, armiesOn.get(at) + p.left);
527
+ }
528
+ }
529
+ const sources = [...new Set(attacks.map((a) => a.source))].filter((t) => t !== saveAt);
530
+ for (const src of sources) {
531
+ const to = forward(attacks.filter((a) => a.source === src).map((a) => a.target));
532
+ armiesOn.set(src, armiesOn.get(src) - avail.get(src));
533
+ armiesOn.set(to, armiesOn.get(to) + avail.get(src) + (carry.get(src) ?? 0));
534
+ }
535
+ for (const t of captured)
536
+ held.add(t);
537
+ if (captured.size)
538
+ touching = null;
539
+ checkComplete(turn);
540
+ }
541
+ const progress = new Map();
542
+ const threats = new Map();
543
+ const risk = new Map();
544
+ const mine = new Set(start);
545
+ let score = 0;
546
+ for (const id of relevant()) {
547
+ const b = ctx.bonuses.get(id);
548
+ const turn = completions.get(id);
549
+ if (turn !== undefined) {
550
+ // Credited by who can reach it (#166): my own picks are no threat to it.
551
+ const reach = (ctx.threats.get(id)?.[turn] ?? NO_THREATS).filter((q) => !mine.has(q));
552
+ const p = threatChance(ctx, reach, start.length, taken, known);
553
+ threats.set(id, reach);
554
+ risk.set(id, p);
555
+ score += b.value * (PICK_HORIZON + 1 - turn) * b.defense * (1 - THREAT_LOSS * p);
556
+ continue;
557
+ }
558
+ const share = b.members.filter((m) => held.has(m)).length / b.members.length;
559
+ // A bonus someone else holds part of is not progress (#129).
560
+ if (share > 0 && !b.members.some((m) => taken.has(m) || ctx.friendly.has(m))) {
561
+ progress.set(id, share);
562
+ score += PROGRESS_WEIGHT * b.value * share * b.defense;
563
+ }
564
+ }
565
+ for (const [id, turn] of penalties)
566
+ score += ctx.penalties.get(id).value * (PICK_HORIZON + 1 - turn);
567
+ return { completions, penalties, progress, threats, risk, twoOrders, held, incomes, score };
568
+ }
569
+ /**
570
+ * The income the pick advisor's opening simulation gives a player from `starts` on each turn
571
+ * 1..PICK_HORIZON + 1 (index 0: turn 1), the last being what it holds after PICK_HORIZON turns
572
+ * (#166: the opening threat model, from the opponent's starts the award of picks proves). The same
573
+ * simulation, rules and income rule (`boardIncome`) as {@link planPicks}; the settings it lacks
574
+ * take its defaults. Pure and deterministic.
575
+ */
576
+ export function openingIncome(input) {
577
+ const { graph: g } = input;
578
+ const s = input.settings ?? {};
579
+ const starts = [...new Set(input.starts)].filter((t) => g.territoryById.has(t)).sort(byNum);
580
+ const taken = new Set((input.taken ?? []).filter((t) => g.territoryById.has(t) && !starts.includes(t)));
581
+ const pickSet = new Set(input.pickable ?? [...starts, ...taken]);
582
+ const known = input.neutralArmies ?? new Map();
583
+ const neutralsIn = s.initialNeutralsInDistribution ?? DEFAULT_NEUTRALS_IN_DISTRIBUTION;
584
+ const neutralsOut = s.initialNonDistributionArmies ?? DEFAULT_NON_DISTRIBUTION_ARMIES;
585
+ const off = s.offensiveKillRate ?? DEFAULT_OFFENSIVE_KILL_RATE;
586
+ const def = s.defensiveKillRate ?? DEFAULT_DEFENSIVE_KILL_RATE;
587
+ const rates = { offensiveKillRate: off, defensiveKillRate: def, luckModifier: s.luckModifier };
588
+ const { armies, cost, lost } = territoryCosts(g, (t) => known.get(t) ?? (pickSet.has(t) ? neutralsIn : neutralsOut), rates);
589
+ // Defensibility weighs only the score, never the income: no weight.
590
+ const { bonuses, bonusesOf, penalties, penaltiesOf } = bonusTables(g, 0, 1);
591
+ const ctx = {
592
+ g,
593
+ cost,
594
+ lost,
595
+ armies,
596
+ bonuses,
597
+ bonusesOf,
598
+ penalties,
599
+ penaltiesOf,
600
+ pickArmies: s.initialPlayerArmiesPerTerritory ?? DEFAULT_PICK_ARMIES,
601
+ guard: s.oneArmyStandsGuard === false ? 0 : 1,
602
+ baseIncome: s.minimumArmyBonus ?? DEFAULT_BASE_INCOME,
603
+ bonusArmyPer: s.bonusArmyPer ?? 0,
604
+ localDeployments: s.localDeployments === true,
605
+ off,
606
+ def,
607
+ twoOrders: luckFraction(s.luckModifier) === 0 && (s.roundingMode === undefined || s.roundingMode === 'StraightRound') && s.noSplit !== true,
608
+ pickCount: pickSet.size,
609
+ opponentStarts: 0,
610
+ teammateStarts: 0,
611
+ friendly: NO_TAKEN,
612
+ threats: new Map(),
613
+ };
614
+ const sim = simulate(ctx, starts, taken);
615
+ const last = boardIncome(g, sim.held, { base: ctx.baseIncome, per: ctx.bonusArmyPer }).total;
616
+ return [...sim.incomes, last];
617
+ }
618
+ function luckPercent(v) {
619
+ if (!v || v <= 0)
620
+ return 0;
621
+ return Math.round(Math.min(v > 1 ? v / 100 : v, 0.95) * 100);
622
+ }
623
+ /** Neutral armies, capture cost and the armies a capture loses, per territory of the map. */
624
+ function territoryCosts(g, neutralOf, rates) {
625
+ const armies = new Map();
626
+ const cost = new Map();
627
+ const lost = new Map();
628
+ for (const t of g.map.territories) {
629
+ const n = Math.max(0, neutralOf(t.id));
630
+ armies.set(t.id, n);
631
+ cost.set(t.id, captureCost(n, rates));
632
+ lost.set(t.id, straightKills(n, rates.defensiveKillRate));
633
+ }
634
+ return { armies, cost, lost };
635
+ }
636
+ /** The bonuses the opening steers for (value > 0) and the negative ones it is charged for, by id and by territory. */
637
+ function bonusTables(g, entryWeight, hardness) {
638
+ // Anchorable bonuses: value > 0, territories listed directly (superbonuses skipped).
639
+ const bonuses = new Map();
640
+ const bonusesOf = new Map();
641
+ for (const b of g.map.bonuses) {
642
+ if (b.value <= 0 || b.bonusIds.length > 0)
643
+ continue;
644
+ const a = analyzeBonus(g, b.id);
645
+ const members = a.territoryIds.filter((t) => g.territoryById.has(t));
646
+ if (!members.length)
647
+ continue;
648
+ // Exposure: each entry point counted once per member it borders, so a double border
649
+ // (one outside territory next to two members) weighs twice (#166).
650
+ const touches = [...entryTouches(g, b.id)];
651
+ const exposure = touches.reduce((n, [, k]) => n + k, 0);
652
+ bonuses.set(b.id, {
653
+ id: b.id,
654
+ name: b.name,
655
+ value: b.value,
656
+ members,
657
+ entryPoints: a.entryPointIds.length,
658
+ doubleBorders: touches.filter(([, k]) => k > 1).map(([territoryId, k]) => ({ territoryId, touches: k })),
659
+ defense: 1 / (1 + entryWeight * exposure * hardness),
660
+ });
661
+ for (const t of members)
662
+ bonusesOf.set(t, [...(bonusesOf.get(t) ?? []), b.id]);
663
+ }
664
+ // Negative bonuses: never steered for, but charged when held in full (#129).
665
+ const penalties = new Map();
666
+ const penaltiesOf = new Map();
667
+ for (const b of g.map.bonuses) {
668
+ if (b.value >= 0 || b.bonusIds.length > 0)
669
+ continue;
670
+ const members = (analyzeBonus(g, b.id)?.territoryIds ?? []).filter((t) => g.territoryById.has(t));
671
+ if (!members.length)
672
+ continue;
673
+ penalties.set(b.id, { id: b.id, name: b.name, value: b.value, members, entryPoints: 0, doubleBorders: [], defense: 1 });
674
+ for (const t of members)
675
+ penaltiesOf.set(t, [...(penaltiesOf.get(t) ?? []), b.id]);
676
+ }
677
+ return { bonuses, bonusesOf, penalties, penaltiesOf };
678
+ }
679
+ function planCore(input, friendlyIds = []) {
680
+ const { graph: g } = input;
681
+ const friendly = friendlyIds.length ? new Set(friendlyIds) : NO_TAKEN;
682
+ const s = input.settings ?? {};
683
+ const warnings = [];
684
+ const rationale = [];
685
+ // Pickable territories: known, unique, sorted.
686
+ const unknown = [];
687
+ // `pickSet` is every pickable territory (for neutral sizes); `pickable` leaves out a teammate's top
688
+ // picks (C2): theirs, and known starts, so neither mine to pick nor a threat.
689
+ const pickSet = new Set();
690
+ for (const t of input.pickable) {
691
+ if (g.territoryById.has(t))
692
+ pickSet.add(t);
693
+ else if (!unknown.includes(t))
694
+ unknown.push(t);
695
+ }
696
+ if (unknown.length)
697
+ warnings.push(`Ignored pickable ids not on the map: ${unknown.sort(byNum).join(', ')}.`);
698
+ const pickable = [...pickSet].filter((t) => !friendly.has(t)).sort(byNum);
699
+ // Settings and assumptions.
700
+ const pickArmies = s.initialPlayerArmiesPerTerritory ?? DEFAULT_PICK_ARMIES;
701
+ if (s.initialPlayerArmiesPerTerritory === undefined)
702
+ warnings.push(`Starting armies per picked territory missing from settings; assumed ${DEFAULT_PICK_ARMIES}.`);
703
+ const baseIncome = s.minimumArmyBonus ?? DEFAULT_BASE_INCOME;
704
+ if (s.minimumArmyBonus === undefined)
705
+ warnings.push(`Base income missing from settings; assumed ${DEFAULT_BASE_INCOME}.`);
706
+ const off = s.offensiveKillRate ?? DEFAULT_OFFENSIVE_KILL_RATE;
707
+ const def = s.defensiveKillRate ?? DEFAULT_DEFENSIVE_KILL_RATE;
708
+ if (s.offensiveKillRate === undefined || s.defensiveKillRate === undefined)
709
+ warnings.push(`Kill rates missing from settings; assumed ${off}/${def} (offence/defence).`);
710
+ const neutralsIn = s.initialNeutralsInDistribution ?? DEFAULT_NEUTRALS_IN_DISTRIBUTION;
711
+ const neutralsOut = s.initialNonDistributionArmies ?? DEFAULT_NON_DISTRIBUTION_ARMIES;
712
+ const known = input.neutralArmies ?? new Map();
713
+ const missingIn = s.initialNeutralsInDistribution === undefined && pickable.some((t) => !known.has(t));
714
+ const missingOut = s.initialNonDistributionArmies === undefined &&
715
+ g.map.territories.some((t) => !pickSet.has(t.id) && !known.has(t.id));
716
+ if (missingIn)
717
+ warnings.push(`Neutral size of unpicked pickable territories missing from settings; assumed ${DEFAULT_NEUTRALS_IN_DISTRIBUTION}.`);
718
+ if (missingOut)
719
+ warnings.push(`Neutral size of territories outside the distribution missing from settings (and not on the board); assumed ${DEFAULT_NON_DISTRIBUTION_ARMIES}.`);
720
+ const luck = luckPercent(s.luckModifier);
721
+ if (luck > 0)
722
+ warnings.push(`Luck is ${luck}%: capture costs carry a margin and can still fail.`);
723
+ if (s.roundingMode !== undefined && s.roundingMode !== 'StraightRound')
724
+ warnings.push(`Capture costs assume straight rounding; this game uses ${s.roundingMode}.`);
725
+ if (s.localDeployments)
726
+ warnings.push('Local deployments are on: bonus income must be deployed inside its bonus, and the opening simulation deploys it only there.');
727
+ const guard = s.oneArmyStandsGuard === false ? 0 : 1;
728
+ const players = Number.isFinite(input.players) ? Math.max(1, Math.floor(input.players)) : 2;
729
+ const maxPicks = Math.max(0, Math.floor(input.maxPicks));
730
+ const limit = Math.max(0, Math.floor(input.territoryLimit));
731
+ const duel = players <= 2;
732
+ // A team game (C2): teammates are no threat; at most every other player.
733
+ const teamGame = input.team !== undefined;
734
+ const teammates = teamGame ? Math.min(players - 1, Math.max(0, Math.floor(input.team.teammates) || 0)) : 0;
735
+ const awardOrders = teamGame ? ['reversing', 'repeating'] : ['reversing'];
736
+ const entryWeight = duel ? ENTRY_WEIGHT_1V1 : ENTRY_WEIGHT;
737
+ const rates = { offensiveKillRate: off, defensiveKillRate: def, luckModifier: s.luckModifier };
738
+ // Per-territory capture cost.
739
+ const { armies, cost, lost } = territoryCosts(g, (t) => known.get(t) ?? (pickSet.has(t) ? neutralsIn : neutralsOut), rates);
740
+ // Attack hardness vs the standard kill rates, for defensibility.
741
+ const probe = armiesToTake(HARDNESS_PROBE, { offensiveKillRate: off, defensiveKillRate: def });
742
+ const standard = armiesToTake(HARDNESS_PROBE);
743
+ const hardness = probe === null ? 4 : Math.max(0.25, probe / standard);
744
+ /** The size a neutral starts at when nothing special is placed on it. */
745
+ const ordinary = (t) => (pickSet.has(t) ? neutralsIn : neutralsOut);
746
+ const { bonuses, bonusesOf, penalties, penaltiesOf } = bonusTables(g, entryWeight, hardness);
747
+ const ctx = {
748
+ g,
749
+ cost,
750
+ lost,
751
+ armies,
752
+ bonuses,
753
+ bonusesOf,
754
+ penalties,
755
+ penaltiesOf,
756
+ pickArmies,
757
+ guard,
758
+ baseIncome,
759
+ bonusArmyPer: s.bonusArmyPer ?? 0,
760
+ localDeployments: s.localDeployments === true,
761
+ off,
762
+ def,
763
+ twoOrders: luckFraction(s.luckModifier) === 0 && (s.roundingMode === undefined || s.roundingMode === 'StraightRound') && s.noSplit !== true,
764
+ pickCount: pickable.length,
765
+ opponentStarts: Math.max(0, players - 1 - teammates) * limit,
766
+ // A teammate's top picks are known teammate starts: only the rest may hide among the unknown ones.
767
+ teammateStarts: Math.max(0, teammates * limit - friendly.size),
768
+ friendly,
769
+ threats: new Map(),
770
+ };
771
+ // Who can reach a bonus (#166). From each pickable territory q, a lone stack: the starting
772
+ // armies on q, then each turn the base income is deployed on it and it may send everything
773
+ // but the guard into one neighbour whose capture cost that covers, arriving with what it
774
+ // sent less the armies lost. Every other territory is a neutral at its size. `most` is the
775
+ // most armies the stack can have on a territory at the end of the turn — more is never worse
776
+ // — so the first turn a territory appears is the earliest it can be held.
777
+ const arrivalFrom = (q) => {
778
+ const arrival = new Map([[q, 0]]);
779
+ let most = new Map([[q, pickArmies]]);
780
+ for (let turn = 1; turn <= PICK_HORIZON; turn++) {
781
+ const next = new Map();
782
+ const put = (t, n) => {
783
+ if ((next.get(t) ?? -1) < n)
784
+ next.set(t, n);
785
+ };
786
+ for (const [from, n] of most) {
787
+ put(from, n + baseIncome);
788
+ const sent = n - guard + baseIncome;
789
+ for (const to of neighborsOf(g, from)) {
790
+ const c = cost.get(to);
791
+ if (to === q || c === null || c === undefined || sent < c)
792
+ continue;
793
+ put(to, sent - lost.get(to));
794
+ if (!arrival.has(to))
795
+ arrival.set(to, turn);
796
+ }
797
+ }
798
+ most = next;
799
+ }
800
+ return arrival;
801
+ };
802
+ // A bonus is reached through its zone: its territories (holding one denies it) and the
803
+ // territories next to them (standing there means an attack the turn after).
804
+ const zoneOf = new Map();
805
+ for (const b of bonuses.values()) {
806
+ const zone = new Set(b.members);
807
+ for (const m of b.members)
808
+ for (const n of neighborsOf(g, m))
809
+ zone.add(n);
810
+ for (const t of zone)
811
+ zoneOf.set(t, [...(zoneOf.get(t) ?? []), b.id]);
812
+ }
813
+ /** Bonus id → pickable territory → the earliest turn-end its stack is in the bonus's zone. */
814
+ const reach = new Map();
815
+ for (const q of pickable)
816
+ for (const [t, turn] of arrivalFrom(q))
817
+ for (const id of zoneOf.get(t) ?? []) {
818
+ let by = reach.get(id);
819
+ if (!by)
820
+ reach.set(id, (by = new Map()));
821
+ const known = by.get(q);
822
+ if (known === undefined || turn < known)
823
+ by.set(q, turn);
824
+ }
825
+ // Per bonus and completion turn, once: `simulate` only filters these (it runs very many times).
826
+ for (const [id, by] of reach)
827
+ ctx.threats.set(id, Array.from({ length: PICK_HORIZON + 1 }, (_, turn) => [...by].filter(([, at]) => at <= turn).map(([q]) => q)));
828
+ // Contestedness from centrality among the pickables.
829
+ const contestWeight = Math.min(CONTEST_MAX, Math.max(0, (players - 2) * CONTEST_PER_PLAYER));
830
+ const meanDist = new Map();
831
+ for (const t of pickable) {
832
+ const d = bfsDistances(g, [t]);
833
+ let sum = 0;
834
+ let count = 0;
835
+ for (const o of pickable) {
836
+ if (o === t || !d.has(o))
837
+ continue;
838
+ sum += d.get(o);
839
+ count++;
840
+ }
841
+ if (count)
842
+ meanDist.set(t, sum / count);
843
+ }
844
+ const means = [...meanDist.values()];
845
+ const lo = Math.min(...means);
846
+ const hi = Math.max(...means);
847
+ const centrality = (t) => {
848
+ const m = meanDist.get(t);
849
+ return m === undefined || hi === lo ? 0 : (hi - m) / (hi - lo);
850
+ };
851
+ const contestFactor = (t) => 1 - contestWeight * centrality(t);
852
+ const terrName = (id) => g.territoryById.get(id)?.name ?? String(id);
853
+ /** "3 entry points, 1 a double border (T7 touches 2 of its territories)"; three named at most. */
854
+ const entriesText = (b) => {
855
+ const entries = `${b.entryPoints} entry point${b.entryPoints === 1 ? '' : 's'}`;
856
+ const doubles = b.doubleBorders;
857
+ if (!doubles.length)
858
+ return entries;
859
+ const shown = doubles
860
+ .slice(0, MAX_NAMED)
861
+ .map((d, i) => `${terrName(d.territoryId)} touches ${d.touches}${i === 0 ? ' of its territories' : ''}`);
862
+ const more = doubles.length > MAX_NAMED ? ` and ${doubles.length - MAX_NAMED} more` : '';
863
+ return `${entries}, ${doubles.length === 1 ? '1 a double border' : `${doubles.length} double borders`} (${shown.join(', ')}${more})`;
864
+ };
865
+ /** "A", "A and B", "A, B and C", then "A, B, C and n more". */
866
+ const namesOf = (ids) => {
867
+ const names = ids.slice(0, MAX_NAMED).map(terrName);
868
+ if (ids.length > MAX_NAMED)
869
+ return `${names.join(', ')} and ${ids.length - MAX_NAMED} more`;
870
+ return names.length > 1 ? `${names.slice(0, -1).join(', ')} and ${names.at(-1)}` : (names[0] ?? '');
871
+ };
872
+ /** Who can reach a bonus completed on `turn`, and what that costs its credit (#166). */
873
+ const threatText = (threats, p, turn, taken) => {
874
+ const by = `by turn ${turn + 1}`;
875
+ if (!threats.length)
876
+ return `no other pickable territory can reach it ${by}`;
877
+ const pct = Math.round(THREAT_LOSS * p * 100);
878
+ const cost = pct >= 1 ? `score −${pct}%` : 'score down by less than 1%';
879
+ const known = threats.filter((q) => taken.has(q));
880
+ if (known.length)
881
+ return `${namesOf(known)} (another player's when this pick is granted) can reach it ${by} (${cost})`;
882
+ if (p <= 0)
883
+ return `no other player's start can reach it ${by}`;
884
+ return (`${namesOf(threats)} can reach it ${by} (${cost})` +
885
+ (threats.length <= 2 ? `, safe only if you also hold ${namesOf(threats)}` : ''));
886
+ };
887
+ const assess = (t, taken) => {
888
+ const sim = simulate(ctx, [t], taken);
889
+ const factor = contestFactor(t);
890
+ const lines = [];
891
+ const touched = [...new Set([...sim.completions.keys(), ...sim.progress.keys()])].sort(byNum);
892
+ for (const id of touched) {
893
+ const b = bonuses.get(id);
894
+ const turn = sim.completions.get(id);
895
+ const head = `${b.name} (+${b.value})`;
896
+ const entries = entriesText(b);
897
+ const negatives = [];
898
+ let point;
899
+ let worth;
900
+ if (turn !== undefined) {
901
+ const when = turn === 0
902
+ ? 'held at once (single-territory bonus)'
903
+ : turn === 1
904
+ ? 'first-turn bonus (complete on turn 1)'
905
+ : `complete on turn ${turn}`;
906
+ const p = sim.risk.get(id) ?? 0;
907
+ const reached = threatText(sim.threats.get(id) ?? NO_THREATS, p, turn, taken);
908
+ point = `${head}: ${when}, +${b.value} income from turn ${turn + 1}; ${entries}; ${reached}`;
909
+ worth = b.value * (PICK_HORIZON + 1 - turn) * (1 - THREAT_LOSS * p);
910
+ }
911
+ else {
912
+ const share = sim.progress.get(id);
913
+ const have = Math.round(share * b.members.length);
914
+ // The pick itself is held; the rest are captured. A member that cannot be
915
+ // taken at these kill rates makes the bonus unreachable, not cheaper.
916
+ const rest = b.members.filter((m) => m !== t).map((m) => cost.get(m));
917
+ const left = rest.some((c) => c === null || c === undefined)
918
+ ? 'a member cannot be taken at these kill rates'
919
+ : `~${rest.reduce((acc, c) => acc + c, 0)} armies to take all of it from this pick`;
920
+ point = `${head}: ${have} of ${b.members.length} territories by turn ${PICK_HORIZON}, ${left}; ${entries}`;
921
+ negatives.push(`${head}: not complete within ${PICK_HORIZON} turns`);
922
+ worth = PROGRESS_WEIGHT * b.value * share;
923
+ }
924
+ worth *= b.defense;
925
+ // A wasteland is a member other than the pick standing larger than an ordinary neutral
926
+ // (#129: the pick itself, at the 4-army distribution size, was called one).
927
+ const waste = b.members.filter((m) => m !== t && !taken.has(m) && armies.get(m) > ordinary(m)).sort(byNum);
928
+ if (waste.length)
929
+ negatives.push(`${head} holds a wasteland: ${waste.map((m) => `${terrName(m)} (${armies.get(m)} armies)`).join(', ')}`);
930
+ lines.push({ id, worth, head, point, negatives });
931
+ }
932
+ lines.sort((a, b) => b.worth - a.worth || a.id - b.id);
933
+ // Captures that take two orders (#166), each under the first bonus listed that holds it.
934
+ const twice = sim.twoOrders.map((c) => {
935
+ const [first, second] = c.orders;
936
+ const of = lines.find((l) => bonuses.get(l.id).members.includes(c.territoryId));
937
+ const armies = `${first.armies} arm${first.armies === 1 ? 'y' : 'ies'}`;
938
+ const how = first.from === second.from
939
+ ? `${armies} first, then ${second.armies}`
940
+ : `${armies} from ${terrName(first.from)} first, then ${second.armies} from ${terrName(second.from)}`;
941
+ return `${of ? `${of.head} needs` : 'Needs'} two orders on ${terrName(c.territoryId)}: ${how}`;
942
+ });
943
+ // Negative bonuses held in full: a cost, listed with the negatives (#129).
944
+ const charged = [...sim.penalties.entries()]
945
+ .sort((a, b) => a[1] - b[1] || a[0] - b[0])
946
+ .map(([id, turn]) => {
947
+ const n = penalties.get(id);
948
+ const head = `${n.name} (−${-n.value})`;
949
+ return turn === 0
950
+ ? `${head}: a negative bonus held at once, −${-n.value} income from turn 1`
951
+ : `${head}: a negative bonus completed on turn ${turn}, −${-n.value} income from turn ${turn + 1}`;
952
+ });
953
+ const why = [];
954
+ const anchor = lines[0];
955
+ if (anchor) {
956
+ const verb = sim.completions.has(anchor.id) ? 'Anchors' : 'Advances';
957
+ why.push(`${verb} ${anchor.point}`);
958
+ for (const l of lines.slice(1))
959
+ why.push(`Also ${sim.completions.has(l.id) ? 'completes' : 'advances'} ${l.point}`);
960
+ why.push(...twice);
961
+ for (const l of lines)
962
+ why.push(...l.negatives);
963
+ }
964
+ else
965
+ why.push(`No bonus within reach in ${PICK_HORIZON} turns`);
966
+ why.push(...charged);
967
+ if (contestWeight > 0 && 1 - factor >= 0.05)
968
+ why.push(`Central: likely contested with ${players} players (score −${Math.round((1 - factor) * 100)}%)`);
969
+ return { score: round2(sim.score * factor), reasons: why, anchor: anchor?.id ?? null, completions: sim.completions };
970
+ };
971
+ const viewOf = (pool, taken) => ({
972
+ taken,
973
+ of: new Map(pool.map((t) => [t, assess(t, taken)])),
974
+ });
975
+ const firstView = viewOf(pickable, NO_TAKEN);
976
+ // Hop distances on the map graph (the one warapp_plan_route uses), cached per territory.
977
+ const bfsCache = new Map();
978
+ const hops = (a, b) => {
979
+ if (!bfsCache.has(a))
980
+ bfsCache.set(a, bfsDistances(g, [a]));
981
+ return bfsCache.get(a).get(b) ?? Infinity;
982
+ };
983
+ // Groups. A pick joins a group when it lies within `hop` hops of a pick already in it
984
+ // (hop starts at COMPACT_DISTANCE) — or, with `spread: true` in a 1v1, when it anchors a
985
+ // bonus no group pick anchors and lies within max(SPREAD_DISTANCE, hop) hops. Every seed
986
+ // (the MAX_SEEDS best) grows a group and the best-scoring one wins (#129); when no seed grows
987
+ // a full group, hop relaxes by one and the search repeats.
988
+ const spread = duel && input.spread === true;
989
+ const tryGroup = (view, pool, size, seed, hop) => {
990
+ const score = (t) => view.of.get(t).score;
991
+ const group = [seed];
992
+ const left = new Set(pool.filter((t) => t !== seed));
993
+ let current = simulate(ctx, group, view.taken).score;
994
+ const distTo = (c) => Math.min(...group.map((x) => hops(x, c)));
995
+ while (group.length < size) {
996
+ const anchored = new Set(group.map((t) => view.of.get(t).anchor));
997
+ const eligible = [...left].sort(byNum).filter((c) => {
998
+ const d = distTo(c);
999
+ if (d <= hop)
1000
+ return true;
1001
+ const a = view.of.get(c).anchor;
1002
+ return spread && a != null && !anchored.has(a) && d <= Math.max(SPREAD_DISTANCE, hop);
1003
+ });
1004
+ if (!eligible.length)
1005
+ return null;
1006
+ let best = null;
1007
+ for (const c of eligible) {
1008
+ const total = simulate(ctx, [...group, c], view.taken).score;
1009
+ const gain = round2((total - current) * contestFactor(c));
1010
+ if (!best ||
1011
+ gain > best.gain ||
1012
+ (gain === best.gain && (score(c) > score(best.t) || (score(c) === score(best.t) && c < best.t))))
1013
+ best = { t: c, gain, total };
1014
+ }
1015
+ group.push(best.t);
1016
+ left.delete(best.t);
1017
+ current = best.total;
1018
+ }
1019
+ return group;
1020
+ };
1021
+ const relaxedTo = new Map();
1022
+ /** Fewest hops between a pick of `ids` and one of `away` (the gap between two groups). */
1023
+ const gapTo = (ids, away) => Math.min(...ids.flatMap((a) => away.map((b) => hops(a, b))));
1024
+ // The best-scoring group any seed grows at this hop limit (ties: the better seed). With
1025
+ // `away` (a 1v1 fallback), among the groups scoring as much as the best, the one farthest
1026
+ // from `away` wins.
1027
+ const bestGroup = (view, pool, size, seeds, hop, away = []) => {
1028
+ const groupScore = (ids) => round2(simulate(ctx, ids, view.taken).score);
1029
+ let best = null;
1030
+ let bestScore = -Infinity;
1031
+ let bestGap = -Infinity;
1032
+ for (const seed of seeds.slice(0, MAX_SEEDS)) {
1033
+ const group = tryGroup(view, pool, size, seed, hop);
1034
+ if (!group)
1035
+ continue;
1036
+ const sc = groupScore(group);
1037
+ const gap = away.length ? gapTo(group, away) : 0;
1038
+ if (sc > bestScore || (sc === bestScore && gap > bestGap)) {
1039
+ best = group;
1040
+ bestScore = sc;
1041
+ bestGap = gap;
1042
+ }
1043
+ }
1044
+ // None of the best seeds grows a group at this hop limit: try the rest, first that grows,
1045
+ // before the caller relaxes the limit (as the single-seed search did; #143).
1046
+ if (!best)
1047
+ for (const seed of seeds.slice(MAX_SEEDS)) {
1048
+ const group = tryGroup(view, pool, size, seed, hop);
1049
+ if (group)
1050
+ return group;
1051
+ }
1052
+ return best;
1053
+ };
1054
+ const buildGroup = (view, pool, size, label, away = [], notes = { warnings, relaxedTo }) => {
1055
+ if (size <= 0 || !pool.length)
1056
+ return [];
1057
+ const score = (t) => view.of.get(t).score;
1058
+ const byScore = (a, b) => score(b) - score(a) || a - b;
1059
+ const groupScore = (ids) => simulate(ctx, ids, view.taken).score;
1060
+ const seeds = [...pool].sort(byScore);
1061
+ if (size === 1) {
1062
+ if (!away.length)
1063
+ return [seeds[0]];
1064
+ // In a 1v1, the farthest from the primary among the equally scored best.
1065
+ const top = seeds.filter((t) => round2(score(t)) === round2(score(seeds[0])));
1066
+ let pick = top[0];
1067
+ for (const t of top)
1068
+ if (gapTo([t], away) > gapTo([pick], away))
1069
+ pick = t;
1070
+ return [pick];
1071
+ }
1072
+ let widest = 0;
1073
+ for (const a of pool)
1074
+ for (const b of pool)
1075
+ if (a < b && hops(a, b) < Infinity)
1076
+ widest = Math.max(widest, hops(a, b));
1077
+ for (let hop = COMPACT_DISTANCE;; hop++) {
1078
+ // Past every connected distance (and never at the compact limit itself): the
1079
+ // last try allows any distance, so it is a recorded relaxation, not "compact".
1080
+ const last = hop > Math.max(widest, COMPACT_DISTANCE);
1081
+ const group = bestGroup(view, pool, size, seeds, last ? Infinity : hop, away);
1082
+ if (!group) {
1083
+ if (last)
1084
+ return seeds.slice(0, size).sort(byScore);
1085
+ continue;
1086
+ }
1087
+ if (hop > COMPACT_DISTANCE) {
1088
+ notes.relaxedTo.set(label, last ? Infinity : hop);
1089
+ notes.warnings.push(`No compact ${label} group of ${size} picks (each within ${COMPACT_DISTANCE} hops of another) exists among the pickable territories; ` +
1090
+ (last ? 'relaxed until every pick could join (some are not connected).' : `relaxed to within ${hop} hops.`));
1091
+ }
1092
+ // With `spread: true` in a 1v1 the hop bound must not quietly hand a far better group
1093
+ // to the fallback: spread past it when that scores SPREAD_RELAX_GAIN times as much, at
1094
+ // the smallest hop limit that does.
1095
+ const bound = Math.max(hop, SPREAD_DISTANCE);
1096
+ if (spread && !last && bound < widest) {
1097
+ const bounded = groupScore(group);
1098
+ const better = (g2) => {
1099
+ const sc = g2 ? groupScore(g2) : -Infinity;
1100
+ return sc > bounded && sc >= SPREAD_RELAX_GAIN * bounded ? sc : null;
1101
+ };
1102
+ if (better(bestGroup(view, pool, size, seeds, Infinity)) !== null) {
1103
+ for (let h = bound + 1; h <= widest + 1; h++) {
1104
+ const limit = h > widest ? Infinity : h;
1105
+ const wide = bestGroup(view, pool, size, seeds, limit);
1106
+ const sc = better(wide);
1107
+ if (sc === null)
1108
+ continue;
1109
+ notes.relaxedTo.set(label, limit);
1110
+ const within = Number.isFinite(limit) ? `within ${limit} hops` : 'any distance';
1111
+ notes.warnings.push(`In a 1v1 the best ${label} group within ${bound} hops scores ${round2(bounded)}, but one spread to ${within} scores ${round2(sc)} ` +
1112
+ `(at least ${SPREAD_RELAX_GAIN}× as much): the ${label} group spreads to ${within}, so its picks can support each other less.`);
1113
+ return wide.sort(byScore);
1114
+ }
1115
+ }
1116
+ }
1117
+ return group.sort(byScore);
1118
+ }
1119
+ };
1120
+ const primarySize = Math.min(limit, maxPicks, pickable.length);
1121
+ if (pickable.length < limit)
1122
+ warnings.push(`Only ${pickable.length} pickable territor${pickable.length === 1 ? 'y' : 'ies'} for a limit of ${limit}: the list has no full fallback.`);
1123
+ const primary = buildGroup(firstView, pickable, primarySize, 'primary');
1124
+ const rest = pickable.filter((t) => !primary.includes(t));
1125
+ // Commanders (#129): the first pick awarded carries the commander, so the primary's safest
1126
+ // pick goes first — the fewest other pickable territories (where other players may start)
1127
+ // within COMPACT_DISTANCE hops, then the fewest neighbours outside the primary, then score.
1128
+ let commanderPick = null;
1129
+ let commanderExposure = 0;
1130
+ /** Of `ids`, the pick safest to carry the commander: fewest other pickables within reach, then fewest outside neighbours, then score. */
1131
+ const safestOf = (ids) => {
1132
+ const inSet = new Set(ids);
1133
+ const exposure = (t) => pickable.filter((o) => !inSet.has(o) && hops(t, o) <= COMPACT_DISTANCE).length;
1134
+ const open = (t) => neighborsOf(g, t).filter((n) => !inSet.has(n)).length;
1135
+ const score = (t) => firstView.of.get(t).score;
1136
+ const pick = [...ids].sort((a, b) => exposure(a) - exposure(b) || open(a) - open(b) || score(b) - score(a) || a - b)[0];
1137
+ return { pick, exposure: exposure(pick) };
1138
+ };
1139
+ if (s.commanders && primary.length) {
1140
+ ({ pick: commanderPick, exposure: commanderExposure } = safestOf(primary));
1141
+ primary.splice(0, primary.length, commanderPick, ...primary.filter((t) => t !== commanderPick));
1142
+ }
1143
+ /** The joint opening's score from `start` with `taken` held by someone else, remembered. */
1144
+ const simScores = new Map();
1145
+ const simScore = (start, taken) => {
1146
+ const key = `${[...start].sort(byNum).join(',')}|${[...taken].sort(byNum).join(',')}`;
1147
+ let sc = simScores.get(key);
1148
+ if (sc === undefined)
1149
+ simScores.set(key, (sc = simulate(ctx, start, new Set(taken)).score));
1150
+ return sc;
1151
+ };
1152
+ // The fallback is granted only when someone else holds primary picks: it is scored, and
1153
+ // its reasons written, with the primary taken (#129). A list longer than twice the limit
1154
+ // (war.app's client allows players × territories per player) is a series of tiers, each a
1155
+ // group of the primary's size scored with the primary and the earlier tiers taken.
1156
+ const fallbackSize = Math.max(0, Math.min(maxPicks - primary.length, rest.length));
1157
+ const tierSize = Math.max(1, primary.length);
1158
+ // In a two-player game with 2 to 4 picks each (#166) the first tier is not a second group:
1159
+ // each of its picks answers the loss that grants it. `answerSets` are the sets of list
1160
+ // positions the award can grant from a list of twice the primary; null: the tier rule stands.
1161
+ const answerSets = players === 2 && !spread && primary.length >= 2 && primary.length <= 4 && fallbackSize >= primary.length
1162
+ ? pickOutcomes({ listLength: 2 * primary.length, perPlayer: primary.length, players })
1163
+ : null;
1164
+ // Positions primary + 1 … 2 × primary, one at a time. A pick at position p is granted exactly
1165
+ // in the outcomes whose last granted position is p, and each of those is settled by the list
1166
+ // so far plus the candidate: I hold the granted set G, the opponent the picks above p that I
1167
+ // was not granted, K. The candidate is worth my opening from G with K the opponent's, less
1168
+ // OPPONENT_WEIGHT × the opponent's from K with G mine — so standing where a lost pick's bonus
1169
+ // can be reached counts (a known threat halves its credit), and so does its own bonus. The
1170
+ // best mean over those outcomes wins; ties: its own score with the primary taken, then id.
1171
+ const answerTier = (order, view, others = rest) => {
1172
+ const n = order.length;
1173
+ const list = [...order];
1174
+ for (let p = n; p < 2 * n; p++) {
1175
+ const sets = answerSets
1176
+ .filter((o) => o[o.length - 1] === p)
1177
+ .map((o) => {
1178
+ const kept = o.slice(0, -1).map((i) => list[i]);
1179
+ const lost = list.filter((_, i) => !o.includes(i));
1180
+ // Most candidates stand nowhere the opponent's opening looks: for those it is the
1181
+ // same opening, simulated once with one more start of mine known.
1182
+ const apart = simulate(ctx, lost, new Set(kept), kept.length + 1);
1183
+ return { kept, lost, apart: apart.score, read: territoriesRead(ctx, apart) };
1184
+ });
1185
+ let best = null;
1186
+ for (const c of others) {
1187
+ if (list.includes(c))
1188
+ continue;
1189
+ const own = view.of.get(c).score;
1190
+ // No outcome ends at p: the candidate's own score with the primary taken decides.
1191
+ let value = own;
1192
+ if (sets.length) {
1193
+ let sum = 0;
1194
+ for (const o of sets) {
1195
+ const granted = [...o.kept, c];
1196
+ const theirs = o.read.has(c) ? simScore(o.lost, granted) : o.apart;
1197
+ sum += simScore(granted, o.lost) - OPPONENT_WEIGHT * theirs;
1198
+ }
1199
+ value = round2(sum / sets.length);
1200
+ }
1201
+ if (!best || value > best.value || (value === best.value && own > best.own))
1202
+ best = { t: c, value, own };
1203
+ }
1204
+ if (!best)
1205
+ break;
1206
+ list.push(best.t);
1207
+ }
1208
+ return list.slice(n);
1209
+ };
1210
+ const buildFallback = (order, others = rest) => {
1211
+ const out = {
1212
+ tiers: [],
1213
+ views: new Map(order.map((t) => [t, firstView])),
1214
+ firstView: viewOf([], new Set(order)),
1215
+ warnings: [],
1216
+ relaxedTo: new Map(),
1217
+ };
1218
+ let pool = [...others];
1219
+ let done = 0;
1220
+ const add = (tier, view) => {
1221
+ for (const t of tier)
1222
+ out.views.set(t, view);
1223
+ out.tiers.push(tier);
1224
+ done += tier.length;
1225
+ pool = pool.filter((t) => !tier.includes(t));
1226
+ };
1227
+ if (answerSets) {
1228
+ out.firstView = viewOf(pool, new Set(order));
1229
+ add(answerTier(order, out.firstView, others), out.firstView);
1230
+ }
1231
+ while (done < fallbackSize && pool.length) {
1232
+ const view = viewOf(pool, new Set([...order, ...out.tiers.flat()]));
1233
+ if (!out.tiers.length)
1234
+ out.firstView = view;
1235
+ // In a 1v1 (unless spreading) a first tier built as a group is counter-pick insurance: in another area.
1236
+ const tier = buildGroup(view, pool, Math.min(tierSize, fallbackSize - done), out.tiers.length ? `fallback tier ${out.tiers.length + 1}` : 'fallback', !out.tiers.length && duel && !spread ? [...order] : [], out);
1237
+ if (!tier.length)
1238
+ break;
1239
+ add(tier, view);
1240
+ }
1241
+ return out;
1242
+ };
1243
+ let listed = buildFallback(primary);
1244
+ /** Farthest pair (hops) and the longest step that links the picks into one cluster. */
1245
+ const spreadOf = (ids) => {
1246
+ let far = 0;
1247
+ let pair = null;
1248
+ for (const a of ids)
1249
+ for (const b of ids) {
1250
+ if (a >= b)
1251
+ continue;
1252
+ const d = hops(a, b);
1253
+ if (pair === null || d > far) {
1254
+ far = d;
1255
+ pair = [a, b];
1256
+ }
1257
+ }
1258
+ // The longest step needed to link every pick into one cluster (minimax spanning tree).
1259
+ let link = 0;
1260
+ if (ids.length > 1) {
1261
+ const inTree = new Set([ids[0]]);
1262
+ while (inTree.size < ids.length) {
1263
+ let step = Infinity;
1264
+ let next = -1;
1265
+ for (const a of ids) {
1266
+ if (inTree.has(a))
1267
+ continue;
1268
+ for (const b of inTree) {
1269
+ const d = hops(a, b);
1270
+ if (next < 0 || d < step) {
1271
+ step = d;
1272
+ next = a;
1273
+ }
1274
+ }
1275
+ }
1276
+ inTree.add(next);
1277
+ link = Math.max(link, step);
1278
+ }
1279
+ }
1280
+ return { far, pair, link };
1281
+ };
1282
+ const groupOf = (ids, taken) => {
1283
+ if (!ids.length)
1284
+ return { territoryIds: [], score: 0, bonuses: [], twoOrderCaptures: [], maxHops: 0 };
1285
+ const sim = simulate(ctx, ids, taken);
1286
+ const done = [...sim.completions.entries()]
1287
+ .map(([id, turn]) => ({
1288
+ bonusId: id,
1289
+ name: bonuses.get(id).name,
1290
+ value: bonuses.get(id).value,
1291
+ turn,
1292
+ threats: [...(sim.threats.get(id) ?? [])],
1293
+ }))
1294
+ .sort((a, b) => a.turn - b.turn || a.bonusId - b.bonusId);
1295
+ const far = spreadOf(ids).far;
1296
+ return {
1297
+ territoryIds: ids,
1298
+ score: round2(sim.score),
1299
+ bonuses: done,
1300
+ twoOrderCaptures: sim.twoOrders,
1301
+ maxHops: Number.isFinite(far) ? far : null,
1302
+ };
1303
+ };
1304
+ // The award order (#129): a list is judged by the sets it can actually yield. The worst
1305
+ // outcome is scored with the other players holding the picks it implies they took; the
1306
+ // primary's order is changed only when another order raises that worst outcome.
1307
+ const outcomeScore = (list, ids) => round2(simScore(ids, impliedOpponentStarts(list, ids)));
1308
+ const worstOf = (list, sets) => {
1309
+ let worst = null;
1310
+ for (const set of sets) {
1311
+ const ids = set.map((i) => list[i]);
1312
+ const sc = outcomeScore(list, ids);
1313
+ if (!worst || sc < worst.score)
1314
+ worst = { territoryIds: ids, score: sc };
1315
+ }
1316
+ return worst;
1317
+ };
1318
+ const outcomeSets = primary.length > 0
1319
+ ? pickOutcomes({ listLength: primary.length + listed.tiers.flat().length, perPlayer: primary.length, players, orders: awardOrders })
1320
+ : null;
1321
+ let award;
1322
+ if (outcomeSets?.length) {
1323
+ const base = [...primary];
1324
+ const baseWorst = worstOf([...base, ...listed.tiers.flat()], outcomeSets);
1325
+ let bestOrder = base;
1326
+ let bestWorst = baseWorst;
1327
+ if (primary.length <= MAX_REORDER) {
1328
+ const orders = commanderPick === null ? permutations(base) : permutations(base.slice(1)).map((rest) => [commanderPick, ...rest]);
1329
+ for (const order of orders) {
1330
+ const w = worstOf([...order, ...listed.tiers.flat()], outcomeSets);
1331
+ if (w.score > bestWorst.score) {
1332
+ bestOrder = order;
1333
+ bestWorst = w;
1334
+ }
1335
+ }
1336
+ }
1337
+ if (bestOrder !== base && answerSets) {
1338
+ // An answering fallback (#166) depends on the primary's order: it is built again for the
1339
+ // new one, and the new order stands only if the list as it then reads still has a better
1340
+ // worst outcome than the list it replaces.
1341
+ const again = buildFallback(bestOrder);
1342
+ const w = worstOf([...bestOrder, ...again.tiers.flat()], outcomeSets);
1343
+ if (w.score > baseWorst.score) {
1344
+ listed = again;
1345
+ bestWorst = w;
1346
+ }
1347
+ else {
1348
+ bestOrder = base;
1349
+ bestWorst = baseWorst;
1350
+ }
1351
+ }
1352
+ const reordered = bestOrder !== base;
1353
+ primary.splice(0, primary.length, ...bestOrder);
1354
+ award = {
1355
+ outcomes: outcomeSets.length,
1356
+ ...(teamGame ? { orders: awardOrders } : {}),
1357
+ worst: { ...bestWorst, opponentStarts: impliedOpponentStarts([...primary, ...listed.tiers.flat()], bestWorst.territoryIds) },
1358
+ reordered,
1359
+ };
1360
+ }
1361
+ const { tiers } = listed;
1362
+ const fallback = tiers.flat();
1363
+ const firstTier = tiers[0] ?? [];
1364
+ const firstFallbackView = listed.firstView;
1365
+ const viewFor = (t) => listed.views.get(t);
1366
+ warnings.push(...listed.warnings);
1367
+ for (const [label, hop] of listed.relaxedTo)
1368
+ relaxedTo.set(label, hop);
1369
+ // What each pick of an answering fallback answers (#166): the picks lost in the outcomes that
1370
+ // grant it whose own bonus (one the lost pick completes alone, by that turn) it reaches in
1371
+ // time. One bonus is named per lost pick — the one worth most to it — and the rest counted.
1372
+ const answers = new Map();
1373
+ if (answerSets) {
1374
+ const list = [...primary, ...firstTier];
1375
+ for (let p = primary.length; p < list.length; p++) {
1376
+ const lost = new Set();
1377
+ for (const o of answerSets)
1378
+ if (o[o.length - 1] === p)
1379
+ for (let i = 0; i < p; i++)
1380
+ if (!o.includes(i))
1381
+ lost.add(i);
1382
+ const parts = [];
1383
+ for (const i of [...lost].sort(byNum)) {
1384
+ const credit = (id, turn) => bonuses.get(id).value * (PICK_HORIZON + 1 - turn);
1385
+ const reached = [...firstView.of.get(list[i]).completions]
1386
+ .map(([id, turn]) => ({ id, turn, at: reach.get(id)?.get(list[p]) }))
1387
+ .filter((b) => b.at !== undefined && b.at <= b.turn)
1388
+ .sort((a, b) => credit(b.id, b.turn) - credit(a.id, a.turn) || a.id - b.id);
1389
+ const top = reached[0];
1390
+ if (!top)
1391
+ continue;
1392
+ const more = reached.length - 1;
1393
+ parts.push(`${terrName(list[i])}: reaches ${bonuses.get(top.id).name} by turn ${top.at + 1}` +
1394
+ (more ? ` (and ${more} more of its bonuses)` : ''));
1395
+ }
1396
+ if (parts.length)
1397
+ answers.set(list[p], `Answers the loss of ${parts.join('; of ')}`);
1398
+ }
1399
+ }
1400
+ const pickOf = (t) => {
1401
+ const a = viewFor(t).of.get(t);
1402
+ const commander = t === commanderPick
1403
+ ? [
1404
+ `Commander: listed first, so the commander most likely starts here — the primary's safest pick ` +
1405
+ `(${commanderExposure} other pickable territor${commanderExposure === 1 ? 'y' : 'ies'} within ${COMPACT_DISTANCE} hops)`,
1406
+ ]
1407
+ : [];
1408
+ const answer = answers.get(t);
1409
+ return { score: a.score, reasons: [...a.reasons, ...(answer ? [answer] : []), ...commander] };
1410
+ };
1411
+ const picks = [
1412
+ ...primary.map((t) => ({ territoryId: t, group: 'primary', ...pickOf(t) })),
1413
+ ...fallback.map((t) => ({ territoryId: t, group: 'fallback', ...pickOf(t) })),
1414
+ ];
1415
+ const hopsText = (n) => (Number.isFinite(n) ? `${n} hop${n === 1 ? '' : 's'}` : 'unconnected');
1416
+ // Compact means one cluster whose picks link up in steps of at most COMPACT_DISTANCE
1417
+ // hops — not merely each pick having a group-mate that close (two tight pairs far
1418
+ // apart pass that test).
1419
+ const describe = (ids) => {
1420
+ if (ids.length < 2)
1421
+ return 'a single pick';
1422
+ const { far, pair, link } = spreadOf(ids);
1423
+ const names = `${terrName(pair[0])} and ${terrName(pair[1])}`;
1424
+ const between = Number.isFinite(far) ? `the farthest two ${hopsText(far)} apart (${names})` : `${names} not connected`;
1425
+ if (link <= COMPACT_DISTANCE)
1426
+ return `compact: one cluster, each pick within ${COMPACT_DISTANCE} hops of another, ${between}`;
1427
+ if (!Number.isFinite(link))
1428
+ return `spread: some picks are not connected to the others, ${between}`;
1429
+ return `spread: its picks link up only in steps of up to ${hopsText(link)}, ${between}`;
1430
+ };
1431
+ const relaxed = relaxedTo.size > 0;
1432
+ rationale.push(`Each pick is scored by the bonus armies it earns through turn ${PICK_HORIZON + 1} in a ${PICK_HORIZON}-turn opening simulation: ` +
1433
+ `${pickArmies} starting armies, ${baseIncome} base income${ctx.bonusArmyPer > 0 ? ` (or 1 per ${ctx.bonusArmyPer} territories when more)` : ''}, ` +
1434
+ `capture costs at ${off}/${def} kill rates against the neutrals' real sizes; ` +
1435
+ `armies attack only from a territory held at the start of the turn that borders the target, topped up by that turn's deploys` +
1436
+ (ctx.twoOrders ? '; a neutral no single order can pay for may be taken in two, the first only wearing it down.' : '.'), `A pick's reasons are its opening alone (a fallback pick's with the primary taken); a group's bonuses are its picks' joint opening, so one bonus can complete on different turns in the two.`, `Bonuses are weighted by defensibility (fewer entry points is better, and one next to two of a bonus's territories counts twice${hardness > 1 ? '; attacks here are dearer than at 60/70, so this weighs more' : ''}), ` +
1437
+ `and a completed bonus by who can reach it: it loses up to ${Math.round(THREAT_LOSS * 100)}% of its credit with the chance that another player starts on a pickable territory ` +
1438
+ `whose armies can stand in or next to it by the turn it completes (their starts taken as equally likely on every pickable territory left).`, contestWeight > 0
1439
+ ? `With ${players} players central picks are likely contested: scores drop by up to ${Math.round(contestWeight * 100)}% with centrality, and ` +
1440
+ (relaxed
1441
+ ? `each group is kept as compact as the map allows (no group of the needed size forms one cluster with each pick within ${COMPACT_DISTANCE} hops of another, so the hop limit was relaxed; see the warnings).`
1442
+ : `each group is compact (one cluster, each pick within ${COMPACT_DISTANCE} hops of another).`)
1443
+ : spread
1444
+ ? `In a 1v1 centrality is not penalised and entry points weigh twice as much; with spread on, a pick may join a group within ${SPREAD_DISTANCE} hops when it anchors a different bonus, so one counter-pick cannot wipe them` +
1445
+ (relaxed ? `; a group spreads farther only when no bounded group exists or spreading scores ${SPREAD_RELAX_GAIN}× as much (see the warnings).` : '.')
1446
+ : `In a 1v1 centrality is not penalised and entry points weigh twice as much; ` +
1447
+ (answerSets
1448
+ ? (relaxedTo.has('primary')
1449
+ ? `the primary group is kept as compact as the map allows (the hop limit was relaxed; see the warnings), `
1450
+ : `the primary group is compact (one cluster, each pick within ${COMPACT_DISTANCE} hops of another), `) +
1451
+ `so the start has one front, not several; each fallback pick is chosen for the outcomes that grant it, in which the picks lost above it ` +
1452
+ `are the opponent's starts: its opening there, less ${OPPONENT_WEIGHT} × the opponent's from those starts.`
1453
+ : (relaxed
1454
+ ? `each group is kept as compact as the map allows (the hop limit was relaxed; see the warnings), `
1455
+ : `each group is compact (one cluster, each pick within ${COMPACT_DISTANCE} hops of another), `) +
1456
+ 'so the start has one front, not several; the fallback, in another area when one scores as much, is the insurance against a counter-pick.'), `The first ${primary.length} picks are the primary group, ${describe(primary)}; ` +
1457
+ `the rest are a disjoint fallback${firstTier.length ? ` (${describe(firstTier)})` : ''}, granted in order when another player picks first` +
1458
+ (tiers.length > 1
1459
+ ? `; it runs in ${tiers.length} tiers of up to ${tierSize}, each scored as if the picks before it were taken.`
1460
+ : '.'));
1461
+ // The fallback group's score, bonuses and spread are its first tier's: the picks granted
1462
+ // when the primary is taken.
1463
+ const groups = {
1464
+ primary: groupOf(primary, NO_TAKEN),
1465
+ fallback: { ...groupOf(firstTier, firstFallbackView.taken), territoryIds: fallback },
1466
+ };
1467
+ if (groups.fallback.score > groups.primary.score)
1468
+ warnings.push(`The fallback group scores more than the primary (${groups.fallback.score} vs ${groups.primary.score}): the primary keeps to ` +
1469
+ (players > 2
1470
+ ? `one compact cluster, since with ${players} players spread picks are likely contested.`
1471
+ : spread
1472
+ ? `within ${SPREAD_DISTANCE} hops unless spreading scores ${SPREAD_RELAX_GAIN}× as much.`
1473
+ : answerSets
1474
+ ? 'one compact cluster, so the start has one front; each fallback pick is listed for the outcomes in which a pick above it is lost.'
1475
+ : 'one compact cluster, so the start has one front; the fallback covers a counter-pick.') +
1476
+ ' Weigh the trade before submitting.');
1477
+ if (commanderPick !== null)
1478
+ rationale.push(`Commanders are on: the first pick awarded carries the commander, so the primary's safest pick (${terrName(commanderPick)}: ` +
1479
+ `fewest other pickable territories within ${COMPACT_DISTANCE} hops) is listed first; if another player takes it, the next pick awarded carries it.`);
1480
+ if (award) {
1481
+ const names = (ids) => ids.map(terrName).join(', ') || 'none of this list';
1482
+ rationale.push(`Picks are awarded round by round in move order, the award order reversing each round, each player getting their highest-ranked territory still free: ` +
1483
+ `this list can yield ${award.outcomes} different set${award.outcomes === 1 ? '' : 's'}. The worst (score ${award.worst.score}) is ${names(award.worst.territoryIds)}` +
1484
+ (award.worst.opponentStarts.length ? `, with other players starting on ${names(award.worst.opponentStarts)}` : '') +
1485
+ '.' +
1486
+ (award.reordered ? ' The primary is ordered to raise that worst outcome, not by score.' : ''));
1487
+ }
1488
+ else if (primary.length)
1489
+ rationale.push('Picks are awarded round by round in a reversing move order; this list has too many possible outcomes to enumerate.');
1490
+ if (teamGame)
1491
+ rationale.push(`A team game: ${players - 1 - teammates} opponent${players - 1 - teammates === 1 ? '' : 's'} and ${teammates} teammate${teammates === 1 ? '' : 's'}. ` +
1492
+ 'Only opponents threaten a bonus; a pick lost to another player is still taken as an opponent\'s start (it may be your teammate\'s), the worst case. ' +
1493
+ 'The award order of a team game is not settled (unverified): the list is judged by both a reversing and a repeating order, and the worst outcome of either is reported. ' +
1494
+ 'The list is as long as the client allows (starts × all players), since your list and your teammate\'s are not agreed: a pick you both list goes to one of you.');
1495
+ // The coverage-first alternative (#166): the primary is kept; this is offered beside it.
1496
+ const coverageOf = coverageModel({ graph: g, pickable, settings: s, neutralArmies: input.neutralArmies });
1497
+ const primaryCoverage = coverageOf(primary);
1498
+ let alternative;
1499
+ if (players === 2 && !spread && primary.length >= 2) {
1500
+ const score = (t) => firstView.of.get(t).score;
1501
+ const seeds = [...pickable].sort((a, b) => score(b) - score(a) || a - b);
1502
+ const pair = bestGroup(firstView, pickable, 2, seeds, COMPACT_DISTANCE);
1503
+ if (pair) {
1504
+ const alt = [...pair].sort((a, b) => score(b) - score(a) || a - b);
1505
+ while (alt.length < primary.length) {
1506
+ let best = null;
1507
+ for (const c of pickable) {
1508
+ if (alt.includes(c))
1509
+ continue;
1510
+ const covered = coverageOf([...alt, c]).covered;
1511
+ if (!best || covered > best.covered || (covered === best.covered && score(c) > score(best.t)))
1512
+ best = { t: c, covered };
1513
+ }
1514
+ if (!best)
1515
+ break;
1516
+ alt.push(best.t);
1517
+ }
1518
+ // With commanders the first pick awarded carries the commander: the alternative's safest goes first too.
1519
+ if (s.commanders) {
1520
+ const safe = safestOf(alt).pick;
1521
+ alt.splice(0, alt.length, safe, ...alt.filter((t) => t !== safe));
1522
+ }
1523
+ const altCoverage = coverageOf(alt);
1524
+ const same = alt.length === primary.length && alt.every((t) => primary.includes(t));
1525
+ if (!same && altCoverage.covered > primaryCoverage.covered) {
1526
+ const altFallback = buildFallback(alt, pickable.filter((t) => !alt.includes(t))).tiers.flat();
1527
+ alternative = {
1528
+ group: groupOf(alt, NO_TAKEN),
1529
+ coverage: altCoverage,
1530
+ fallback: altFallback,
1531
+ submitPicks: [...alt, ...altFallback],
1532
+ };
1533
+ const of = (c) => `${c.covered} of ${c.reasonable}`;
1534
+ rationale.push(`A coverage-first alternative (${alt.map(terrName).join(', ')}: a pair within ${COMPACT_DISTANCE} hops, then the picks that most widen ` +
1535
+ `the reach) can stand next to ${of(altCoverage)} reasonable bonuses within ${COVERAGE_DISTANCE} moves, against ${of(primaryCoverage)} ` +
1536
+ `for the primary, and scores ${alternative.group.score} against ${groups.primary.score}. Prefer the compact primary by default; ` +
1537
+ 'prefer the alternative on a small board when knowing where the opponent is and keeping a way into every region matter more than the fastest start.');
1538
+ }
1539
+ }
1540
+ }
1541
+ const plain = { ...ctx, friendly: NO_TAKEN };
1542
+ return {
1543
+ plan: {
1544
+ picks,
1545
+ groups,
1546
+ ...(award ? { award } : {}),
1547
+ coverage: primaryCoverage,
1548
+ ...(alternative ? { alternative } : {}),
1549
+ warnings,
1550
+ rationale,
1551
+ },
1552
+ completes: (start, taken) => new Set(simulate(plain, start, new Set(taken)).completions.keys()),
1553
+ bonuses,
1554
+ };
1555
+ }
1556
+ /**
1557
+ * Rank the pickable territories (the module header). In a team game with my teammates' lists read
1558
+ * (`team.lists`, C2), the plan is the split one — their top picks left to them, a bonus they pick into
1559
+ * not credited to me — with a {@link TeamPicksReport}; with none, or only empty ones, exactly as before.
1560
+ */
1561
+ export function planPicks(input) {
1562
+ const lists = input.team?.lists ?? [];
1563
+ if (!input.team || !lists.some((l) => l.length))
1564
+ return planCore(input).plan;
1565
+ return coordinate(input, input.team.teammates, lists);
1566
+ }
1567
+ function coordinate(input, teammateCount, rawLists) {
1568
+ const g = input.graph;
1569
+ const limit = Math.max(0, Math.floor(input.territoryLimit));
1570
+ const players = Number.isFinite(input.players) ? Math.max(1, Math.floor(input.players)) : 2;
1571
+ const teammates = Math.min(players - 1, Math.max(0, Math.floor(teammateCount) || 0));
1572
+ const onMap = (t) => g.territoryById.has(t);
1573
+ const pickables = new Set(input.pickable.filter(onMap));
1574
+ const lists = rawLists.map((l) => [...new Set(l.filter(onMap))]);
1575
+ const tops = lists.map((l) => l.filter((t) => pickables.has(t)).slice(0, limit));
1576
+ const friendly = [...new Set(tops.flat())].sort(byNum);
1577
+ const theirs = new Set(lists.flat());
1578
+ const listOf = (p) => p.picks.map((x) => x.territoryId);
1579
+ const disjoint = (l) => l.every((t) => !theirs.has(t));
1580
+ let core = planCore(input, friendly);
1581
+ // Starts × all players covers a pick we both list going to one of us; with the lists disjoint my
1582
+ // list needs only my starts and the opponents' (C2).
1583
+ // A teammate list shorter than the client allows can run out (an opponent takes its picks first), and
1584
+ // war.app then grants that teammate from what is left, a pick of mine included: no shortening then.
1585
+ const clientMax = Math.max(0, Math.floor(input.maxPicks));
1586
+ const shortList = lists.findIndex((l) => l.length < clientMax);
1587
+ let shortened;
1588
+ let keptLong;
1589
+ const long = listOf(core.plan);
1590
+ const short = Math.max(core.plan.groups.primary.territoryIds.length, limit * Math.max(1, players - teammates));
1591
+ if (disjoint(long) && short < long.length && shortList >= 0)
1592
+ keptLong = { length: lists[shortList].length };
1593
+ else if (disjoint(long) && short < long.length) {
1594
+ const c = planCore({ ...input, maxPicks: short }, friendly);
1595
+ if (disjoint(listOf(c.plan))) {
1596
+ core = c;
1597
+ shortened = { from: long.length, to: listOf(c.plan).length };
1598
+ }
1599
+ }
1600
+ const { plan } = core;
1601
+ const mine = listOf(plan);
1602
+ const terrName = (id) => g.territoryById.get(id)?.name ?? String(id);
1603
+ const bonusName = (id) => core.bonuses.get(id)?.name ?? String(id);
1604
+ const names = (ids) => ids.map(terrName).join(', ');
1605
+ const overlap = [];
1606
+ mine.forEach((t, i) => lists.forEach((l, j) => {
1607
+ const at = l.indexOf(t);
1608
+ if (at >= 0)
1609
+ overlap.push({ territoryId: t, mine: i + 1, teammate: j, theirs: at + 1 });
1610
+ }));
1611
+ const friendlySet = new Set(friendly);
1612
+ const sharedBonuses = [];
1613
+ for (const b of [...core.bonuses.values()].sort((x, y) => x.id - y.id)) {
1614
+ const theirsIn = b.members.filter((m) => friendlySet.has(m)).sort(byNum);
1615
+ const mineIn = b.members.filter((m) => mine.includes(m)).sort(byNum);
1616
+ if (theirsIn.length && mineIn.length)
1617
+ sharedBonuses.push({ bonusId: b.id, mine: mineIn, theirs: theirsIn });
1618
+ }
1619
+ // The mirrored alternative: my primary and each teammate's top, one group per hand.
1620
+ const primary = plan.groups.primary.territoryIds;
1621
+ const groups = [primary, ...tops];
1622
+ const k = groups.length;
1623
+ let mirrored = null;
1624
+ if (limit > 0 &&
1625
+ teammates > 0 &&
1626
+ lists.length === teammates &&
1627
+ primary.length === limit &&
1628
+ tops.every((t) => t.length === limit) &&
1629
+ new Set(groups.flat()).size === k * limit) {
1630
+ /** List positions (0-based) each of us takes from the shared top, under `order`. */
1631
+ const positions = (order) => groups.map((_, j) => Array.from({ length: limit }, (_, r) => r * k + (order === 'reversing' && r % 2 === 1 ? k - 1 - j : j)));
1632
+ const top = new Array(k * limit);
1633
+ const laid = positions('reversing');
1634
+ groups.forEach((gr, j) => gr.forEach((t, r) => (top[laid[j][r]] = t)));
1635
+ const handsOf = (order) => positions(order).map((ps) => ps.map((i) => top[i]));
1636
+ const others = (h) => top.filter((t) => !h.includes(t));
1637
+ const intended = new Set(groups.flatMap((gr) => [...core.completes(gr, others(gr))]));
1638
+ const splits = [];
1639
+ for (const order of ['reversing', 'repeating']) {
1640
+ const done = new Set(handsOf(order).flatMap((h) => [...core.completes(h, others(h))]));
1641
+ const lost = [...intended].filter((id) => !done.has(id)).sort(byNum);
1642
+ if (lost.length)
1643
+ splits.push({
1644
+ order,
1645
+ bonuses: lost.map((id) => ({ bonusId: id, picks: core.bonuses.get(id).members.filter((m) => top.includes(m)).sort(byNum) })),
1646
+ });
1647
+ }
1648
+ mirrored = {
1649
+ top,
1650
+ hands: handsOf('reversing'),
1651
+ splits,
1652
+ // The shared top, then my own fallback, never past what the client allows (players × limit).
1653
+ submitPicks: [...top, ...mine.filter((t) => !top.includes(t))].slice(0, Math.max(top.length, clientMax)),
1654
+ };
1655
+ }
1656
+ const rationale = [...plan.rationale];
1657
+ rationale.push(`Your teammate${lists.length === 1 ? "'s list is" : "s' lists are"} read: their top pick${friendly.length === 1 ? '' : 's'} (${names(friendly)}) ` +
1658
+ `${friendly.length === 1 ? 'is' : 'are'} left to them, as known starts of your team that threaten nothing. A bonus pays one holder: a pick in a bonus they pick into is not credited with it` +
1659
+ (sharedBonuses.length ? ` (${sharedBonuses.map((b) => bonusName(b.bonusId)).join(', ')})` : '') +
1660
+ '. This list is the split one: it leaves their top picks out.');
1661
+ if (overlap.length)
1662
+ rationale.push(`Both lists carry ${names([...new Set(overlap.map((o) => o.territoryId))])}: such a pick goes to whichever of you the award reaches first.`);
1663
+ if (shortened)
1664
+ rationale.push(`Your list is disjoint from your teammate's, so it is shortened from ${shortened.from} to ${shortened.to}: your starts and the opponents' ` +
1665
+ '(a pick on both lists could go to either of you; none is).');
1666
+ if (keptLong)
1667
+ rationale.push(`Your list is disjoint from your teammate's but not shortened: your teammate's list has ${keptLong.length} pick${keptLong.length === 1 ? '' : 's'}, ` +
1668
+ `fewer than the ${clientMax} the client allows, so if an opponent takes them first war.app grants your teammate from what is left, one of yours included.`);
1669
+ if (mirrored) {
1670
+ rationale.push(`A mirrored alternative: each of you lists the same top ${mirrored.top.length} (${names(mirrored.top)}), so whoever the award reaches next takes the next one. ` +
1671
+ 'They are laid on the positions a reversing award gives one player, so each start group stays in one hand' +
1672
+ (mirrored.splits.length
1673
+ ? `; under a ${mirrored.splits.map((x) => x.order).join(' or ')} award order (a team game's is unverified) ` +
1674
+ `${mirrored.splits.flatMap((x) => x.bonuses.map((b) => bonusName(b.bonusId))).join(', ')} would be split between you and lost`
1675
+ : '') +
1676
+ '. It assumes no opponent takes one of them first: one that does moves every later pick to the other hand.');
1677
+ }
1678
+ return {
1679
+ ...plan,
1680
+ rationale,
1681
+ team: { tops, overlap, sharedBonuses, mirrored, ...(shortened ? { shortened } : {}) },
1682
+ };
1683
+ }
1684
+ /**
1685
+ * The pick-list bounds of war.app's own client (read from its bundle, #129): per player,
1686
+ * floor(pickables / players) capped by the territory limit (0: no limit); the client stops
1687
+ * adding picks at players × that, and the game's pick validation rejects a list shorter than
1688
+ * min(10, that). No maximum is enforced in that validation, only in the client's picking UI
1689
+ * (docs/WARAPP-API.md: unverified against the server). Without the pickable count the
1690
+ * territory limit stands in for the per-player share; `null` when neither is known.
1691
+ */
1692
+ export function clientPickLimits(input) {
1693
+ const players = Math.max(1, Math.floor(input.players));
1694
+ const limit = input.territoryLimit !== undefined && input.territoryLimit > 0 ? Math.floor(input.territoryLimit) : 0;
1695
+ let perPlayer;
1696
+ if (input.pickable === undefined) {
1697
+ if (!limit)
1698
+ return null;
1699
+ perPlayer = limit;
1700
+ }
1701
+ else {
1702
+ perPlayer = Math.floor(Math.max(0, input.pickable) / players);
1703
+ if (limit)
1704
+ perPlayer = Math.min(perPlayer, limit);
1705
+ }
1706
+ return { perPlayer, min: Math.min(10, perPlayer), max: players * perPlayer };
1707
+ }
1708
+ /** Most search states {@link pickOutcomes} explores before giving up (`null`). */
1709
+ const MAX_AWARD_STATES = 50_000;
1710
+ /**
1711
+ * Every set of list positions (0 = first pick) the award order can grant (#129). Picks are
1712
+ * awarded round by round in move order, the order reversing each round, each player getting
1713
+ * the highest-ranked territory still free on their own list (the community wiki). The other
1714
+ * players' lists are unknown, so each of their picks may be any free territory of this list
1715
+ * or one outside it; this player's move position is unknown too. `orders` (default the reversing
1716
+ * one) are the award orders enumerated, the outcomes of each joined. A position set shorter than
1717
+ * `perPlayer` means the list ran out (war.app then grants what is left). Sorted ascending,
1718
+ * each set ascending; `null` when the search would pass {@link MAX_AWARD_STATES} states.
1719
+ */
1720
+ export function pickOutcomes(input) {
1721
+ const n = Math.max(0, Math.floor(input.listLength));
1722
+ const rounds = Math.max(0, Math.floor(input.perPlayer));
1723
+ const players = Number.isFinite(input.players) ? Math.max(1, Math.floor(input.players)) : 2;
1724
+ if (n > 30)
1725
+ return null;
1726
+ const orders = input.orders?.length ? [...new Set(input.orders)] : ['reversing'];
1727
+ const outcomes = new Set();
1728
+ const seen = new Set();
1729
+ let states = 0;
1730
+ let reversing = true;
1731
+ // step: index into the whole pick sequence; taken: bitmask of list positions anyone holds; mine: mine.
1732
+ const visit = (pos, step, taken, mine) => {
1733
+ const key = `${reversing ? '' : 'r'}${pos}:${step}:${taken}:${mine}`;
1734
+ if (seen.has(key))
1735
+ return true;
1736
+ seen.add(key);
1737
+ if (++states > MAX_AWARD_STATES)
1738
+ return false;
1739
+ if (step === rounds * players) {
1740
+ outcomes.add(mine);
1741
+ return true;
1742
+ }
1743
+ const round = Math.floor(step / players);
1744
+ const slot = step % players;
1745
+ const mover = !reversing || round % 2 === 0 ? slot : players - 1 - slot;
1746
+ if (mover === pos) {
1747
+ let first = -1;
1748
+ for (let i = 0; i < n; i++)
1749
+ if (!(taken & (1 << i))) {
1750
+ first = i;
1751
+ break;
1752
+ }
1753
+ return first < 0 ? visit(pos, step + 1, taken, mine) : visit(pos, step + 1, taken | (1 << first), mine | (1 << first));
1754
+ }
1755
+ // Another player: a territory outside this list, or any free one on it.
1756
+ if (!visit(pos, step + 1, taken, mine))
1757
+ return false;
1758
+ for (let i = 0; i < n; i++)
1759
+ if (!(taken & (1 << i)) && !visit(pos, step + 1, taken | (1 << i), mine))
1760
+ return false;
1761
+ return true;
1762
+ };
1763
+ for (const order of orders) {
1764
+ reversing = order === 'reversing';
1765
+ for (let pos = 0; pos < players; pos++)
1766
+ if (!visit(pos, 0, 0, 0))
1767
+ return null;
1768
+ }
1769
+ const sets = [...outcomes].map((m) => Array.from({ length: n }, (_, i) => i).filter((i) => m & (1 << i)));
1770
+ return sets.sort((a, b) => {
1771
+ for (let i = 0; i < Math.min(a.length, b.length); i++)
1772
+ if (a[i] !== b[i])
1773
+ return a[i] - b[i];
1774
+ return a.length - b.length;
1775
+ });
1776
+ }
1777
+ /**
1778
+ * The other players' starts a pick list implies once picks are awarded (#129): every
1779
+ * territory ranked above the last one granted that was not granted went to another player
1780
+ * (an opponent, or a teammate in a team game) — the award gives each player their
1781
+ * highest-ranked territory still free.
1782
+ */
1783
+ export function impliedOpponentStarts(list, granted) {
1784
+ const got = new Set(granted);
1785
+ let last = -1;
1786
+ list.forEach((t, i) => {
1787
+ if (got.has(t))
1788
+ last = i;
1789
+ });
1790
+ return list.slice(0, last + 1).filter((t) => !got.has(t));
1791
+ }
1792
+ /** Every ordering of `xs`, starting with `xs` itself (lexicographic by position). */
1793
+ function permutations(xs) {
1794
+ if (xs.length <= 1)
1795
+ return [[...xs]];
1796
+ const out = [];
1797
+ xs.forEach((x, i) => {
1798
+ for (const rest of permutations([...xs.slice(0, i), ...xs.slice(i + 1)]))
1799
+ out.push([x, ...rest]);
1800
+ });
1801
+ return out;
1802
+ }
1803
+ /** Moves within which a pick covers a bonus: it can stand in or next to the bonus (#166). */
1804
+ const COVERAGE_DISTANCE = 2;
1805
+ /**
1806
+ * The coverage of every pick set on one board (#166), set up once. A wasteland is a territory
1807
+ * whose neutral is larger than an ordinary one (the distribution size on a pickable territory,
1808
+ * the non-distribution size elsewhere), as the advisor's reasons define it. A bonus is
1809
+ * reasonable — one an opponent would reasonably start in — when its value is positive, it is not
1810
+ * a superbonus, no member is a wasteland, a member is pickable, every member can be taken, and
1811
+ * its value per capture cost (every member at `captureCost`, as in the opening simulation) is at
1812
+ * least the median over such bonuses. A pick covers a bonus when a territory of the bonus, or
1813
+ * one next to it, lies within COVERAGE_DISTANCE hops of the pick, walking only through
1814
+ * territories that are not wastelands.
1815
+ */
1816
+ function coverageModel(input) {
1817
+ const g = input.graph;
1818
+ const s = input.settings ?? {};
1819
+ const pickSet = new Set(input.pickable.filter((t) => g.territoryById.has(t)));
1820
+ const known = input.neutralArmies ?? new Map();
1821
+ const neutralsIn = s.initialNeutralsInDistribution ?? DEFAULT_NEUTRALS_IN_DISTRIBUTION;
1822
+ const neutralsOut = s.initialNonDistributionArmies ?? DEFAULT_NON_DISTRIBUTION_ARMIES;
1823
+ const rates = {
1824
+ offensiveKillRate: s.offensiveKillRate ?? DEFAULT_OFFENSIVE_KILL_RATE,
1825
+ defensiveKillRate: s.defensiveKillRate ?? DEFAULT_DEFENSIVE_KILL_RATE,
1826
+ luckModifier: s.luckModifier,
1827
+ };
1828
+ const ordinary = (t) => (pickSet.has(t) ? neutralsIn : neutralsOut);
1829
+ const { armies, cost } = territoryCosts(g, (t) => known.get(t) ?? ordinary(t), rates);
1830
+ const waste = new Set([...armies].filter(([t, n]) => n > ordinary(t)).map(([t]) => t));
1831
+ const candidates = [];
1832
+ for (const b of g.map.bonuses) {
1833
+ if (b.value <= 0 || b.bonusIds.length > 0)
1834
+ continue;
1835
+ const members = (analyzeBonus(g, b.id)?.territoryIds ?? []).filter((t) => g.territoryById.has(t));
1836
+ if (!members.length || members.some((m) => waste.has(m)) || !members.some((m) => pickSet.has(m)))
1837
+ continue;
1838
+ const costs = members.map((m) => cost.get(m));
1839
+ if (costs.some((c) => c === null || c === undefined))
1840
+ continue;
1841
+ const total = costs.reduce((a, c) => a + c, 0);
1842
+ const zone = new Set(members);
1843
+ for (const m of members)
1844
+ for (const n of neighborsOf(g, m))
1845
+ zone.add(n);
1846
+ candidates.push({ id: b.id, name: b.name, ratio: total > 0 ? b.value / total : Infinity, zone });
1847
+ }
1848
+ const ratios = candidates.map((c) => c.ratio).sort(byNum);
1849
+ const mid = ratios.length >> 1;
1850
+ const median = !ratios.length ? 0 : ratios.length % 2 ? ratios[mid] : (ratios[mid - 1] + ratios[mid]) / 2;
1851
+ const reasonable = candidates.filter((c) => c.ratio >= median).sort((a, b) => a.id - b.id);
1852
+ return (picks) => {
1853
+ // Breadth-first from every pick at once, never entering a wasteland.
1854
+ const seen = new Set(picks.filter((t) => g.territoryById.has(t) && !waste.has(t)));
1855
+ let frontier = [...seen];
1856
+ for (let d = 0; d < COVERAGE_DISTANCE && frontier.length; d++) {
1857
+ const next = [];
1858
+ for (const t of frontier)
1859
+ for (const n of neighborsOf(g, t))
1860
+ if (!seen.has(n) && !waste.has(n)) {
1861
+ seen.add(n);
1862
+ next.push(n);
1863
+ }
1864
+ frontier = next;
1865
+ }
1866
+ const uncovered = reasonable.filter((b) => ![...b.zone].some((t) => seen.has(t)));
1867
+ const covered = reasonable.length - uncovered.length;
1868
+ return {
1869
+ share: reasonable.length ? round2(covered / reasonable.length) : 1,
1870
+ covered,
1871
+ reasonable: reasonable.length,
1872
+ uncovered: uncovered.map((b) => ({ bonusId: b.id, name: b.name })),
1873
+ };
1874
+ };
1875
+ }
1876
+ /** The coverage of one pick set (see {@link coverageModel}). */
1877
+ export function coverage(input, picks) {
1878
+ return coverageModel(input)(picks);
1879
+ }