@chrischall/warapp-mcp 0.0.0 → 0.2.0

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