@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,140 @@
1
+ // Rule 5b, a capture the leftover pays for (#218, last comment): once the leftover is placed, a
2
+ // neutral a source it reached can now take from what stands above its hold is taken. Live, a capture
3
+ // was ruled out because its source "stays to hold its border" (2 armies against a hold of ~5), and the
4
+ // leftover then put 1 and 7 on that same source as its comfortable margin — 13 against that hold,
5
+ // beside a 1-army neutral that 3 take for +1 — and nothing attacked it. planPass runs it after the
6
+ // leftover, the strike stack's orders and the lead strikes, before the efficient sizes, the transfers
7
+ // (rule 6) and the #226 margin.
8
+ import { straightKills } from '../combat.js';
9
+ import { neighborsOf } from '../graph.js';
10
+ import { lateArrivals } from './holds.js';
11
+ import { PLAIN_EXPANSION_LOSS } from './shared.js';
12
+ import { notFromTransit, plainOrderCosts } from './vacated.js';
13
+ /**
14
+ * Pass 3's economy test (#125) for capturing `id` (its income change `gain`): a member of an economic
15
+ * bonus is judged by that bonus, a focused one always passes; any other capture repays the armies it
16
+ * loses (the defenders' kills) with the income it adds within PAYBACK_TURNS, and one adding none may
17
+ * lose at most PLAIN_EXPANSION_LOSS. `null` when it passes, else its armies lost and the worth it adds.
18
+ */
19
+ export function plainEconomy(pc, tgt, id, gain) {
20
+ if (pc.inFocus(id) || tgt.economicMember.has(id))
21
+ return null;
22
+ const lost = straightKills(pc.defenceAt(id), pc.rates.defensiveKillRate);
23
+ const worth = pc.plainWorth(id, gain);
24
+ return (worth > 0 ? lost > pc.paybackTurns * worth : lost > PLAIN_EXPANSION_LOSS) ? { lost, worth } : null;
25
+ }
26
+ /**
27
+ * Pass 3's eligibility (#125): not a player's under `balanced` (but #281's empty enemy territory), and
28
+ * not only a member of an uneconomic bonus (but #281's denial: what it denies the opponent beside it is
29
+ * its worth, not my bonus).
30
+ */
31
+ export function plainEligible(pc, tgt, id, enemy) {
32
+ return (!(pc.balanced && enemy && !tgt.emptyEnemies.has(id)) &&
33
+ (tgt.economicMember.has(id) ||
34
+ !tgt.uneconomicMember.has(id) ||
35
+ tgt.denials.has(id) ||
36
+ (pc.territoryShare(1) > 0 && !tgt.negativeMember.has(id))));
37
+ }
38
+ /**
39
+ * Rule 5b. `before`: the deploys before the leftover (rule 5), so the sources are the territories
40
+ * the leftover reached. `skip`: sources the caller keeps whole (the strike stack, the step the
41
+ * leftover saves toward). `caps.tryExpand`: pass 3's capture (R3, rule 4d and the usual sizing). Returns
42
+ * the targets taken.
43
+ */
44
+ export function afterLeftoverCaptures(pc, ps, book, threats, hd, tgt, caps, before, skip, poolDeployed) {
45
+ const { g, territories: state, label, mineSet, unitsAt, noSplit, myCommanders, goal } = pc;
46
+ const { rationale, warnings, avail, deployed, captured, moves, centralKeep } = ps;
47
+ const { coverOf, gainWith } = book;
48
+ const { borderAt, forceAt, holdArmies } = threats;
49
+ const { conceded, stayAt, twoStepKeep } = hd;
50
+ const { targets } = tgt;
51
+ const { tryExpand, stopped, notCompleted } = caps;
52
+ // No-Split (#124) sends the whole stack: nothing would stay to hold the source. `complete-bonus`
53
+ // never expands (as pass 3).
54
+ if (noSplit || goal === 'complete-bonus' || ps.budget > 0)
55
+ return [];
56
+ /** A player's territory: an attack on it may fail, and the #226 margin sizes those from the source's spare. */
57
+ const onPlayer = (n) => state.get(n)?.owner.kind === 'player';
58
+ const sources = [...mineSet]
59
+ .filter((x) => (deployed.get(x) ?? 0) > (before.get(x) ?? 0) &&
60
+ !conceded.has(x) &&
61
+ !myCommanders.has(x) &&
62
+ !skip.has(x) &&
63
+ !moves.some((m) => m.from === x && m.kind === 'attack' && onPlayer(m.to)))
64
+ .sort((a, b) => a - b);
65
+ if (!sources.length)
66
+ return [];
67
+ /**
68
+ * What `x` has above its hold once it attacks `t`: what holds it against the threat beside it —
69
+ * judged as if this turn's attacks on players there failed, and without the armies withdrawn into
70
+ * it unless I am known to move first (#215: as `keepFor` sizes a hold) — and at least what a stack
71
+ * two steps away needs it to keep (#172), what covers a finished-off player's exit (#179), the
72
+ * leftover kept central (#218) and a Local Deployment pool's armies (#103). `null` when it cannot
73
+ * hold on what it has.
74
+ */
75
+ const spareFor = (x, t) => {
76
+ const gone = (n) => n === t || (captured.has(n) && !onPlayer(n));
77
+ const b = borderAt(x, gone);
78
+ const stays = stayAt(x) - lateArrivals(pc, ps, x);
79
+ let need = b ? Math.max(0, holdArmies(b.threat) - unitsAt(x)) : 0;
80
+ // #128: what holds it against two opponents attacking together, when it holds that now: the
81
+ // capture never brings on the warning that it does not.
82
+ const pile = b ? forceAt(x, gone, { trend: true, allPlayers: true, pileOn: true })?.split : undefined;
83
+ const together = pile && pile.players.length >= 2 && stays + unitsAt(x) > pile.takes ? pile : undefined;
84
+ const alone = need;
85
+ if (together)
86
+ need = Math.max(need, together.takes + 1 - unitsAt(x));
87
+ if (stays < need)
88
+ return null;
89
+ const keep = Math.max(avail.get(x) - (stays - need), twoStepKeep(x, (n) => n === t), coverOf(x), centralKeep.get(x) ?? 0, poolDeployed.get(x) ?? 0);
90
+ return { spare: Math.max(0, avail.get(x) - keep), keep, need, threat: b?.threat, together: need > alone ? together : undefined };
91
+ };
92
+ const taken = [];
93
+ const eligible = [...targets.values()].filter((tg) => state.get(tg.id)?.owner.kind === 'neutral' && !captured.has(tg.id) && tg.sources.some((x) => sources.includes(x)));
94
+ const order = plainOrderCosts(pc, tgt, eligible.map((tg) => tg.id));
95
+ const candidates = eligible.sort((a, b) => order.get(a.id) - order.get(b.id) || a.cost - b.cost || a.id - b.id);
96
+ for (const tg of candidates) {
97
+ const t = tg.id;
98
+ const gain = gainWith([t]);
99
+ if (gain < 0 || !plainEligible(pc, tgt, t, false) || plainEconomy(pc, tgt, t, gain))
100
+ continue;
101
+ // #281 × #282: a denial is never sourced from the territory my commander walks from (its transit hold).
102
+ const best = (tgt.denials.has(t) ? notFromTransit(pc, tg) : tg).sources
103
+ .filter((x) => sources.includes(x))
104
+ .map((x) => ({ x, f: spareFor(x, t) }))
105
+ .filter((c) => c.f !== null && c.f.spare >= tg.cost)
106
+ .sort((a, b) => b.f.spare - a.f.spare || a.x - b.x)[0];
107
+ if (!best)
108
+ continue;
109
+ const { x, f } = best;
110
+ const late = lateArrivals(pc, ps, x);
111
+ const had = stayAt(x) - late;
112
+ const left = had - tg.cost;
113
+ const failing = neighborsOf(g, x).some((n) => captured.has(n) && onPlayer(n));
114
+ const held = f.threat === undefined
115
+ ? 'and no enemy is beside it'
116
+ : `${left > f.need ? `above the ${f.need} that hold it` : 'what holds it'} against the ~${f.threat} threat${f.together ? ` and against players ${f.together.players.join(' and ')} attacking it together (up to ${f.together.takes} armies)` : ''}${failing ? " even if this turn's attacks on players beside it fail" : ''}`;
117
+ const reason = `a neutral${gain > 0 ? ` (+${gain} income)` : ''} the leftover pays for (#218): of the ${had} on ${label(x)} after the leftover${late > 0 ? ` (the ${late} withdrawn into it left out: they may land too late)` : ''}, the ${tg.cost} sent leave ${left}, ${held}`;
118
+ // A refused try leaves no line: this pass is an extra, and rule 4e or the frontier report already
119
+ // says why the turn takes nothing more (R3's and rule 4d's refusals would otherwise repeat it).
120
+ const lines = { rationale: rationale.length, warnings: warnings.length, stopped: stopped.length };
121
+ const refusedBefore = new Set(notCompleted.keys());
122
+ if (!tryExpand(t, reason, false, { from: x, keep: f.keep })) {
123
+ rationale.length = lines.rationale;
124
+ warnings.length = lines.warnings;
125
+ stopped.length = lines.stopped;
126
+ for (const id of [...notCompleted.keys()])
127
+ if (!refusedBefore.has(id))
128
+ notCompleted.delete(id);
129
+ continue;
130
+ }
131
+ taken.push(t);
132
+ }
133
+ if (taken.length) {
134
+ // A capture is planned now: the stand-still warning (rule 4e) no longer holds.
135
+ for (let i = warnings.length - 1; i >= 0; i--)
136
+ if (warnings[i].startsWith('Standing still: no capture is planned'))
137
+ warnings.splice(i, 1);
138
+ }
139
+ return taken;
140
+ }
@@ -0,0 +1,242 @@
1
+ // Rule 4h, the army cap prices idle armies (#253): war.app pays min(income, round(cap × income) −
2
+ // my armies on the board), so when my armies after this turn plus next income exceed the cap, every
3
+ // army above it costs an army of next income. A capture whose expected losses are below that cost
4
+ // is free: it is taken from idle armies first (the deploys still left, before the leftover's margins,
5
+ // make up a shortfall: deployed or not, they count against the cap), every hold respected. Rule 4e's
6
+ // army-cap fallback (#104) runs only when the plan captures nothing; this rule runs whatever else the
7
+ // plan captures (live, a plan that completed a bonus elsewhere parked 54 armies beside two enemy
8
+ // territories holding 0 and 1). #272: once one of a player's territories is taken so, its owner's
9
+ // other territories beside mine are candidates whatever they hold — a fork its one deploy must split to
10
+ // save them all (the line says it cannot when the summed saves exceed its estimate) — each still only while its loss is below the income at stake. planPass runs it after rules
11
+ // 4e and 4g.
12
+ import { straightKills } from '../combat.js';
13
+ import { neighborsOf } from '../graph.js';
14
+ import { armyCapIncome } from '../player.js';
15
+ import { standStillKit } from './stand-still.js';
16
+ import { byNum } from './util.js';
17
+ /** A player's territory is a candidate only while it holds at most this many armies ("0 or 1"). */
18
+ export const CAP_SPEND_ENEMY_MAX = 1;
19
+ /** "my ~A armies after this turn reach the army cap next turn (C× income N = L): ~E of next turn's income N would be lost". */
20
+ function capText(c) {
21
+ return `my ~${c.armies} armies after this turn reach the army cap next turn (${c.next.cap}× income ${c.next.uncapped} = ${c.next.limit}): ~${c.eaten} of next turn's income ${c.next.uncapped} would be lost`;
22
+ }
23
+ export function spendUnderCap(pc, ps, book, threats, hd, tgt, caps) {
24
+ const { g, s, goal, foe, income, cardArmies, earnedIncome, territories: state, label, mine, mineSet, armiesOf, unitsAt, uncounted, rates, incomeGain } = pc;
25
+ const { warnings, rationale, captured, spared, moves, avail } = ps;
26
+ const { gainWith, heldNow } = book;
27
+ const { conceded } = hd;
28
+ const { targets } = tgt;
29
+ const { defendersSeen } = caps;
30
+ const cap = pc.incomeCap?.cap ?? s.armyCap ?? null;
31
+ if (goal === 'complete-bonus' || cap === null || !(cap > 0))
32
+ return;
33
+ const start = pc.incomeCap?.armies ?? mine.reduce((n, id) => n + armiesOf(id), 0);
34
+ /** Next income before the cap, card armies out. */
35
+ const baseIncome = Math.max(0, earnedIncome - cardArmies);
36
+ /** What the plan's attacks are expected to lose (the defenders' kills on the armies sent). */
37
+ const lostInPlan = () => {
38
+ let lost = 0;
39
+ for (const t of captured) {
40
+ const sent = moves.filter((m) => m.kind === 'attack' && m.to === t).reduce((n, m) => n + m.armies, 0);
41
+ lost += Math.min(sent, straightKills(defendersSeen(t), rates.defensiveKillRate));
42
+ }
43
+ return lost;
44
+ };
45
+ const nextCap = () => {
46
+ const armies = Math.max(0, start + income - lostInPlan());
47
+ const next = armyCapIncome(Math.max(0, baseIncome + incomeGain(heldNow())), cap, armies);
48
+ return { armies, next, eaten: next.uncapped - next.received };
49
+ };
50
+ const first = nextCap();
51
+ if (first.eaten <= 0)
52
+ return;
53
+ /** The expected loss of a capture of `t`: the defenders' kills on its attackers. */
54
+ const lossAt = (t) => straightKills(defendersSeen(t), rates.defensiveKillRate);
55
+ // Candidates: the neutral targets (rule 2's: next to a territory I held at the start), and every
56
+ // visible player's territory next to mine holding at most CAP_SPEND_ENEMY_MAX armies (no commander,
57
+ // no truce, no teammate; `expand` attacks no player) — none lowering income.
58
+ const added = [];
59
+ const cands = [];
60
+ for (const t of [...g.territoryById.keys()].sort(byNum)) {
61
+ if (mineSet.has(t) || captured.has(t) || spared.has(t) || pc.truce.noTarget(t))
62
+ continue;
63
+ const st = state.get(t);
64
+ if (!st || st.armies === null || uncounted(t) || unitsAt(t) > 0)
65
+ continue;
66
+ const tg = targets.get(t);
67
+ if (st.owner.kind === 'player') {
68
+ if (goal === 'expand' || !foe(st.owner.playerId) || st.armies > CAP_SPEND_ENEMY_MAX)
69
+ continue;
70
+ if (!tg) {
71
+ const sources = neighborsOf(g, t).filter((n) => mineSet.has(n));
72
+ const cost = pc.costAt(t);
73
+ if (!sources.length || cost === null)
74
+ continue;
75
+ targets.set(t, { id: t, cost, enemy: true, sources });
76
+ added.push(t);
77
+ }
78
+ }
79
+ else if (!tg || tg.enemy)
80
+ continue;
81
+ if (gainWith([t]) < 0)
82
+ continue;
83
+ cands.push(t);
84
+ }
85
+ cands.sort((a, b) => lossAt(a) - lossAt(b) ||
86
+ Number(!targets.get(a).enemy) - Number(!targets.get(b).enemy) ||
87
+ gainWith([b]) - gainWith([a]) ||
88
+ targets.get(a).cost - targets.get(b).cost ||
89
+ a - b);
90
+ const kit = standStillKit(pc, ps, book, threats, hd, tgt, caps);
91
+ const refused = [];
92
+ /** A candidate not taken, and why (a clause after its name); the offence report repeats it (ps.capRefused). */
93
+ const refuse = (t, why) => {
94
+ refused.push(`${label(t)} ${why}`);
95
+ ps.capRefused.set(t, why);
96
+ };
97
+ const taken = [];
98
+ /** A candidate's owner, when a player holds it. */
99
+ const ownerOf = (t) => {
100
+ const o = state.get(t)?.owner;
101
+ return o?.kind === 'player' ? o.playerId : undefined;
102
+ };
103
+ /** The territories `p` loses to this plan's captures, sorted. */
104
+ const lostBy = (p) => [...captured].filter((x) => ownerOf(x) === p).sort(byNum);
105
+ /**
106
+ * Try `t`, the `i`th of `list`. 'stop' when it loses as much as the income still at stake (the list
107
+ * is ranked by loss, so every later one does too: one clause for them all). `fork`: #272, a
108
+ * territory above CAP_SPEND_ENEMY_MAX taken only beside another of its owner's this turn.
109
+ */
110
+ const tryOne = (t, i, list, fork) => {
111
+ const now = nextCap();
112
+ if (now.eaten <= 0)
113
+ return 'stop';
114
+ const loss = lossAt(t);
115
+ if (loss >= now.eaten) {
116
+ const rest = list.slice(i + 1);
117
+ const tail = `more than the ~${now.eaten} of next income the army cap would take`;
118
+ ps.capRefused.set(t, `loses ~${loss}, ${tail}`);
119
+ for (const x of rest)
120
+ ps.capRefused.set(x, `loses ~${lossAt(x)}, ${tail}`);
121
+ refused.push(rest.length
122
+ ? `${label(t)} and ${rest.length} more ${rest.length === 1 ? 'candidate' : 'candidates'} lose ~${loss} or more, ${tail}`
123
+ : `${label(t)} loses ~${loss}, ${tail}`);
124
+ return 'stop';
125
+ }
126
+ const reach = kit.reachOf(t);
127
+ const cand = { ...reach, t, cost: targets.get(t).cost };
128
+ if (reach.from === undefined) {
129
+ refuse(t, kit.failText(cand, undefined));
130
+ return undefined;
131
+ }
132
+ if (conceded.has(reach.from)) {
133
+ refuse(t, `could be taken only from conceded ${label(reach.from)}, whose armies stay or withdraw`);
134
+ return undefined;
135
+ }
136
+ const before = ps.budget;
137
+ const reason = `the army cap: ${capText(now)}, and this capture loses ~${loss} (#253, rule 4h)`;
138
+ const undo = kit.attempt(cand, reason);
139
+ if (!undo) {
140
+ const r = ps.refusal;
141
+ refuse(t, kit.failText(cand, r));
142
+ return undefined;
143
+ }
144
+ // Every source keeps what holds its border (deploys still free may top one up).
145
+ const short = kit.holdLeftShort(t);
146
+ if (short) {
147
+ undo();
148
+ refuse(t, `is not taken: attacking it would leave ${label(short.from)} unable to hold its border (${kit.holdText(short)})`);
149
+ return undefined;
150
+ }
151
+ // Its survivors stay on the board (above the cap they cost nothing either): named, not priced.
152
+ const exposed = kit.exposure(t);
153
+ taken.push(t);
154
+ const paid = before - ps.budget;
155
+ const p = ownerOf(t);
156
+ const lost = p === undefined ? [] : lostBy(p);
157
+ // #272 review: the fork's claim is stated only when computed — the deploy each attacked territory
158
+ // needs to repel what this plan sends there, summed, against the owner's deploy estimate.
159
+ const forkText = () => {
160
+ const est = Math.max(0, ...lost.map((x) => threats.reinforcementAt(x)));
161
+ let need = 0;
162
+ for (const x of lost) {
163
+ const sent = moves.filter((m) => m.kind === 'attack' && m.to === x).reduce((n, m) => n + m.armies, 0);
164
+ const d = pc.defenceAt(x);
165
+ let e = 0;
166
+ // The least deploy there that makes the attack fall short (capped one past the estimate).
167
+ while (e <= est) {
168
+ const c = pc.costAt(x, d + e);
169
+ if (c === null || c > sent)
170
+ break;
171
+ e++;
172
+ }
173
+ need += e;
174
+ }
175
+ const head = `a fork (#272): player ${p} is attacked on ${lost.length} territories this turn (${lost.map(label).join(', ')})`;
176
+ return est > 0 && need > est
177
+ ? `${head}, more than its ~${est} deploy can all save (saving them all takes ~${need})`
178
+ : `${head}, so its one deploy must be split to save them all`;
179
+ };
180
+ rationale.push(`Take ${label(t)} for the army cap (rule 4h, #253): ${capText(now)}; it loses ~${loss}${exposed ? ` (and its ${exposed.survivors} may fall next turn)` : ''}, below that, ${paid > 0 ? `paid from idle armies and ${paid} of the deploys left` : 'paid from idle armies'}${fork
181
+ ? `; ${forkText()}`
182
+ : ''}.`);
183
+ return undefined;
184
+ };
185
+ ps.evenTradesOnly = true;
186
+ try {
187
+ for (const [i, t] of cands.entries())
188
+ if (tryOne(t, i, cands, false) === 'stop')
189
+ break;
190
+ // #272: a fork. Live, the cap spend took three near-empty territories of one weakened owner and
191
+ // left two more of its territories beside my stacks (4 and 14 armies) though its one deploy could
192
+ // not save five attacks at once. A foe's territory holding more than CAP_SPEND_ENEMY_MAX is a
193
+ // candidate once another of its owner's is taken this turn, ranked as above, its loss still below
194
+ // the income at stake.
195
+ const forks = [];
196
+ for (const t of [...g.territoryById.keys()].sort(byNum)) {
197
+ if (mineSet.has(t) || captured.has(t) || spared.has(t) || pc.truce.noTarget(t) || cands.includes(t))
198
+ continue;
199
+ const st = state.get(t);
200
+ if (st?.owner.kind !== 'player' || st.armies === null || st.armies <= CAP_SPEND_ENEMY_MAX)
201
+ continue;
202
+ if (goal === 'expand' || !foe(st.owner.playerId) || uncounted(t) || unitsAt(t) > 0)
203
+ continue;
204
+ if (!targets.get(t)) {
205
+ const sources = neighborsOf(g, t).filter((n) => mineSet.has(n));
206
+ const cost = pc.costAt(t);
207
+ if (!sources.length || cost === null)
208
+ continue;
209
+ targets.set(t, { id: t, cost, enemy: true, sources });
210
+ added.push(t);
211
+ }
212
+ if (gainWith([t]) < 0)
213
+ continue;
214
+ forks.push(t);
215
+ }
216
+ forks.sort((a, b) => lossAt(a) - lossAt(b) || gainWith([b]) - gainWith([a]) || targets.get(a).cost - targets.get(b).cost || a - b);
217
+ const open = forks.filter((t) => lostBy(ownerOf(t)).length > 0);
218
+ for (const [i, t] of open.entries()) {
219
+ // A fork only while its owner still loses another territory this turn.
220
+ if (!lostBy(ownerOf(t)).length)
221
+ continue;
222
+ if (tryOne(t, i, open, true) === 'stop')
223
+ break;
224
+ }
225
+ }
226
+ finally {
227
+ ps.evenTradesOnly = false;
228
+ }
229
+ for (const t of added)
230
+ if (!captured.has(t))
231
+ targets.delete(t);
232
+ if (refused.length)
233
+ rationale.push(`Army cap (rule 4h, #253), not taken: ${refused.join('; ')}.`);
234
+ const after = nextCap();
235
+ if (after.eaten > 0) {
236
+ const idle = mine
237
+ .map((x) => ({ x, n: avail.get(x) ?? 0 }))
238
+ .filter((e) => e.n > 0)
239
+ .sort((a, b) => b.n - a.n || a.x - b.x)[0];
240
+ warnings.push(`Army cap: ${capText(after)} unless armies are spent${idle ? ` (the largest idle stack is ${idle.n} on ${label(idle.x)})` : ''}${taken.length ? `; the plan already spends idle armies on ${taken.map(label).join(', ')}` : ''}.`);
241
+ }
242
+ }