@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,236 @@
1
+ // #274 items 2 and 3: where my commander should stand. Pure and deterministic (ties on ascending id).
2
+ //
3
+ // A commander within COMMANDER_CLEAR_MOVES moves of an enemy or fogged territory (the distance
4
+ // warapp_plan_turn's `commander` block reports) walks one step a turn toward a territory of mine
5
+ // farther from every one of them, until it is that many moves clear. It walks only through my
6
+ // own land, never onto a territory nearer an enemy than the one it leaves nor onto one beside an
7
+ // enemy or the fog (taken before my order runs, the step would turn the commander's transfer into
8
+ // an attack): the safest path; and only toward a territory strictly farther than where it stands.
9
+ // With no such territory it stays, and rule 1k holds it against the worst case.
10
+ import { COMMANDER_STRENGTH, guaranteedKills } from '../combat.js';
11
+ import { bfsDistances, neighborsOf } from '../graph.js';
12
+ import { byNum } from './util.js';
13
+ /** Moves from every enemy or fogged territory past which my commander stops walking away. */
14
+ export const COMMANDER_CLEAR_MOVES = 3;
15
+ /**
16
+ * Where my commander on `from` stands, and its step toward safety when it is within `clear` moves
17
+ * of a `hostile` territory and a territory of mine (`isMine`) farther from all of them is reachable
18
+ * through my land without coming nearer one.
19
+ */
20
+ export function commanderPlace(g, from, isMine, hostile, clear = COMMANDER_CLEAR_MOVES) {
21
+ const away = bfsDistances(g, hostile);
22
+ const far = (t) => away.get(t) ?? Infinity;
23
+ const here = far(from);
24
+ const distance = Number.isFinite(here) ? here : null;
25
+ if (here >= clear)
26
+ return { territory: from, distance };
27
+ // Through my land, never nearer an enemy than here, and never onto a territory beside one: an
28
+ // enemy that takes the step first would turn my commander's transfer into an attack.
29
+ const floor = Math.max(here, 2);
30
+ const passable = (t) => t === from || (isMine(t) && far(t) >= floor);
31
+ const hops = bfsDistances(g, [from], { passable });
32
+ let best;
33
+ for (const [t, h] of [...hops].sort((a, b) => a[0] - b[0])) {
34
+ const d = far(t);
35
+ if (t === from || d <= here)
36
+ continue;
37
+ const score = Math.min(d, clear);
38
+ if (!best || score > best.score || (score === best.score && (h < best.hops || (h === best.hops && d > best.d))))
39
+ best = { t, score, hops: h, d };
40
+ }
41
+ if (!best)
42
+ return { territory: from, distance };
43
+ // The first step on a shortest such path, the one farthest from every enemy (then the lowest id).
44
+ const back = bfsDistances(g, [best.t], { passable });
45
+ const to = neighborsOf(g, from)
46
+ .filter((n) => passable(n) && back.get(n) === best.hops - 1)
47
+ .sort((a, b) => far(b) - far(a) || byNum(a, b))[0];
48
+ const fin = (d) => (Number.isFinite(d) ? d : clear);
49
+ return {
50
+ territory: from,
51
+ distance,
52
+ retreat: { from, to, distance: here, toDistance: fin(far(to)), target: best.t, targetDistance: fin(best.d), steps: best.hops },
53
+ };
54
+ }
55
+ /** The first warning of a plan that walks my commander (#274). */
56
+ export function commanderMoveWarning(r, label, clear = COMMANDER_CLEAR_MOVES) {
57
+ const moves = (n) => `${n} move${n === 1 ? '' : 's'}`;
58
+ return (`My commander moves from ${label(r.from)} to ${label(r.to)} this turn (#274): ${label(r.from)} is ${moves(r.distance)} from the nearest enemy or fog, ` +
59
+ `and ${label(r.to)} is ${moves(r.toDistance)}${r.to === r.target ? '' : `, on the way to ${label(r.target)} (${moves(r.targetDistance)}, ${r.steps} steps)`}; ` +
60
+ `it walks one step a turn until it is ${moves(clear)} clear. ${label(r.from)} is no longer must-hold: it is held only for what it is worth itself. ` +
61
+ `The order takes the commander along (the commander option, its encoding not yet verified live), listed as early as the move order allows.`);
62
+ }
63
+ /** Why my commander stays where it is (#274), for the rationale. */
64
+ export function commanderStaysLine(place, label, clear = COMMANDER_CLEAR_MOVES) {
65
+ const where = label(place.territory);
66
+ if (place.pinned)
67
+ return `My commander stays on ${where}: this plan does not walk it (commanderWalks off).`;
68
+ if (place.distance === null)
69
+ return `My commander stays on ${where}: no enemy or fogged territory is on the map.`;
70
+ const d = `${place.distance} move${place.distance === 1 ? '' : 's'}`;
71
+ return place.distance >= clear
72
+ ? `My commander stays on ${where}: it is ${d} from the nearest enemy or fog, clear at ${clear} (#274).`
73
+ : `My commander stays on ${where}, ${d} from the nearest enemy or fog: no territory of mine farther from every enemy is reachable through my land without coming nearer one, so it holds there (#274).`;
74
+ }
75
+ /** The reason a commander's walk carries. */
76
+ const stepReason = (r, label) => `my commander walks toward safety (#274): ${label(r.to)} is farther from every enemy and the fog than ${label(r.from)} (${r.toDistance} moves, not ${r.distance})`;
77
+ /**
78
+ * #274: under No-Split my commander's territory issues one order, so its walk is that order: it is
79
+ * entered before any pass plans (each sees the territory already ordering) and sized at the end
80
+ * ({@link placeCommanderMove}: the whole stack goes with it). The walk wins: a commander strike or a
81
+ * kill that territory could have made is not made (getting the commander out of reach comes first).
82
+ */
83
+ export function reserveCommanderMove(pc, ps) {
84
+ const r = pc.commanderAt?.retreat;
85
+ if (!r || !pc.noSplit)
86
+ return;
87
+ ps.moves.push({ from: r.from, to: r.to, armies: 0, kind: 'transfer', reason: stepReason(r, pc.label), commander: true });
88
+ }
89
+ /**
90
+ * #274: once every other order is planned, my commander's walk: it rides the move from its
91
+ * territory to the step when there is one, else goes as its own transfer carrying no armies (what
92
+ * it leaves is held only for its own worth). Under No-Split the reserved order sends the whole stack.
93
+ */
94
+ export function placeCommanderMove(pc, ps) {
95
+ const r = pc.commanderAt?.retreat;
96
+ if (!r)
97
+ return;
98
+ const at = ps.moves.find((m) => m.commander);
99
+ if (at) {
100
+ // No-Split's whole stack: what the passes moved into it already, plus anything still idle there.
101
+ at.armies += Math.max(0, ps.avail.get(r.from) ?? 0);
102
+ ps.avail.set(r.from, Math.min(0, ps.avail.get(r.from) ?? 0));
103
+ return;
104
+ }
105
+ const along = ps.moves.find((m) => m.from === r.from && m.to === r.to && m.kind === 'transfer');
106
+ if (along)
107
+ along.commander = true;
108
+ else
109
+ ps.moves.push({ from: r.from, to: r.to, armies: 0, kind: 'transfer', reason: stepReason(r, pc.label), commander: true });
110
+ }
111
+ /**
112
+ * #274: my commander stays where it stood until its walk runs, and the opponent's orders may come
113
+ * before it: the territory it leaves gets the deploys that make it survive what can land there first.
114
+ * Each player's attack there is its stack beside it with its owner's whole deploy (at least my own
115
+ * income, as warapp_submit_turn sizes its replies; a what-if `enemyDeploy` as given), my commander
116
+ * counted. Even when I am known to move first (#274 review): warapp_submit_turn's commander check is
117
+ * not told who moves first and tries the opponent first too, so a walk without this hold would be
118
+ * refused there. Nothing more: once it has walked, the territory is held only for its own worth.
119
+ *
120
+ * #274 review 2: the walk is my first order only when nothing else claims that slot (a strike, a
121
+ * kill, a conceded withdrawal); moving first, the zigzag then runs my first order, the opponent's
122
+ * first and second, then the walk, so two attacks land before it. So the hold is sized, in order:
123
+ * 1. every enemy stack beside it attacking in turn, each player's deploy on one of its stacks
124
+ * (each stack tried as the last, as the border threat sizes separate attacks): whatever order
125
+ * the walk ends up in, nothing more can land there before it;
126
+ * 2. when that does not fit, each player's strongest single attack in turn (one player: its first
127
+ * attack), and the walk is made my first order (`ps.commanderWalkFirst`): then only those land
128
+ * before it whoever moves first. No Order Priority is advised for it: the hold covers them;
129
+ * 3. when neither fits, all that may go there goes there, a warning says so and `ps.commanderCaught`
130
+ * makes the walk my first order with Order Priority advised for it (plan/move-order.ts), as a
131
+ * fogged neighbour does (what hides there cannot be sized).
132
+ * The hold where it walks to (rule 1k) is reserved first. Run after the strikes (a territory `gone`
133
+ * — struck or finished off — threatens nothing), before triage.
134
+ */
135
+ export function commanderTransit(pc, ps, book, threats, gone = () => false) {
136
+ const r = pc.commanderAt?.retreat;
137
+ if (!r)
138
+ return;
139
+ // A fogged neighbour may hide a stack: no hold can be sized against it.
140
+ if (neighborsOf(pc.g, r.from).some((n) => {
141
+ const st = pc.territories.get(n);
142
+ return !gone(n) && (st === undefined || st.owner.kind === 'unknown' || (st.armies === null && st.owner.kind === 'player' && pc.foe(st.owner.playerId)));
143
+ }))
144
+ ps.commanderCaught = true;
145
+ const floor = pc.custom ? 0 : Math.max(0, pc.income - pc.cardArmies);
146
+ /** Per player beside it: each stack's movable armies and the deploy that can land on it, strongest first. */
147
+ const byPlayer = new Map();
148
+ for (const n of [...neighborsOf(pc.g, r.from)].sort(byNum)) {
149
+ const st = pc.territories.get(n);
150
+ if (gone(n) || st?.owner.kind !== 'player' || !pc.foe(st.owner.playerId) || st.armies === null)
151
+ continue;
152
+ const p = st.owner.playerId;
153
+ const add = Math.max(floor, pc.custom ? pc.deployOf(p) : threats.deployReaching(p, [n]));
154
+ byPlayer.set(p, [...(byPlayer.get(p) ?? []), { id: n, movable: Math.max(0, st.armies - pc.guard) + pc.unitsAt(n), add }]);
155
+ }
156
+ if (!byPlayer.size)
157
+ return;
158
+ const players = [...byPlayer].sort((a, b) => a[0] - b[0]);
159
+ for (const [, xs] of players)
160
+ xs.sort((a, b) => b.movable + b.add - (a.movable + a.add) || a.id - b.id);
161
+ /** The strongest single attack (the lowest player id on a tie): what the opponent's first order may be. */
162
+ let single = 0;
163
+ let by = players[0][0];
164
+ for (const [p, xs] of players)
165
+ if (xs[0].movable + xs[0].add > single)
166
+ [single, by] = [xs[0].movable + xs[0].add, p];
167
+ const kills = (n) => guaranteedKills(n, pc.rates.offensiveKillRate, 0, 'StraightRound');
168
+ /**
169
+ * The attack sequences to survive: softening attacks (their kills come off first) and a last one
170
+ * that must not take what is left. `every`: all the stacks, each tried as the last with its own
171
+ * deploy, every other player's deploy on its strongest stack; else each player's strongest attack.
172
+ */
173
+ const sequences = (every) => players.flatMap(([lastP, lastXs]) => (every ? lastXs : lastXs.slice(0, 1)).map((L) => {
174
+ const soft = [];
175
+ for (const [p, xs] of players)
176
+ for (const [i, x] of xs.entries()) {
177
+ if (x === L || (!every && i > 0))
178
+ continue;
179
+ const armies = x.movable + (p !== lastP && i === 0 ? x.add : 0);
180
+ if (armies > 0)
181
+ soft.push(armies);
182
+ }
183
+ return { soft, last: L.movable + L.add };
184
+ }));
185
+ const all = sequences(true);
186
+ /** Some player has two stacks beside it: more can land before a later walk than before my first order. */
187
+ const stacked = players.some(([, xs]) => xs.length > 1);
188
+ const many = players.reduce((n, [, xs]) => n + xs.length, 0) > 1;
189
+ const have = ps.avail.get(r.from) + book.guardAt(r.from) + pc.unitsAt(r.from) + COMMANDER_STRENGTH;
190
+ /** Whether `d` defenders (my commander counted) survive every sequence, each last attack sized for a Bomb as a border's threat is. */
191
+ const survives = (d, seqs) => seqs.every(({ soft, last }) => {
192
+ const left = d - soft.reduce((a, n) => a + kills(n), 0);
193
+ return left > 0 && (pc.toTake(left) ?? Infinity) > threats.bombSized(r.from, last);
194
+ });
195
+ // Where it walks to holds it for the rest of the turn (rule 1k there): its hold comes first.
196
+ const dest = threats.borderAt(r.to, gone);
197
+ let reserve = 0;
198
+ if (dest) {
199
+ const there = ps.avail.get(r.to) + book.guardAt(r.to) + pc.unitsAt(r.to);
200
+ while (reserve <= ps.budget && (pc.toTake(there + reserve) ?? Infinity) <= dest.threat)
201
+ reserve++;
202
+ }
203
+ const room = Math.max(0, Math.min(book.roomAt(r.from), ps.budget - reserve));
204
+ const needFor = (seqs) => {
205
+ let need = 0;
206
+ while (need <= room && !survives(have + need, seqs))
207
+ need++;
208
+ return need;
209
+ };
210
+ const label = pc.label;
211
+ const threat = threats.bombSized(r.from, single);
212
+ // `need` past `room`: no deploy there makes it hold.
213
+ const need = needFor(all);
214
+ if (need <= room) {
215
+ if (need > 0) {
216
+ book.deploy(r.from, need);
217
+ ps.rationale.push(many
218
+ ? `Deploy ${need} to ${label(r.from)}: my commander walks from it this turn (#274), but until the walk runs every enemy stack beside it may attack it, one after another (moving first, two land before a walk that is not my first order): with my commander it then holds against all of them (each player's whole deploy, never below my own income).`
219
+ : `Deploy ${need} to ${label(r.from)}: my commander walks from it this turn (#274), but until my first order runs the opponent's first attack may land there: with my commander it then holds against ~${threat} (player ${by}'s strongest stack beside it and its whole deploy, never below my own income).`);
220
+ }
221
+ return;
222
+ }
223
+ // #274 review 2: holding against each player's first attack only, the walk must be my first order.
224
+ const first = stacked ? needFor(sequences(false)) : Infinity;
225
+ if (first <= room) {
226
+ ps.commanderWalkFirst = true;
227
+ if (first > 0)
228
+ book.deploy(r.from, first);
229
+ ps.rationale.push(`My commander's walk from ${label(r.from)} is my first order (#274): ${first > 0 ? `the ${first} deployed there hold` : 'it holds'} against ${players.length > 1 ? "each player's strongest attack" : `player ${by}'s first attack (~${threat}, its strongest stack beside it and its whole deploy)`}, all that can land before my first order, but not against every stack beside it attacking in turn, which could land before a later one.`);
230
+ return;
231
+ }
232
+ // Short of it, all that may go there goes there (an attack smaller than the worst case may come).
233
+ ps.commanderCaught = true;
234
+ book.deploy(r.from, room);
235
+ ps.warnings.push(`My commander may be caught on ${label(r.from)} before it walks (#274): if the opponent moves first, ${players.length > 1 ? `the first attacks of players ${players.map(([p]) => p).join(' and ')} there land` : `player ${by}'s first attack there (~${threat}) lands`} before my first order, and ${room ? `the ${room} deployed there` : 'nothing more deployed there'} cannot make it hold against ${players.length > 1 ? 'them' : 'that'} (it needs more). Order Priority, when I hold one, runs the walk first.`);
236
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * `weakMember(id)`: my open `id` in a positive bonus this turn's captures complete (one I did not
3
+ * hold at the start), next to a visible enemy once the captures land, whose `stays` armies (with
4
+ * its special units) fall to that threat — else `undefined`. `need` is what it still lacks to
5
+ * hold. The bonus named is the most valuable one it completes this turn (ties by id).
6
+ */
7
+ export function completedMembers(pc, ps, threats, open, stays) {
8
+ const { g, mine, mineSet, completedBy, bonusTs, unitsAt, toTake } = pc;
9
+ const before = new Set(completedBy(mineSet));
10
+ const now = completedBy(new Set([...mine, ...ps.captured]))
11
+ .filter((b) => !before.has(b) && (g.bonusById.get(b)?.value ?? 0) > 0)
12
+ .sort((a, b) => g.bonusById.get(b).value - g.bonusById.get(a).value || a - b);
13
+ const weakMember = (id) => {
14
+ if (!now.length || !mineSet.has(id) || !open(id))
15
+ return undefined;
16
+ const bonusId = now.find((b) => bonusTs.get(b)?.includes(id));
17
+ if (bonusId === undefined)
18
+ return undefined;
19
+ const b = threats.borderAt(id, (n) => ps.captured.has(n));
20
+ if (!b)
21
+ return undefined;
22
+ const at = stays(id) + unitsAt(id);
23
+ let need = 0;
24
+ while ((toTake(at + need) ?? Infinity) <= b.threat)
25
+ need++;
26
+ return need > 0 ? { threat: b.threat, need, bonusId } : undefined;
27
+ };
28
+ return { weakMember, completedNow: now };
29
+ }
@@ -0,0 +1,131 @@
1
+ // #272 (item 1): a conceded border attacks out for a free step into a bonus before it withdraws.
2
+ // Rule 1b withdraws a conceded border's movable armies toward a border that holds; the capture
3
+ // passes only use such a border for a completion it is in (#122) or a capture its armies already
4
+ // cover. Live, the last member of a +3 bonus stood empty beside a border the plan conceded and
5
+ // withdrew from, and two more empty territories beside another: the play session held the border
6
+ // and took the member, completing the bonus. So, once the bonus passes have run and before rule 1b
7
+ // withdraws: a territory next to a conceded border of mine holding at most CONCEDED_OUT_MAX armies
8
+ // (a neutral, or a foe's with no special unit; never a truce's or, under `expand`, a player's), in a
9
+ // positive bonus whose capture completes it or advances one I am building (another member mine or
10
+ // captured; under No-Split, which sends the whole stack, a completion only), is taken with that
11
+ // border's own armies (no deploy) when they cover what the capture sends (a lead step's or a
12
+ // repulsed territory's size included) beyond its exit cover — completions
13
+ // first, then by bonus value, cost, a teammate's focus (C3.4) and id, repeated while a capture makes another complete. R3 does
14
+ // not refuse it (the armies would otherwise leave the border it gives up); a completed bonus then
15
+ // keeps the border as rule 1c keeps any member of a bonus this turn completes. The rest withdraw.
16
+ // planPass runs it just before rule 1c's re-valuation and rule 1b's withdrawal.
17
+ import { bonusTerritories } from '../bonuses.js';
18
+ import { neighborsOf } from '../graph.js';
19
+ import { teamFocusLine } from './team.js';
20
+ import { byNum } from './util.js';
21
+ /** #272: a target holding at most this many armies is "empty or near-empty". */
22
+ export const CONCEDED_OUT_MAX = 2;
23
+ export function attackOutOfConceded(pc, ps, book, hd, tgt, caps) {
24
+ const { g, goal, foe, territories: state, label, bonusName, mineSet, unitsAt, uncounted, defenceAt, costAt, myCommanders, noSplit } = pc;
25
+ const { avail, captured, spared, rationale } = ps;
26
+ const { conceded } = hd;
27
+ const { targets } = tgt;
28
+ const { gainWith, coverOf } = book;
29
+ if (!conceded.size)
30
+ return;
31
+ const holding = (x) => mineSet.has(x) || captured.has(x);
32
+ /** The positive bonuses taking `t` completes, and those it advances (another member already mine or captured). */
33
+ const stepOf = (t) => {
34
+ const completes = [];
35
+ const advances = [];
36
+ for (const b of g.map.bonuses) {
37
+ if (b.value <= 0)
38
+ continue;
39
+ const ts = bonusTerritories(g, b.id);
40
+ if (!ts.includes(t) || ts.every((x) => mineSet.has(x)))
41
+ continue;
42
+ if (ts.every((x) => x === t || holding(x)))
43
+ completes.push(b.id);
44
+ else if (ts.some((x) => x !== t && holding(x)))
45
+ advances.push(b.id);
46
+ }
47
+ return { completes, advances };
48
+ };
49
+ const tried = new Set();
50
+ for (;;) {
51
+ const cands = [];
52
+ for (const x of [...conceded].sort(byNum)) {
53
+ if (!mineSet.has(x) || myCommanders.has(x))
54
+ continue;
55
+ // #272 review: what tryCapture's forced source may spend: a covered exit (#179) keeps its cover
56
+ // (No-Split sends the whole stack).
57
+ const n = (avail.get(x) ?? 0) - (noSplit ? 0 : coverOf(x));
58
+ if (n <= 0)
59
+ continue;
60
+ for (const t of neighborsOf(g, x)) {
61
+ if (mineSet.has(t) || captured.has(t) || spared.has(t) || tried.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
+ if (st.owner.kind === 'player' && (goal === 'expand' || !foe(st.owner.playerId)))
67
+ continue;
68
+ if (st.owner.kind !== 'player' && st.owner.kind !== 'neutral')
69
+ continue;
70
+ if (defenceAt(t) > CONCEDED_OUT_MAX)
71
+ continue;
72
+ const cost = costAt(t);
73
+ // What the capture must send (#272 review: what tryCapture sends, the target's cost): a repulsed
74
+ // territory's size (#240) or a lead step's sure size (#203) may be more than the plain cost.
75
+ // Never more than the border's own armies: a conceded border gets no deploy.
76
+ if (cost === null || Math.max(tgt.sizeOf(t, cost), targets.get(t)?.cost ?? cost) > n || gainWith([t]) < 0)
77
+ continue;
78
+ const { completes, advances } = stepOf(t);
79
+ // No-Split: the whole stack goes, none withdraws — only for a completion.
80
+ const ids = completes.length ? completes : noSplit ? [] : advances;
81
+ if (!ids.length)
82
+ continue;
83
+ const best = ids.map((id) => g.bonusById.get(id)).sort((a, b) => b.value - a.value || a.id - b.id)[0];
84
+ // PLAN-TEAMS C3.4: a player my teammate attacks this turn ranks above an equal capture.
85
+ const focus = st.owner.kind === 'player' && pc.teamFocus.has(st.owner.playerId);
86
+ cands.push({ t, from: x, cost, bonus: best.id, value: best.value, completes: completes.length > 0, focus });
87
+ }
88
+ }
89
+ if (!cands.length)
90
+ return;
91
+ cands.sort((a, b) => Number(b.completes) - Number(a.completes) ||
92
+ b.value - a.value ||
93
+ a.cost - b.cost ||
94
+ Number(b.focus) - Number(a.focus) ||
95
+ (avail.get(b.from) ?? 0) - (avail.get(a.from) ?? 0) ||
96
+ a.t - b.t ||
97
+ a.from - b.from);
98
+ const c = cands[0];
99
+ tried.add(c.t);
100
+ const owner = (t) => {
101
+ const o = state.get(t).owner;
102
+ return o.kind === 'player' ? o.playerId : undefined;
103
+ };
104
+ /** PLAN-TEAMS C3.4: the candidate the focus put this one above, when only the focus decided. */
105
+ const passed = c.focus ? cands.find((d) => !d.focus && d.completes === c.completes && d.value === c.value && d.cost === c.cost) : undefined;
106
+ const st = state.get(c.t);
107
+ const added = !targets.has(c.t);
108
+ if (added)
109
+ targets.set(c.t, { id: c.t, cost: c.cost, enemy: st.owner.kind === 'player', sources: [c.from] });
110
+ const reason = `${c.completes ? 'completes' : 'advances'} bonus ${bonusName(c.bonus)} (+${c.value}) out of conceded ${label(c.from)}, with armies that would otherwise withdraw (#272)`;
111
+ caps.r3Exempt.add(c.t);
112
+ const ok = caps.tryCapture(c.t, reason, { from: c.from, keep: 0 });
113
+ if (!ok) {
114
+ caps.r3Exempt.delete(c.t);
115
+ if (added)
116
+ targets.delete(c.t);
117
+ continue;
118
+ }
119
+ // What the attack sends (a repulsed territory's sure size may be more than its plain cost, #240).
120
+ const sent = ps.moves.filter((m) => m.kind === 'attack' && m.from === c.from && m.to === c.t).reduce((n, m) => n + m.armies, 0);
121
+ // #272 review: rule 1b withdraws only into a neighbour of mine that is not conceded; with none, the
122
+ // armies would have stayed, and the attack thins the border instead.
123
+ const canWithdraw = neighborsOf(g, c.from).some((x) => mineSet.has(x) && !conceded.has(x));
124
+ const verb = `${c.completes ? 'completing' : 'advancing'} bonus ${bonusName(c.bonus)} (+${c.value}) (#272)`;
125
+ rationale.push(canWithdraw
126
+ ? `Attack out of conceded ${label(c.from)} before withdrawing: ${label(c.t)} holds ${defenceAt(c.t)}, and ${sent} of the armies leaving the border anyway take it, ${verb}.`
127
+ : `Attack out of conceded ${label(c.from)}: ${label(c.t)} holds ${defenceAt(c.t)}, and ${sent} of its armies take it, ${verb}; it has nowhere to withdraw to, so they leave a border that keeps the rest.`);
128
+ if (passed)
129
+ rationale.push(teamFocusLine(pc, { kind: 'capture', id: c.t, target: c.t, owner: owner(c.t) }, { kind: 'capture', id: passed.t, target: passed.t, ...(owner(passed.t) !== undefined ? { owner: owner(passed.t) } : {}) }));
130
+ }
131
+ }