@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,2922 @@
1
+ // Turn planner: deploys and moves for one turn, from one player's view of a
2
+ // board. Pure and deterministic (every choice tie-breaks on ascending id); no
3
+ // I/O. Advisory only — it never submits orders.
4
+ //
5
+ // Where each rule lives. `planPass` (below) runs the phases in order; each phase is a module
6
+ // under src/analysis/plan/ taking `(ctx, state)`:
7
+ // constants, types, 3. capture cost (#126), fog, deploy estimates .. plan/shared.ts
8
+ // estimates, the enemy estimates and the plan context ........ plan/estimates.ts
9
+ // the deploy book (budget, guard, deploys, pools) ............. plan/orders.ts
10
+ // 1. defence, 1t. trend ....................................... plan/threats.ts
11
+ // 1a. triage, 1k. my commander, 1h, 1b, 1c, 1g / #122, #172 .. plan/holds.ts
12
+ // 2. targets, 4. bonus scoring, 4d. frontier cost, 4f / #101 .. plan/targets.ts
13
+ // R3 / 4b, No-Split, 3a. combined, 3b / #121, passes 1 and 2 .. plan/captures.ts
14
+ // 1e, 1s, #165, 0p.3c strike stack, #102 spend, #167 lead ..... plan/strike.ts
15
+ // #276 guard off: second line, raids, free retakes ........... plan/guard-off.ts
16
+ // 4e. never stand still ...................................... plan/stand-still.ts
17
+ // 4h. the army cap prices idle armies (#253) .................. plan/cap-spend.ts
18
+ // 5. the leftover deploy, 3b's short borders (#121) ........... plan/leftover.ts
19
+ // 5b. a neutral the leftover pays for (#218) ................. plan/after-leftover.ts
20
+ // 6. transfers, #125 staging ................................. plan/transfers.ts
21
+ // 7. move order, rule 1s's Order Priority ..................... plan/move-order.ts
22
+ // 1w. my commander walks, its transit hold (#274) ............. plan/commander.ts
23
+ // 7r. reports, the offence report, 1i (#109), the final plan .. plan/report.ts
24
+ // T1–T9. truces (B2, `relations`): the rule logic .............. plan/relations.ts
25
+ // PLAN-TEAMS C3.3–C3.6, `team`, the team focus (C3.4) ........ plan/team.ts
26
+ // #275 (b): `PlanInput.untrusted` — an opponent whose estimate the tripwire (tripwire.ts) broke is sized,
27
+ // at the borders of bonuses I hold in full at the start, for max(its deploy, the caller's figure), in
28
+ // threats.ts's forceAt (a rationale line names those borders); every other border, and an explicit
29
+ // enemyDeploy, are unchanged. Under Local Deployment that figure is not bounded by where the
30
+ // opponent's bonus pools can land (`deployReaching` bounds the estimate): such a border is
31
+ // over-sized, the conservative direction. A held bonus contested on that sizing (#118: its hold costs
32
+ // more than CONCEDE_FACTOR × its worth, or does not pay back) whose border faces the untrusted opponent
33
+ // is held whole before any capture when what is left covers it (`settleContested('untrusted')`, every
34
+ // goal), so no expansion goes ahead of the gate; one it cannot cover, or one triage conceded beside that
35
+ // opponent's stack, gets everything left to deploy before any capture and is not conceded
36
+ // (`fillUntrustedGates`: nothing that pays +1 goes ahead of it; a warning names what still takes it) — unless
37
+ // its stacks take it with no deploy whatever is left goes there: that one stays conceded. The game
38
+ // profile compares that opponent at its figure and is never `even` while the mark runs (profile.ts).
39
+ // Absent, the plan is byte-identical.
40
+ // Rule 1k's commander reserve is read by every phase that spends armies: captures, strike and
41
+ // stand-still keep what holds my commander's territory (#274: where it walks to, when it walks).
42
+ // `byNum` and `pct` live in plan/util.ts.
43
+ // plan/shared.ts is a leaf (it imports no phase and not planner.ts), and the phases import one
44
+ // another for types only, so the import graph has no cycle.
45
+ // Still inline in planPass (ordering dependencies on the shared state): rules 0p.1 / 0p.2 and
46
+ // 4a's `balanced` greedy, pass 3, 4g card pieces, rule 4c's guard, No-Split's whole-stack carry
47
+ // (#124), and S2's efficient sizes with their #120 warnings.
48
+ //
49
+ // Rules, in decision order:
50
+ // 0s. Static seats (#270, src/analysis/static-seats.ts): a player out of the game (SurrenderAccepted,
51
+ // Booted, Eliminated, EndedByVote) whose seat no AI plays (not `humanTurnedIntoAI`, nor a surrender
52
+ // or boot the game's end rules turn into an AI) deploys and attacks nothing. `planTurn` first reads
53
+ // its territories as neutrals on the board and the previous board (`planningInput`; armies and
54
+ // units kept) and drops its tracks, truces, Sanctions and opening: it is no opponent in any
55
+ // estimate, threat, standing or strike, its land is priced like a wasteland, and no border beside
56
+ // only it needs a hold. A rationale line names each such player holding land. Never me or a
57
+ // teammate; an AI that replaced a player stays an opponent. #281: the territories it left are
58
+ // kept (`PlanInput.vacated`, `BoardCtx.vacated`) for rule 4d and pass 3 (src/analysis/plan/vacated.ts;
59
+ // rule 4d below, with the owner's extension to empty enemy territory with the guard off).
60
+ // 0p. Game profile (`gameProfile`, src/analysis/profile.ts), computed on every plan and
61
+ // returned as `profile`: format (1v1 / ffa / teams), phase (opening / expansion /
62
+ // contact / late; in an FFA, contact only when an enemy stack as it stands can take a
63
+ // territory of mine or most of my borders face enemies, #132), standing (my income against the strongest opponent's estimate:
64
+ // ahead ≥ AHEAD_RATIO×, behind ≤ BEHIND_RATIO×, unknown when fog hides most of the
65
+ // board) and the settings that shape strategy. #276: with One Army Must Stand Guard off it
66
+ // names that case first (`guard`, `guardCase`: what it means for interior defence) and its note
67
+ // leads `notes`; with the guard on it is absent, so a guard-on plan is unchanged
68
+ // (`warapp_plan_turn` names both cases). Only with `options.adapt` and no `goal`
69
+ // does it change the plan (each rule a rationale line when it fires):
70
+ // 1. 1v1 in contact: a break is weighted like a completion of equal value (weight 1),
71
+ // and an advance (expansion that completes no bonus) ranks below every hold, unit,
72
+ // break and completion, and never defers a hold for the expansion share. #215: a
73
+ // contested held bonus (rule 1h, #118: its hold pays back within PAYBACK_TURNS but costs
74
+ // more than CONCEDE_FACTOR × its worth, so the captures go first) is held whole before the
75
+ // first advance when what is left covers it (best worth per army first, never weighed
76
+ // against spreading: `settleContested(true)`); the rest stays contested as before.
77
+ // 2. FFA with two or more opponents left: no second front — a break (also from a held
78
+ // border, rule 4a) against a player that can take no member of a bonus I hold next
79
+ // turn and loses nothing to this turn's strike / finishing off is skipped when a
80
+ // neutral bonus capture scores at least SECOND_FRONT_SIMILAR × its score per army.
81
+ // Finishing off (rule 1e) and strikes (rule 1s) are untouched.
82
+ // #167, scaled by my army lead (my visible armies and special units over the largest
83
+ // opponent's in view): the neutral needs SECOND_FRONT_SIMILAR × the lead (at least 1×, at
84
+ // most SECOND_FRONT_LEAD×) of the break's score; above SECOND_FRONT_LEAD× the rule is off,
85
+ // here and in rule 4e. Visible armies only, so the lead counts only when I also lead the
86
+ // profile's FFA ranking on strength (fog can hide a strong player behind one small stack).
87
+ // A clear leader that is not me (the profile's FFA ranking: strength = armies +
88
+ // STRENGTH_INCOME_TURNS × income, at least AHEAD_RATIO × the next player's) is never
89
+ // a second front: the others combine against it. Lead strikes: above the lead, under
90
+ // `balanced`, every enemy territory next to mine (no special unit, never one lowering income)
91
+ // is attacked after the leftover deploy from the neighbour with the most armies beyond what
92
+ // holds it once the target falls (#172's two-step keep too; never a hold, a conceded border,
93
+ // my commander's territory or the strike stack; not under No-Split), when that covers an
94
+ // attack sized for its defenders plus its owner's deploy there (rule 3's #120 sizing):
95
+ // breaks first, then a step into a positive bonus, then cheapest, then id ("army lead: …").
96
+ // #203: before that, such a territory in a positive bonus is a step into the bonus in the
97
+ // bonus passes (rules 4, 4a, 4f) with the same sure sizing, funded from this turn's deploy
98
+ // in rule 4f's order — the closest bonus's enemy member gets the deploy before a farther
99
+ // bonus does ("… player P's member, taken on my army lead", whichever pass takes it). #212:
100
+ // its source may be a border held under `balanced` (never my commander's territory): the
101
+ // border keeps what holds it once the step is taken, the deploy covers the attack and the
102
+ // hold together, and the hold is then funded ("T keeps N to hold its border …"). #214: or a
103
+ // conceded border (never my commander's territory): this turn's deploy funds the attack
104
+ // alone and its hold stays conceded unless rule 1c keeps it for a bonus completed this
105
+ // turn ("T is conceded, but the deploy there leaves with the attack …"). Pass 2 takes such
106
+ // a step alone only when the bonus cannot be completed whole with it last: taken first, it
107
+ // could make rule 1c's guard refuse its sibling's completion (or leave the sibling to rule
108
+ // 4d), sinking the deploy into a conceded border for half a bonus. When it cannot, the step
109
+ // is taken before or after the bonus's other steps, whichever plans more captures (a tie:
110
+ // whichever leaves more of the deploy; a tie again: after), so it never crowds out a
111
+ // sibling a held border funds for less. #214: when the turn cannot fund a step toward the
112
+ // closest bonus (or in a completion) at that sure size, it is retried at its bare cost, a sure
113
+ // capture of the defenders standing there now — the cost rule 4f ranks the bonuses on — with
114
+ // no worst case: #120's warning says what it faces if the owner deploys there first, and the
115
+ // reason says what would be sure ("sized for the N defenders there now: S would be sure …,
116
+ // more than this turn can fund"). Only a funding shortfall retries (an R3 or trade refusal of
117
+ // the sure step stands — a combined capture refused for a below-even trade or by R3 included),
118
+ // and only after every step had its sure try: pass 1 retries a
119
+ // completion with each step sure first and the ones that failed bare, pass 2 runs the closest
120
+ // bonus's leftover steps again bare once its sure round is done, so a bare step never takes
121
+ // the deploy a sibling's sure size would have had. Pass 2's retry runs only while rule 4f
122
+ // commits to the closest bonus (otherwise its order is the score order, with no closest
123
+ // bonus). #214 review: nor does a bare step take a hold's armies. Holds are sized after the
124
+ // captures (a contested held bonus is held whole from what they leave, #118), so planTurn
125
+ // checks the plan: when one with bare steps leaves a border of mine still threatened after
126
+ // its captures without a hold — conceded, short at the end, or a floored member — that the
127
+ // plan made without bare steps deploys to (or holds) and holds, that plan stands, with a
128
+ // rationale line "Lead step … not taken at its bare cost (#214 review): taking it would
129
+ // leave … without the hold this plan gives it". A failed completion retry leaves the skip
130
+ // line what the sure try said (a bare step it undid erased its member's entry). One those
131
+ // passes do not take is an ordinary enemy territory again for every later rule
132
+ // (rule 4e's fallback, 4g's card pieces, the lead strikes): its plain size, no sure sizing;
133
+ // its "Not attacking" line still ends with why its bonus's step failed (the hold it had to
134
+ // keep, the deploy that could reach it, or why no neighbour could attack).
135
+ // 2f. Front outlook (#167; adapting, contact and late phases): rule 4a's expansion share stands
136
+ // only when the main front (the biggest enemy stack next to me against my biggest stack
137
+ // beside it) is no worse than a stand-off with the income less the share deployed there each
138
+ // turn (`forecastBorder`, src/analysis/exchange.ts: both owners deploy on the stacks every
139
+ // turn, simulated with `simulateTurn`; "press" — I attack every turn — and "pressed"); ground
140
+ // down so, the share is 0 this turn and holds come first. A front my stack breaks only if
141
+ // pressed counts as one only when the orders already take that stack; otherwise the share
142
+ // also goes when the border pins more than the income less the share (pressed, I am ground
143
+ // down). A rationale line gives the outcome, the turn and the income the border pins (or
144
+ // that not even the whole income keeps it). #218: the front is `mainFront` (exchange.ts),
145
+ // shared with the game outlook; the plan reports `front`, the same front forecast with my
146
+ // whole income, which warapp_plan_turn feeds back to the outlook (my income there, as the
147
+ // opponent's, is every turn's: a Reinforcement card played this turn is left out, #164), and when that outcome
148
+ // differs the line says what it is ("With my whole N a turn there (as the outlook's front
149
+ // forecast deploys it) …").
150
+ // 3. Behind on income: pressure (rule 1e) is sized with no margin. Outside a 1v1 the goal
151
+ // is `defend`; in a 1v1 (#72) it stays `balanced` — strike: rule 1's ordering puts
152
+ // breaks before expansion that completes nothing, and held-bonus units that pay for
153
+ // themselves still come first (rule 1h). Behind on armies in a 1v1 (my visible armies
154
+ // and special units below BEHIND_RATIO × the strongest opponent's): no trade below even —
155
+ // a combined capture of a player's territory whose attacks lose more armies than they
156
+ // kill (its softeners each attack a stack larger than they can take) is not made.
157
+ // Ahead in a 1v1: pressure is allowed up to AHEAD_PRESSURE_FACTOR typical
158
+ // expansions (instead of PRESSURE_FACTOR).
159
+ // 3c. Concentrate (#72; adapting in a 1v1, facing the opponent): the leftover deploy (rule 5) goes
160
+ // to one strike stack — an open border next to the strongest opponent (highest income
161
+ // estimate, tracked when trusted), chosen by what it can take (#120): each border's best
162
+ // strike this turn with the whole leftover on it (an adjacent target of that opponent sized
163
+ // for its defenders plus what it may deploy there first, rule 3; never one that lowers
164
+ // income) and the armies it then has to spare once it still holds; the border with the most
165
+ // to spare wins (ties: more armies, then id), and a rationale line names it and the
166
+ // bigger border passed over. With no border able to strike (and always under No-Split), the
167
+ // border holding the most armies, as before — before any comfort margin;
168
+ // the rationale names it and `offence` reports it as a strike. Holds still come first:
169
+ // a border kept for a bonus this turn completes (rule 1c) is first topped up to a
170
+ // comfortable margin, and any other open border that would fall to just hold. Only in a
171
+ // 1v1: in an FFA or team game (several fronts) the comfort margins keep the leftover.
172
+ // Spend it (#102): every turn the stack attacks each adjacent enemy territory it can take
173
+ // at the plan's win chance (ordinary capture sizing; never one that lowers income, re-checked
174
+ // against the strike's own captures, which can complete a negative bonus only together),
175
+ // breaking or retaking a bonus first (one the opponent holds in full, or one I held in full
176
+ // on `previousBoard`; only the first member of a bonus to fall this turn breaks it, and a
177
+ // retake that cannot finish this turn is "toward retaking"), then by that bonus's value,
178
+ // then cheapest, then id — while what
179
+ // stays on it holds against the threat left after those attacks (rule 1's arithmetic,
180
+ // the captured territories gone), never below the opponent's deploy alone (orders
181
+ // interleave: it may land on a target first; the target's survivors striking back after a
182
+ // failed attack are not added — an approximation). No S2 top-up draws on that hold, and
183
+ // the transfer step never moves it (its captures can leave it interior). Then (#120) each of
184
+ // the stack's attacks on a player (its earlier breaks and counter-attacks first, then the
185
+ // strikes in order) is sized for its defenders plus what the owner may deploy there first,
186
+ // as rule 3 sizes one, while what stays still holds. Each attack
187
+ // is a rationale line and an `offence` strike entry (target, armies, win chance, what it
188
+ // breaks or retakes); a target not attacked is a strike entry with `taken: false` and why.
189
+ // It only grows (deploy, no attack) when nothing in reach is worth taking: a rationale line
190
+ // ("Grow the strike stack …") names each target and why. The stack's own entry is
191
+ // `taken` only when it attacks this turn — also when it got no deploys (Local Deployment,
192
+ // no room, or holds and captures took the whole income: the stack is chosen the same way
193
+ // with no leftover, and a rationale line says none reached it): a strike stack, once
194
+ // built, is spent.
195
+ // #201: with no border able to strike this turn (not under No-Split), the multi-turn border
196
+ // forecast (`forecastBorder`) chooses: the border whose stack, with the leftover and then the
197
+ // income every turn, breaks the opponent's biggest stack beside it soonest (its owner
198
+ // deploying there every turn), when that is not the border holding the most armies and
199
+ // breaks sooner than it ("Strike stack on … (#201): no border can strike this turn; …").
200
+ // 3d. Decided (#201): given `options.outlook` (#178) reporting winning or losing, the game is
201
+ // decided, and every payback test (PAYBACK_TURNS everywhere it appears in these rules)
202
+ // counts the turns it has left instead: the loser's strength over the winner's income a
203
+ // turn (winning: the strongest opponent's, its high when bounded — #208: its likely high,
204
+ // called an estimate, when only that showed the win — over my income; losing:
205
+ // mine over its income estimate — #228: also when losing rests on the estimate, mine far
206
+ // below its likely high and corroborated by the main front on my boards' incomes or by my
207
+ // income, the line then calling it an estimate), at least DECIDED_PAYBACK_MIN, at most
208
+ // PAYBACK_TURNS; a rationale line ("Outlook (#201): …") says so. The strike stack's forecast
209
+ // uses it too.
210
+ // 4. An explicit `goal` always wins: none of the above, and the rationale says the
211
+ // profile was overridden.
212
+ // 1. Defence. A visible enemy next to my territory T threatens it when
213
+ // `armiesToTake(armies(T)) ≤ E + enemyDeploy`, where E is that player's
214
+ // movable armies (minus the guard) summed over its territories bordering T.
215
+ // #128: that one attack is not the whole threat. Separate stacks attack separately and
216
+ // each rounds on its own (a 1-army softener kills 1 at 60%), so the threat is the single
217
+ // attack equivalent to the most the stacks take sent one after another: Σ kills of the
218
+ // softeners + what the last (the deploy on it) takes, best last stack (`forceAt`).
219
+ // Opponents on one team attack together (their stacks and deploys combine); two FFA
220
+ // players are judged alone, and a border that holds against each but not against both in
221
+ // one turn gets a warning — except (#201) when I lead an FFA on strength (adapting, two or more
222
+ // opponents left): the others may combine against the leader, so every adjacent opponent's
223
+ // stacks and deploys count together, like a team's, and a rationale line names each border held
224
+ // so ("I lead this free-for-all …") — #235: but only while that pays. A leader's border whose
225
+ // joint hold costs more than CONCEDE_FACTOR × its worth (rule 1a) or the whole income, while
226
+ // its hold against the strongest single opponent passes both, is sized for that opponent
227
+ // (`soloHeld`, read by `borderAt` and `threatAt`), as in any FFA, with #128's pile-on warning;
228
+ // never my commander's territory. A member of a bonus I hold in full is judged with its bonus
229
+ // (#235 review): when the unit sized for them together costs more than the income (rule 1h
230
+ // could never hold it whole) while the unit sized for the strongest single opponent pays, the
231
+ // members that sizing lowers are sized so ("holding bonus … against players attacking together
232
+ // …"), unless another held bonus that fits the income holds them too. Any other held bonus not
233
+ // funded whole up front (#235 review 2: it may be conceded, another member hopeless or the
234
+ // captures leaving too little) gives each member it lowers the per-border test on its value
235
+ // without that bonus — the judgement it gets with no bonus. A rationale line says so ("… as FFA players attack alone (#235)") when the plan
236
+ // keeps it (live: a 23-stack that held against each neighbour alone, even at a 40 deploy, was
237
+ // conceded on the two together and withdrawn as the first order). Teammates (the game's team list) are never a threat, an
238
+ // estimate or a target. Under Local Deployment an opponent's visibly held bonus pays
239
+ // only into its own territories: what reaches T is its estimate less its visible pools
240
+ // plus the pools that contain one of its stacks next to T. An enemy commander counts in
241
+ // the expected attack too (rule 1h's near miss, kept garrisons).
242
+ // enemyDeploy is estimated per opponent (`enemyDeployEstimates`): base
243
+ // income (the larger of MinimumArmyBonus and, with BonusArmyPer on, its
244
+ // visible territories / BonusArmyPer) plus the bonuses that player
245
+ // visibly holds in full, never below max(MIN_ENEMY_DEPLOY, base income).
246
+ // Its stack next to me is no part of it: a stack says how much can *move*,
247
+ // never how much can be deployed (live, a 0.75 × 15 guess on an all-15
248
+ // opening board made every base-income opponent look like ~11; and capping
249
+ // the estimate at 0.75 × a small stack hid income held in plain view — a
250
+ // +10 holder with a 2-stack on my border read as 5). On the opening board (every
251
+ // visible player territory still holds the same count; neutrals aside, and only on the first
252
+ // turn — no previous board, the turn unknown or 1, #128) every opponent gets the
253
+ // floor. Given `previousBoard`, each estimate is at least the deploy observed since
254
+ // then (`observeDeploy`, issue #57: the net change of its armies visible on both
255
+ // boards — shrinks included, so a transfer between its own territories is not deploy —
256
+ // plus, on each territory it captured from a visibly held or neutral territory, the
257
+ // attackers the previous defenders killed at the game's kill rates, and its armies there
258
+ // only up to what its visible-both-turns neighbours sent away (their shrink, each claimed
259
+ // once, ascending id); the rest, when a neighbour was hidden, counts as deployed on the
260
+ // visible stack that attacked when one did shrink into it (deploy-then-capture, #123, up to
261
+ // what it could earn), else arrived from the fog (a move and a threat, never income, issue
262
+ // #86), or counts as deploy when every neighbour was in view). One-off movements (#123):
263
+ // growth on a territory it held both times next to a hidden one, beyond what it was expected
264
+ // to deploy (its visible income, or the fog prior), is a stack walking in from the fog, not
265
+ // income; a capture from me is priced at what the guard I may have left kills, never my
266
+ // stack last turn (I may have attacked out of it). Each observation carries the low and the
267
+ // high reading of those ambiguous armies, and a rationale line names them. A territory hidden last turn
268
+ // (fogged, or under a fog level that hid its armies) is a fog reveal, never growth or a
269
+ // capture (issue #69). The observed figure is capped
270
+ // at what the opponent could earn on this board: its base income plus every bonus none of
271
+ // whose territories someone else visibly holds, owner-only included (a warning says when) —
272
+ // #226: with per-territory income the base counts every territory it could hold (its visible
273
+ // ones and every one whose owner the board hides), so the cap and the fog prior are not held
274
+ // at the base its few visible territories pay; a fog reveal stays no income, but one whose
275
+ // armies exceed its estimate in such a game is named in a warning (stacks that size say it
276
+ // holds more than is in view). #226: given my orders on the previous turn
277
+ // (`previousOrders`, what warapp_submit_turn cached), the defenders my failed attack killed
278
+ // on a territory that stayed its count back into its growth there (after = before + deploy
279
+ // − kills, kills straight-rounded at the offensive kill rate; beside the fog an ambiguous
280
+ // growth like any other, within #123's bound), and a rationale line says so. #271: given those
281
+ // orders, a failed attack on a hold of mine (`repelledFloor`) bounds its deploy from below, fog or
282
+ // not: my loss there (what my orders do not explain) needed at least `fewestAttackersToKill`
283
+ // attackers (luck included), all from its stacks beside the hold at the start of the turn (less
284
+ // the guard) plus what it deployed there — counted when every neighbour showed its owner, its own
285
+ // showed their armies, it is the only other player beside the hold, and Multi-Attack is off;
286
+ // only when every transfer of mine into the hold surely arrived whole (`HoldLoss.inflowSure`: its
287
+ // source mine on both boards, showing exactly what my orders leave there, and left more than the
288
+ // guard or beside no other player), never a hold an order `moves` does not carry touched (a
289
+ // Transfer Only, Attack Only or percentage order in `sent`, a card play in `cards`; orders cached
290
+ // before those were kept read nothing), and on a turn an opponent may have played a Bomb
291
+ // (`bombPossibleOn`, `PlannerSettings.bombFrom`) after taking out half the hold, rounded up. A
292
+ // capture of a neutral in view beside the fog that needed more attackers (`fewestAttackersToTake`)
293
+ // than its stacks in view sent (`unseenAttackers`) reads what stands there beyond those as deploy
294
+ // within #123's bound, the rest a move out of the fog. Its stacks in view beside a capture, hidden
295
+ // the turn after, may have moved in (`arrivals`): never deploy (only the high reading counts them).
296
+ // A known under-read: such a stack is claimed whether or not it emptied, and it is often hidden
297
+ // only because the capture took my territory and my sight with it, so a real deploy-then-capture
298
+ // beside one reads its surplus as an arrival, in the high reading only.
299
+ // A rationale line says each. A rationale line names
300
+ // the turns compared and the territories counted vs skipped as reveals; the warning
301
+ // names which source won. Given `tracks` (`trackOpponents` over my board history, S3), an
302
+ // opponent observed over at least TRACKED_MIN_TURNS turns gets its tracked income (the
303
+ // larger of the most it was observed to deploy over its last three observed turns — each a
304
+ // lower bound — and its visible army growth plus losses per turn less fog arrivals, capped at what it could
305
+ // earn, floored at base + visible bonuses; #99, `trackedIncome` — and never decaying: an
306
+ // earlier window's figure is carried until a bonus it visibly held is visibly broken, less
307
+ // that bonus's value, and never above what it could earn; my own orders, when known, are
308
+ // measurements; #119) in place of the
309
+ // single-turn observed figure, and a rationale line says so; fewer turns change nothing.
310
+ // The newest observed turn never lifts a usable track (#235 1c): a stack walking in beside
311
+ // the fog is not income (#123 lesson 5). When the track ends on this board and #123's bound cut
312
+ // armies beside the fog on its newest turn, a warning labels the cut reading ("reads up to +N
313
+ // if the armies that arrived beside the fog were deploys …; the estimate keeps ~T") and names
314
+ // warapp_check_plan's enemy_deploy to test it (`newestCut`). The planner reads that turn with
315
+ // the track's own bound (`ObservedTurn.expected`), so its observed line agrees with the track.
316
+ // With a usable track the fog prior stays out of the bound (#235 review).
317
+ // The fog prior (#119, `EnemyIncomePrior`): when `game.symmetricStart` says every player
318
+ // started even, with no teams and every seated player still playing — a 1v1, or (#226) a
319
+ // free-for-all, each opponent alike (a game with a player out is not: a survivor, or I, may
320
+ // have absorbed its territories; a player that never took its seat does not count) — an opponent
321
+ // bordering the fog (a territory next to one of its own shows no owner) is estimated at
322
+ // least at my own income (card armies out), capped at what it could earn on this board —
323
+ // every observed figure is a lower bound under fog, and the estimates read 2–3× low
324
+ // against a finished game's true deploys without it. When the award of picks proved all its
325
+ // starts (`game.opening`, #166), the prior is the larger of my income and the income the pick
326
+ // advisor's opening simulation (`openingIncome`) gives it this turn from those starts. It only raises an
327
+ // estimate; the warning calls it a prior, not an observation, and says which. #235: "even" is any
328
+ // distribution but a custom scenario (a map's scenario distribution included: it only says where
329
+ // each player starts); in a free-for-all the cap is an even share (1 of its opponents) of the
330
+ // territories the board hides and of the bonuses it could still hold (its own in full), and a
331
+ // free-for-all with no teams that gets no prior says why (`game.unevenStart`, a player out — never
332
+ // listed among the opponents beside the fog). The
333
+ // prior shrinks with evidence: with a usable track it keeps PRIOR_EVIDENCE_TURNS / (PRIOR_EVIDENCE_TURNS
334
+ // + its consecutive observed turns up to the newest board, none when the run stopped earlier, × the
335
+ // share of its edge in view) of its lead over the larger of
336
+ // its tracked income and its visible income (`priorBlend`), and the warning names both.
337
+ // In a 1v1 too, so it trades #119's prior back toward tracked figures #119 found 2-3x low:
338
+ // PRIOR_EVIDENCE_TURNS (4) is unmeasured against a finished 1v1.
339
+ // #164, exact income: under a fog setting that shows every owner (`OWNERS_SHOWN_FOG`: No, Light
340
+ // and Dense fog, matched by name, never by the engine's order) on a board that shows every
341
+ // territory's owner, an opponent's estimate is its base plus the bonuses it holds, exactly
342
+ // (`source` 'exact', no MIN_ENEMY_DEPLOY floor; the opening board keeps its floor): observed,
343
+ // tracked and prior figures are reported, not used — a deploy above it was a card or a misread.
344
+ // Only the army cap, Sanctions and a Reinforcement card are unknown. #164, Reinforcement card
345
+ // (`game.reinforcement`, the card clock): from the first turn one can be in a hand, its armies
346
+ // are added to every opponent's estimate until a deployment above its income is seen (its low
347
+ // reading over the exact income; under other fog, a jump of the card's armies over its visible
348
+ // income), then again from the turn the next card can be due (the first turn plus a card's
349
+ // capturing turns per card played, never before the turn after the play); a warning names it.
350
+ // It is coarse both ways, and the warnings say so: one card at most is counted, though more may
351
+ // be in hand after a long time due; and under fog, income the fog hides can read as a play, so
352
+ // the card is dropped and the estimate errs low (a warning names the play it took, under exact
353
+ // income too: armies that came into view or were misread can read as one).
354
+ // #164, hidden stacks: an opponent's territory next to mine whose owner shows and whose armies
355
+ // the fog hides (Dense / Heavy fog) is one of its stacks in rule 1's threat, of its unaccounted
356
+ // armies (the tracker's `unexplained`, at most HIDDEN_POOL_INCOMES turns of its income, a
357
+ // Reinforcement card left out; the guard alone without a track) — never unseen land and never a target (a warning says the win
358
+ // chance is unknown). The pool is one: its first hidden stack next to a territory of mine
359
+ // carries it, any other there the guard alone (movable 0).
360
+ // A large stack that left view (the tracker's `lostStacks`, for LOST_STACK_TURNS turns after it
361
+ // was seen: a stack whose territory the fog hid, or, under Normal fog, one that walked off a
362
+ // territory still in view into the fog) is, from the turn it can stand on a territory the fog
363
+ // hides next to mine (one move a turn since it was seen, never through my land), a separate
364
+ // stack of its owner there in that border's threat (its armies less the guard; the larger of
365
+ // the two when that territory is also a hidden stack of its owner; its armies are part of the
366
+ // pool, so the pool's carrier on that border keeps only what the lost stacks elsewhere leave
367
+ // of it, and at least a lost stack that can stand on the carrier itself), and
368
+ // a rationale line names it. Under Normal fog every territory next to mine shows, so it never
369
+ // stands there unseen: where it can stand beside a border of mine by next turn, a warning says
370
+ // so a turn ahead (not counted in this turn's holds). #201: a capture of mine out of the fog fixes
371
+ // where it is (the tracker counts it from the territory it took, on that turn). Arrivals assume one move a turn; with
372
+ // Multi-attack on it can come sooner, and the lines say so.
373
+ // #199: under Multi-Attack an attack's survivors carry on, so a visible enemy stack's chain
374
+ // (chains.ts, shared with check_plan's stress test: its deploy that reaches it, less the
375
+ // guard, luck-free, at most CHAIN_MAX_STEPS attacks deep) that takes one territory or more not
376
+ // mine and then attacks a territory of mine — or one the plan captures (not the chain's own
377
+ // player's: its stacks next to it already count) — is a threat there, the armies it lands; a
378
+ // border's threat is the larger of that and its stacks next to it, and a territory no stack
379
+ // touches can be a border by a chain alone. A chain through a territory the plan captures does
380
+ // not count. The floor tier (#118) counts a chain of the stack's armies alone, no deploy, as
381
+ // armies already next to a border. A warning names each chain that sets a border's threat
382
+ // ("Multi-Attack chain: …"), and its player's deploy estimate is explained like a stack's.
383
+ // `options.enemyDeploy` overrides all of them. Always a warning.
384
+ // 1t. Trend. Given `previousBoard` (my view one turn earlier), each visible
385
+ // enemy territory next to me that was visible then (owner and armies, #69) under the same owner and
386
+ // has grown is "building" at growth = armies now − armies then per turn, less what a visible
387
+ // neighbour of the same owner sent (its shrink, claimed once: a transfer is a one-off, not a
388
+ // trend; a neighbour that shrank beside another player's shrinking stack fought and sent
389
+ // nothing) and at most its owner's observed deploy with every ambiguous army read as deploy
390
+ // (#123, `high`: a stack that walked in beside the fog is massing all the same) (a
391
+ // warning naming my most exposed neighbour and the armies it needs to hold
392
+ // next turn and the turn after). A border's threat becomes movable +
393
+ // max(enemyDeploy, the owner's fastest growth next to it), so its hold cost
394
+ // and the leftover margin both use the projection (a rationale line says so).
395
+ // 1e. Finish off (under `balanced` and `defend`, before triage; issue #45). For
396
+ // each visible opponent whose every territory is visible (none borders the fog)
397
+ // and borders mine — fewest territories, then fewest armies, then id — size
398
+ // attacks on its territories against its best response: its deploy estimate D is
399
+ // ONE budget, split (in whole armies) over its territories to save as many as it
400
+ // can. An attack that takes up to c defenders is saved by c − armies + 1 deploys
401
+ // there; saving the cheapest first is optimal, so the sure falls are exact
402
+ // (`guaranteedFalls`). Every sizing is searched: each territory attacked as if
403
+ // 0..D of the deploy lands there, or not attacked (all of them while there are at
404
+ // most 1024 sizings, else evenly spaced shares, always including D), with the
405
+ // usual capture rules (single and combined attacks, kill rates, luck, R3);
406
+ // a softener in a combined capture never kills the defenders there now either.
407
+ // Every opponent in reach is tried, not only weak ones. A sizing succeeds when every
408
+ // territory falls for sure (elimination, so each attack is sized for all of D), or
409
+ // when the sure falls leave it at most one territory or take at least half of it,
410
+ // no attacking border faces a territory left unattacked, and every hold worth
411
+ // paying for against those is funded. The best success wins: elimination, then
412
+ // more sure falls, then fewer attacking armies, then a dearer cheapest save, then
413
+ // fewer deploys. Holds that pass rule 1a's CONCEDE_FACTOR test against other
414
+ // players (and against what a retry leaves unattacked) come first: an attacking
415
+ // source keeps what holds it; on a border that attacks nothing, each hold, best
416
+ // worth per army first, is deployed there while the attacks are sized when it fits
417
+ // what is left (one that does not is left to triage), then released for triage to
418
+ // deploy. When the best sizing fails only on an unfunded hold, the search runs once
419
+ // more with those holds reserved and those territories left unattacked, and its
420
+ // best is kept if it beats the first search's. With no success, nothing changes.
421
+ // #179: under Local Deployment each territory is sized for the deploy that can reach it
422
+ // (`deployReaching`: its bonus pools pay only into their own territories), and a target whose
423
+ // save needs more than that falls for sure (`guaranteedFallsReaching`). Unless I am known to
424
+ // move first, an elimination is first tried covering its exits onto my land: each territory
425
+ // of mine next to it holds against its stacks there plus that deploy (as if halved by a Bomb
426
+ // first when an opponent may hold one, #163; a source keeps it and
427
+ // what its attack would lose defending; a border that attacks nothing is deployed to), and
428
+ // keeps it through the later passes (`coverKeep`); unaffordable, it is planned uncovered with
429
+ // the move-order caveat ("Cover player …'s exits"). In an FFA (two or more opponents) an
430
+ // elimination is priced first: the players its land makes me border and the frontier cost
431
+ // before and after (`frontierDelta`, its threat gone); a buffer whose removal costs more than
432
+ // a turn of my income and more than PAYBACK_TURNS × the income its land adds is left standing
433
+ // ("Not finishing off player …"), and no pass takes its territories this turn.
434
+ // #201 (adapting, an FFA with two or more opponents and a leader on strength that is not me): a
435
+ // player smaller than me, not the leader, is finished off or pressed only when its income added
436
+ // to mine reaches the leader's ("Absorb player …"); otherwise it is left standing the same way
437
+ // ("Not finishing off player … (#201)"), no pass takes its territories, and its "Not attacking"
438
+ // reason says so: the armies are better spent with the others against the leader.
439
+ // An opponent bordering the fog is never eliminated (issue #60): it is pressured
440
+ // instead — every visible territory attacked, each sized for its full deploy plus
441
+ // pressureMargin (an attack sized for exactly the estimate failed live), and
442
+ // only when all of them fall for sure ("Pressure player …: take all N of its visible
443
+ // territories …, so this is not an elimination", with a warning that it may hold more
444
+ // in the fog) — when each of those margin-sized captures costs at most PRESSURE_FACTOR × a typical
445
+ // expansion capture (the median capture cost of the visible neutrals next to me; with
446
+ // none, any cost), or (#120) is paid outright from the armies already on one of my
447
+ // territories next to it beyond what holds it (no deploys; each source pays once; never under
448
+ // No-Split, where it takes that source's one order): it then displaces no expansion, and a
449
+ // rationale line names the source ("… is paid from idle armies on …"). Otherwise it is not attempted (a warning says so when its visible
450
+ // territories could all be taken); with fog anywhere else, the
451
+ // elimination is hedged ("if it holds nothing in the fog") and a warning says it
452
+ // may hold unseen territories. When it can save some attacked territories, a
453
+ // warning says it chooses which. Borders next to the attacks are then re-judged
454
+ // without the territories attacked, and triage judges each border by the armies
455
+ // that stay on it. A border held last turn (per `previousBoard`) by a weak opponent
456
+ // (fully visible, fewer territories than mine, deploy below my income) that
457
+ // threatens it now is never conceded economically (the rationale says so once its
458
+ // hold is deployed); under `balanced` its hold goes first.
459
+ // 1a. Triage (every goal). Each threatened border's protected value is the sum
460
+ // of my complete bonuses containing it, plus incomplete bonuses containing it
461
+ // that I would lose all access to without it, plus (#122) its share of every other
462
+ // incomplete bonus containing it that I am building — value × the members I hold ÷ its
463
+ // size, one decimal, when every missing member is a visible neutral and finishing it passes
464
+ // rule 4's economy tests (PAYBACK_TURNS, WASTELAND_FACTOR) — plus the per-territory
465
+ // income it carries (each bonus counted once). Its worth adds the armies a
466
+ // hold saves, in income terms (armies / PAYBACK_TURNS): a top-up that keeps a
467
+ // big stack is worth paying even for a small bonus (live, a 60-army border
468
+ // protecting +4 needed 20 and held against 105). #235: a border whose loss cuts my
469
+ // holdings in two (its neighbours of mine fall into two or more parts without it) also
470
+ // protects what it cuts off — every part but the largest (most territories, then armies, then
471
+ // id): their income (positive bonuses held in full inside them, plus their per-territory
472
+ // income) in its protected value, their armies in its worth (/ PAYBACK_TURNS) — and a
473
+ // rationale line names the cut ("… links my holdings: losing it cuts off …") when it can change
474
+ // the judgement: income, or at least PAYBACK_TURNS armies (never a 1-army leaf). The cut's
475
+ // per-territory share uses my start-of-turn count, as the border's own does. #275 (pattern 2),
476
+ // guard off only: a border also protects BREACH_WEIGHT (0.5) of its breach cost
477
+ // (src/analysis/breach.ts, the deploy book's `breachAt`): the positive bonuses held in full (its own
478
+ // left out) with a member among my territories within two steps behind it that face no enemy or
479
+ // fog, that no other front reaches within two steps, and that are hollow (none of mine beside
480
+ // them, themselves included, holds the largest visible foe stack beside the border plus its
481
+ // owner's deploy), plus their per-territory income; what #235 cuts off is not counted twice. A
482
+ // rationale line names it ("… alone shields … (#275)"). Its hold cost is the fewest
483
+ // deploys making `armiesToTake(armies + d) > threat`. Every border facing one
484
+ // opponent is sized for that opponent's whole deploy (#69): it picks where to land
485
+ // after I commit, so that is each border's worst case, and a sure hold of several
486
+ // needs each sized for it (a rationale line says so when two or more are held
487
+ // against one player); a held bonus whose borders cannot all be sized so is floored and
488
+ // kept rather than conceded (rule 1h's floor tier, #118). Borders are taken in
489
+ // order of worth per army of hold cost (ties: lower hold cost, then id); a
490
+ // border is conceded when its hold cost exceeds the budget left or
491
+ // CONCEDE_FACTOR × its worth (so a thin border protecting nothing is
492
+ // conceded) — but never on worth in the opening phase when the hold costs no more than
493
+ // the armies already there (#122: a start facing an enemy start was stripped for want of
494
+ // 2 armies). Under `goal: 'defend'` the plan deploys each hold, and a held
495
+ // border then makes no moves.
496
+ // #201, holds by the standing (adapting, the profile's standing): ahead, every held bonus is held
497
+ // for the worst case — its units (rule 1h) run before any capture in rule 4a's greedy step,
498
+ // completions included ("Ahead (#201): …"); behind, each border is sized for the expected attack
499
+ // (#59: the movable armies next to it plus the whole deploy estimate, the largest over every
500
+ // adjacent player), not the worst case the growth trend projects — the deploy still counts in
501
+ // full on every border, so no border is short of one deploy landing there; separate attacks,
502
+ // chains, Bomb sizing, my commander's territory and an `enemyDeploy` override keep the worst case —
503
+ // and a warning names the gamble ("Behind (#201): …"), and a border's "could be taken" warning is
504
+ // restated against its worst case. Even keeps the rules above. The behind gamble is only the
505
+ // growth trend above the deploy: with no trend above it, behind sizes each border as `defend`
506
+ // does. A border sized below the whole deploy (the movable stacks alone) was tried and dropped:
507
+ // it broke #118, and one stack beside two such borders splits its deploy to take both.
508
+ // Expected-case holds below the whole deploy (cover odds k ≤ 1) remain open on #201.
509
+ // Scope of "protected value", deliberately narrow: only bonuses containing T
510
+ // count (not a bonus T merely borders; a negative bonus I hold in full that contains T
511
+ // counts against it, #128 — losing T lifts it — floored at 0), and an incomplete one counts in full
512
+ // when T is my only foothold, however much of it the enemy holds, else by its share
513
+ // while I am building it (above). So with no complete bonus, no bonus being built and
514
+ // no per-territory income (`bonusArmyPer` off, or its armies still below the base income
515
+ // they replace), a threatened border protects +0 and is conceded: early in a game
516
+ // `defend` holds nothing and withdraws from every threatened border, keeping armies for
517
+ // expansion.
518
+ // Triage deploys nothing to a conceded border (unless every territory I hold is
519
+ // conceded): it may still attack out with the armies already on it, since they
520
+ // are lost anyway if they stay, but no capture is funded there. A conceded border
521
+ // can still get deploys three ways: as a finish-off source (rule 1e runs before
522
+ // triage, and its attacks keep the deploys they were sized with), under Local
523
+ // Deployment, from its held bonus's own pool, which lands only inside that bonus (rule 1b),
524
+ // and (#214) as the source of a lead step (#203, rule 0p.2), sized for the attack alone.
525
+ // Under `balanced` a hold is not deployed here: it competes in the greedy
526
+ // step (rule 4a), and a threatened border it might hold makes no attacks. #215: one whose
527
+ // hold costs more than the whole deploy left is conceded here as under every other goal (the
528
+ // greedy step could never fund it; left pending, a border just taken from a weak opponent —
529
+ // exempt from the economic test — kept its armies home beside a 2-army member of an enemy
530
+ // bonus), and a pending hold the greedy step concedes is unlocked: every break and counter
531
+ // candidate next to it that has not yet captured runs again, in its order, before rule 1b
532
+ // withdraws (the breaks were tried while it was still locked, so its armies would otherwise
533
+ // only withdraw). Except (#215 review) a border in a bonus this turn's captures may complete
534
+ // without it (every missing member a capture target next to another territory of mine, its
535
+ // armies to finish within the income plus the armies there): it stays a pending hold, and once conceded it
536
+ // stays locked until the greedy step ends; then it is unlocked (and its breaks retried) only if
537
+ // no capture completed that bonus — else rule 1c keeps it and the leftover garrisons it (an
538
+ // attack out first, under No-Split with its whole stack, left the kept border empty). Only the
539
+ // lock triage itself added is lifted. The "Not attacking" line gives what a conceded neighbour
540
+ // can still send once its orders leave ("has left for it … conceded"; the guard-off cover's
541
+ // army excluded; under No-Split, one whose order already carries its whole stack says so),
542
+ // never "spare once it holds its border".
543
+ // 1h. Held bonuses (under `balanced` and `defend`; issue #51). Every bonus I hold in
544
+ // full with a threatened border is one unit: its threatened borders are all held
545
+ // or none (holding some while conceding another breaks it anyway). Its hold cost
546
+ // is the sum of its borders' (a border shared by two held bonuses counts in both
547
+ // units' feasibility, and is paid for once). A unit pays for itself when that cost
548
+ // ≤ PAYBACK_TURNS × its value and, as rule 1a asks of every border, ≤ CONCEDE_FACTOR
549
+ // × its worth (waived when a member was just taken from a weak opponent); one that
550
+ // does not is not conceded yet (#118): those tests concede only when the armies have a
551
+ // better use. It is floored (below) and waits for the captures; once they are planned
552
+ // (before rule 1c, and under `defend` after passes 1–2), it is held whole if what is left
553
+ // covers it (rationale "… (more than …), and nothing else this turn uses those armies"),
554
+ // else spread (below) when floored, else conceded whole as before. Under Local Deployment (#103) those tests (and its score)
555
+ // use the cost net of the bonus's own pool, max(0, cost − pool): the pool can be
556
+ // deployed nowhere else. A unit that pays is funded before any capture that
557
+ // completes no bonus (advances, breaks, other expansion, unless focused): under `defend` with the
558
+ // other holds, by worth per army (worth = value + the armies its holds save /
559
+ // PAYBACK_TURNS); under `balanced` it competes on that score with holds and
560
+ // completions, and at the first advance or break every pending unit runs first
561
+ // (with the completions outscoring the weakest of them). A completion that runs
562
+ // before a pending unit and would leave too little to fund it (under Local Deployment,
563
+ // a unit counts as fundable only when its own pool and the free armies cover it) waits
564
+ // until they are funded unless (#122): when a starved unit would be conceded (not even
565
+ // kept as a near miss or floored on what is left), its one turn of value beats
566
+ // PAYBACK_TURNS × the bonuses conceded — waiting costs the completion one turn, losing a
567
+ // held bonus costs it every turn until retaken; when every starved unit is only left
568
+ // short, its bonus earns more than they do, or each stays a near miss and the completion
569
+ // pays for itself within a turn (cost ≤ value). It waits for
570
+ // rule 4a's expansion share only until then. Finishing off (rule 1e) keeps its place before
571
+ // it. A unit the armies left cannot cover is first tried as a near miss (issue #59):
572
+ // each border not yet held gets what may still be deployed there, up to its hold
573
+ // cost (pools respected), and the unit is kept — deploys stay, nothing withdrawn,
574
+ // a warning "… is held though short …; X may fall" — when the total is short by at
575
+ // most nearMissMargin(need) = max(NEAR_MISS_ARMIES, NEAR_MISS × need), or when every
576
+ // short border still holds against the expected attack (movable + deploy estimate,
577
+ // no trend projection). Otherwise it is floored (below) and kept, or, when no floor is
578
+ // funded, conceded whole ("conceding bonus …:
579
+ // holding all N threatened borders needs X, more than …"; a one-border unit keeps
580
+ // rule 1a's warnings).
581
+ // Floor tier and one shared deploy (#118). One enemy deploy lands on one target, and
582
+ // sizing each border for all of it (rule 1a) conceded every bonus once the deploy outgrew
583
+ // them though the stacks next to them could take none. So a unit about to be conceded
584
+ // (either test above, or the armies left cannot cover it) whose every threatened border
585
+ // faces a player with two or more threatened borders of mine to aim at gets its floor
586
+ // first: the deploys making each border beat the armies already next to it (the most
587
+ // movable armies one player has there, its commander included; at most its hold cost),
588
+ // all of the unit's floor or none, by value per army. Against a player with one target
589
+ // its whole deploy lands there, so a floor alone saves nothing and the unit goes the old
590
+ // way. A floored unit is kept ("contested"): never conceded or withdrawn from, its borders
591
+ // make no attacks. After the captures, what is left first holds contested units whole (best
592
+ // worth per army first) — unless spreading it over the floored units instead loses less
593
+ // bonus value to the opponents' best response (each player's one deploy split to break the
594
+ // most value, a knapsack over its cheapest break per unit; both simulated, Local Deployment
595
+ // off; a rationale line says so) — then is spread over the borders still short one army at a time, to
596
+ // the one the opponent's deploy breaks most cheaply (armies to take it less the armies next
597
+ // to it; ties: the higher bonus value, then id), each up to its full hold — the way
598
+ // `guaranteedFalls` sizes the opponent's single budget on offence (rule 1e). A warning names
599
+ // a bonus left short ("… is not safe against the whole enemy deploy …, but it is not
600
+ // conceded: … it falls only to armies deployed against it", then one line per opponent:
601
+ // "Player P's ~D deploy can still break … (N of it needed): +V at risk this turn"). Idle armies next to a border
602
+ // are not counted as hold funding: a transfer runs in move order, interleaved with the
603
+ // opponent's attacks, so it may arrive after the attack it was meant to stop.
604
+ // Each border of a conceded unit is then judged alone by rule
605
+ // 1a with its protected value less that bonus (other bonuses, per-territory income,
606
+ // the stack it saves), and held only when that justifies it. Under `expand`
607
+ // nothing changes, but a warning names each held bonus whose holds would pay back;
608
+ // `complete-bonus` is unchanged.
609
+ // 1k. My commander (every goal; #61). A territory where my own commander stands is
610
+ // must-hold: when threatened it is held before any other hold or capture (only a
611
+ // commander strike, rule 1s, comes first, and it reserves this hold), never
612
+ // conceded, and it makes no attack or transfer except that strike. When the hold
613
+ // does not fit, all that may still be deployed there goes there, with a warning.
614
+ // Unthreatened, any attack from it keeps what holds it against the visible enemies
615
+ // next to it; next to an enemy at the start of the turn, or to a border the plan concedes
616
+ // (#121: the enemy takes that next), it never transfers out (a capture that makes it
617
+ // interior can still fail). A held bonus containing it leaves
618
+ // its hold, once fully funded here, out of the bonus's cost and payback test (rule 1h):
619
+ // neither its hold cost nor the stack it saves counts for the unit.
620
+ // #274: its threat is the worst case, never less than the visible one: per opponent (a team
621
+ // together; as the FFA leader every opponent together) its whole deploy, at least my own
622
+ // income (as warapp_submit_turn sizes its replies; a what-if `enemyDeploy` as given), plus the
623
+ // movable armies of every stack of its within two moves of it. Under Multi-Attack this holds
624
+ // even with no enemy beside it: a stack two moves away may chain through my land onto it.
625
+ // 1w. My commander walks (#274, plan/commander.ts). Within COMMANDER_CLEAR_MOVES (3) moves of an
626
+ // enemy or fogged territory, with a territory of mine strictly farther from all of them
627
+ // reachable through my land — never onto one nearer an enemy than where it stands, nor onto
628
+ // one beside an enemy or the fog (taken first, the step would turn the transfer into an
629
+ // attack) — it walks one step a turn along that path (`commander: true` on a transfer, the
630
+ // #165 option, encoding unverified live): on the move out of its territory to that step when
631
+ // the plan has one, else its own transfer carrying no armies (under No-Split, the territory's
632
+ // one order, entered before any pass plans, with the whole stack: it wins over a commander
633
+ // strike or a kill that territory could have made, which the passes then leave out; a commander
634
+ // kill it alone could have sent is named in a warning, with how to send it by hand). The step,
635
+ // not where it stood, is my commander's territory for rule 1k this turn; where it stood is held
636
+ // only for its own worth, its commander's 7 not counted there — except that after the strikes
637
+ // and before triage it gets the deploys that survive what may land there before the walk
638
+ // (each stack plus its owner's whole deploy, at least my income; my commander counted), after
639
+ // the hold the step needs. Moving first, a walk that is not my first order runs after two of
640
+ // the opponent's (me1, opp1, opp2, me2), so the hold is sized for every enemy stack beside it
641
+ // attacking in turn (#274 review 2); when that does not fit, for each player's strongest attack
642
+ // only, and the walk is then my first order (`commanderWalkFirst`, no Order Priority advised for
643
+ // it: the hold covers what lands before it; a warning if a strike or kill still goes first); when
644
+ // neither fits, all that is left goes there, with a warning. It does so even when I am known to
645
+ // move first: warapp_submit_turn's commander check is not told who moves first and tries the
646
+ // opponent first too. The walk goes early; it is my first order after a strike that protects my
647
+ // commander or ends a player when the hold covers only the first attacks, or when my commander
648
+ // may be caught before it runs — the transit hold falls short, or the fog borders where it
649
+ // stands — and only then is Order Priority advised for it when I hold one, whatever it carries;
650
+ // otherwise the first order is chosen as before. Every other move out of its territory waits for
651
+ // the walk (the armies there hold it until it leaves), except a strike that ends a player. A walk
652
+ // carrying no armies never waits behind a move into its territory (one carrying armies does:
653
+ // they may be arriving). The plan's first warning says it
654
+ // walks. With no such territory it stays, rule 1k holds it against the worst case, and a hold it
655
+ // cannot fund is the first warning. `commanderWalks: false` keeps it where it is.
656
+ // 1s. Commander strike (every goal, before finishing off, triage and any expansion; #61).
657
+ // A visible enemy commander next to a territory I held at the start of the turn is
658
+ // attacked first — killing it eliminates its owner — sized for its armies + the
659
+ // commander's 7 + its owner's full deploy estimate (#179: under Local Deployment, what can
660
+ // reach it). In an FFA a rationale line says who borders the land it leaves neutral; a
661
+ // commander strike is never gated. Nothing is conceded yet, so a thin
662
+ // border next to it may strike with deploys. No vanishing: war.app interleaves both
663
+ // players' attacks, so only the struck territory stops threatening; the owner's other
664
+ // stacks still count in every threat this turn (elimination changes next turn). My
665
+ // commander's must-hold reserve is funded first: the deploys its territory needs against
666
+ // those threats (all that may be deployed there when the hold does not fit). The strike
667
+ // is funded from what is left plus each source's movable armies beyond its keep (what
668
+ // holds it); a source other than my commander's whose hold is hopeless even with the
669
+ // deploys left keeps nothing (its armies are lost anyway). R3 never vetoes a strike (the
670
+ // bonus side-effect is irrelevant). A source that already issues an order (No-Split) does
671
+ // not strike (strikes run before every other pass, so no source is locked or conceded
672
+ // yet). With no source able to send that many, and no finishing off taking it, a warning
673
+ // names what held it back — a source's keep (only when that source could send enough
674
+ // without it and the reserve), the reserve (only when it binds: a source could send
675
+ // enough with its keep but for the reserve, or dropping the keep alone would not do),
676
+ // No-Split, or "unaffordable" — and nothing is attacked.
677
+ // When a strike is planned and, once every deploy and move is planned, what stays on my
678
+ // commander's territory falls to the visible stacks next to it — the struck one included
679
+ // (attacks interleave, so it may attack before the strike lands; a strike from my
680
+ // commander's territory thins it) — `cardAdvice` is Order Priority if I hold one
681
+ // (`holdsOrderPriority`: my attacks resolve first), with a rationale line; without one, a
682
+ // warning says the attacks interleave. Its owner is not also finished off (rule 1e).
683
+ // 1c. Reconsider (every goal, after the capture passes, and again before the leftover for
684
+ // captures made later, #122). Triage runs before captures are known, so a border in a
685
+ // bonus this turn's captures complete may have been conceded. Protected value is then
686
+ // re-judged against my holdings plus this turn's captures: a conceded border in a bonus
687
+ // completed this turn (not already withdrawn from) is kept (its concession warning
688
+ // dropped, a rationale line added), never withdrawn from, and garrisoned from the leftover
689
+ // (rule 5); a warning says so when the leftover still cannot make it hold. A conceded
690
+ // border may fund (be deployed to for) a capture that completes a bonus it is in — with the
691
+ // members already taken, or (#214) with the sibling steps the same completion (pass 1, all or
692
+ // nothing: undone whole if one fails) plans this turn.
693
+ // 1g. Garrison a completion (under `balanced` and `defend`; #122). Once a capture completes a
694
+ // bonus, its members I held at the start that face an enemy and would fall are held whole
695
+ // right away, before any later capture — a held bonus's unit tests (cost ≤ PAYBACK_TURNS ×
696
+ // value and ≤ CONCEDE_FACTOR × worth), and its members' deploys must fit together what may
697
+ // still be deployed (under Local Deployment, the pools checked for all of them at once);
698
+ // otherwise they get the leftover as in rule 1c. A rationale line "Garrison … completed this
699
+ // turn" names each; the leftover then tops them up to a comfortable margin as it does a
700
+ // border rule 1c keeps. Captured members are not garrisoned (next turn's deploys land first).
701
+ // 1b. Withdraw (under `defend` and `balanced`, after 1c). A conceded border's movable armies move first
702
+ // to the adjacent territory of mine nearest a border that holds (then the
703
+ // one protecting the most value, then id); the largest is my first order, and the plan
704
+ // advises Order Priority (`cardAdvice`) under rule 7's test, because a withdrawal only
705
+ // executes while the border is mine.
706
+ // A conceded border of a bonus I hold in full whose armies staying still hold
707
+ // against the expected attack (movable + deploy estimate) is never withdrawn from
708
+ // (issue #59): its garrison stays, and under Local Deployment its bonus's leftover
709
+ // pool may go there as if it were not conceded. Nor is any other conceded border of a bonus
710
+ // I hold in full (#118; Local Deployment off) unless its armies make the territory they
711
+ // would go to — a border facing an enemy, protecting value, not conceded — hold this turn
712
+ // when it would not without them: where they stand they kill attackers ("Keep the N
713
+ // movable armies on … (not withdrawn): it is a border of held bonus …"). Under Local Deployment (#103) a border
714
+ // of a conceded held bonus also keeps its garrison unless the bonus truly cannot be held
715
+ // (one of its threatened borders needs more than the pools containing it plus every free
716
+ // army): withdrawing turns "might lose it" into "certainly loses it". A warning says which
717
+ // case applied ("… is conceded but might still hold" / "… cannot be held"); a kept border
718
+ // may also take the leftover deploy.
719
+ // #272, before rule 1c re-values the borders and it withdraws (plan/conceded-out.ts): a conceded border attacks out with its own
720
+ // armies (no deploy) into a neighbour holding at most CONCEDED_OUT_MAX (2) armies — a neutral,
721
+ // or a foe's with no special unit, never a truce's, a player's only off `expand` — whose capture
722
+ // completes a positive bonus or advances one I am building (another member mine or captured;
723
+ // under No-Split, which sends the whole stack, a completion only), when its armies cover the
724
+ // cost: completions first, then bonus value, cost, a teammate's focus (C3.4) and id, again
725
+ // while one capture makes another complete. R3 does not refuse it (the armies would otherwise
726
+ // leave a border the plan gives up), and a completed bonus keeps the border (rule 1c). Live, the
727
+ // last empty members of a bonus stood beside a conceded border: one was taken, the other refused
728
+ // ("a conceded border never attacks out for a capture that only costs nothing").
729
+ // 1i. Income at risk (#109). `expected.nextIncome` is next turn's income if every territory
730
+ // the plan keeps and captures is held — the borders it concedes included, withdrawn from
731
+ // or not. A conceded border is not kept, so the plan also reports
732
+ // `expected.nextIncomeIfConcededFall` — the one income rule (`incomeAfter`, negative and
733
+ // overlapping bonuses and per-territory armies included) over the holdings after the plan
734
+ // less every conceded border — and `expected.bonusesAtRisk`: each positive bonus complete
735
+ // after the plan (held at the start or completed this turn) with a conceded member. Both are
736
+ // present only when the figures differ or a bonus is at risk. When the at-risk figure is
737
+ // lower a warning names both ("This plan concedes bonus …: next income A if they hold, B if
738
+ // the conceded borders fall."), and the frontier rationale's next income names both.
739
+ // Under an army cap (#253) both start from this turn's capped income plus the gains
740
+ // (`nextIncomeWith`): the cap is not re-run for next turn, whose cut depends on the armies
741
+ // spent and on the larger income; R3, rule 4d's frontier test and `sinceLastTurn` read that figure.
742
+ // 2. Targets: visible neutrals adjacent to a territory I held at the start of
743
+ // the turn (plus visible enemy territories under `goal: 'complete-bonus'`, and
744
+ // under `balanced` only enemy territories in a breakable bonus — one whose
745
+ // every territory is visible and held by a single enemy, or (#72) a probable one: the
746
+ // opponent's track over at least TRACKED_MIN_TURNS turns lists it in every combination
747
+ // fitting its income gap (none unlisted) or in its single best fit (fewer bonuses than the
748
+ // next), and every member is that opponent's or
749
+ // hidden — and counter-attack targets: an enemy stack next to me visible on both boards
750
+ // that shrank fighting me (every neighbour visible on both, one of them mine on both, every
751
+ // neighbour neither mine nor its owner's unchanged in owner and armies, the shrink not
752
+ // absorbed by its own neighbours' growth) and is now cheaper to take than it
753
+ // was; never under `expand`/`defend`). Fogged or unknown neighbours are never attacked — they
754
+ // produce a warning.
755
+ // 3. Capture cost (#126): the fewest armies whose exact `winChance` reaches the capture's
756
+ // chance — certain (chance 1) means every roll and rounding takes it: `armiesToTake` at 0%
757
+ // luck under straight rounding, one army more where weighted-random rounding could round a
758
+ // kill down, the kills the luck-free share guarantees with luck. An ordinary capture's
759
+ // chance is `minWinChance` (default 1 with no luck, LUCK_WIN_CHANCE = 0.95 with luck on,
760
+ // where certainty costs several times a likely win), taken to the power 1/k for a
761
+ // territory in a positive bonus with k members not mine, so the captures a bonus still
762
+ // needs reach it together; the plan states each completion's joint chance when below 1.
763
+ // Worst-case sizings (finishing a player off, fog pressure, commander strikes) stay
764
+ // certain. Holds (#126): with luck or weighted rounding a stack "needs N to take" where N
765
+ // is the fewest attackers winning more than HOLD_FALL_CHANCE (5%), so a hold above the
766
+ // threat falls to it at most that often (exact `armiesToTake` otherwise); every attack carries its
767
+ // `winChance`; after the leftover deploy an attack on a player's territory (not already
768
+ // sized for a worst case) is sized for its defenders plus what its owner may deploy there
769
+ // first (its deploy estimate, or its growth there per turn when larger; #120) when the
770
+ // armies on its source beyond what holds it (never a hold, a conceded border or the strike
771
+ // stack) cover the difference — the plain "assumes its owner does not reinforce it" warning
772
+ // is then dropped, and the attack counts as landing for sure (rule 6). Otherwise an attack
773
+ // is topped up to its next kill breakpoint from idle armies on its source (never a hold, a
774
+ // conceded border, my commander's territory or a source still facing an enemy) when its
775
+ // target is a player's or it is not certain, else an attack between breakpoints is named;
776
+ // and an attack on a player's still sized below that deploy keeps the warning, which then
777
+ // gives its win chance against the reinforced target and the size that would be sure.
778
+ // #240, repeated failure is evidence: a territory `input.repulsed` names (`repulsedAttacks`
779
+ // over my board history and cached orders: my attacks on it failed on REPULSE_MIN (2) or more
780
+ // of the last REPULSE_WINDOW (3) turns, its owner reinforcing it each time — its armies after
781
+ // plus my kills above its armies before), still that player's, next to mine and its owner able
782
+ // to deploy there, is attacked only at that sure size: its defenders plus the owner's deploy
783
+ // (a worst case, so no warning and no bare retry), or not at all; a rationale line names the
784
+ // failed turns. #272: when the most its owner reinforced it on those turns (after + my kills −
785
+ // before) is less than that deploy, it is sized for that instead — no worst case then: a larger
786
+ // deploy can still repel it, so it keeps #120's "assumes" warning, may still be sized up to the
787
+ // whole deploy by #120 when the source has the armies, and rule 6 does not count it as held
788
+ // (`repulsed`'s `sure` is false). Never retried at its bare cost either way. Every pass: rule 2's targets and the bonus, break and counter passes, rule 4e's
789
+ // fallback, the 1v1 strike stack, finishing off and fog pressure (rule 1e: its only sizing, or
790
+ // not attacked — never a share of the deploy) and the guard-off one-army break (#165: skipped,
791
+ // with a line saying why). It ranks on its PLAIN cost (#240 review: ranked on the sure size, a
792
+ // target that fitted dropped behind a worse one, most often under No-Split, where the whole stack
793
+ // goes anyway): the sure size only decides what fits (`sizeOf`) and what is sent, rule 4e's
794
+ // contact ranking tries it at its plain size (`ps.plainRepulsed`), and its survivors and trade are
795
+ // read against the defenders there now (`defendersSeen`), as without the evidence. One whose sure
796
+ // size the turn cannot fund when it is taken, but its source and the whole budget could reach,
797
+ // is taken at its plain size pending (`ps.repulsedPending`) — the plan without the evidence pays
798
+ // its sure size from the leftover (#120, #226) — and dropped once the margin has run if it is
799
+ // still short ("Drop the attack on …"). The evidence never shrinks the attack (#240 review):
800
+ // rule 5 judges its source's comfort, and whether to revive a conceded border, as the plan
801
+ // without it would (`repulsedSurplus`: the sure size's surplus over the plain one still on the
802
+ // source; one that would fall without it stays short), and the leftover put there is not kept
803
+ // from the #226 margin; the strike stack reports such an attack as sized for the deploy.
804
+ // #226, a margin: once the transfers (rule 6) have moved what they move, an attack on a
805
+ // player's territory whose owner may deploy there (not a combined capture; not under No-Split,
806
+ // which sends the whole stack already) takes the armies still on its source beyond what holds
807
+ // it (`spareBeyondHold`; never from a source rule 5's leftover went to for a comfortable margin,
808
+ // a hold before the strike stack or saving toward a step, `leftoverKept`; and, as rule 6's #128 keep, what holds the source against the threat
809
+ // beside it as if this turn's attacks on players there failed — each such target then also
810
+ // holding its owner's stacks beside it that are not beside the source, which may move in
811
+ // before my attack runs), the target with the most
812
+ // defenders first: sized to the exact kill count at an estimate the plan calls a floor, it
813
+ // would otherwise fail to one army more deployed while those armies sit idle. A rationale
814
+ // line ("Margin on the attack on …") says how much deploy it now covers; when that is the
815
+ // whole estimate the "assumes" warning goes.
816
+ // 3a. Combined (multi-source) captures (R4). When no single source can afford a
817
+ // target (its movable armies plus the deploys left), two or more of my
818
+ // sources held at the start of the turn (not locked, not conceded) attack it
819
+ // in sequence: sources by most movable armies, then id; the first is the
820
+ // finisher, the others ("softeners", in id order) each attack first with their
821
+ // movable armies (capped so they never kill the last defender), killing
822
+ // round(off × armies) defenders each, cumulatively; their survivors stay home.
823
+ // The finisher then sends armiesToTake(defenders left), deploying its
824
+ // shortfall. Fewest sources first. Exact only under straight rounding at 0%
825
+ // luck: otherwise it is skipped with a warning. It is a fallback inside every
826
+ // pass, so it only ever takes a target the passes already chose (economic by
827
+ // the same scoring), and only when no single source suffices. The plan lists
828
+ // such targets in `multiSourceCaptures`. #265: once the captures are known (before the
829
+ // leftover), a combined capture one of whose sources is a weak member of a bonus this turn
830
+ // completes (plan/completed.ts: facing an enemy once the captures land, and falling to it) is
831
+ // rebalanced at the same kills to leave armies on it — any split of the same sources that
832
+ // still takes the target with no new deploy (each softener short of the last defender) and
833
+ // lands as many survivors, leaving every other source holding as it held and never spending
834
+ // what it kept back when the capture was built (#121's safe-border keep, #172's two-step hold,
835
+ // #179's cover), never below even where the capture had to trade even (rule 0p.3 / 4e), judged
836
+ // by the armies left on the weak members up to their holds, then the smallest change, then the
837
+ // fewest lost — once they hold, nothing more moves ("Rebalance the combined capture of …").
838
+ // Never under No-Split.
839
+ // 4. Bonuses (value > 0) are scored by value / remaining capture cost, ties by
840
+ // fewest external borders, then id; focused bonuses come first. The economy test charges
841
+ // what a capture costs, not what it sends (#125): the armies its attackers lose (the
842
+ // defenders' kills at the defensive rate) plus the one army left on it, that army waived
843
+ // when a territory of mine beside it facing no visible enemy already has idle armies enough
844
+ // to take it. A bonus whose remaining members lose over PAYBACK_TURNS × value, or with one
845
+ // remaining territory losing over WASTELAND_FACTOR × value, is uneconomic and its
846
+ // territories are not planned (unless focused or also in an economic bonus); the "Skip
847
+ // bonus" line names both the armies to finish and the armies lost. Rule 1a's "being built"
848
+ // share uses the same test. With Extra Armies for Territories (`bonusArmyPer`), a bonus's net
849
+ // worth adds the per-territory income its missing members bring (1/per a territory once past
850
+ // the base income, #125), and plain expansion counts that share as each capture's income, so
851
+ // a member of an uneconomic bonus is still a territory worth taking (never a negative
852
+ // bonus's member).
853
+ // A negative-value bonus is always uneconomic unless focused, so the plan
854
+ // never captures into it (completing one would cut income). A positive bonus is
855
+ // scored by its net worth (rule 4c), not its value, in every test above.
856
+ // One owner per bonus (PLAN-TEAMS C3.3): a positive bonus with a member my teammate visibly
857
+ // holds is not scored at all (a bonus pays only the player holding every member), focused or
858
+ // not (a focus on it is ignored with a warning); its other members are plain expansion. The
859
+ // plan's `team.sharedBonuses` (plan/team.ts) lists each such bonus I hold members of too, and
860
+ // who holds the most (`nearer`), from the start-of-turn board. No-team plans are unchanged.
861
+ // Team focus (PLAN-TEAMS C3.4): with my teammates' entered orders read (V5, unverified), a
862
+ // capture of a player one of them attacks this turn ranks above one that is otherwise equal —
863
+ // right after the score in the balanced greedy (breaks, counter-attacks), before the last
864
+ // tie-breaks in rule 4e's contact ranking — and a rationale line says so. With none read,
865
+ // nothing changes. The team section also reports, advisory only (plan/team.ts): a teammate's
866
+ // border my idle armies would make hold (`team.support`, C3.5; a move onto a teammate is V7)
867
+ // and a target we take only together, on the turn simulator in both orders
868
+ // (`team.jointCaptures`, C3.6).
869
+ // 4c. Net income (#70). Maps with overlapping bonuses (each sea tile a single-territory
870
+ // −4 bonus and a member of a +22 group) are scored by every capture's effect on
871
+ // income: `incomeGain` — the one income rule's (`boardIncome`, #85) total after the
872
+ // captures less its total now (every bonus whose completion changes, per-territory
873
+ // armies, the 0 floor), the one computation `expected.nextIncome` and R3 use. A positive bonus's
874
+ // net worth is its value plus the (negative) values of the other negative bonuses its
875
+ // missing members complete (= value on a map without negative bonuses); net ≤ 0 is
876
+ // uneconomic unless focused. Completing it is all or nothing (pass 1), refused when it
877
+ // would lower income. A capture that lowers income this turn (it completes a negative
878
+ // bonus) is taken only when (a) it is part of completing a positive bonus this turn,
879
+ // (b) it is in a focused bonus, or (c) it stages a bonus: with k = ceil(the capture
880
+ // cost of the bonus's other missing members / the income left after this step) turns
881
+ // to finish (≥ 1; unknown under fog, or no income left: refused), k ≤ PAYBACK_TURNS and k × every penalty its missing
882
+ // members carry ≤ PAYBACK_TURNS × its net worth; the reason then says "stages", never
883
+ // "advances". Pass 3 never takes one. Guard: after the capture passes, while next income
884
+ // is below this turn's, the latest capture that completes a negative bonus is dropped
885
+ // (its attacks taken back, its deploys left where they are) unless focused, staging,
886
+ // a commander strike or finishing off; whatever remains is a warning with the numbers.
887
+ // Pass 1 completes bonuses that can be finished this turn (all or nothing);
888
+ // pass 2 advances bonuses one capture at a time, cheapest first; pass 3
889
+ // (not under `complete-bonus`) takes any other affordable target (never an
890
+ // enemy one under `balanced`) that passes its own economy test (#125): a member of an
891
+ // economic bonus is judged by that bonus; any other capture's armies lost (the defenders'
892
+ // kills) must be repaid by the income it adds within PAYBACK_TURNS, and one that adds no
893
+ // income may lose at most PLAIN_EXPANSION_LOSS (a rationale line "Do not expand into …"
894
+ // names an affordable one refused). The leftover's expansion stack (rule 5) is a capture's
895
+ // finisher, never a combined capture's softener.
896
+ // 4a. Balanced (the default goal). Instead of passes 1–2, every candidate is
897
+ // scored as income per army and taken greedily (focus first, then score, then
898
+ // cheaper, fewer bonus borders, id): a hold (protected value / hold cost),
899
+ // completing or advancing a bonus (value / remaining cost), breaking an enemy
900
+ // bonus (#72: sized to land, not to survive — aimed at its cheapest visible member, worth
901
+ // BREAK_WEIGHT / opponents × (its value + the armies retaking it costs, at least
902
+ // armiesToTake(my survivors), / PAYBACK_TURNS) over its capture cost plus the frontier it
903
+ // changes without its own hold need, warning when it can be retaken; #201: when I lead an FFA,
904
+ // sized to land for certain against its owner's one deploy there, as rule 1e sizes a target, and
905
+ // its reason says so), or a counter-attack
906
+ // (scored like a break worth no bonus). Every break and counter-attack considered is
907
+ // reported in `offence` with whether it was made and why (a bonus broken through another
908
+ // member, by any path, counts as made). A threatened border whose only
909
+ // visible threat is a member of a breakable bonus also attacks it, once per
910
+ // bonus: it deploys its hold plus the capture, so what stays still holds if
911
+ // the enemy reinforces that member first and the attack fails; when it cannot
912
+ // afford both it just holds (a held border otherwise makes no attacks). While expansion candidates
913
+ // remain, a hold protecting less than the best expansion's value may not dip
914
+ // into the first MIN_EXPANSION_SHARE of income not yet spent on expansion; it
915
+ // is deferred and funded afterwards if the budget allows, else conceded — but (#128) a
916
+ // capture that completes nothing never starves it: when one would leave too little for a
917
+ // deferred hold, it is undone, the hold funded first, and it runs on what is left.
918
+ // 4b. Defensibility (R3). A capture that completes a bonus is checked against the
919
+ // frontier it leaves: each member a visible enemy could take next turn (threat as
920
+ // in rule 1, armies staying after this turn's moves; a fresh capture holds its
921
+ // attack's survivors) needs holdArmies(threat) − armies more. When the total
922
+ // exceeds my next income (#128: the income the plan keeps — without the borders it concedes
923
+ // or a held bonus it has not yet decided to hold whole; rule 4d and `frontier.income` use the
924
+ // same figure) (plus this turn's leftover, for members I held at the
925
+ // start) the bonus would fall at once. #128: a member I held at the start that is exposed
926
+ // either way (its armies before any attack leaves it, against the threat without this turn's
927
+ // captures) counts only the need the completion adds — refusing would not save it — and the
928
+ // bonuses this turn's earlier captures completed share the same next income (their added
929
+ // needs count too). Then: under `balanced`/`defend` the capture is
930
+ // refused (warning "… indefensible …: not completed"); under `expand` and
931
+ // `complete-bonus` it is made with a warning. Under `balanced`/`defend` a bonus's
932
+ // score is value / (capture cost + DEFENSE_DISCOUNT × that defence cost).
933
+ // 4d. Frontier cost (#71). Every capture pays for the frontier it adds, in armies: for each
934
+ // territory it touches (the capture and its held neighbours), its border cost after minus
935
+ // before. A border (a territory of mine next to one I do not hold) costs
936
+ // NEUTRAL_BORDER_COST, plus, when it faces a visible enemy and the goal is guarded, the
937
+ // deploys it needs next turn to hold (R3's arithmetic; a capture holds its survivors).
938
+ // A capture that closes a gap lowers it, one that opens fronts raises it. A bonus's score
939
+ // is net / (cost + DEFENSE_DISCOUNT × defence cost + frontier) — its missing members' own
940
+ // hold need left out when R3 judged it, never counted twice — at least 1 army; advances,
941
+ // plain expansion (pass 3) order by capture cost + frontier; breaks and counter-attacks by
942
+ // capture cost + frontier without the captured territory's own hold need (#72: a break
943
+ // only has to land; the frontier change of my borders around it stays). Budget: the plan
944
+ // reports `frontier` (borders, enemy-facing borders, their hold cost — conceded borders
945
+ // excluded — and the next income). Under a guarded goal, a capture that adds an enemy-
946
+ // facing border without completing a bonus (not focused) is undone when the hold cost
947
+ // would then exceed the next income and the start-of-turn hold cost (in rule 4e's
948
+ // contact/late fallback it is a cost instead, #114); a warning ("Frontier grows faster than
949
+ // income") names it, and also fires when the plan's frontier ends so. #281: never a territory a
950
+ // static seat left (rule 0s) that costs at most VACATED_MAX_COST and borders a live opponent's
951
+ // stack able to take it with what stands there (`denialOf`): that border comes either way, so
952
+ // it is let through, a line ("Take … though it faces player …") says so, and pass 3 ranks it by
953
+ // capture cost plus the frontier without its own hold need, less the denial (1 + PAYBACK_TURNS ×
954
+ // the bonus progress it gives that opponent: a bonus it completes, else value ÷ size per bonus
955
+ // it holds a member of). That credit can put a denial ahead of every plain capture (its score
956
+ // may fall to 0 or below; a plain capture's never goes below one army), and a member of an
957
+ // uneconomic bonus of mine is still eligible for it. Each denial is judged once per plan
958
+ // (`denialsOf`, `Targets.denials`). It spends only what stands above its source's hold (#121).
959
+ // #281, the owner's extension (2026-11-16; guard off, not under No-Split, `balanced`/`defend`):
960
+ // a live opponent's own territory beside mine in view at 0 (no special unit) whose owner holds
961
+ // no positive bonus it is in (#165 breaks those) and that was not mine on `previousBoard` (#276
962
+ // retakes those) — `emptyEnemiesOf`, `Targets.emptyEnemies` — is a pass 3 target (`balanced`
963
+ // included; out of the targets again after pass 3 when not taken). It is tried sized for its
964
+ // owner's deploy there (#120, a worst case: no "assumes" warning) and, only when no source can
965
+ // pay that (a refusal stands), at its bare cost with #120's warning (`tryEmptyEnemy`); ranked as
966
+ // a capture of the size it is first tried at plus its frontier. Rule 4d does not undo it when the
967
+ // border it adds faces only enemy (or hidden) territories that a territory of mine beside it
968
+ // already faces (`sameFront`: the front moves one step; a "Take … though it adds a border facing
969
+ // an enemy … (#281)" line says so); a border to a new stack is judged as any. Never a truce's
970
+ // covered territory, a #240 repulsed one, a counter-attack target, or one lowering income; what
971
+ // the #276 second line still lacks is kept out of the deploy it may use. Both exemptions (the
972
+ // denial's and the same front's) live in rule 4d's check itself (`outgrows`), so they also hold
973
+ // in rule 4e's non-contact fallback, where rule 4d is still a veto (in contact it is a cost,
974
+ // #114). #281 × #282: no #281 capture (a denial or an empty enemy territory) is sourced from the
975
+ // territory my commander walks from — all that stands there is its transit hold (rule 1w,
976
+ // `commanderTransit` sizes it on the whole stack); a commander that stays keeps its worst-case
977
+ // hold through `keepOf`, as from any capture.
978
+ // 4e. Never stand still (#104, #107; every goal but `complete-bonus`, after pass 3). A plan that
979
+ // makes no capture at all (no expansion, break, finishing off or strike) in the opening or
980
+ // expansion phase takes one neutral capture toward a positive bonus (net > 0, never a negative
981
+ // one), uneconomic or not, never one that lowers income. Its candidate steps (#107) are ranked
982
+ // by what this turn can afford first — each step's shortfall: its cost less the armies that can
983
+ // reach it (its best usable source's movable armies plus what may still be deployed there,
984
+ // after every hold; a conceded border counts with the armies rule 1b withdrew and with deploys:
985
+ // rather than withdraw, it attacks out, its deploys leaving with the attack, and the rationale
986
+ // says so) — then by its bonus's armies to finish (ties: higher value, then id), then
987
+ // pass 2's order; the first that fits is taken (usual sizing). So a cheap neutral next to my
988
+ // stack beats a far step toward a bonus with fewer armies to finish; the reason says "the
989
+ // fewest of any bonus in reach" or "… with a capture affordable this turn", and the rationale
990
+ // names the closer bonus and why it was passed over. Rule 4d may stop a step, except in the
991
+ // contact/late fallback (a cost there, below, #114) and in the opening: when 4d refused every
992
+ // step that fits, the first of them is taken anyway (one capture that grows the frontier beats
993
+ // none; the rationale says 4d is waived for it, and 4d still judges every other capture). In
994
+ // every phase, and under the waiver too, every source of the capture must still hold its border
995
+ // once the attack leaves (a softener of a combined capture included; a conceded source
996
+ // excepted): a source left short gets the deploys still available there that make it hold, and
997
+ // a capture they cannot cover is not made — standing still beats trading a held territory and
998
+ // its armies for a neutral that pays nothing (live, an 8-player opening sent a 15-stack's every
999
+ // army at a 15-neutral from beside two enemy 15-stacks). The rationale says nothing passed the economy test and standing
1000
+ // still is worse than the cheapest expansion; when nothing is taken, a warning names the
1001
+ // top-ranked step and the actual reason: rule 4d's frontier stop, R3 (it completes a bonus
1002
+ // that falls next turn), No-Split, no neighbour able to attack (each named as holding its
1003
+ // border or already ordered), the holds (it would fit without what they took), or its size
1004
+ // (its cost against the movable armies and deploys that can reach it); #235: when the leftover
1005
+ // then stages on another source toward that step (rule 5), the warning names that source. Army cap (`armyCap`, × income): war.app
1006
+ // pays min(income, round(cap × income) − my armies on the board) (#253, verified by six live cases, the cap on
1007
+ // this turn's income), so the
1008
+ // caller passes the cut income and `incomeCap`, its arithmetic. When the cap cuts this turn's
1009
+ // income, armies left standing cost income next turn, so the same fallback fires in any phase,
1010
+ // and the rationale says so; without `incomeCap` it fires when my armies after deploy exceed
1011
+ // cap × income. The fog prior and the standing read my income before the cut (the cap is mine).
1012
+ // Under Local Deployment the cut income's pools are trimmed outermost first (`deployPools`), a
1013
+ // guess: warapp_plan_turn warns so (`armyCapPoolsUncertainty`) and the submit pool check only warns.
1014
+ // Contact and late phases (#107): a plan with no capture at all falls back too — unless the
1015
+ // caller chose `defend` (a `defend` that adapt picked, rule 0p.3 behind outside a 1v1, still
1016
+ // falls back: its holds come first), or the 1v1 strike stack (rule 0p.3c) spends itself this
1017
+ // turn. Its candidates are the neutral steps above and (unless the caller chose `expand`) every visible
1018
+ // enemy territory next to mine without an enemy commander (rule 1s's) whose capture does not
1019
+ // lower income, sized like any capture at the plan's win chance. A capture of a player's
1020
+ // territory must trade at least even (defenders killed ≥ attackers lost; a single capture
1021
+ // always does, a combined one whose softeners lose more is refused with a warning, "… a trade
1022
+ // below even"), and every source must still hold its border once the attack leaves: a source
1023
+ // left short gets the deploys still available there that make it hold (a rationale line says
1024
+ // so), and a capture they cannot cover is refused (a conceded source excepted; a warning names
1025
+ // an enemy capture refused so, with what would stay and the deploys left). Here rule 4d's
1026
+ // frontier stop is a cost, not a veto (#114): each candidate is tried (and undone) to find its
1027
+ // armies at risk — the survivors its capture leaves on a border that cannot hold next turn at
1028
+ // the expected enemy deploy (4d's and R3's arithmetic; 0 when it holds or faces no enemy).
1029
+ // Order (#112, #114): affordable first, then (#240) a capture that completes a bonus this turn
1030
+ // (every other member already mine) whose bonus repays its cost below within the payback horizon
1031
+ // (cost ≤ payback turns × value), then its cost — the armies the capture is expected to
1032
+ // lose (the defenders' kills on its attackers at the game's rates; for a combined capture, the
1033
+ // total over its attacks) plus its armies at risk — then the armies it sends, then one that
1034
+ // breaks a bonus (its owner holds it in full) or advances one of mine (a tie-break only), then
1035
+ // (neutral steps) the order above, then id; the reason names both parts ("loses ~3 armies, and
1036
+ // its 5 survivors may fall next turn", "loses no armies"). So an enemy 4 taken for ~3 lost, or
1037
+ // an empty one for none, beats a 15-neutral taken for ~11 toward a big bonus, even when 4d
1038
+ // would refuse their new border. After the capture taken, every other candidate that loses no
1039
+ // armies is taken too (by armies sent, then id), when every hold stays covered and income does
1040
+ // not fall, never attacking out of a conceded border; 4d does not stop one either (its
1041
+ // survivors at risk never exceed the armies it sends); a rationale line says "Also take …: it
1042
+ // costs nothing" (with "; its S survivors may fall next turn …" when its border is exposed,
1043
+ // and, for one that opens a second front, "… taken only because it costs nothing"). Every
1044
+ // candidate considered and not taken is named in one rationale line, "Other candidates not
1045
+ // taken: …", with its reason (refused, does not fit, ranked after the capture taken and at
1046
+ // what cost, or after a completion that repays its cost, or — rule 0p.2 — tried only after every
1047
+ // other); an enemy capture refused as a
1048
+ // trade or for a hold is left to its own warning, and when nothing is taken the top one is in
1049
+ // the stand-still warning instead. In an FFA with two or more opponents (rule 0p.2's setting,
1050
+ // applied here whether or not the plan adapts), a capture against a player that cannot
1051
+ // currently attack me (it could take no territory of mine next turn) opens a second front and
1052
+ // is tried only after every other — unless it completes a bonus this turn (#240: never demoted;
1053
+ // its reason says "completes bonus …"); the rationale says which ("can already attack me …:
1054
+ // opens no new front" / "cannot attack me now: … opens a second front (no second front in an
1055
+ // FFA), taken only because no neutral capture fits" / "cannot attack me now: … completes bonus
1056
+ // … this turn, so the second front is taken for it"), and the trade ("kills K for L lost"). Outside
1057
+ // the contact/late fallback (passes 1–3, the opening/expansion and army-cap fallback) rule 4d
1058
+ // keeps its veto. An enemy capture carries the usual warning that it assumes the owner does
1059
+ // not reinforce first, unless rule 3 sizes it for that deploy (#120).
1060
+ // 4g. A capture worth a card piece (#127; every goal but `complete-bonus`, after rule 4e, not while
1061
+ // the 1v1 strike stack, rule 0p.3c, is contact's answer). Any capture this turn earns the turn's
1062
+ // card pieces; `cardPieceValue` is what they are worth in armies (the Reinforcement pieces a
1063
+ // capturing turn brings × its armies over its pieces: src/strategy/card-clock.ts
1064
+ // `capturePieceValue`; the other cards are not valued). With no capture planned, the target
1065
+ // whose capture loses the fewest armies (the defenders' kills on its attackers) is taken when
1066
+ // that loss is at most the value — neutrals before players' territories, then the cheapest, then
1067
+ // id — with the usual sizing (tryCapture: each source keeps what holds it), never one lowering
1068
+ // income. Absent (no Reinforcement card, or a progressive one and none in hand): off.
1069
+ // 4h. The army cap prices idle armies (#253; every goal but `complete-bonus`; after rules 4e and 4g,
1070
+ // whatever else the plan captures — rule 4e's army-cap fallback runs only when it captures
1071
+ // nothing). When my armies after this turn (on the board, plus this turn's income, less what the
1072
+ // plan's captures lose) and next income (this turn's plus the plan's gains, card armies out)
1073
+ // exceed the cap, `eaten` = next income − what the cap would pay is lost unless armies are spent.
1074
+ // Candidates: rule 2's neutral targets and every foe territory next to mine holding at most
1075
+ // `CAP_SPEND_ENEMY_MAX` (1) armies (no commander, no truce, no teammate; `expand` attacks no
1076
+ // player), none lowering income, ranked by expected loss (the defenders' kills on the attackers),
1077
+ // neutrals first, then gain, cost, id. Each is taken while its loss is below what the cap would
1078
+ // still eat, from idle armies first (deploys still left make up a shortfall; a combined capture
1079
+ // of a player's territory only at an even trade), never from a conceded source, and undone when a source could then not hold its border. The
1080
+ // rationale names the cap's arithmetic per capture ("Take … for the army cap (rule 4h, #253): …");
1081
+ // what it did not take is listed with why, and the "Not attacking" line repeats it ("the army
1082
+ // cap's spend of idle armies (rule 4h) tried it: …"); while the cap still eats income a warning
1083
+ // names the largest idle stack. #272, a fork: once one of a player's territories is captured this
1084
+ // turn (by any pass), its other foe territories next to mine are candidates whatever they hold,
1085
+ // ranked and taken the same way after the first list ("… a fork (#272): player P is attacked on N
1086
+ // territories this turn (…), more than its one deploy can all save"). Live, three near-empty
1087
+ // territories of one owner were taken and two more beside mine (4 and 14 armies) left untouched.
1088
+ // 4f. Commit to the closest bonus (#101; every goal). While no positive bonus is held in full, in
1089
+ // the opening and expansion phases, and in an FFA while a neutral borders a territory of mine
1090
+ // (#132: one front leaves the rest of the map to expand into; the rationale says "neutrals in
1091
+ // reach"), completions and advances keep the slots their scores give them (rules 4, 4a) but
1092
+ // fill them closest to completion first: fewest turns to finish at
1093
+ // this income (armies to finish, counting the members I hold, over the income — and never
1094
+ // fewer than its depth, #125: the farthest missing member's distance from what I hold, since
1095
+ // a capture's armies attack no further this turn; "N turns (N layers deep)"), so a farther
1096
+ // bonus gets only armies the closer ones cannot use; bonuses as close as each other keep the
1097
+ // score order. Given `previousBoard`, a bonus advanced last turn (a member captured since) keeps
1098
+ // priority unless another is strictly closer; the rationale lists the order and says which
1099
+ // kept or gave way. Armies to finish count every missing member: a fogged one at its bonus's
1100
+ // costliest visible missing member (counted as free before, the figure jumped when it came into
1101
+ // view), named in every "N armies to finish".
1102
+ // 3b. One surplus per territory (#121). A border that holds at the start of the turn (its armies
1103
+ // beat its visible threat, rule 1) and is not conceded keeps what holds it, as my commander's
1104
+ // territory does (rule 1k): a capture from it spends only its armies above that, plus deploys
1105
+ // (a rationale line names those that keep it holding), so it never ends the turn takeable
1106
+ // after starting safe. The threat counts its captured neighbours as gone. A target no source
1107
+ // affords on its surplus may still fall to a combined capture (rule 3a), whose softeners and
1108
+ // finisher keep what holds a safe border too; in rule 4e a step
1109
+ // that fails only because of a keep is reported as the hold it would leave short.
1110
+ // 5. Deploys cover only the shortfall of a chosen capture; leftover income never
1111
+ // goes to a conceded border. #265: first (after #121's hold after all, when that runs), each
1112
+ // weak member of a bonus this turn completes (rule 3a's #265) is brought to its hold — a
1113
+ // source of an order too (its size is fixed), except under No-Split, where the deploy would
1114
+ // leave with it — most protected value first, when the leftover covers it whole ("it is a
1115
+ // member of bonus …, completed this turn, and faces the ~N threat"), before the worse-order
1116
+ // holds, the strike stack and any comfort margin. #215: armies withdrawn into a border (rule 1b) land by my own
1117
+ // order, after the opponent's first attack when it moves first, so unless `movesFirst` the
1118
+ // leftover makes each open border that falls without them hold on its own ("so it holds
1119
+ // whoever moves first", most protected value first, only when it can afford the whole hold —
1120
+ // #215 review: then its own orders have not run either, so the armies it sends out still
1121
+ // stand and only the withdrawal less those is left out (`lateNet`), and it never spends what
1122
+ // another open border needs to hold whoever moves first: moving first, only my first order
1123
+ // lands before the opponent's first, so a border another withdrawal goes into needs its
1124
+ // worse-order hold either way, kept back from the one my first order goes into (two such
1125
+ // borders go most at stake first, neither reserving for the other);
1126
+ // after #121's hold after all below, when that runs: a conceded border falls whoever moves
1127
+ // first, this one only if the opponent does),
1128
+ // and a border's keep (`keepFor`: what a capture, a top-up or rule 4e's fallback may not spend)
1129
+ // leaves them out too; a border that still holds only with them gets a warning ("holds only
1130
+ // if I move first", with the deploy that would hold it either way). #215 review: "known to move
1131
+ // first" means `movesFirst` from the user (`movesFirstUnverified` unset: the award of picks'
1132
+ // first mover is the wiki's rule, and holds treat it as unknown, the warning naming it) and no
1133
+ // opponent that may hold Order Priority (`opponentsMayHoldOrderPriority`, named likewise); and
1134
+ // idle armies rule 6 transfers in never count toward a hold — a border that holds only with
1135
+ // them gets the same warning, naming the one transfer that must be my first order (moving
1136
+ // first, only that one lands before the opponent's first; when I am known to move first, the
1137
+ // warning is "holds only if my first order is …"). The warning names why the leftover made no
1138
+ // deploy there (too little left, Local Deployment, No-Split sending the stack with its order)
1139
+ // only when that was the reason. Then it goes to the held
1140
+ // border with the highest protected value still short of COMFORT_MARGIN × its threat (counting
1141
+ // armies withdrawn into it) — but first (#121), when it would go to such margins (no strike stack;
1142
+ // #215 review: judged and run before the worse-order deploys above), a conceded border the leftover can make hold is held after all, from what is left once
1143
+ // every held border that would fall as it stands has its hold (best worth per army; its
1144
+ // withdrawal taken back unless the territory it went to needs it to hold — #215 review: unless
1145
+ // I am known to move first, it may still be taken back when the leftover also pays what holds
1146
+ // that territory without it, which the worse-order step would spend anyway; never one that
1147
+ // attacks out or whose garrison already stays); with two or more such borders, each is first brought to that
1148
+ // margin in the same order (#121: two symmetric borders at an exact hold ended as 16 and 7),
1149
+ // the rest to the first — #218: unless the step it would save toward (below) has its source on
1150
+ // an open border of equal defensive value (the same player's threat, the same size, from the
1151
+ // same enemy territories, protecting as much, in the same bonuses): then every short border
1152
+ // first gets its margin (a lone one too), and the rest goes to that source, saving toward the
1153
+ // step; a margin itself stays on its border. #268: otherwise, once every short border has its
1154
+ // margin (a lone short border gets its own first), the rest is spread over the open borders
1155
+ // facing that border's opponent alone (its threat that player's, no other opponent's stack
1156
+ // beside it; not an attack's source, no order under No-Split; one protecting nothing only when
1157
+ // the first protects nothing too), an army at a time to the one that breaks at the smallest
1158
+ // deploy (its armies' take less the stacks beside it), ties to the most at stake: the smallest
1159
+ // deploy that breaks any of them is as large as it can be, the estimate being only a floor
1160
+ // ("Spread the leftover N over the borders facing player P (#268) …", its "~D" the threat
1161
+ // arithmetic before any move, which #275's headroom table — the whole turn carried out — may
1162
+ // not match, and the line says so; Local Deployment's pools
1163
+ // respected, no Bomb split, since it already makes several stacks). With fewer than two such
1164
+ // borders, when the first is my commander's or an attack's source, or when every army would go
1165
+ // to the first anyway, the rest goes to the first as before — else (#125) it saves toward a capture this turn cannot afford:
1166
+ // rule 4e's top-ranked step when it stood still for want of armies, else (rule 4f committing)
1167
+ // the closest bonus's cheapest missing member in reach when this turn made no capture into
1168
+ // that bonus, and only when its armies free plus what may still be deployed there fall short
1169
+ // of it, or (#218 comment, any goal) of it and what holds that source's border once it is
1170
+ // taken (armies withdrawn into it counted only when I am known to move first: "which this turn
1171
+ // cannot afford and still hold S against the ~T threat") — a step refused for another reason
1172
+ // — R3, rule 4c or 4d — is no reason to save; it
1173
+ // goes to my territory beside that member with the most armies free (open, not a softener, no
1174
+ // order under No-Split; "save toward …, the next step of bonus …") — else the
1175
+ // source of the top expansion (a capture's finisher; it then makes no transfer) — #218: but
1176
+ // with no enemy territory in view (no front to go to), when that source's attacks land for
1177
+ // sure and it lies more than CENTRE_SLACK hops farther from my farthest border than the
1178
+ // territory central to what I hold (open, issuing no order; my largest connected holding,
1179
+ // then the fewest hops through my land to its farthest border, then the least sum, then id),
1180
+ // the leftover stays on that centre ("no front to go to: it stays central …"; rule 6 moves
1181
+ // the armies already there, never the leftover) — else the
1182
+ // border with the most fogged neighbours, else my biggest stack.
1183
+ // 5b. A neutral the leftover pays for (#218; live: a capture ruled out because its source "stays
1184
+ // to hold its border", then the leftover put 8 on that source as its comfortable margin, and
1185
+ // nothing took the 1-army neutral beside it). After the leftover, the strike stack's orders and
1186
+ // the lead strikes, a territory of mine the leftover reached (not conceded, not my commander's,
1187
+ // not the strike stack nor the step's source it saves on, attacking no player's territory: the
1188
+ // #226 margin sizes those; never under No-Split or `complete-bonus`) takes a neutral beside it
1189
+ // from what stands above its hold, by pass 3's order, eligibility and economy test (#125),
1190
+ // sized as any capture (the target's cost, R3 and rule 4d through pass 3's capture, which
1191
+ // deploys nothing: the leftover is spent). What it keeps: the hold against the threat beside
1192
+ // it as if this turn's attacks on players there failed, without armies withdrawn into it
1193
+ // unless I am known to move first (#215, as `keepFor`); what holds it against two opponents
1194
+ // attacking together when it holds that now (#128); and at least its two-step keep (#172), an
1195
+ // exit's cover (#179), the leftover kept central (#218) and a Local Deployment pool's armies
1196
+ // (#103). The attack's line gives the arithmetic ("the leftover pays for (#218): of the N on
1197
+ // S …, the C sent leave L, above the H that hold it …"); a capture removes rule 4e's
1198
+ // stand-still warning, and a refused try leaves no line.
1199
+ // 6. Idle armies on interior territories transfer one step toward the front,
1200
+ // only into territories held at the start of the turn and never into, or
1201
+ // measured through, a conceded border
1202
+ // (unless `idleTransfers` is off: the planner's own switch, not war.app's AllowTransferOnly,
1203
+ // which toggles the per-order Transfer Only mode, #257). First (#257), an idle interior stack
1204
+ // (no enemy beside it, not my commander's) moves into a conceded border beside it when that
1205
+ // transfer plus what the plan leaves there (its deploys included) makes the border hold against
1206
+ // the threat it was conceded on: the border is then held, not conceded ("Hold X after all (not
1207
+ // conceded): transfer N idle armies from Y into it …"), the conceded border the plan attacks
1208
+ // from first, then worth per army needed. It sends what makes it hold (No-Split: the whole
1209
+ // stack), so one stack may hold several; never into a border a withdrawal leaves. Live, 10
1210
+ // idle armies walked to a territory beside empty neutrals while the conceded border the plan
1211
+ // attacked from, just as near, would have held with them. The front is the territories a visible
1212
+ // enemy holds. When no revival applies and the front is reached only through a conceded border
1213
+ // the plan attacks an enemy from (#260; #272: or strictly sooner through it than any other way —
1214
+ // live, the other way ran through a neutral captured this turn, one step longer, and the stack
1215
+ // went there), an idle stack still steps toward it, into that border,
1216
+ // when the nearest territory not mine is no nearer ("… is reached only (or soonest) through a border
1217
+ // the plan concedes …; they are lost with it if it falls"); never into another conceded border or one a
1218
+ // withdrawal leaves. Live, 10 idle armies walked to an empty neutral edge while the border the
1219
+ // plan attacked from missed holding by one; the stress test preferred them there. Only an
1220
+ // interior stack steps so: never one beside a visible enemy at the start of the turn, interior
1221
+ // only once a strike lands (its armies stay for that strike's #226 margin, sized after rule 6;
1222
+ // in the golden corpus a first strike's fell from 26 to 6 before this was kept). When the steps
1223
+ // into a conceded border make it hold together (two stacks, each too small for #257 alone), it is
1224
+ // held after all, as #257 says ("Hold X after all (not conceded): the N idle armies transferred
1225
+ // into it from Y, Z make it hold together …"), never left reported conceded. Only a stack
1226
+ // no enemy can be reached from heads for the nearest territory
1227
+ // not mine (neutral or fog; never a teammate's, PLAN-TEAMS C3) instead (#121: idle armies walked toward a worthless neutral
1228
+ // while the enemy front was short, and a stack beside one never moved). This turn's
1229
+ // captures count as mine only when they land for sure — a neutral, or an attack on a player
1230
+ // sized for its owner's whole deploy (rule 1e, 1s, or rule 3's #120 sizing): an exact-sized attack on a player fails
1231
+ // if the owner reinforces, and the garrison beside it is not idle. Even a sure one may fail
1232
+ // (#128): a territory interior only once an attack on a player beside it lands keeps what
1233
+ // holds it against the threat there as the board stands (its neighbours' owners' stacks and
1234
+ // deploy) and transfers only the rest. A leftover deploy (rule 5)
1235
+ // to a border short of its margin is never transferred away.
1236
+ // Two steps away (#172): a territory interior now can be a border next turn when an enemy
1237
+ // stack takes the territory in between this turn — the look-ahead warapp_check_plan reports
1238
+ // as `exposedNextTurn`, one computation (`twoStepReaches`, lookahead.ts). Wherever armies leave
1239
+ // a territory of mine that protects something — a member of a bonus I hold in full, or my
1240
+ // commander's — it keeps what it needs against the strongest such reach: these transfers,
1241
+ // staging, an attack from it (rule 3b's keep, softeners included) and rule 3's top-ups. Never
1242
+ // added to a one-step hold or the hold above (the larger binds), never against a reach whose
1243
+ // stack or territory in between this plan takes — by any order, a later one included: when a
1244
+ // two-step hold binds, the plan is made again with those reaches cut (the captures of the plan
1245
+ // and of one whose attacks ignore the hold, narrowed to those the re-made plan still takes,
1246
+ // at most TWO_STEP_PASSES times; else the plan that cuts nothing) — nor through a territory of
1247
+ // mine the plan holds (its own hold covers that): one the plan ends keeping (not conceded)
1248
+ // with enough on it after the final orders to hold its border. That is judged against how the
1249
+ // plan ends, never mid-way (triage concedes a border this turn's captures then keep, rule 1c):
1250
+ // a plan that decided a territory otherwise than it ends is made again with the end's answer,
1251
+ // at most VIA_PASSES times, else with no territory in between counted held — one answer every
1252
+ // order shares, so no "kept N" is stated and then transferred away. And never when even what
1253
+ // is there now and what next turn can deploy there (the whole income; under Local Deployment
1254
+ // its bonuses' pools and the free rest) could not make it hold (keeping them home saves
1255
+ // nothing). What it needs
1256
+ // is measured as a one-step hold is (holdArmies: under luck or weighted-random rounding, it
1257
+ // falls at most HOLD_FALL_CHANCE of the time), never below check_plan's luck-free `needs`. A
1258
+ // territory protecting nothing is not held so: its armies serve the front. The rationale says
1259
+ // "Hold X against a stack two steps away (kept N on X: player P can reach it next turn from Y
1260
+ // via Z …)" once, at the end, with the stay the plan ends on (an order that keeps it names it
1261
+ // without numbers); kept short of what it needs (next turn's deploy makes up the rest), it
1262
+ // adds "bring K more next turn". When the one-step hold (or #128's) already needs at least as
1263
+ // much, the line claims no "kept N" (#192): it says "already held against the adjacent stack
1264
+ // (~T; it needs M to hold)" and what the two-step reach needs.
1265
+ // Under No-Split a transfer that must keep some (this hold, or #128's) is not made: it would
1266
+ // send the whole stack.
1267
+ // Staging (#125): when the leftover saved toward a step (rule 5), idle armies on my other
1268
+ // territories facing no visible enemy (a border beside neutrals included; never one that
1269
+ // attacks, a conceded border, my commander's, or one beside the step itself) walk one step
1270
+ // toward its source first, when it is no farther than the enemy front ("Move N from … to …:
1271
+ // stages toward …"): live, a stack two steps from the one neutral its bonus lacked stood
1272
+ // still for five turns. A transfer between the same two territories is planned once: a later
1273
+ // one is added to it.
1274
+ // 7r. Reports (#167; every goal, around rule 7). Exchange: every attack on a
1275
+ // player's territory is judged by `classifyExchange` (src/analysis/exchange.ts) — kills, losses
1276
+ // and capture against its defenders now, plus its owner's estimated deploy there, plus its whole
1277
+ // income, labelled certain first strike / favourable exchange / strike last / stand — in
1278
+ // `exchanges` and one rationale line. Cover odds: against a player facing two or more of my kept
1279
+ // borders, those holding against its stacks alone but not with its whole deploy on them are a
1280
+ // gamble on where that one deploy lands; a rationale line names them and the chance each (and
1281
+ // all) hold if it picks at random. A deploy can be split: those whose shortfall it funds
1282
+ // together with another's are no gamble — the line says how many (k) the split takes at once and
1283
+ // gives each 0% when there are k of them or fewer; with m > k (#201), it picks k of the m, so
1284
+ // each holds with (m − k) ÷ m and all of them with 0%. Left alone: every visible enemy territory next to mine that no
1285
+ // order attacks is named in one line, "Not attacking … next to mine", with its first reason: a
1286
+ // special unit, the offence report's reason (a second front, unaffordable, a trade below even), a
1287
+ // capture lowering income, its size against the most a neighbour can spare, a lead strike's sure
1288
+ // size against what a neighbour can spare for it (#203: and why its bonus's step failed when
1289
+ // that pass tried it — the source it tried, what that source could spare and what of the deploy
1290
+ // could still reach it then; or R3, a trade below even, rule 4d's frontier budget), or that it
1291
+ // is no target of the plan's (rule 2;
1292
+ // under another goal, naming the player's territories other rules do attack). The first
1293
+ // NOT_ATTACKING_REASONS (by id) get a reason, the rest are named.
1294
+ // Retaliation (#201; an FFA with two or more opponents): a capture that breaks a positive bonus
1295
+ // a player held in full, while that player keeps a visible territory or one beside the fog, is a
1296
+ // warning ("Breaking player … without eliminating it invites retaliation"): what it has left is
1297
+ // likeliest aimed at whoever broke it. In a 1v1 it attacks me anyway, so no warning there.
1298
+ // Wastelands (#167, `settings.wastelands`): a fogged missing member of a bonus is costed at the
1299
+ // costliest visible missing member plus the expected surcharge of being a wasteland
1300
+ // (ceil(count ÷ the map's territories × (a wasteland's capture cost − that))), with a rationale line.
1301
+ // #201: given `options.rememberedNeutrals` (the picking board's neutrals, which warapp_plan_picks
1302
+ // and warapp_submit_picks' preview keep per game), a fogged missing member the picking board showed
1303
+ // as a neutral (and whose owner the fog does not show as a player now) is costed at that size
1304
+ // instead, never attacked, with a rationale line ("… fogged now, was a neutral of N on the picking
1305
+ // board (#201)").
1306
+ // 7. Move order (#127; every goal, last). Orders zigzag — the first mover's 1st, the other's
1307
+ // 1st and 2nd, the first mover's 2nd and 3rd, … — so `moves` is scheduled
1308
+ // (`scheduleMoves`, src/analysis/schedule.ts), earliest first: the one order Order Priority
1309
+ // protects (the strike, when rule 1s advised the card for it; else the move out of a conceded
1310
+ // border carrying the most armies, which is my first order whether or not the card is
1311
+ // advised — and if a move it depends on must run before it, that move is my first order
1312
+ // instead, and the card is judged for it); withdrawals, attacks
1313
+ // out of a conceded border and transfers into a territory facing a visible enemy at the start
1314
+ // of the turn; attacks on a player sized for its owner's whole deploy (rules 1e, 1s, 3's #120
1315
+ // sizing) and neutral captures another player can reach whose survivors (sent less the
1316
+ // defenders' kills) need more to take than its own capture of that neutral (its capture
1317
+ // cost, at most its stacks next to it plus its deploy: a 2-neutral taken with 4 leaves 3,
1318
+ // which need 5; with 3 it leaves 2, which 3 retake); filler
1319
+ // (uncontested neutral captures, interior transfers); last, attacks into a player's stack
1320
+ // not sized for its deploy (a defender kills 70% per army, an attacker 60%: attacking second
1321
+ // fights its survivors — 24 against 28 loses attacking first and wins attacking second) and
1322
+ // contested neutrals whose survivors would fall (taken last, they meet what is left there).
1323
+ // Within a slot, early moves go largest first (one grouped early transfer beats several
1324
+ // small ones); other ties keep decision order. Dependencies hold: attacks on one target keep their order
1325
+ // (softeners before the finisher), a move out of a territory stays after any earlier move
1326
+ // into it, and a transfer into a territory captured this turn after the capture. A rationale
1327
+ // line "Move order (#127): …" names the protected order and each move put last, and why.
1328
+ // With one opponent in view, a line "Move position (#127): …" gives each move put last its
1329
+ // place in the zigzag (`opponentOrdersBefore`: moving first, my k-th order runs after
1330
+ // 2·floor(k/2) of the opponent's; moving second, after 2·ceil(k/2) − 1; both when the order is
1331
+ // not known, first when Order Priority is advised) and, against the opponent's territories in
1332
+ // view with armies to move (one order each, at least), the index from which it runs after
1333
+ // them all (`indexAfterAll`) and how many more orders above it that takes. It adds no fillers.
1334
+ // Deploys are listed next to a visible enemy first, in the back after (ascending id within
1335
+ // each): they interleave too, and their order shows the opponent my income and the move order.
1336
+ // Order Priority (`cardAdvice`) moves only my FIRST order ahead of the opponent's first: for a
1337
+ // move out of a conceded border it is advised only when I hold one (`holdsOrderPriority`), I
1338
+ // am not known to move first (`movesFirst`), and that order carries at least
1339
+ // ORDER_PRIORITY_MIN_ARMIES; its warning then says so, and the other such moves' warnings say
1340
+ // they are listed early but may come too late. Under `movesFirst` the strike's card advice is
1341
+ // dropped too, unless `opponentsMayHoldOrderPriority` (two cards cancel, so mine keeps it
1342
+ // first; #179). The strike that eliminates a finished-off player (#179: the attack on its
1343
+ // largest stack, by armies plus special units) is my first order after a commander strike, and
1344
+ // Order Priority is advised for it on the same terms (no minimum armies). With no finish-off and
1345
+ // no strike the threat to my commander advised the card for, a commander strike (rule 1s) that
1346
+ // eliminates a player is that first order instead, on the same terms: its commander could
1347
+ // walk away before it lands. When a combined
1348
+ // capture (rule 3a) takes that stack, its first attack only wears it down: no card is advised
1349
+ // for it, and a warning says the card cannot secure the kill. Finishing a player off (rule 1e)
1350
+ // assumes my attacks land before its own orders: unless `movesFirst`, a warning says it can move between its territories or take my
1351
+ // borders next to it that its stacks plus the deploy that can reach them can take (named), and
1352
+ // survive. Rule 1e's cover (#179) holds those borders when it can afford to, so the warning then
1353
+ // names none; it names those left exposed when the cover was unaffordable.
1354
+ // T. Truces (B2, docs/PLAN-TEAMS.md section 8; `relations`, resolved by warapp_plan_turn from the
1355
+ // agreement ledger). Honoured only in a free-for-all (with teams or two players: ignored, with a
1356
+ // warning — all but T1, which holds wherever the agreement binds: never a surprise break, and
1357
+ // warapp_submit_turn refuses the order in any format), with a foe, while `active` or in `notice`
1358
+ // before its `endsTurn`. Absent or empty,
1359
+ // no rule here runs and the plan is byte-identical to one made without them.
1360
+ // T1. A covered territory of the partner is never a target: not in the targets, tryCapture,
1361
+ // the commander strikes, the strike stack, the lead strikes, the guard-off breaks or rule
1362
+ // 4e's enemy fallback; its "Not attacking" line says the truce covers it.
1363
+ // T2. A covered border of mine facing only the partner is sized for the partner's stacks
1364
+ // next to it attacking with no deploy and no trend (`forceAt`; separate attacks still
1365
+ // count; its Multi-Attack chains from the armies standing).
1366
+ // T3. Never relaxed: my commander's territory, a border protecting more than
1367
+ // TRUCE_RELAX_VALUE (0.25) × my income, and every border while the trust is `watch`.
1368
+ // T4. The partner is no front: rule 0p.2 counts the opponents less the partners still playing
1369
+ // (`partnerFronts`: on the player list and `Playing`, else in sight), and rule 6's
1370
+ // idle armies never head for a covered territory — while a territory beside one keeps what
1371
+ // holds it there (T2's truce hold, or T3's full one).
1372
+ // T5. A border cap: what my orders leave on a covered border territory is at most the cap.
1373
+ // No fill move overfills it (`capRoom`): rule 1b withdraws only where the whole
1374
+ // withdrawal fits (else to another neighbour, or a warning that a truce caps them), and
1375
+ // #125's staging and rule 6 send at most the room left and never back along a transfer
1376
+ // planned this turn (`capStepRoom`). After rule 6, any excess still there: this turn's
1377
+ // deploys land one step behind, then a transfer of mine into it carries fewer (its own
1378
+ // line retold), then the armies standing move back (toward a foe's territory no truce
1379
+ // covers, else any open territory), said so when it already stood above the cap; what
1380
+ // cannot go is a warning — naming this plan's own deploy when that is what exceeds it
1381
+ // (deploy less there, or give notice and ask the owner first: never a silent break), or
1382
+ // Local Deployment's room on the step. A capped border that also faces another
1383
+ // opponent is no "toward another front": when what the cap leaves no longer holds it
1384
+ // against that opponent (and it held before), a warning names the opponent and the hold;
1385
+ // so does one where my commander stands, when the cap leaves it short of T3's full hold
1386
+ // against the partner.
1387
+ // The report never calls a T2-relaxed border sized for (or a gamble on) the partner's
1388
+ // deploy: #69's line, #167's cover odds, #201's gamble and #118's best response leave it
1389
+ // out (`relaxedFor`).
1390
+ // T6. What a break would cost (`lossIfBroken`, after the orders are final; plan/relations.ts
1391
+ // `truceBreakLosses`): per binding, unenforced truce, the partner's whole deploy estimate on
1392
+ // any territory of its in view beside a covered territory of mine (covered or not: T2
1393
+ // relaxes against every stack there) and an attack on it with everything there (its commander too), carried out against this plan's deploys and
1394
+ // moves on the turn simulator (turn-sim.ts; both move orders unless the first mover is known
1395
+ // and verified; no other player moves). The costliest pair is reported — my commander, then
1396
+ // the income lost, the territories, the armies — with a rationale line; `null` when none
1397
+ // exists. It changes no order: the plan is what it was, and only reports what it risks.
1398
+ // T7. Never a surprise break: a notice binds until `endsTurn`, then the partner is an
1399
+ // ordinary opponent; the plan's `advice` says `give-notice` when the trust turned `watch`
1400
+ // for the endgame or for outgrowing (not when I already gave notice).
1401
+ // T8. Broken by them (`state: 'broken'`): an ordinary opponent at once; a warning names the
1402
+ // term, the turn and the evidence, and says to record `broken-by-them` with
1403
+ // warapp_record_agreement before submitting (warapp_submit_turn reads only the ledger).
1404
+ // T9. Enforced (a Diplomacy card the decoder is sure of): that player is no foe this turn
1405
+ // (`foe`), so its threat is 0 and no attack on any of its territories is planned. A card
1406
+ // gone by next turn leaves its player a foe for next turn's reasoning (`lookAheadFoes`): the
1407
+ // two-step hold (#172), the frontier (rule 4d) and R3's defensibility (G2, `nextTurnAt`).
1408
+ // The plan's `relations` reports each truce: its state, whether it binds, the trust and its
1409
+ // flags, the borders relaxed and kept full (and why), the armies the relaxed holds free (per
1410
+ // border, what its full hold needs beyond the armies there less what the truce hold needs —
1411
+ // only where the full hold would have been funded: not on a border this plan concedes, nor one
1412
+ // whose full hold rule 1a would refuse; capped at what the plan's orders really leave short of
1413
+ // the full hold, so armies that end there anyway are not freed; at most my income), the armies
1414
+ // the cap moved and what
1415
+ // a break would cost (T6). A plan holding no territory still reports each truce given.
1416
+ // Local Deployment (`localDeployments`): a held bonus's value is a pool deployable
1417
+ // only on that bonus's territories (a superbonus's on all of its territories, beside
1418
+ // its member bonuses' pools); the rest of the income (base, per-territory, card
1419
+ // armies) may go anywhere. Every affordability check above uses the armies
1420
+ // deployable at that territory; leftover bonus pools are still deployed inside their
1421
+ // bonus, on its most threatened member: a border next to an enemy always before an
1422
+ // interior member (#103), then not withdrawn from, then most threatened, then id. A
1423
+ // pool deployed on a border is never moved out the same turn. A rationale line names
1424
+ // each pool. Off (the default), plans are unchanged.
1425
+ // No-Split (`noSplit`): a territory issues at most one order (attack or transfer)
1426
+ // this turn, and the order sends its whole stack (#124; the wiki, and a live turn with the
1427
+ // guard off that left every source at 0): every army there, this turn's deploys included,
1428
+ // less the guard (whether the guard stays behind under No-Split is unverified; a warning says
1429
+ // so). Orders are planned in decision order, so a territory's first order is its best by the
1430
+ // scoring above; any later attack, withdrawal or transfer from it is not planned (a warning
1431
+ // names it), and another source may take that target instead. Nothing is kept back on a
1432
+ // source (no keep for a hold, rule 1e's or rule 1k's): a territory that must hold issues no
1433
+ // order — one that protects something (a bonus, income, my commander), is not conceded, and
1434
+ // would fall to the visible threat left once this turn's captures land with only the guard
1435
+ // (and armies withdrawn into it) on it; the target counts as gone only when the whole stack
1436
+ // takes it even if its owner deploys there first (a warning names the attack not planned).
1437
+ // Combined captures (rule 3a) use only sources with no order yet that need not hold, a
1438
+ // softener only when its whole stack leaves the last defender alive; each still issues one.
1439
+ // A deploy that reaches a source after its order was planned (the leftover, a pool) leaves
1440
+ // with it, a rationale line says so; the leftover never goes to a softener, nor a hold top-up
1441
+ // to a territory with an order. The strike stack (rule 0p.3c) attacks one target with the
1442
+ // whole stack, only when it need not hold; its one order goes to the strike before a small
1443
+ // expansion (an attack on a neutral that completes no bonus this turn: taken back, its armies
1444
+ // rejoin the stack). Efficient sizes (S2) do not apply. Off (the default), plans are unchanged.
1445
+ // Bomb (#163; `opponentsMayHoldBomb`: the card clock's fastest turn lets an opponent hold one by
1446
+ // now; whether hands are hidden is not checked, since the plan never sees an opponent's hand). A bomb halves one territory of mine next to the bomber after the deploys and before any
1447
+ // move (my stack keeps the smaller half; a commander is unharmed), so every threat to my territory
1448
+ // (rule 1's `forceAt`) becomes the attack that twice the armies just hold against: every hold, near
1449
+ // miss, keep and comfort margin sized against that threat is sized as if halved first (one bomb,
1450
+ // but it may land on any border, so each is sized for it, as each is for the whole deploy), and so
1451
+ // is #179's cover of a finished-off player's exits (`bombSized`). Not
1452
+ // bomb-adjusted: #172's two-step holds (`twoStepHold`) and #118's floor tier (`floorOf`, against
1453
+ // the armies already next to a border). The threat warning names the
1454
+ // bombed take. And the leftover deploy (rule 5), when it goes to a border facing an enemy, gives
1455
+ // half to a second open border facing an enemy (the same opponent first, then the bigger stack,
1456
+ // then id): one bomb halves only one of two stacks. Not a strike, saving or expansion stack: each
1457
+ // concentrates for one attack, which a split would halve for certain. Off (the default), plans are unchanged.
1458
+ // Guard off (#165; `oneArmyStandsGuard: false`, not under No-Split): every army may move, but an
1459
+ // empty territory falls to any single army, so each territory of mine next to a visible enemy at the
1460
+ // start of the turn keeps one army all the same (never my commander's: it is not empty; a rationale
1461
+ // line names them) — every pass, withdrawals from a conceded border included, counts it as staying.
1462
+ // And after the holds, before any other capture (every goal), an enemy territory next to mine at 0
1463
+ // armies (no special unit) whose owner holds a positive bonus it is in is attacked with one army —
1464
+ // it breaks the bonus — from the neighbour with the most to spare beyond what holds it once the
1465
+ // target falls, else one deployed on a neighbour not conceded; never one lowering income. Sized for
1466
+ // the board as it stands: if the owner deploys there first, the one army is lost. #276: an enemy
1467
+ // stack advancing two steps loses nothing per step either — the two-step look-ahead (#172,
1468
+ // `twoStepReaches`) moves every army each step, so its holds count the stack whole. #276
1469
+ // (plan/guard-off.ts; none with the guard on or under No-Split): (1) a second line — an interior
1470
+ // member of a held bonus within two moves of an enemy stack of at least SECOND_LINE_STACK_INCOMES ×
1471
+ // my income keeps `garrisonSize` (what one army cannot take) through `guardAt`, its shortfall deployed
1472
+ // before the leftover (`fillSecondLine`); (2) a raid one step deeper — an empty territory beside me
1473
+ // taken when the empty enemy territory behind it breaks its owner's bonus (no Multi-Attack chain:
1474
+ // the far one is the one-army break next turn); (3) a free retake — an enemy territory beside me at
1475
+ // 0 that `previousBoard` showed mine, taken back. (2) and (3) run right after the one-army breaks,
1476
+ // from spare armies, else topped up with a deploy; on a player's territory each is sized for its
1477
+ // owner's deploy there (#120; the raid one army more, to go on), and goes at its bare size
1478
+ // (RAID_ARMIES, or 1) with #120's "assumes" warning only when nothing covers that.
1479
+ // Special units: a commander fights as COMMANDER_STRENGTH (7) armies, attacking and
1480
+ // defending, and takes no partial damage (armies die first; it falls to 7 damage left
1481
+ // over), so a stack of d armies plus a commander defends exactly as d + 7: every capture
1482
+ // cost, worst case, survivor count and hold above counts it, and an enemy commander next
1483
+ // to my border adds 7 to that player's threat. A target with a special unit is never a
1484
+ // combined capture. Bosses and custom units are not counted (the board carries no strength for
1485
+ // them): #128, a territory holding one is never attacked (a warning says so), and an enemy one
1486
+ // next to me is named as left out of the threat.
1487
+ // Kill rates: every combat computation above (capture cost, threats and holds,
1488
+ // survivors, R3's frontier, R4's kills) uses the game's offensive/defensive kill
1489
+ // rates; only when the settings carry none does it assume 60/70, with a warning.
1490
+ // Every combination of these rules is planned and then checked by
1491
+ // warapp_submit_turn's validator (`validateTurn`) in the lessons suite: the planner
1492
+ // never proposes a turn the validator refuses.
1493
+ // Accounting: a territory's outgoing armies never exceed its armies after deploy
1494
+ // minus the guard. Armies never move twice and captured armies never attack, so
1495
+ // the plan is valid with or without multi-attack.
1496
+ import { analyzeBonus, bonusTerritories } from './bonuses.js';
1497
+ import { guaranteedKills, nextBreakpoint, straightKills, } from './combat.js';
1498
+ import { neighborsOf } from './graph.js';
1499
+ import { forecastBorder, mainFront } from './exchange.js';
1500
+ import { byNum, pct } from './plan/util.js';
1501
+ import { BREAK_WEIGHT, MIN_EXPANSION_SHARE, PLAIN_EXPANSION_LOSS, SECOND_FRONT_LEAD, SECOND_FRONT_SIMILAR, captureCost, } from './plan/shared.js';
1502
+ import { emptyPlan, noteEstimates, planContext } from './plan/estimates.js';
1503
+ import { neutralizeSeats, seatTerritories, staticSeats } from './static-seats.js';
1504
+ import { deployBook } from './plan/orders.js';
1505
+ import { holdsPhase } from './plan/holds.js';
1506
+ import { threatsPhase } from './plan/threats.js';
1507
+ import { targetsPhase } from './plan/targets.js';
1508
+ import { capturesPhase } from './plan/captures.js';
1509
+ import { completedMembers } from './plan/completed.js';
1510
+ import { chooseStrikeStack, leadStrikes, spendStrikeStack, strikesPhase } from './plan/strike.js';
1511
+ import { afterLeftoverCaptures, plainEconomy, plainEligible } from './plan/after-leftover.js';
1512
+ import { leftoverDeploy } from './plan/leftover.js';
1513
+ import { fillSecondLine, guardOffRaids } from './plan/guard-off.js';
1514
+ import { neverStandStill } from './plan/stand-still.js';
1515
+ import { addEmptyEnemyTargets, dropEmptyEnemyTargets, plainOrderCosts, tryEmptyEnemy, withoutTransit } from './plan/vacated.js';
1516
+ import { spendUnderCap } from './plan/cap-spend.js';
1517
+ import { attackOutOfConceded } from './plan/conceded-out.js';
1518
+ import { transfers } from './plan/transfers.js';
1519
+ import { scheduleOrders, strikeOrderPriority } from './plan/move-order.js';
1520
+ import { commanderMoveWarning, placeCommanderMove, reserveCommanderMove } from './plan/commander.js';
1521
+ import { finishPlan, reportExpected, reportOffence } from './plan/report.js';
1522
+ import { newPlanState } from './plan/state.js';
1523
+ import { teamFocusLine, teamReport } from './plan/team.js';
1524
+ import { applyBorderCaps, armiesFreed, partnerFronts, reportBreakLosses, reportTruce, trucePass } from './plan/relations.js';
1525
+ export * from './plan/shared.js';
1526
+ export { alliesOf, planEnemyEstimates } from './plan/estimates.js';
1527
+ export { TRUCE_RELAX_VALUE } from './plan/relations.js';
1528
+ /** Passes that refine the cut set (#172) before falling back to the plan that cuts nothing. */
1529
+ const TWO_STEP_PASSES = 3;
1530
+ /** Passes that learn which territories in between end held (#172) before none is counted held. */
1531
+ const VIA_PASSES = 3;
1532
+ const twoStepPass = (shared, cut, relaxAttacks, viaHeld = new Map(), viaNever = false) => ({ cut, relaxAttacks, used: false, viaHeld, viaNever, viaSeen: new Map(), viaMixed: false, viaFinal: new Map(), shared });
1533
+ /**
1534
+ * One plan whose "through a territory of mine the plan holds" cut (#172) agrees with how the plan
1535
+ * ends: triage can concede a border that this turn's captures make worth keeping (rule 1c), or
1536
+ * keep one its stay does not hold, so a decision taken while attacks are sized may not stand at
1537
+ * the end. A pass that decided some territory otherwise than it ends is made again with the
1538
+ * end's answer (at most VIA_PASSES times), else with none counted held — a decision every order
1539
+ * shares, so no rationale states a hold the orders then drop.
1540
+ */
1541
+ function settledPass(input, shared, cut, relaxAttacks) {
1542
+ let learned = new Map();
1543
+ for (let i = 0; i < VIA_PASSES; i++) {
1544
+ const pass = twoStepPass(shared, cut, relaxAttacks, learned);
1545
+ const plan = planPass(input, pass);
1546
+ if (!pass.viaMixed && [...pass.viaSeen].every(([v, d]) => pass.viaFinal.get(v) === d))
1547
+ return { plan, used: pass.used };
1548
+ learned = new Map([...learned, ...pass.viaFinal]);
1549
+ }
1550
+ const pass = twoStepPass(shared, cut, relaxAttacks, learned, true);
1551
+ return { plan: planPass(input, pass), used: pass.used };
1552
+ }
1553
+ /**
1554
+ * Plan one turn (see the header). #172: when a two-step hold binds anywhere, the plan is made
1555
+ * again with the reaches cut whose stack or territory in between the plan takes, wherever in the
1556
+ * plan that order lands: first the captures of the plan as made and of one sized without the
1557
+ * hold, then only those the re-made plan still takes, until it takes every territory it cut
1558
+ * (a fixed point, so no cut reach is still there); without one, the plan that cuts nothing.
1559
+ */
1560
+ export function planTurn(input) {
1561
+ // #270: a player out of the game whose seat no AI plays deploys and attacks nothing: its
1562
+ // territories are planned as neutrals (static armies), and it is no opponent anywhere below.
1563
+ const seats = staticSeats(input.game?.players, input.game?.endRules, input.me);
1564
+ const held = seatTerritories(input.board, seats);
1565
+ const plan = planSettled(withoutStaticSeats(input, seats));
1566
+ for (const [p, n] of [...held].sort((a, b) => a[0] - b[0]))
1567
+ plan.rationale.push(`Player ${p} is out (${seats.get(p)}) and no AI plays its seat: it deploys and attacks nothing, so its ${n} territor${n === 1 ? 'y is' : 'ies are'} planned as neutrals — static armies to take, no hold needed beside them (#270).`);
1568
+ return plan;
1569
+ }
1570
+ /**
1571
+ * #270: the input every pass plans on — {@link planTurn}'s first step: the static seats' territories
1572
+ * neutral and the seats no opponent. The same object when the game has no static seat holding land.
1573
+ */
1574
+ export function planningInput(input) {
1575
+ return withoutStaticSeats(input, staticSeats(input.game?.players, input.game?.endRules, input.me));
1576
+ }
1577
+ /** {@link PlanInput} with the static seats' territories neutral and the seats no opponent (#270). */
1578
+ function withoutStaticSeats(input, seats) {
1579
+ if (!seats.size)
1580
+ return input;
1581
+ const opening = input.game?.opening;
1582
+ // #281: which neutrals the seats left, so the planner can still tell them from any other.
1583
+ const vacated = new Map(input.vacated);
1584
+ for (const t of input.board.territories)
1585
+ if (t.owner.kind === 'player' && seats.has(t.owner.playerId))
1586
+ vacated.set(t.territoryId, t.owner.playerId);
1587
+ return {
1588
+ ...input,
1589
+ ...(vacated.size ? { vacated } : {}),
1590
+ board: neutralizeSeats(input.board, seats),
1591
+ ...(input.previousBoard ? { previousBoard: neutralizeSeats(input.previousBoard, seats) } : {}),
1592
+ ...(input.tracks ? { tracks: input.tracks.filter((t) => !seats.has(t.playerId)) } : {}),
1593
+ ...(input.relations ? { relations: input.relations.filter((r) => !seats.has(r.player)) } : {}),
1594
+ ...(input.sanctions ? { sanctions: input.sanctions.filter((x) => !seats.has(x.player)) } : {}),
1595
+ ...(input.game && opening ? { game: { ...input.game, opening: new Map([...opening].filter(([p]) => !seats.has(p))) } } : {}),
1596
+ };
1597
+ }
1598
+ function planSettled(input) {
1599
+ const plan = planRun(input, false);
1600
+ const bare = runOutcome.get(plan);
1601
+ if (!bare || !bare.bareSteps.length)
1602
+ return plan;
1603
+ // #214 review: a lead step retried at its bare cost is not sure to land, so it may never take the
1604
+ // armies a hold gets in the plan without bare steps. The planner sizes holds after captures (a
1605
+ // contested held bonus is held whole from what they leave, #118), so this is checked on the two
1606
+ // plans: when the bare one leaves a border that the other holds (funded there) without its hold,
1607
+ // the plan without bare steps stands, and says why.
1608
+ const sure = planRun(input, true);
1609
+ const kept = runOutcome.get(sure);
1610
+ if (!kept)
1611
+ return plan;
1612
+ const lost = [...kept.held].filter((x) => bare.unheld.has(x)).sort((a, b) => a - b);
1613
+ if (!lost.length)
1614
+ return plan;
1615
+ const label = (id) => `${input.graph.territoryById.get(id).name} (#${id})`;
1616
+ const list = (ids) => ids.map(label).join(', ');
1617
+ const one = bare.bareSteps.length === 1;
1618
+ sure.rationale.push(`Lead step${one ? '' : 's'} ${list(bare.bareSteps)} not taken at ${one ? 'its' : 'their'} bare cost (#214 review): taking ${one ? 'it' : 'them'} would leave ${list(lost)} without the hold this plan gives ${lost.length === 1 ? 'it' : 'them'} — a bare step lands only if its owner does not deploy there first, and never takes a hold's armies.`);
1619
+ return sure;
1620
+ }
1621
+ /**
1622
+ * #214 review: per plan, the lead steps it takes at their bare cost, the borders it deploys to (or
1623
+ * funds a hold on) that end holding, and the borders of mine still threatened once its captures
1624
+ * land that end without a hold.
1625
+ */
1626
+ const runOutcome = new WeakMap();
1627
+ function planRun(input, noBare) {
1628
+ const shared = noBare ? { noBare } : {};
1629
+ const { plan, used } = settledPass(input, shared, new Set(), false);
1630
+ if (!used)
1631
+ return plan;
1632
+ const free = settledPass(input, shared, new Set(), true).plan;
1633
+ let cut = new Set([...plan.expected.captures, ...free.expected.captures]);
1634
+ for (let i = 0; i < TWO_STEP_PASSES && cut.size > 0; i++) {
1635
+ const p = settledPass(input, shared, cut, false).plan;
1636
+ const taken = new Set(p.expected.captures);
1637
+ const still = new Set([...cut].filter((t) => taken.has(t)));
1638
+ if (still.size === cut.size)
1639
+ return p;
1640
+ cut = still;
1641
+ }
1642
+ return plan;
1643
+ }
1644
+ function planPass(input, pass) {
1645
+ // ---- estimates (plan/estimates.ts) ----
1646
+ const pc = planContext(input);
1647
+ const ps = newPlanState();
1648
+ noteEstimates(pc, ps);
1649
+ const { g, board, s, opts, income, foe, profile, auto, goal, balanced, reserve, enemyDeploy, deployOf, incomeOfPlayer, paybackTurns, } = pc;
1650
+ const { territories: state, label, bonusName, mine, mineSet, incomeGain, nextIncomeWith, armiesOf, unitsAt, defenceAt, bonusTs, completedBy, inFocus, } = pc;
1651
+ const { guard, rates, chanceOf, chanceAt, costAt, toTake, luck, noSplit, } = pc;
1652
+ const { armyLead, leadLever, clearLeader, ffaLeader, holdPasses, leadText, myCommanders } = pc;
1653
+ const { warnings, rationale, avail, locked, spared, captured, combined, moves, survivorsAt, captureOrder, captureUndo, staged, incoming, } = ps;
1654
+ if (!mine.length) {
1655
+ const empty = emptyPlan(pc, ps);
1656
+ // B2: each truce given is still reported, as the plan treated it (nothing to relax or cap).
1657
+ const report = reportTruce(pc, ps, undefined, () => 0);
1658
+ if (report) {
1659
+ empty.relations = report.relations;
1660
+ if (report.advice.length)
1661
+ empty.advice = report.advice;
1662
+ }
1663
+ return empty;
1664
+ }
1665
+ // ---- the deploy book (plan/orders.ts): budget, guard, deploys, pools, protected value ----
1666
+ const book = deployBook(pc, ps);
1667
+ // #274: under No-Split my commander's walk is its territory's one order, entered before any pass plans.
1668
+ reserveCommanderMove(pc, ps);
1669
+ const { guardAt, coverOf, heldNow, gainWith, orderOf, deploy, pools, roomAt, spareAt, } = book;
1670
+ // ---- B2 (T2, T3): the truce holds, once the book knows what each border protects (plan/relations.ts) ----
1671
+ ps.truce = trucePass(pc, book.valueOf);
1672
+ // As the deploy book reads it, restated here so TypeScript narrows `pools` wherever it is tested.
1673
+ const local = pools !== null && pools.bonuses.length > 0;
1674
+ // ---- 1t. threat trend, 1. defence (plan/threats.ts) ----
1675
+ const threats = threatsPhase(pc, ps, input);
1676
+ const { growthOf, reinforcementAt, borders, facing, borderAt } = threats;
1677
+ // ---- 1. holds, #172, 1h, 1b, 1c, #122 garrisons (plan/holds.ts) ----
1678
+ const hd = holdsPhase(pc, ps, book, threats, pass);
1679
+ const { acting, conceded, concedeUnaffordable, floorOrConcede, fundNearMiss, fundUnit, garrisonCompleted, heldBorders, heldStack, hold, holds, keepFor, kept, keptShort, leftFor, mayComplete, mayHold, noteRecent, pendingLocks, reconsider, settleContested, twoStepBound, twoStepKeep, uneconomic, units, withdraw, } = hd;
1680
+ // ---- 2. targets, 4d. frontier cost, bonus scoring, #101 (plan/targets.ts) ----
1681
+ const tgt = targetsPhase(pc, ps, input, threats, hd);
1682
+ const { breakable, counterAt, targets, leadSteps, landScoreCost, offence, skipOffence, plans, ratio, committing, byCloseness, retakeChecks, retakeWarning, } = tgt;
1683
+ // #215 review: rule 1a's triage (run with the strikes, below) leaves pending a border in a bonus
1684
+ // these plans may complete this turn.
1685
+ for (const p of plans)
1686
+ if (p.completable)
1687
+ hd.completable.set(p.bonusId, p.cost);
1688
+ // ---- R3, No-Split, capture helper, 3a. combined, passes 1 and 2 (plan/captures.ts) ----
1689
+ const caps = capturesPhase(pc, ps, pass, book, threats, hd, tgt);
1690
+ const { strikes, worstCase, defendersAt, tryCapture, snapshot, complete, tryExpand, advance } = caps;
1691
+ // ---- 1e. finish off an opponent, 1s. strike an enemy commander, #165 guard-off breaks (plan/strike.ts) ----
1692
+ const { struck } = strikesPhase(pc, ps, book, threats, hd, tgt, caps);
1693
+ // ---- #276: guard off — free retakes and raids one step deeper (plan/guard-off.ts) ----
1694
+ guardOffRaids(pc, ps, book, hd, tgt, threats, worstCase, input.previousBoard);
1695
+ if (balanced) {
1696
+ // ---- balanced: greedy by income per army ----
1697
+ const opponents = Math.max(1, Math.floor(opts.opponents ??
1698
+ new Set(board.territories.flatMap((t) => t.owner.kind === 'player' && foe(t.owner.playerId) ? [t.owner.playerId] : [])).size));
1699
+ // Rule 0p.1: in a 1v1 in contact, a break is a completion of equal value (the opponent
1700
+ // loses that income), and expansion that completes nothing ranks below holds and breaks.
1701
+ const oneVsOne = auto && profile.format === '1v1' && facing.size > 0;
1702
+ // Rule 0p.2: in an FFA with two or more opponents left, no second front.
1703
+ // B2 (T4): a player a truce holds is no front.
1704
+ const ffa = auto && profile.format === 'ffa' && profile.opponents - partnerFronts(pc) >= 2;
1705
+ if (oneVsOne)
1706
+ rationale.push('1v1 in contact: breaking an enemy bonus counts like completing one of equal value (the opponent loses that income), and expansion that completes no bonus this turn ranks below holding, breaking and completing.');
1707
+ const weight = oneVsOne ? 1 : BREAK_WEIGHT / opponents;
1708
+ /** Bonuses I hold in full (value > 0). */
1709
+ const heldBonusMembers = g.map.bonuses
1710
+ .filter((b) => b.value > 0)
1711
+ .map((b) => bonusTerritories(g, b.id))
1712
+ .filter((ts) => ts.length > 0 && ts.every((t) => mineSet.has(t)));
1713
+ /** Player `p` could take a member of a bonus I hold next turn (its stacks next to it plus its deploy). */
1714
+ const threatensMyBonus = (p) => heldBonusMembers.some((ts) => ts.some((m) => {
1715
+ let movable = 0;
1716
+ let growth = 0;
1717
+ let next = false;
1718
+ for (const n of neighborsOf(g, m)) {
1719
+ const st = state.get(n);
1720
+ if (st?.owner.kind !== 'player' || st.owner.playerId !== p || st.armies === null)
1721
+ continue;
1722
+ next = true;
1723
+ movable += Math.max(0, st.armies - guard) + unitsAt(n);
1724
+ growth = Math.max(growth, growthOf.get(n)?.growth ?? 0);
1725
+ }
1726
+ const take = toTake(defenceAt(m));
1727
+ return next && take !== null && take <= movable + Math.max(deployOf(p), growth);
1728
+ }));
1729
+ /** Player `p` loses a territory to this turn's earlier passes (a strike, finishing off, pressure). */
1730
+ const beingFinished = (p) => [...captured].some((t) => {
1731
+ const o = state.get(t)?.owner;
1732
+ return o?.kind === 'player' && o.playerId === p;
1733
+ });
1734
+ /** The best neutral bonus capture per army (complete or advance), 0 with none. */
1735
+ const bestNeutral = Math.max(0, ...plans.map(ratio));
1736
+ /**
1737
+ * Rule 0p.2: breaking `b` would open a second front (said once per bonus; the general rule
1738
+ * is said with the first break it skips). Call it only for a break the plan could afford.
1739
+ */
1740
+ const secondFrontSaid = new Set();
1741
+ /** #167: the neutral's share of a break's score that skips it, scaled by my army lead (at least 1×). */
1742
+ const similar = SECOND_FRONT_SIMILAR * Math.max(1, Math.min(SECOND_FRONT_LEAD, armyLead.ratio));
1743
+ const opensSecondFront = (b, score) => ffa &&
1744
+ !leadLever &&
1745
+ b.player !== clearLeader &&
1746
+ !threatensMyBonus(b.player) &&
1747
+ !beingFinished(b.player) &&
1748
+ bestNeutral >= similar * score;
1749
+ const secondFront = (b, score) => {
1750
+ if (!opensSecondFront(b, score))
1751
+ return false;
1752
+ if (!secondFrontSaid.has(b.bonusId)) {
1753
+ if (!secondFrontSaid.size)
1754
+ rationale.push(`FFA with ${profile.opponents} opponents left: no second front — a player that threatens no bonus of mine and is not being finished off is not attacked while a neutral capture of similar value exists.`);
1755
+ secondFrontSaid.add(b.bonusId);
1756
+ rationale.push(`Not breaking ${bonusName(b.bonusId)} (+${b.value} from player ${b.player}): no second front in an FFA — player ${b.player} threatens no bonus of mine and is not being finished off, and a neutral capture earns ${bestNeutral.toFixed(2)} per army against ${score.toFixed(2)}${similar > SECOND_FRONT_SIMILAR ? ` (it needs ${similar.toFixed(2)}× of it, scaled by my army lead of ${leadText()})` : ''}.`);
1757
+ }
1758
+ return true;
1759
+ };
1760
+ // Enemy armies that could hit `t` next turn once it is mine (its own armies excluded).
1761
+ const counterThreat = (t) => {
1762
+ const byPlayer = new Map();
1763
+ for (const n of neighborsOf(g, t)) {
1764
+ const st = state.get(n);
1765
+ if (st?.owner.kind !== 'player' || !foe(st.owner.playerId) || st.armies === null)
1766
+ continue;
1767
+ byPlayer.set(st.owner.playerId, (byPlayer.get(st.owner.playerId) ?? 0) + Math.max(0, st.armies - guard) + unitsAt(n));
1768
+ }
1769
+ // Each opponent's movable armies plus its own deploy estimate; with none next to it, the reported estimate.
1770
+ if (!byPlayer.size)
1771
+ return enemyDeploy;
1772
+ return Math.max(...[...byPlayer].map(([p, movable]) => movable + deployOf(p)));
1773
+ };
1774
+ const rank = { unit: 0, hold: 0, complete: 1, advance: 2, break: 3, counter: 3 };
1775
+ const candidates = [];
1776
+ const deferred = [];
1777
+ /** #215: pending holds this step conceded and unlocked, whose armies may still attack out. */
1778
+ const unlocked = new Set();
1779
+ /** #215 review: conceded pending holds left locked until the captures are known (`mayComplete`). */
1780
+ const parked = new Set();
1781
+ /** #215: unlock a pending hold triage locked (only that lock: never one another rule added). */
1782
+ const unlockPending = (id) => {
1783
+ if (!pendingLocks.delete(id))
1784
+ return;
1785
+ locked.delete(id);
1786
+ unlocked.add(id);
1787
+ };
1788
+ /**
1789
+ * #215: a pending hold (locked by triage until this step decides) conceded here is unlocked: as
1790
+ * any conceded border, it may still attack out with the armies on it (rule 1a). One in a bonus
1791
+ * this turn's captures may complete stays locked until they are known: rule 1c keeps it for a
1792
+ * completed bonus, and an attack out would have emptied it first.
1793
+ */
1794
+ const concedePending = (t, room) => {
1795
+ concedeUnaffordable(t, room);
1796
+ if (heldBorders.has(t.id))
1797
+ return;
1798
+ if (mayComplete(t.id))
1799
+ parked.add(t.id);
1800
+ else
1801
+ unlockPending(t.id);
1802
+ };
1803
+ let expansionLeft = 0;
1804
+ let expansionSpent = 0;
1805
+ let topValue = 0;
1806
+ const spend = (f) => () => {
1807
+ const before = ps.budget;
1808
+ f();
1809
+ expansionSpent += before - ps.budget;
1810
+ expansionLeft--;
1811
+ };
1812
+ /** A bonus's worth as the rationale states it: "+22, net +6" when its members carry penalties. */
1813
+ const worthOf = new Map();
1814
+ for (const p of plans) {
1815
+ const score = ratio(p);
1816
+ // Rule 4c: a completion competes with holds at its net worth (`value` feeds topValue and
1817
+ // rule 1h.3's starve check), never its gross value.
1818
+ worthOf.set(p.bonusId, p.net === p.value ? `+${p.value}` : `+${p.value}, net +${p.net}`);
1819
+ if (p.completable)
1820
+ candidates.push({ kind: 'complete', score, cost: p.cost, id: p.bonusId, value: p.net, focus: p.focus, borders: p.borders, run: spend(() => complete(p)) });
1821
+ candidates.push({ kind: 'advance', score, cost: p.cost, id: p.bonusId, value: p.net, focus: p.focus, borders: p.borders, run: spend(() => advance(p)) });
1822
+ }
1823
+ // Capturing a member of a breakable bonus: what survives it, and whether that holds next turn.
1824
+ // A break is sized to land (#72): its score leaves out what holding it would need.
1825
+ const breakOption = (t) => {
1826
+ // #201: the FFA leader's break is sized to land for certain against its owner's one deploy.
1827
+ const landing = ffaLeader ? defenceAt(t) + reinforcementAt(t) : undefined;
1828
+ const cost = (landing !== undefined ? captureCost(landing, s) : null) ?? targets.get(t).cost;
1829
+ const survivors = cost - straightKills(defenceAt(t), rates.defensiveKillRate);
1830
+ const counter = counterThreat(t);
1831
+ const take = toTake(survivors);
1832
+ return { t, cost, survivors, counter, take, survives: take === null || take > counter, scoreCost: landScoreCost(t) };
1833
+ };
1834
+ /**
1835
+ * What a strike is worth (#72), in income terms like a hold's worth: the income the opponent
1836
+ * loses this turn plus the armies it must spend to retake the territory (at least what my
1837
+ * survivors need to be taken) over PAYBACK_TURNS, weighted as breaks are.
1838
+ */
1839
+ const strikeWorth = (lost, o) => weight * (lost + (o.take ?? o.survivors) / paybackTurns);
1840
+ const round2 = (v) => Math.round(v * 100) / 100;
1841
+ /**
1842
+ * At most what a capture of `t` could draw on now: every source free to attack plus the
1843
+ * deployable budget. Below its cost the capture cannot be planned this turn.
1844
+ */
1845
+ const affordable = (t) => {
1846
+ const tg = targets.get(t);
1847
+ const free = tg.sources.filter((x) => !locked.has(x) && !orderOf(x)).reduce((n, x) => n + Math.max(0, avail.get(x)), 0);
1848
+ // #240 review: a repulsed territory's sure size (it ranks on its plain cost).
1849
+ return free + Math.max(0, ps.budget - reserve) >= tgt.sizeOf(t);
1850
+ };
1851
+ const broken = (b) => bonusTerritories(g, b.bonusId).some((x) => captured.has(x));
1852
+ const breakReason = (b) => b.probable
1853
+ ? `breaks probable enemy bonus ${bonusName(b.bonusId)} (+${b.value} from player ${b.player}; ${b.probable})`
1854
+ : `breaks enemy bonus ${bonusName(b.bonusId)} (+${b.value} from player ${b.player})`;
1855
+ const warnRetake = (b, o) => {
1856
+ const warning = retakeWarning(o.t, b.bonusId, o.survivors, o.counter);
1857
+ retakeChecks.set(o.t, { bonusId: b.bonusId, survivors: o.survivors, counter: o.counter, warning });
1858
+ if (warning)
1859
+ warnings.push(warning);
1860
+ };
1861
+ const breakOf = new Map();
1862
+ for (const b of breakable)
1863
+ for (const t of bonusTerritories(g, b.bonusId))
1864
+ breakOf.set(t, b);
1865
+ // A threatened border whose only visible threat is a member of a breakable enemy
1866
+ // bonus also attacks it: the capture removes the threat and breaks the bonus. It
1867
+ // attacks on top of its hold, never instead of it: the threat assumes the enemy
1868
+ // reinforces that member first, so the capture can fail, and what stays on the
1869
+ // border must still hold. When the hold plus the capture is unaffordable, it just
1870
+ // holds. (A held border otherwise makes no attacks.)
1871
+ const holdAndBreak = (t, rest = 0) => {
1872
+ const threats = neighborsOf(g, t.id).filter((n) => {
1873
+ const st = state.get(n);
1874
+ return st?.owner.kind === 'player' && foe(st.owner.playerId) && st.armies !== null;
1875
+ });
1876
+ if (threats.length !== 1)
1877
+ return false;
1878
+ const n = threats[0];
1879
+ const b = breakOf.get(n);
1880
+ if (!b || !targets.has(n) || broken(b) || orderOf(t.id))
1881
+ return false;
1882
+ const o = breakOption(n);
1883
+ if (t.holdCost + o.cost > spareAt(t.id) - rest)
1884
+ return false;
1885
+ // Scored as the break candidates are: landing armies plus the frontier it adds (#71, #72).
1886
+ if (secondFront(b, strikeWorth(b.value, o) / Math.max(1, o.scoreCost)))
1887
+ return false;
1888
+ const before = ps.budget;
1889
+ noteRecent(t);
1890
+ deploy(t.id, t.holdCost);
1891
+ if (!tryCapture(n, breakReason(b), { from: t.id, keep: avail.get(t.id) })) {
1892
+ // Refused (R3: it would complete a bonus I cannot hold next turn): just hold.
1893
+ rationale.push(`Deploy ${t.holdCost} to ${label(t.id)} so it holds (protects +${t.value}): ${heldStack(t)} need ${toTake(t.have + t.units + t.holdCost)} to take, above the ~${t.threat} threat.`);
1894
+ return true;
1895
+ }
1896
+ expansionSpent += before - ps.budget - t.holdCost;
1897
+ ps.anchor ??= moves[moves.length - 1].from;
1898
+ rationale.push(`${label(n)} is the only visible threat to ${label(t.id)}: capturing it removes that threat and breaks the bonus.`, noSplit
1899
+ ? `Deploy ${t.holdCost} to ${label(t.id)}: under No-Split its whole stack attacks ${label(n)} and nothing stays behind, so ${label(t.id)} (protects +${t.value}) is safe only once ${label(n)} falls.`
1900
+ : `Deploy ${t.holdCost} to ${label(t.id)} so it still holds (protects +${t.value}) after attacking ${label(n)}: ${heldStack(t)} stay, needing ${toTake(t.have + t.units + t.holdCost)} to take, above the ~${t.threat} threat if the attack fails.`);
1901
+ warnRetake(b, o);
1902
+ // Its own offence entry (#72): the break option may be another member, which never runs.
1903
+ offence.set(`break:${b.bonusId}`, {
1904
+ bonusId: b.bonusId,
1905
+ target: n,
1906
+ kind: 'break',
1907
+ cost: o.cost,
1908
+ value: round2(strikeWorth(b.value, o)),
1909
+ taken: true,
1910
+ why: `${breakReason(b)}, removing the only visible threat to ${label(t.id)}`,
1911
+ });
1912
+ return true;
1913
+ };
1914
+ for (const b of breakable) {
1915
+ // Its cheapest visible member (#72: a break only has to land), then the least frontier, then id.
1916
+ const options = bonusTerritories(g, b.bonusId)
1917
+ .filter((t) => targets.has(t))
1918
+ .map(breakOption)
1919
+ .sort((a, b) => a.cost - b.cost || a.scoreCost - b.scoreCost || a.t - b.t);
1920
+ const o = options[0];
1921
+ if (!o)
1922
+ continue;
1923
+ const worth = strikeWorth(b.value, o);
1924
+ const score = worth / Math.max(1, o.scoreCost);
1925
+ offence.set(`break:${b.bonusId}`, {
1926
+ bonusId: b.bonusId,
1927
+ target: o.t,
1928
+ kind: 'break',
1929
+ cost: o.cost,
1930
+ value: round2(worth),
1931
+ taken: false,
1932
+ why: breakReason(b),
1933
+ });
1934
+ // An FFA skips a second-front break, but only one the plan could pay for is named as
1935
+ // skipped: an unaffordable one is dropped quietly (it could not run either way).
1936
+ if (opensSecondFront(b, score) && !affordable(o.t)) {
1937
+ skipOffence(o.t, 'not affordable this turn');
1938
+ continue;
1939
+ }
1940
+ if (secondFront(b, score)) {
1941
+ skipOffence(o.t, `no second front in an FFA: player ${b.player} threatens no bonus of mine`);
1942
+ continue;
1943
+ }
1944
+ candidates.push({
1945
+ kind: 'break',
1946
+ score,
1947
+ cost: o.cost,
1948
+ id: b.bonusId,
1949
+ value: b.value,
1950
+ focus: false,
1951
+ borders: analyzeBonus(g, b.bonusId).borderTerritoryIds.length,
1952
+ target: o.t,
1953
+ owner: b.player,
1954
+ run: spend(() => {
1955
+ // Already broken (by a border attacking its only threat): one capture is enough.
1956
+ if (broken(b))
1957
+ return;
1958
+ if (ffaLeader && o.cost > targets.get(o.t).cost) {
1959
+ const tg = targets.get(o.t);
1960
+ const was = worstCase.get(o.t);
1961
+ targets.set(o.t, { ...tg, cost: o.cost });
1962
+ worstCase.set(o.t, defenceAt(o.t) + reinforcementAt(o.t));
1963
+ if (!tryCapture(o.t, `${breakReason(b)}, sized to land against player ${b.player}'s ~${reinforcementAt(o.t)} deploy (#201: I lead this free-for-all)`)) {
1964
+ targets.set(o.t, tg);
1965
+ if (was === undefined)
1966
+ worstCase.delete(o.t);
1967
+ else
1968
+ worstCase.set(o.t, was);
1969
+ return;
1970
+ }
1971
+ }
1972
+ else if (!tryCapture(o.t, breakReason(b)))
1973
+ return;
1974
+ ps.anchor ??= moves[moves.length - 1].from;
1975
+ warnRetake(b, o);
1976
+ }),
1977
+ });
1978
+ }
1979
+ // Counter-attacks (#72): a stack that shrank fighting me, scored like a break that breaks no
1980
+ // bonus (the armies its owner must spend to retake it). It is already fighting me (it
1981
+ // attacked me, or held off my attack), so it is never a second front.
1982
+ for (const [t, c] of counterAt) {
1983
+ if (!targets.has(t))
1984
+ continue;
1985
+ const o = breakOption(t);
1986
+ const worth = strikeWorth(0, o);
1987
+ const reason = `counter-attacks player ${c.player}'s ${label(t)}, which shrank from ${c.from} to ${c.to} fighting me last turn (attacking me, or holding off an attack of mine) (${c.costNow} to take now, ${c.costThen} before)`;
1988
+ offence.set(`counter:${t}`, { target: t, kind: 'counter', cost: o.cost, value: round2(worth), taken: false, why: reason });
1989
+ candidates.push({
1990
+ kind: 'counter',
1991
+ score: worth / Math.max(1, o.scoreCost),
1992
+ cost: o.cost,
1993
+ id: t,
1994
+ value: worth,
1995
+ focus: false,
1996
+ borders: 0,
1997
+ target: t,
1998
+ owner: c.player,
1999
+ run: spend(() => {
2000
+ if (captured.has(t))
2001
+ return;
2002
+ if (!tryCapture(t, reason))
2003
+ return;
2004
+ ps.anchor ??= moves[moves.length - 1].from;
2005
+ }),
2006
+ });
2007
+ }
2008
+ expansionLeft = candidates.length;
2009
+ // Under rule 0p.1 an advance never outranks a hold, so it never defers one either.
2010
+ topValue = Math.max(0, ...candidates.filter((c) => !(oneVsOne && c.kind === 'advance')).map((c) => c.value));
2011
+ let floor = expansionLeft ? Math.ceil(MIN_EXPANSION_SHARE * income) : 0;
2012
+ // #167: a multi-turn view of the main front. Adapting in contact, the expansion share stands only
2013
+ // when the front is no worse than a stand-off without those armies: my biggest stack facing the
2014
+ // opponent with the biggest stack next to me, deploying the income less the share every turn
2015
+ // against that stack on the opponent's whole deploy (`forecastBorder`). Ground down so, the share
2016
+ // is dropped this turn and holds come first.
2017
+ if (floor > 0 && auto && (profile.phase === 'contact' || profile.phase === 'late')) {
2018
+ // #218: one definition of the main front, shared with the game outlook (`mainFront`).
2019
+ const enemies = [];
2020
+ for (const [id, st] of state)
2021
+ if (st.owner.kind === 'player' && foe(st.owner.playerId) && st.armies !== null)
2022
+ enemies.push({ id, armies: st.armies + unitsAt(id), player: st.owner.playerId });
2023
+ const front = mainFront(g, (x) => mineSet.has(x), enemies, (x) => armiesOf(x) + unitsAt(x));
2024
+ if (front) {
2025
+ const settingsF = { offensiveKillRate: rates.offensiveKillRate, defensiveKillRate: rates.defensiveKillRate, oneArmyStandsGuard: guard === 1 };
2026
+ // Every turn's income, not this turn's deploy: a card is played once (#164).
2027
+ const theirIncome = incomeOfPlayer(front.player);
2028
+ // #218 review: my side likewise — the board income, a Reinforcement card's armies out
2029
+ // (`income` counts them this turn only), and the expansion share taken of that.
2030
+ const every = nextIncomeWith(0);
2031
+ const share = Math.min(floor, Math.ceil(MIN_EXPANSION_SHARE * every));
2032
+ const cardNote = pc.cardArmies > 0 ? ` (my board income: the ${pc.cardArmies} armies of this turn's card are played once)` : '';
2033
+ const f = forecastBorder({ mine: front.mine, theirs: front.theirs, myIncome: every, theirIncome, myDeploy: every - share, settings: settingsF });
2034
+ // #218: the same front with my whole income deployed there every turn — what the game
2035
+ // outlook's front forecast assumes — so the two can be read together.
2036
+ const whole = forecastBorder({ mine: front.mine, theirs: front.theirs, myIncome: every, theirIncome, settings: settingsF, outcomeOnly: true });
2037
+ ps.front = { ...front, myIncome: every, theirIncome, outcome: whole.outcome, turn: whole.turn };
2038
+ const wholeText = whole.outcome === f.outcome && whole.turn === f.turn
2039
+ ? ''
2040
+ : ` With my whole ${every} a turn there (as the outlook's front forecast deploys it) ${whole.outcome === 'ground-down'
2041
+ ? `I am ground down on turn ${whole.turn}`
2042
+ : whole.outcome === 'breaks'
2043
+ ? `my stack breaks it on turn ${whole.turn}`
2044
+ : 'it is a stand-off'}.`;
2045
+ const pins = f.pinnedHolds ? `the border pins ${f.pinned} of my ${every} income` : `not even my whole ${every} income keeps the border`;
2046
+ const pair = `my ${front.mine} on ${label(front.from)} against player ${front.player}'s ${front.theirs} on ${label(front.at)}, each deploying there every turn${cardNote}`;
2047
+ // `breaks` means pressing captures before being pressed grinds me down; the plan commits to
2048
+ // pressing only when its orders already take that stack. Otherwise being pressed with the
2049
+ // income less the share decides: the border pins more than that, so the share goes.
2050
+ const pressedGrinds = f.pinned > every - share;
2051
+ const pressing = captured.has(front.at);
2052
+ if (f.outcome === 'ground-down') {
2053
+ rationale.push(`Front outlook (#167): ${pair}, with ${every - share} a turn (the income less the ${share} expansion share) I am ground down on turn ${f.turn} — ${pins}. Holds come before the expansion share this turn.${wholeText}`);
2054
+ floor = 0;
2055
+ }
2056
+ else if (f.outcome === 'breaks' && pressedGrinds && !pressing) {
2057
+ rationale.push(`Front outlook (#167): ${pair}, my stack breaks it on turn ${f.turn} only if the plan presses it, and it does not; pressed, with ${every - share} a turn (the income less the ${share} expansion share) I am ground down — ${pins}. Holds come before the expansion share this turn.${wholeText}`);
2058
+ floor = 0;
2059
+ }
2060
+ else if (f.outcome === 'breaks' && pressedGrinds)
2061
+ rationale.push(`Front outlook (#167): ${pair}, my stack breaks it on turn ${f.turn}, and the plan presses it this turn (pressed instead, ${pins}): the expansion share stands.${wholeText}`);
2062
+ else
2063
+ rationale.push(`Front outlook (#167): ${pair}, ${f.outcome === 'breaks' ? `my stack breaks it on turn ${f.turn}` : 'it is a stand-off'} even with ${share} of income going to expansion (${f.pinnedHolds ? `the border pins ${f.pinned}` : `not even my whole ${every} keeps the border`}): the expansion share stands.${wholeText}`);
2064
+ }
2065
+ }
2066
+ for (const t of holds)
2067
+ candidates.push({
2068
+ kind: 'hold',
2069
+ // A border just taken from a weak opponent is held first: conceding it hands it back.
2070
+ score: t.recentFrom !== undefined ? Infinity : t.worth / t.holdCost,
2071
+ cost: t.holdCost,
2072
+ id: t.id,
2073
+ value: t.value,
2074
+ focus: false,
2075
+ borders: 0,
2076
+ run: () => {
2077
+ // Already garrisoned for a bonus this turn completed (#122).
2078
+ if (heldBorders.has(t.id))
2079
+ return;
2080
+ if (holdAndBreak(t))
2081
+ return;
2082
+ const pending = expansionLeft > 0 && t.worth < topValue && t.recentFrom === undefined ? Math.max(0, floor - expansionSpent) : 0;
2083
+ const room = roomAt(t.id);
2084
+ // #215: conceded, its armies may attack out (rule 1a) in the passes still to run.
2085
+ if (t.holdCost > room)
2086
+ return concedePending(t, room);
2087
+ if (t.holdCost > room - pending) {
2088
+ deferred.push(t);
2089
+ rationale.push(`Hold ${label(t.id)} later (needs ${t.holdCost}, protects +${t.value}): at least ${floor} of income (${MIN_EXPANSION_SHARE * 100}%) goes to expansion first, worth up to +${topValue}.`);
2090
+ return;
2091
+ }
2092
+ hold(t);
2093
+ },
2094
+ });
2095
+ // A conceded unit's members, judged on their own now (rule 1a, against what is left).
2096
+ const singleNow = (t, quiet) => {
2097
+ if (t.critical)
2098
+ return;
2099
+ if (uneconomic(t)) {
2100
+ conceded.add(t.id);
2101
+ if (!quiet)
2102
+ warnings.push(`${label(t.id)} cannot be held economically (needs ${t.holdCost}, protects +${t.value}): conceded`);
2103
+ return;
2104
+ }
2105
+ const room = roomAt(t.id);
2106
+ if (t.holdCost > room) {
2107
+ if (quiet)
2108
+ conceded.add(t.id);
2109
+ else
2110
+ concedeUnaffordable(t, room);
2111
+ return;
2112
+ }
2113
+ hold(t);
2114
+ heldBorders.add(t.id);
2115
+ };
2116
+ /** Units waiting for the expansion share (rule 4a's MIN_EXPANSION_SHARE), funded before any advance or break. */
2117
+ const waiting = [];
2118
+ const fundOrConcede = (u) => {
2119
+ if (u.conceded)
2120
+ return;
2121
+ if (!fundUnit(u, holdAndBreak) && !fundNearMiss(u))
2122
+ floorOrConcede(u, leftFor(u), singleNow);
2123
+ };
2124
+ let unitsDue = false;
2125
+ const unitOf = new Map();
2126
+ for (const u of units) {
2127
+ if (u.conceded || u.contested)
2128
+ continue;
2129
+ const c = {
2130
+ kind: 'unit',
2131
+ score: u.members.some((m) => m.recentFrom !== undefined) ? Infinity : u.worth / u.net,
2132
+ cost: u.cost,
2133
+ id: u.members[0].id,
2134
+ value: u.value,
2135
+ focus: false,
2136
+ borders: 0,
2137
+ run: () => {
2138
+ if (u.conceded)
2139
+ return;
2140
+ const recent = u.members.some((m) => m.recentFrom !== undefined);
2141
+ // #201, ahead: held for the worst case before any capture, completions included — no
2142
+ // waiting behind the expansion share.
2143
+ const pending = holdPasses !== 'worst' && !unitsDue && expansionLeft > 0 && u.worth < topValue && !recent ? Math.max(0, floor - expansionSpent) : 0;
2144
+ const cost = u.members.filter((m) => !heldBorders.has(m.id)).reduce((n, m) => n + m.holdCost, 0);
2145
+ if (cost <= ps.budget && cost > ps.budget - pending) {
2146
+ waiting.push(u);
2147
+ rationale.push(`Hold ${u.members.map((m) => label(m.id)).join(', ')} after this turn's bonus completions (needs ${cost}, protects +${u.value}): a completion worth up to +${topValue} may go first, but the hold is funded before any capture that completes nothing.`);
2148
+ return;
2149
+ }
2150
+ fundOrConcede(u);
2151
+ },
2152
+ };
2153
+ candidates.push(c);
2154
+ unitOf.set(c, u);
2155
+ }
2156
+ // PLAN-TEAMS C3.4: a capture of a player my teammate attacks this turn ranks above an equal one.
2157
+ const teamFocused = (c) => Number(c.owner !== undefined && pc.teamFocus.has(c.owner));
2158
+ const ahead = (a, b) => Number(b.focus) - Number(a.focus) ||
2159
+ // #201: ahead, every held bonus is held for the worst case before any capture (said below).
2160
+ (holdPasses === 'worst' ? Number(b.kind === 'unit') - Number(a.kind === 'unit') : 0) ||
2161
+ (oneVsOne ? Number(a.kind === 'advance') - Number(b.kind === 'advance') : 0) ||
2162
+ b.score - a.score;
2163
+ const after = (a, b) => a.cost - b.cost || a.borders - b.borders || rank[a.kind] - rank[b.kind] || a.id - b.id;
2164
+ candidates.sort((a, b) => ahead(a, b) || teamFocused(b) - teamFocused(a) || after(a, b));
2165
+ if (pc.teamFocus.size)
2166
+ for (const [i, c] of candidates.entries()) {
2167
+ if (!teamFocused(c))
2168
+ continue;
2169
+ const passed = candidates.slice(i + 1).find((d) => !teamFocused(d) && ahead(c, d) === 0 && after(c, d) > 0);
2170
+ if (passed)
2171
+ rationale.push(teamFocusLine(pc, c, passed));
2172
+ }
2173
+ if (holdPasses === 'worst' && candidates.some((c) => c.kind === 'unit'))
2174
+ rationale.push(`Ahead (#201): every held bonus is held for the worst case (each threatened border against the whole deploy) before any capture, completions included — the leader takes the option that still works when the opponent guesses right.`);
2175
+ // #101: completions and advances keep the slots their scores give them, but fill them
2176
+ // closest to completion first.
2177
+ if (committing) {
2178
+ const order = new Map(byCloseness.map((p, i) => [p.bonusId, i]));
2179
+ for (const kind of ['complete', 'advance']) {
2180
+ const slots = candidates.flatMap((c, i) => (c.kind === kind ? [i] : []));
2181
+ const sorted = slots.map((i) => candidates[i]).sort((a, b) => order.get(a.id) - order.get(b.id));
2182
+ slots.forEach((i, k) => (candidates[i] = sorted[k]));
2183
+ }
2184
+ }
2185
+ // A held-bonus unit that pays for itself is funded before any capture that completes
2186
+ // no bonus (an advance or a break, unless focused): at the first such capture, every
2187
+ // unit still pending runs first, with the completions that outscore the weakest of them.
2188
+ const done = new Set();
2189
+ // Rule 1h.3: a completion that outscores a pending unit per army still must not starve
2190
+ // it. When completing it first leaves too little to fund units it could have, it runs
2191
+ // only if its bonus earns more than those units; otherwise it waits until they are funded.
2192
+ const postponed = [];
2193
+ const unitNeed = (u) => u.members.filter((m) => !heldBorders.has(m.id)).reduce((n, m) => n + m.holdCost, 0);
2194
+ /** The units `b` armies fund, taken in order (a unit that does not fit is skipped). */
2195
+ const fundable = (us, b) => us.filter((u) => {
2196
+ const need = unitNeed(u);
2197
+ // Under Local Deployment (#122) only what may be deployed on its borders counts (its own
2198
+ // pool and the free armies): a unit that is a near miss already is not starved by a capture.
2199
+ if (need > b || (local && need > leftFor(u)))
2200
+ return false;
2201
+ b -= need;
2202
+ return true;
2203
+ });
2204
+ const run = (c) => {
2205
+ done.add(c);
2206
+ const pending = c.kind === 'complete' && !c.focus
2207
+ ? [...waiting, ...candidates.filter((d) => d.kind === 'unit' && !done.has(d)).map((d) => unitOf.get(d))].filter((u) => !u.conceded)
2208
+ : [];
2209
+ if (!pending.length)
2210
+ return c.run();
2211
+ const before = fundable(pending, ps.budget);
2212
+ const restore = snapshot();
2213
+ const spent = expansionSpent;
2214
+ const left = expansionLeft;
2215
+ c.run();
2216
+ const after = new Set(fundable(pending, ps.budget));
2217
+ const starved = before.filter((u) => !after.has(u));
2218
+ const lost = starved.reduce((n, u) => n + u.value, 0);
2219
+ // #122: a starved unit that cannot even be kept short (near miss, floor) is conceded. Waiting
2220
+ // costs the completion one turn of its value; conceding a held bonus loses its value every
2221
+ // turn until it is retaken — counted over PAYBACK_TURNS, the horizon every payback test
2222
+ // uses. So the completion goes first only when its one turn earns more than that.
2223
+ // Under Local Deployment only what may be deployed on its borders counts (pools respected).
2224
+ const kept = starved.map((u) => keptShort(u, local ? Math.min(ps.budget, leftFor(u)) : ps.budget));
2225
+ const conceding = starved.filter((_, i) => !kept[i]).reduce((n, u) => n + u.value, 0);
2226
+ // Units only left short (a near miss, a floor) still stand: the completion goes first when it
2227
+ // earns more than they are worth, or — when each stays a near miss — pays for itself within a
2228
+ // turn (#122: a +3 for 3 armies was deferred so a near miss could be topped up to sure).
2229
+ const first = conceding > 0
2230
+ ? c.value > paybackTurns * conceding
2231
+ : c.value > lost || (kept.every((k) => k === 'near') && c.cost <= c.value);
2232
+ if (!starved.length || first)
2233
+ return;
2234
+ restore();
2235
+ expansionSpent = spent;
2236
+ expansionLeft = left;
2237
+ postponed.push(c);
2238
+ rationale.push(`Complete bonus ${bonusName(c.id)} (${worthOf.get(c.id) ?? `+${c.value}`}) only after holding ${starved.map((u) => `${bonusName(u.bonusId)} (+${u.value})`).join(', ')}: completing it first would leave too little to hold ${starved.length === 1 ? 'it' : 'them'}, ${conceding > 0 ? `and waiting a turn costs +${c.value} once while losing ${starved.length === 1 ? 'it' : 'them'} costs +${conceding} every turn until retaken` : 'and it earns no more'}.`);
2239
+ };
2240
+ const runPostponed = () => {
2241
+ for (const c of postponed.splice(0))
2242
+ c.run();
2243
+ };
2244
+ /** #215, rule 0p.1: the contested units were held whole (where they fit) before the first advance. */
2245
+ let contestedDue = false;
2246
+ /** #275 (b): the contested units facing an untrusted opponent were held whole (where they fit) before the first capture. */
2247
+ let untrustedDue = false;
2248
+ candidates.forEach((c, i) => {
2249
+ if (done.has(c))
2250
+ return;
2251
+ // #275 (b): while an opponent's estimate is untrusted, a contested held bonus whose border faces
2252
+ // it is held whole before any capture (a +1 expansion once went ahead of the gate it left to fall).
2253
+ if (c.kind !== 'unit' && !c.focus && !untrustedDue) {
2254
+ untrustedDue = true;
2255
+ settleContested('untrusted');
2256
+ }
2257
+ // #215, rule 0p.1: an advance ranks below every hold, a contested held bonus's included
2258
+ // (#118 lets the captures go first, but in a 1v1 in contact not one that completes nothing):
2259
+ // live, a +4 bonus's one border was left to fall while 15 went to a bonus 47 armies from done.
2260
+ if (oneVsOne && c.kind === 'advance' && !c.focus && !contestedDue) {
2261
+ contestedDue = true;
2262
+ settleContested(true);
2263
+ }
2264
+ if ((c.kind === 'advance' || c.kind === 'break' || c.kind === 'counter') && !c.focus && !unitsDue) {
2265
+ unitsDue = true;
2266
+ // Those waiting for the expansion share outscore everything still to run.
2267
+ for (const u of waiting.splice(0))
2268
+ fundOrConcede(u);
2269
+ const pending = candidates.filter((d) => d.kind === 'unit' && !done.has(d));
2270
+ if (pending.length) {
2271
+ const bar = Math.min(...pending.map((d) => d.score));
2272
+ for (const d of candidates.slice(i + 1))
2273
+ if (!done.has(d) && (d.kind === 'unit' || (d.kind === 'complete' && d.score > bar)))
2274
+ run(d);
2275
+ }
2276
+ runPostponed();
2277
+ garrisonCompleted();
2278
+ }
2279
+ // #128: a hold deferred for the expansion share is not then starved by a capture that
2280
+ // completes nothing: when this one leaves too little for a hold still waiting, it is undone,
2281
+ // the waiting holds are funded first, and it runs again on what is left (if it still fits).
2282
+ const owed = deferred.filter((t) => !heldBorders.has(t.id) && !conceded.has(t.id));
2283
+ if ((c.kind === 'advance' || c.kind === 'break' || c.kind === 'counter') && !c.focus && owed.length) {
2284
+ const restore = snapshot();
2285
+ const spent = expansionSpent;
2286
+ const left = expansionLeft;
2287
+ run(c);
2288
+ // Every owed hold must fit what is left together, not each on its own: two holds of 4
2289
+ // with 5 left both pass alone, and the second would be conceded later.
2290
+ if (owed.every((t) => t.holdCost <= roomAt(t.id)) && owed.reduce((n, t) => n + t.holdCost, 0) <= ps.budget)
2291
+ return garrisonCompleted();
2292
+ restore();
2293
+ expansionSpent = spent;
2294
+ expansionLeft = left;
2295
+ for (const t of owed)
2296
+ if (t.holdCost <= roomAt(t.id)) {
2297
+ rationale.push(`Hold ${label(t.id)} now after all: the capture that would have gone first completes no bonus and would leave too little to hold it later.`);
2298
+ hold(t);
2299
+ heldBorders.add(t.id);
2300
+ }
2301
+ }
2302
+ run(c);
2303
+ garrisonCompleted();
2304
+ });
2305
+ unitsDue = true;
2306
+ for (const u of waiting.splice(0))
2307
+ fundOrConcede(u);
2308
+ runPostponed();
2309
+ garrisonCompleted();
2310
+ for (const t of deferred) {
2311
+ if (heldBorders.has(t.id))
2312
+ continue;
2313
+ const room = roomAt(t.id);
2314
+ if (t.holdCost > room)
2315
+ concedePending(t, room);
2316
+ else
2317
+ hold(t);
2318
+ }
2319
+ // #215 review: a parked concession is unlocked now unless this turn's captures complete a bonus
2320
+ // it is in (rule 1c keeps that one, locked, and the leftover garrisons it).
2321
+ for (const x of [...parked].sort(byNum)) {
2322
+ if (heldBorders.has(x) || !conceded.has(x))
2323
+ continue;
2324
+ const holdings = new Set([...mine, ...captured]);
2325
+ const completes = g.map.bonuses.some((b) => {
2326
+ const ts = bonusTs.get(b.id);
2327
+ return b.value > 0 && ts.includes(x) && ts.every((y) => holdings.has(y)) && !ts.every((y) => mineSet.has(y));
2328
+ });
2329
+ if (!completes)
2330
+ unlockPending(x);
2331
+ }
2332
+ // #215: a break or counter tried while a pending hold still locked its source runs again, in
2333
+ // its order, once the greedy step has conceded and unlocked that hold: the border's armies
2334
+ // attack out before rule 1b withdraws them (one already taken returns at once).
2335
+ if (unlocked.size)
2336
+ for (const c of candidates)
2337
+ if (c.target !== undefined && !captured.has(c.target) && targets.get(c.target)?.sources.some((x) => unlocked.has(x)))
2338
+ c.run();
2339
+ settleContested();
2340
+ // #272: a conceded border attacks out for a free step into a bonus before it withdraws (and
2341
+ // before rule 1c re-values the borders, so one whose bonus this completes is kept).
2342
+ attackOutOfConceded(pc, ps, book, hd, tgt, caps);
2343
+ reconsider();
2344
+ withdraw();
2345
+ }
2346
+ else {
2347
+ // #275 (b): as under `balanced`, the gate facing an untrusted opponent before any capture.
2348
+ settleContested('untrusted');
2349
+ for (const p of byCloseness) {
2350
+ complete(p);
2351
+ garrisonCompleted();
2352
+ }
2353
+ for (const p of byCloseness) {
2354
+ advance(p);
2355
+ garrisonCompleted();
2356
+ }
2357
+ settleContested();
2358
+ // #272: a conceded border attacks out for a free step into a bonus before it withdraws (and
2359
+ // before rule 1c re-values the borders, so one whose bonus this completes is kept).
2360
+ if (acting)
2361
+ attackOutOfConceded(pc, ps, book, hd, tgt, caps);
2362
+ reconsider();
2363
+ if (acting)
2364
+ withdraw();
2365
+ }
2366
+ // #203: a lead step the bonus passes did not take is an ordinary enemy territory again: out of
2367
+ // the targets (rule 4e's fallback, the card-piece pass and the lead strikes size it their own
2368
+ // way), its sure cost and sizing gone with it.
2369
+ for (const t of [...leadSteps.keys()])
2370
+ if (!captured.has(t)) {
2371
+ targets.delete(t);
2372
+ leadSteps.delete(t);
2373
+ }
2374
+ // ---- pass 3: other expansion ----
2375
+ if (goal !== 'complete-bonus') {
2376
+ // #281 (the owner's extension): empty enemy territories, with the guard off, are cheap expansion.
2377
+ const empties = addEmptyEnemyTargets(pc, ps, tgt);
2378
+ const eligible = [...targets.values()]
2379
+ // #125: a member of an uneconomic bonus is still a territory worth its per-territory income.
2380
+ .filter((t) => !captured.has(t.id) && plainEligible(pc, tgt, t.id, t.enemy));
2381
+ const plainScore = plainOrderCosts(pc, tgt, eligible.map((t) => t.id));
2382
+ const rest = eligible.sort((a, b) => plainScore.get(a.id) - plainScore.get(b.id) || a.cost - b.cost || a.id - b.id);
2383
+ // Rule 4c: plain expansion never lowers income (a capture completing a negative bonus).
2384
+ for (const t of rest) {
2385
+ const gain = gainWith([t.id]);
2386
+ if (gain < 0 && !inFocus(t.id))
2387
+ continue;
2388
+ if (tgt.emptyEnemies.has(t.id)) {
2389
+ // #281: never one lowering income, focused or not; sized for its owner's deploy (#120).
2390
+ if (gain >= 0)
2391
+ tryEmptyEnemy(pc, ps, book, tgt, caps, t.id);
2392
+ continue;
2393
+ }
2394
+ // #125: its own economy test. A member of an economic bonus is judged by that bonus; any
2395
+ // other capture pays for the armies it loses with the income it adds within PAYBACK_TURNS,
2396
+ // and one that adds none may lose at most PLAIN_EXPANSION_LOSS.
2397
+ {
2398
+ const refused = plainEconomy(pc, tgt, t.id, gain);
2399
+ if (refused) {
2400
+ const { lost, worth } = refused;
2401
+ const reach = Math.max(...neighborsOf(g, t.id).filter((x) => avail.has(x)).map((x) => (avail.get(x) ?? 0) + roomAt(x)));
2402
+ if (reach >= t.cost)
2403
+ rationale.push(worth > 0
2404
+ ? `Do not expand into ${label(t.id)}: it adds +${worth} a turn and loses ~${lost} armies, more than ${paybackTurns} turns of it pay back.`
2405
+ : `Do not expand into ${label(t.id)}: it adds no income and loses ~${lost} armies (more than ${PLAIN_EXPANSION_LOSS}), in no bonus worth completing.`);
2406
+ continue;
2407
+ }
2408
+ }
2409
+ // #281 × #282: a denial is never sourced from the territory my commander walks from (its transit hold).
2410
+ if (tgt.denials.has(t.id))
2411
+ withoutTransit(pc, tgt, t.id, () => tryExpand(t.id, 'expands territory'));
2412
+ else
2413
+ tryExpand(t.id, 'expands territory');
2414
+ }
2415
+ dropEmptyEnemyTargets(ps, tgt, empties);
2416
+ }
2417
+ // ---- 4e. never stand still (#104, #107), the contact fallback (plan/stand-still.ts) ----
2418
+ const { saveStep, standStill } = neverStandStill(pc, ps, book, threats, hd, tgt, caps);
2419
+ // ---- 4g. a capture worth a card piece (#127) ----
2420
+ // Any capture this turn earns the turn's card pieces. With none planned (every goal but
2421
+ // `complete-bonus`; not while the 1v1 strike stack, rule 0p.3c, is contact's answer), the capture
2422
+ // losing the fewest armies (the defenders' kills on its attackers) is taken when that loss is no
2423
+ // more than the pieces are worth (`cardPieceValue`) — neutrals before players' territories, then
2424
+ // the cheapest, then id — with the usual sizing, every source keeping what holds it, never one
2425
+ // lowering income.
2426
+ const pieceValue = opts.cardPieceValue ?? 0;
2427
+ if (pieceValue > 0 && goal !== 'complete-bonus' && captured.size === 0 && !(auto && profile.format === '1v1' && goal !== 'defend' && facing.size > 0)) {
2428
+ const loss = (t) => straightKills(defendersAt(t), rates.defensiveKillRate);
2429
+ const candidates = [...targets.values()]
2430
+ .filter((tg) => !captured.has(tg.id) && !spared.has(tg.id) && loss(tg.id) <= pieceValue && gainWith([tg.id]) >= 0)
2431
+ .sort((a, b) => loss(a.id) - loss(b.id) || Number(a.enemy) - Number(b.enemy) || a.cost - b.cost || a.id - b.id);
2432
+ for (const tg of candidates) {
2433
+ const reason = `a capture earns this turn's card pieces, worth ~${pieceValue} armies, and this one loses ~${loss(tg.id)} (#127)`;
2434
+ if (tryCapture(tg.id, reason))
2435
+ break;
2436
+ }
2437
+ }
2438
+ // ---- 4h. the army cap prices idle armies (#253, plan/cap-spend.ts) ----
2439
+ spendUnderCap(pc, ps, book, threats, hd, tgt, caps);
2440
+ // ---- rule 4c's guard: planned captures never lower next income (#70) ----
2441
+ // Known limit: dropping a capture rewinds its attacks, `avail`, `captured`, `survivorsAt` and
2442
+ // its own move/rationale/warning lines, but decisions made while it was assumed are not
2443
+ // re-checked: an earlier R3 `defensible()` may have counted its survivors, `anchor` may still
2444
+ // name its source, and a "Keep X (not conceded): this turn's captures complete ..." line may
2445
+ // cite a completion that no longer happens. Only maps with overlapping negative bonuses reach
2446
+ // this path (elsewhere no capture lowers income).
2447
+ {
2448
+ const order = captureOrder.filter((t, i) => captured.has(t) && captureOrder.lastIndexOf(t) === i);
2449
+ /** The negative bonuses `t` helps complete in the plan as it stands, as "name value". */
2450
+ const negativesOf = (t) => completedBy(heldNow())
2451
+ .filter((id) => g.bonusById.get(id).value < 0 && bonusTs.get(id).includes(t))
2452
+ .map((id) => `${bonusName(id)} ${g.bonusById.get(id).value}`);
2453
+ let gain = incomeGain(heldNow());
2454
+ for (const t of [...order].reverse()) {
2455
+ if (gain >= 0)
2456
+ break;
2457
+ const after = incomeGain(new Set([...mine, ...captured].filter((x) => x !== t)));
2458
+ if (after <= gain)
2459
+ continue;
2460
+ // Kept: a focused bonus, a staging step (rule c), a commander strike, finishing off.
2461
+ if (inFocus(t) || staged.has(t) || strikes.has(t) || worstCase.has(t))
2462
+ continue;
2463
+ const negatives = negativesOf(t);
2464
+ captureUndo.get(t)();
2465
+ captured.delete(t);
2466
+ survivorsAt.delete(t);
2467
+ combined.delete(t);
2468
+ for (let i = moves.length - 1; i >= 0; i--)
2469
+ if (moves[i].kind === 'attack' && moves[i].to === t)
2470
+ moves.splice(i, 1);
2471
+ const attack = `Attack ${label(t)} `;
2472
+ for (let i = rationale.length - 1; i >= 0; i--)
2473
+ if (rationale[i].startsWith(attack))
2474
+ rationale.splice(i, 1);
2475
+ for (let i = warnings.length - 1; i >= 0; i--)
2476
+ if (warnings[i].startsWith(`Attack on enemy ${label(t)} `) ||
2477
+ warnings[i].startsWith(`${label(t)} can be retaken `) ||
2478
+ warnings[i].startsWith(`The capture of ${label(t)} combines `))
2479
+ warnings.splice(i, 1);
2480
+ rationale.push(`Drop the attack on ${label(t)}: it completes ${negatives.join(', ')}, and next income would fall below the ${nextIncomeWith(0)} it is without these captures (next income ${nextIncomeWith(gain)} → ${nextIncomeWith(after)} without it); its armies stay where they are.`);
2481
+ gain = after;
2482
+ }
2483
+ if (gain < 0) {
2484
+ const kept = order.flatMap((t) => {
2485
+ const negs = captured.has(t) ? negativesOf(t) : [];
2486
+ if (!negs.length)
2487
+ return [];
2488
+ // Dropping it would not raise income: it also completes a positive bonus (rule 4c(a)).
2489
+ const positives = completedBy(heldNow()).filter((id) => g.bonusById.get(id).value > 0 && bonusTs.get(id).includes(t));
2490
+ const why = inFocus(t)
2491
+ ? 'focused'
2492
+ : staged.has(t)
2493
+ ? `stages bonus ${bonusName(staged.get(t))}`
2494
+ : strikes.has(t)
2495
+ ? 'a commander strike'
2496
+ : worstCase.has(t)
2497
+ ? 'finishing off a player'
2498
+ : positives.length
2499
+ ? `completes bonus ${positives.map(bonusName).join(', ')}`
2500
+ : 'dropping it would not raise income';
2501
+ return [`${label(t)} (${negs.join(', ')}; ${why})`];
2502
+ });
2503
+ warnings.push(`This plan lowers next income from ${nextIncomeWith(0)} to ${nextIncomeWith(gain)}: its captures complete negative bonuses — ${kept.join('; ')}.`);
2504
+ }
2505
+ }
2506
+ // Rule 1c again (#122): a capture made after the first reconsideration (pass 3, rule 4e's
2507
+ // fallback) may complete a bonus too, and its conceded borders are kept the same way.
2508
+ reconsider();
2509
+ /** Territories locked before the leftover deploy: holds, kept and standing borders, withdrawals. */
2510
+ const holdLocked = new Set(locked);
2511
+ /** A territory the plan has not given up (or gave up but whose garrison may still hold it). */
2512
+ const open = (id) => !conceded.has(id) || mayHold.has(id);
2513
+ /** Armies that stay on a border after its deploys, outgoing moves and incoming withdrawals. */
2514
+ const stays = (id) => avail.get(id) + guardAt(id) + (incoming.get(id) ?? 0);
2515
+ // ---- #265: a combined capture leaves armies on a weak member of a bonus it completes (plan/captures.ts) ----
2516
+ caps.rebalanceCombined(completedMembers(pc, ps, threats, open, stays).weakMember, stays);
2517
+ // ---- concentrate (#72, rule 0p.3c): the 1v1 strike stack's border (plan/strike.ts) ----
2518
+ const { stack, smallExpansion } = chooseStrikeStack(pc, ps, book, threats, open, stays);
2519
+ // ---- 5. the leftover deploy (plan/leftover.ts) ----
2520
+ // ---- #276: guard off — the second line's shortfall, before the leftover (plan/guard-off.ts) ----
2521
+ fillSecondLine(pc, ps, book);
2522
+ /** The deploys before the leftover: rule 5b's sources are the territories it reached. */
2523
+ const beforeLeftover = new Map(ps.deployed);
2524
+ const leftover = leftoverDeploy(pc, ps, book, threats, hd, tgt, saveStep, stack, open, stays);
2525
+ let { strikeStack } = leftover;
2526
+ const { poolDeployed, staging } = leftover;
2527
+ // #235: the Standing-still warning names the source the leftover actually stages on.
2528
+ // Found by its text: earlier warnings may have been spliced out since (a revival, a dropped capture).
2529
+ if (staging && standStill && staging.t === standStill.t && staging.from !== standStill.named) {
2530
+ const at = ps.warnings.indexOf(standStill.text);
2531
+ if (at >= 0)
2532
+ ps.warnings[at] = standStill.restate(staging.from);
2533
+ }
2534
+ // The stack exists whether or not a leftover reached it (#102): holds and captures may take the
2535
+ // whole income, and an 80-stack must not stand idle for want of one spare army.
2536
+ if (stack && !strikeStack)
2537
+ strikeStack = { ...stack, deployed: 0 };
2538
+ // ---- spend the strike stack (#102) (plan/strike.ts) ----
2539
+ spendStrikeStack(pc, ps, input, book, threats, tgt, caps, strikeStack, poolDeployed, holdLocked, smallExpansion);
2540
+ // A kept border the leftover could not make safe: the completed bonus can fall with it.
2541
+ for (const t of [...kept].sort(byNum)) {
2542
+ const b = borders.get(t);
2543
+ const stays = avail.get(t) + guardAt(t) + (incoming.get(t) ?? 0);
2544
+ const take = toTake(stays + unitsAt(t));
2545
+ if (take !== null && take <= b.threat)
2546
+ warnings.push(`${label(t)} is kept for the bonus this turn completes, but its ${stays} armies need only ${take} to take against the ~${b.threat} threat: the bonus can fall next turn.`);
2547
+ }
2548
+ // ---- No-Split: every order carries the whole stack (#124) ----
2549
+ // An order already sends everything on its source when it is planned; a deploy that reached the
2550
+ // source afterwards (the leftover, a Local Deployment pool) leaves with it too.
2551
+ if (noSplit)
2552
+ for (const m of moves) {
2553
+ const extra = avail.get(m.from);
2554
+ if (extra <= 0)
2555
+ continue;
2556
+ const was = m.armies;
2557
+ avail.set(m.from, 0);
2558
+ m.armies += extra;
2559
+ const at = moves.filter((o) => o.kind === 'attack' && o.to === m.to);
2560
+ if (m.kind === 'transfer')
2561
+ incoming.set(m.to, (incoming.get(m.to) ?? 0) + extra);
2562
+ else if (at[at.length - 1] === m) {
2563
+ // The attack that moves in: more survivors, against what the attacks before it leave.
2564
+ const before = at.slice(0, -1).reduce((n, o) => n + straightKills(o.armies, rates.offensiveKillRate), 0);
2565
+ if (survivorsAt.has(m.to))
2566
+ survivorsAt.set(m.to, survivorsAt.get(m.to) + extra);
2567
+ m.winChance = chanceOf(m.armies, Math.max(0, defenceAt(m.to) - before));
2568
+ }
2569
+ else {
2570
+ // A softener: its survivors come home.
2571
+ incoming.set(m.from, (incoming.get(m.from) ?? 0) + extra);
2572
+ const before = at.slice(0, at.indexOf(m)).reduce((n, o) => n + straightKills(o.armies, rates.offensiveKillRate), 0);
2573
+ if (straightKills(m.armies, rates.offensiveKillRate) >= defenceAt(m.to) - before)
2574
+ warnings.push(`No-Split: ${label(m.from)}'s deploys leave with its softening attack on ${label(m.to)}, which may then take it alone; the attacks after it would then move in as transfers.`);
2575
+ }
2576
+ // Its rationale line names the new size.
2577
+ const heads = (n) => [
2578
+ `Attack ${label(m.to)} from ${label(m.from)} with ${n}`,
2579
+ `Attack ${label(m.to)} from the strike stack ${label(m.from)} with ${n}`,
2580
+ `Withdraw ${n} from ${label(m.from)} to ${label(m.to)}`,
2581
+ ];
2582
+ const old = heads(was);
2583
+ const r = rationale.findIndex((l) => old.some((h) => l.startsWith(h) && /^[:,( ]/.test(l.slice(h.length))));
2584
+ if (r >= 0) {
2585
+ const i = old.findIndex((h) => rationale[r].startsWith(h) && /^[:,( ]/.test(rationale[r].slice(h.length)));
2586
+ rationale[r] = `${heads(m.armies)[i]}${rationale[r].slice(old[i].length)}`;
2587
+ }
2588
+ rationale.push(`No-Split: the ${extra} deployed on ${label(m.from)} after its order was planned leave with it (${m.kind === 'attack' ? 'attacking' : 'moving to'} ${label(m.to)} with ${m.armies}, the whole stack).`);
2589
+ }
2590
+ // ---- #167: lead strikes (plan/strike.ts) ----
2591
+ const { leadSpareFor } = leadStrikes(pc, ps, book, threats, hd, tgt, caps, holdLocked, strikeStack);
2592
+ // ---- 5b. a neutral the leftover pays for (#218) (plan/after-leftover.ts) ----
2593
+ // The strike stack concentrates for its strike, and a step's source saves toward it: neither spends.
2594
+ const keepWhole = new Set([...(strikeStack ? [strikeStack.id] : []), ...(staging ? [staging.from] : [])]);
2595
+ afterLeftoverCaptures(pc, ps, book, threats, hd, tgt, caps, beforeLeftover, keepWhole, poolDeployed);
2596
+ // ---- efficient sizes (S2) ----
2597
+ // An attack below its next kill breakpoint is topped up to it from armies that would sit
2598
+ // idle on its source — never from a hold, a conceded border, my commander's territory, or
2599
+ // a source still facing an enemy after this turn's captures — when the extra kill can matter:
2600
+ // the target is a player's (its owner may reinforce it) or the attack is not certain.
2601
+ // Otherwise an attack between breakpoints is named as wasting armies.
2602
+ const rounding = s.roundingMode ?? 'StraightRound';
2603
+ const killsBy = (n) => guaranteedKills(n, rates.offensiveKillRate, luck, rounding);
2604
+ /**
2605
+ * Armies on `src` that would sit idle: none on a hold, a conceded border, my commander's
2606
+ * territory, or a border still facing an enemy once this turn's captures land (what stays
2607
+ * there defends it).
2608
+ */
2609
+ const idleAt = (src) => {
2610
+ if (!mineSet.has(src) || holdLocked.has(src) || conceded.has(src) || myCommanders.has(src))
2611
+ return 0;
2612
+ if (borderAt(src, (x) => captured.has(x)))
2613
+ return 0;
2614
+ // #172: nor what a stack two steps away needs it to keep.
2615
+ const far = twoStepKeep(src);
2616
+ if (far > 0)
2617
+ twoStepBound.add(src);
2618
+ // #179: nor what covers a finished-off player's exit.
2619
+ return Math.max(0, avail.get(src) - Math.max(far, coverOf(src)));
2620
+ };
2621
+ /**
2622
+ * #120: armies on `src` beyond what holds it once this turn's captures land — none on a hold, a
2623
+ * conceded border or the strike stack; on my commander's territory, or a border that cannot hold
2624
+ * on what it has, none either (keepFor keeps everything there).
2625
+ */
2626
+ const spareBeyondHold = (src) => {
2627
+ if (!mineSet.has(src) || holdLocked.has(src) || conceded.has(src))
2628
+ return 0;
2629
+ // #172: the larger of its one-step hold and what a stack two steps away needs it to keep.
2630
+ const near = keepFor(src, () => false);
2631
+ const far = twoStepKeep(src);
2632
+ if (far > near)
2633
+ twoStepBound.add(src);
2634
+ return Math.max(0, avail.get(src) - Math.max(near, far));
2635
+ };
2636
+ /** The plain "assumes its owner does not reinforce" warning on an attack on `t`. */
2637
+ const assumes = (t) => `Attack on enemy ${label(t)} assumes its owner does not reinforce it first.`;
2638
+ // No-Split (#124): every attack already sends its whole stack; there is nothing to top up or trim.
2639
+ for (const m of noSplit ? [] : moves) {
2640
+ if (m.kind !== 'attack' || combined.has(m.to))
2641
+ continue;
2642
+ // Sized for a worst case already (finishing a player off, fog pressure, a commander strike).
2643
+ const worst = worstCase.has(m.to) || strikes.has(m.to);
2644
+ const d = defenceAt(m.to);
2645
+ const chance = m.winChance ?? chanceOf(m.armies, d);
2646
+ const enemyTarget = state.get(m.to)?.owner.kind === 'player';
2647
+ // #120: an attack on a player's territory is sized for its defenders plus what its owner may
2648
+ // deploy there first, when armies beyond what holds the source cover it.
2649
+ const extra = enemyTarget && !worst ? reinforcementAt(m.to) : 0;
2650
+ const full = extra > 0 ? costAt(m.to, d + extra) : null;
2651
+ if (full !== null && full > m.armies && full - m.armies <= spareBeyondHold(m.from)) {
2652
+ const before = m.armies;
2653
+ const add = full - before;
2654
+ avail.set(m.from, avail.get(m.from) - add);
2655
+ m.armies = full;
2656
+ m.winChance = chanceOf(full, d);
2657
+ worstCase.set(m.to, d + extra);
2658
+ if (survivorsAt.has(m.to))
2659
+ survivorsAt.set(m.to, survivorsAt.get(m.to) + add);
2660
+ const check = retakeChecks.get(m.to);
2661
+ const at = check?.warning === undefined ? -1 : warnings.indexOf(check.warning);
2662
+ if (check && at >= 0) {
2663
+ check.survivors += add;
2664
+ check.warning = retakeWarning(m.to, check.bonusId, check.survivors, check.counter);
2665
+ if (check.warning)
2666
+ warnings[at] = check.warning;
2667
+ else
2668
+ warnings.splice(at, 1);
2669
+ }
2670
+ const w = warnings.indexOf(assumes(m.to));
2671
+ if (w >= 0)
2672
+ warnings.splice(w, 1);
2673
+ const owner = state.get(m.to).owner.playerId;
2674
+ rationale.push(`Size the attack on ${label(m.to)} from ${label(m.from)} up from ${before} to ${full} with ${add} idle armies there: ${full} take it even if player ${owner} deploys its ~${extra} there first (${d} + ${extra} defenders), and ${label(m.from)} still holds.`);
2675
+ continue;
2676
+ }
2677
+ const next = nextBreakpoint(m.armies, rates.offensiveKillRate, luck, rounding);
2678
+ const add = next === null ? 0 : next - m.armies;
2679
+ if (next !== null && add > 0 && !worst && (enemyTarget || chance < 1) && add <= idleAt(m.from)) {
2680
+ const before = m.armies;
2681
+ avail.set(m.from, avail.get(m.from) - add);
2682
+ m.armies = next;
2683
+ m.winChance = chanceOf(next, d);
2684
+ if (survivorsAt.has(m.to))
2685
+ survivorsAt.set(m.to, survivorsAt.get(m.to) + add);
2686
+ // A break's retake warning was judged on the survivors before the top-up: re-judge it.
2687
+ const check = retakeChecks.get(m.to);
2688
+ const at = check?.warning === undefined ? -1 : warnings.indexOf(check.warning);
2689
+ if (check && at >= 0) {
2690
+ check.survivors += add;
2691
+ check.warning = retakeWarning(m.to, check.bonusId, check.survivors, check.counter);
2692
+ if (check.warning)
2693
+ warnings[at] = check.warning;
2694
+ else
2695
+ warnings.splice(at, 1);
2696
+ }
2697
+ const why = enemyTarget ? 'its owner may reinforce it' : `the win chance rises from ${pct(chance)} to ${pct(m.winChance)}`;
2698
+ rationale.push(`Top up the attack on ${label(m.to)} from ${label(m.from)} from ${before} to ${next} with ${add} idle armies there: ${next} is the next efficient size, killing ${killsBy(next)} for sure instead of ${killsBy(before)} (${why}).`);
2699
+ continue;
2700
+ }
2701
+ const kills = killsBy(m.armies);
2702
+ if (kills <= 0 || killsBy(m.armies - 1) < kills)
2703
+ continue;
2704
+ let b = m.armies - 1;
2705
+ while (b > 1 && killsBy(b - 1) === kills)
2706
+ b--;
2707
+ if (chanceOf(b, d) < chance)
2708
+ continue;
2709
+ rationale.push(`The attack on ${label(m.to)} from ${label(m.from)} sends ${m.armies}, but ${b} already kill ${kills} for sure: the other ${m.armies - b} add no kill (only survivors)${next !== null ? `; the next kill needs ${next}` : ''}.`);
2710
+ }
2711
+ // ---- 6. transfers, #125 staging (plan/transfers.ts) ----
2712
+ transfers(pc, ps, book, threats, hd, caps, staging);
2713
+ // ---- B2 (T5): a truce's border cap (plan/relations.ts) ----
2714
+ applyBorderCaps(pc, ps, book, hd, ps.truce, threats);
2715
+ // ---- #226: a margin on attacks on a player from armies that would sit idle ----
2716
+ // An attack on a player's territory is sized to the kill count its defenders plus an ESTIMATED
2717
+ // deploy need (#120), and the estimate is a floor. Once the transfers have moved what they move,
2718
+ // the armies still on its source beyond what holds it (`spareBeyondHold`: none on a hold, a
2719
+ // conceded border or the strike stack; none either where rule 5's leftover went for a comfortable
2720
+ // margin, a hold or saving toward a step) would sit idle: they join the attack (the target with the
2721
+ // most defenders first, then id; No-Split already sends the whole stack).
2722
+ if (!noSplit) {
2723
+ const onPlayers = moves
2724
+ .filter((m) => m.kind === 'attack' && !combined.has(m.to) && state.get(m.to)?.owner.kind === 'player' && reinforcementAt(m.to) > 0)
2725
+ .sort((a, b) => defenceAt(b.to) - defenceAt(a.to) || a.to - b.to);
2726
+ for (const m of onPlayers) {
2727
+ // #226 review: rule 5 deployed the leftover there to defend it (a comfortable margin, a hold)
2728
+ // or to save toward a step: those armies are not idle, and the margin leaves the source alone.
2729
+ if (ps.leftoverKept.has(m.from))
2730
+ continue;
2731
+ // #128, as the transfers keep it: a source beside an attack on a player that may fail keeps
2732
+ // what holds it against the threat there as if those attacks failed.
2733
+ const pending = neighborsOf(g, m.from).filter((x) => captured.has(x) && state.get(x)?.owner.kind === 'player');
2734
+ const ifFail = pending.length ? borderAt(m.from, () => false) : null;
2735
+ // #226 review: each such target's owner may move its stacks beside the target into it before
2736
+ // my attack runs (its stacks beside the source are in the threat already), so the attack
2737
+ // fails and the target then holds them too: the keep counts their movable armies (and units).
2738
+ const fromSide = new Set([m.from, ...neighborsOf(g, m.from)]);
2739
+ let reinforce = 0;
2740
+ const counted = new Set();
2741
+ const movedIn = [];
2742
+ for (const x of pending) {
2743
+ const owner = state.get(x).owner.playerId;
2744
+ let into = 0;
2745
+ for (const n of neighborsOf(g, x)) {
2746
+ const st = state.get(n);
2747
+ if (fromSide.has(n) || counted.has(n) || st?.owner.kind !== 'player' || st.owner.playerId !== owner || st.armies === null)
2748
+ continue;
2749
+ counted.add(n);
2750
+ into += Math.max(0, st.armies - guard) + unitsAt(n);
2751
+ }
2752
+ reinforce += into;
2753
+ if (into > 0)
2754
+ movedIn.push(`player ${owner} first moves the ${into} armies beside ${label(x)} into it`);
2755
+ }
2756
+ const keep128 = ifFail ? Math.max(0, threats.holdArmies(ifFail.threat + reinforce) - unitsAt(m.from)) : 0;
2757
+ const add = Math.min(spareBeyondHold(m.from), Math.max(0, hd.stayAt(m.from) - keep128));
2758
+ if (add <= 0)
2759
+ continue;
2760
+ const d = defenceAt(m.to);
2761
+ const before = m.armies;
2762
+ avail.set(m.from, avail.get(m.from) - add);
2763
+ m.armies += add;
2764
+ m.winChance = chanceOf(m.armies, d);
2765
+ if (survivorsAt.has(m.to))
2766
+ survivorsAt.set(m.to, survivorsAt.get(m.to) + add);
2767
+ const check = retakeChecks.get(m.to);
2768
+ const at = check?.warning === undefined ? -1 : warnings.indexOf(check.warning);
2769
+ if (check && at >= 0) {
2770
+ check.survivors += add;
2771
+ check.warning = retakeWarning(m.to, check.bonusId, check.survivors, check.counter);
2772
+ if (check.warning)
2773
+ warnings[at] = check.warning;
2774
+ else
2775
+ warnings.splice(at, 1);
2776
+ }
2777
+ // The most its owner could deploy there first and still lose it to this attack.
2778
+ const fits = (x) => {
2779
+ const c = costAt(m.to, d + x);
2780
+ return c !== null && c <= m.armies;
2781
+ };
2782
+ let lo = 0;
2783
+ let hi = m.armies;
2784
+ if (!fits(0))
2785
+ hi = -1;
2786
+ while (lo < hi) {
2787
+ const mid = Math.ceil((lo + hi) / 2);
2788
+ if (fits(mid))
2789
+ lo = mid;
2790
+ else
2791
+ hi = mid - 1;
2792
+ }
2793
+ const covered = Math.max(0, hi);
2794
+ const extra = reinforcementAt(m.to);
2795
+ if (hi >= extra) {
2796
+ worstCase.set(m.to, Math.max(worstCase.get(m.to) ?? 0, d + covered));
2797
+ const w = warnings.indexOf(assumes(m.to));
2798
+ if (w >= 0)
2799
+ warnings.splice(w, 1);
2800
+ }
2801
+ const owner = state.get(m.to).owner.playerId;
2802
+ rationale.push(`Margin on the attack on ${label(m.to)} from ${label(m.from)} (#226): up from ${before} to ${m.armies} with the ${add} armies that would otherwise sit idle there (no hold needs them, even if the attack fails${movedIn.length ? `, or ${movedIn.join(' and ')}` : ''})${hi >= 0
2803
+ ? `: ${m.armies} take it even if player ${owner} deploys up to ${covered} there first, against the ~${extra} estimate, which is a floor`
2804
+ : ''}.`);
2805
+ }
2806
+ }
2807
+ // ---- #240 review: a repulsed territory taken pending its sure size ----
2808
+ // Taken at its plain size because the sure size could not be funded when it was captured
2809
+ // (`ps.repulsedPending`): #120, the No-Split leftover and the #226 margin have now added what they
2810
+ // add. At its sure size it is sized for its owner's deploy (no "assumes" warning); still short, the
2811
+ // attack is dropped — a territory my attacks failed on is attacked only at the size that lands —
2812
+ // and its armies stay where they are.
2813
+ for (const t of [...ps.repulsedPending].sort(byNum)) {
2814
+ const rep = tgt.repulsed.get(t);
2815
+ if (!captured.has(t) || combined.has(t))
2816
+ continue;
2817
+ const at = moves.filter((m) => m.kind === 'attack' && m.to === t);
2818
+ const sent = at.reduce((n, m) => n + m.armies, 0);
2819
+ if (sent >= rep.cost) {
2820
+ // #272 review: sized below its owner's deploy estimate, it stays an attack that assumes no more.
2821
+ if (!rep.sure)
2822
+ continue;
2823
+ worstCase.set(t, Math.max(worstCase.get(t) ?? 0, rep.defenders + rep.extra));
2824
+ const w = warnings.indexOf(assumes(t));
2825
+ if (w >= 0)
2826
+ warnings.splice(w, 1);
2827
+ continue;
2828
+ }
2829
+ // Every army the attack carries goes home, those #120 or the margin added included.
2830
+ for (const m of at)
2831
+ avail.set(m.from, avail.get(m.from) + m.armies);
2832
+ captured.delete(t);
2833
+ survivorsAt.delete(t);
2834
+ for (let i = moves.length - 1; i >= 0; i--)
2835
+ if (moves[i].kind === 'attack' && moves[i].to === t)
2836
+ moves.splice(i, 1);
2837
+ const heads = [`Attack ${label(t)} `, `Size the attack on ${label(t)} `, `Top up the attack on ${label(t)} `, `Margin on the attack on ${label(t)} `];
2838
+ for (let i = rationale.length - 1; i >= 0; i--)
2839
+ if (heads.some((h) => rationale[i].startsWith(h)))
2840
+ rationale.splice(i, 1);
2841
+ for (let i = warnings.length - 1; i >= 0; i--)
2842
+ if (warnings[i].startsWith(`Attack on enemy ${label(t)} `) || warnings[i].startsWith(`${label(t)} can be retaken `))
2843
+ warnings.splice(i, 1);
2844
+ rationale.push(`Drop the attack on ${label(t)}: it could send only ${sent} by the end of the turn, short of the ${rep.cost} that take it ${rep.sure ? `even if player ${rep.player} deploys its ~${rep.extra} there first` : `against the ~${rep.extra} player ${rep.player} put there on those turns`}, and my attacks on it failed before, its owner reinforcing it (#240); its armies stay where they are.`);
2845
+ }
2846
+ // #120: an attack on a player's territory still sized below its owner's deploy says what it
2847
+ // faces if that deploy lands there first.
2848
+ for (const m of moves) {
2849
+ if (m.kind !== 'attack' || combined.has(m.to) || worstCase.has(m.to) || strikes.has(m.to))
2850
+ continue;
2851
+ const w = warnings.indexOf(assumes(m.to));
2852
+ const extra = reinforcementAt(m.to);
2853
+ if (w < 0 || extra <= 0)
2854
+ continue;
2855
+ const st = state.get(m.to);
2856
+ if (st.owner.kind !== 'player')
2857
+ continue;
2858
+ const d = defenceAt(m.to);
2859
+ const full = costAt(m.to, d + extra);
2860
+ const aim = chanceAt(m.to);
2861
+ warnings[w] = `Attack on enemy ${label(m.to)} assumes its owner does not reinforce it first: if player ${st.owner.playerId} deploys its ~${extra} there, ${m.armies} attack ${d + extra} (win chance ${pct(chanceOf(m.armies, d + extra))})${full !== null ? `; ${full} would ${aim >= 1 ? 'be sure' : `reach ${pct(aim)}`}` : ''}.`;
2862
+ }
2863
+ // ---- Order Priority for a strike (rule 1s) (plan/move-order.ts) ----
2864
+ const { strikeCard, strikeWho } = strikeOrderPriority(pc, ps, threats, hd, struck);
2865
+ // #274: my commander's step toward safety, once every other order is planned (plan/commander.ts).
2866
+ placeCommanderMove(pc, ps);
2867
+ // ---- expected, frontier, two-step holds, gambled and shared borders (plan/report.ts) ----
2868
+ const expected = reportExpected(pc, ps, book, threats, hd, tgt, caps);
2869
+ // ---- offence report (#72), the warnings after the deploys, "Not attacking" (#167) (plan/report.ts) ----
2870
+ const { sentAt } = reportOffence(pc, ps, book, threats, hd, tgt, holdLocked, leadSpareFor);
2871
+ // ---- 7. schedule the moves (#127), the exits (#179), Order Priority (plan/move-order.ts) ----
2872
+ const { slotOf, facesEnemy, exits } = scheduleOrders(pc, ps, threats, hd, caps, struck, strikeCard, strikeWho);
2873
+ // ---- B2: what the truces did (plan/relations.ts) ----
2874
+ const truceReport = reportTruce(pc, ps, ps.truce, (r) => armiesFreed(pc, ps, threats, r, { conceded, valueOf: book.valueOf }));
2875
+ // ---- the plan: offence list, #172's final check, #201 retaliation, #167 exchanges, #179 ETAs (plan/report.ts) ----
2876
+ const plan = finishPlan(pc, ps, pass, threats, hd, tgt, expected, sentAt, slotOf, facesEnemy, exits);
2877
+ // #218: the main front's forecast at my whole income, for the game outlook to share.
2878
+ if (ps.front)
2879
+ plan.front = ps.front;
2880
+ // PLAN-TEAMS C3.3: the bonuses I share with a teammate (plan/team.ts).
2881
+ const team = teamReport(pc, { ps, threats, hd, deploys: plan.deploys });
2882
+ if (team)
2883
+ plan.team = team;
2884
+ if (truceReport) {
2885
+ // T6: what a break would cost, against the plan's final orders (plan/relations.ts).
2886
+ reportBreakLosses(pc, truceReport.relations, plan);
2887
+ plan.relations = truceReport.relations;
2888
+ if (truceReport.advice.length)
2889
+ plan.advice = truceReport.advice;
2890
+ }
2891
+ // #214 review: what planTurn compares between the plans with and without bare steps. A border
2892
+ // ends holding when it is not conceded and what the final orders leave there (its armies, deploys
2893
+ // and transfers in, less every order out) beats the threat left once this plan's captures land.
2894
+ const gone = (n) => captured.has(n);
2895
+ const holdsAtEnd = (v, b) => {
2896
+ const ends = moves.reduce((n, m) => n - (m.from === v ? m.armies : 0) + (m.kind === 'transfer' && m.to === v ? m.armies : 0), armiesOf(v) + (ps.deployed.get(v) ?? 0));
2897
+ return !conceded.has(v) && (toTake(ends + unitsAt(v)) ?? Infinity) > b.threat;
2898
+ };
2899
+ const held = new Set();
2900
+ const unheld = new Set();
2901
+ for (const v of mine) {
2902
+ const b = borderAt(v, gone);
2903
+ if (!b)
2904
+ continue;
2905
+ if (!holdsAtEnd(v, b))
2906
+ unheld.add(v);
2907
+ else if (heldBorders.has(v) || (ps.deployed.get(v) ?? 0) > 0)
2908
+ held.add(v);
2909
+ }
2910
+ // A held bonus left floored (#118: kept, but short of its whole hold) is short on those borders
2911
+ // whatever the count above says: one shared deploy can still break it.
2912
+ for (const u of units)
2913
+ if (u.contested && !u.conceded)
2914
+ for (const m of u.members)
2915
+ if (!heldBorders.has(m.id))
2916
+ unheld.add(m.id);
2917
+ runOutcome.set(plan, { bareSteps: [...caps.bareTaken].filter(gone).sort(byNum), held, unheld });
2918
+ // #274: a plan that walks my commander says so first.
2919
+ if (pc.commanderAt?.retreat)
2920
+ plan.warnings.unshift(commanderMoveWarning(pc.commanderAt.retreat, label));
2921
+ return plan;
2922
+ }