@chrischall/warapp-mcp 0.5.0 → 0.6.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 (80) hide show
  1. package/.claude-plugin/marketplace.json +3 -3
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +37 -5
  4. package/dist/analysis/card-support.js +2 -1
  5. package/dist/analysis/card-threats.js +59 -12
  6. package/dist/analysis/game-lessons.js +3 -4
  7. package/dist/analysis/hold-diff.js +3 -1
  8. package/dist/analysis/income-trend.js +38 -0
  9. package/dist/analysis/intel.js +75 -0
  10. package/dist/analysis/opens.js +64 -0
  11. package/dist/analysis/opponent-profile.js +75 -7
  12. package/dist/analysis/opponents.js +2 -2
  13. package/dist/analysis/outlook.js +39 -0
  14. package/dist/analysis/picks.js +91 -12
  15. package/dist/analysis/plan/bonus-attempts.js +105 -0
  16. package/dist/analysis/plan/capture-instead.js +116 -0
  17. package/dist/analysis/plan/captures.js +45 -4
  18. package/dist/analysis/plan/conceded-out.js +13 -2
  19. package/dist/analysis/plan/estimates.js +135 -26
  20. package/dist/analysis/plan/holds.js +31 -3
  21. package/dist/analysis/plan/jabs.js +113 -0
  22. package/dist/analysis/plan/leftover.js +249 -4
  23. package/dist/analysis/plan/orders.js +76 -4
  24. package/dist/analysis/plan/relations.js +21 -1
  25. package/dist/analysis/plan/report.js +69 -3
  26. package/dist/analysis/plan/second-sizing.js +133 -0
  27. package/dist/analysis/plan/shared.js +82 -20
  28. package/dist/analysis/plan/siege.js +303 -0
  29. package/dist/analysis/plan/stand-still.js +7 -3
  30. package/dist/analysis/plan/state.js +8 -0
  31. package/dist/analysis/plan/strike.js +10 -5
  32. package/dist/analysis/plan/targets.js +91 -60
  33. package/dist/analysis/plan/threats.js +41 -6
  34. package/dist/analysis/plan/transfers.js +46 -6
  35. package/dist/analysis/planner.js +234 -16
  36. package/dist/analysis/profile.js +13 -2
  37. package/dist/analysis/stress.js +8 -2
  38. package/dist/bonus-attempt-store.js +55 -0
  39. package/dist/bundle.js +47965 -39683
  40. package/dist/cards.js +7 -5
  41. package/dist/chat.js +35 -1
  42. package/dist/commerce.js +111 -0
  43. package/dist/index.js +9 -1
  44. package/dist/live.js +43 -0
  45. package/dist/move-order.js +64 -3
  46. package/dist/normalize.js +17 -0
  47. package/dist/profile-store.js +12 -2
  48. package/dist/protocol/methods.js +60 -5
  49. package/dist/protocol/rpc.js +8 -0
  50. package/dist/relations-store.js +38 -4
  51. package/dist/siege-store.js +49 -0
  52. package/dist/state-bundle.js +525 -0
  53. package/dist/state-cli.js +69 -0
  54. package/dist/team-cards.js +25 -0
  55. package/dist/tools/award.js +15 -1
  56. package/dist/tools/card-advice.js +16 -5
  57. package/dist/tools/card-plays.js +2 -2
  58. package/dist/tools/card-support-advice.js +2 -1
  59. package/dist/tools/chat-inbox.js +4 -0
  60. package/dist/tools/chat.js +65 -6
  61. package/dist/tools/check-plan.js +54 -10
  62. package/dist/tools/commerce-deploy.js +33 -0
  63. package/dist/tools/common.js +31 -0
  64. package/dist/tools/end-of-game.js +5 -3
  65. package/dist/tools/index.js +7 -0
  66. package/dist/tools/picks.js +12 -0
  67. package/dist/tools/profile-opponents.js +2 -0
  68. package/dist/tools/relations.js +137 -0
  69. package/dist/tools/state.js +227 -0
  70. package/dist/tools/stress-opponents.js +5 -2
  71. package/dist/tools/survival.js +11 -3
  72. package/dist/tools/team-brief.js +2 -2
  73. package/dist/tools/team.js +12 -3
  74. package/dist/tools/turn.js +332 -60
  75. package/dist/version.js +1 -1
  76. package/manifest.json +10 -2
  77. package/mint.yaml +14 -4
  78. package/package.json +4 -4
  79. package/server.json +2 -2
  80. package/skills/warapp-mcp/SKILL.md +31 -9
@@ -4,6 +4,7 @@
4
4
  // 4c(c), rule 4d's frontier budget). planPass runs the passes, the strikes and pass 3 with them.
5
5
  import { bonusTerritories } from '../bonuses.js';
6
6
  import { armiesToTake, straightKills } from '../combat.js';
7
+ import { neighborsOf } from '../graph.js';
7
8
  import { captureCost } from './shared.js';
8
9
  import { byNum } from './util.js';
9
10
  import { denialLine, emptyEnemyLine } from './vacated.js';
@@ -1027,11 +1028,43 @@ export function bonusPasses(pc, ps, book, hd, tgt, prev) {
1027
1028
  const denied = new Map();
1028
1029
  /** The start of rule 4d's rationale line for a stopped `t` (one per attempt that differed). */
1029
1030
  const stoppedLine = (t) => `Do not take ${label(t)}: it adds a border facing an enemy without completing a bonus,`;
1031
+ /**
1032
+ * #297: in a 1v1, the gate budget's veto: a capture of `t` that opens another border facing the opponent (a gate,
1033
+ * each sized for its stack plus the whole floating deploy) is stopped when the frontier would then need more next
1034
+ * turn than the next income, and more than it needs without that capture. Its rationale line, else `null`. Rule
1035
+ * 4d runs it in a 1v1 in place of its start-of-turn escape, and rule 4e's contact fallback runs it where rule 4d is
1036
+ * only a cost (#114): a gate the income cannot hold is lost next turn, armies and all.
1037
+ */
1038
+ const gateStop = (t) => {
1039
+ if (pc.profile.format !== '1v1' || !guarded || inFocus(t))
1040
+ return null;
1041
+ const held = heldNow();
1042
+ if (completedBy(held).some((id) => g.bonusById.get(id).value > 0 && bonusTs.get(id).includes(t)))
1043
+ return null;
1044
+ const stays = (x) => (mineSet.has(x) ? stayAt(x) : (survivorsAt.get(x) ?? 0));
1045
+ const without = new Set([...held].filter((x) => x !== t));
1046
+ if (frontierDelta(without, [t], stays).enemy <= 0)
1047
+ return null;
1048
+ const f = frontierOf(held, stays);
1049
+ const next = keptIncome(held);
1050
+ if (f.holdCost <= next || f.holdCost <= frontierOf(without, stays).holdCost)
1051
+ return null;
1052
+ if (!stopped.some((x) => x.t === t))
1053
+ stopped.push({ t, holdCost: f.holdCost, income: next });
1054
+ return `${stoppedLine(t)} and in this 1v1 it opens another gate${gateFoe(t)}: the gates would then need ${f.holdCost} next turn against its one floating deploy, more than the next income of ${next} (#297).`;
1055
+ };
1056
+ /** #297: " facing player P" for the opponent beside `t` (in a 1v1, the one opponent), else nothing. */
1057
+ const gateFoe = (t) => {
1058
+ const o = neighborsOf(g, t)
1059
+ .map((n) => state.get(n)?.owner)
1060
+ .find((x) => x?.kind === 'player' && pc.foe(x.playerId));
1061
+ return o?.kind === 'player' ? ` facing player ${o.playerId}` : '';
1062
+ };
1030
1063
  /**
1031
1064
  * Rule 4d's frontier budget, judged with `t` just captured: under a guarded goal, a capture
1032
1065
  * that adds a border facing an enemy without completing a bonus (and not focused) is stopped
1033
1066
  * when holding the frontier next turn would then need more than the next income, and more than
1034
- * it needed at the start of the turn. Returns the rationale line when stopped, else `null`.
1067
+ * it needed at the start of the turn (in a 1v1, more than without it: {@link gateStop}, #297). Returns the rationale line when stopped, else `null`.
1035
1068
  */
1036
1069
  const outgrows = (t) => {
1037
1070
  if (!guarded || inFocus(t))
@@ -1046,7 +1079,12 @@ export function bonusPasses(pc, ps, book, hd, tgt, prev) {
1046
1079
  const f = frontierOf(held, stays);
1047
1080
  const next = keptIncome(held);
1048
1081
  const start = startHold();
1049
- if (f.holdCost <= next || f.holdCost <= start)
1082
+ if (f.holdCost <= next)
1083
+ return null;
1084
+ // #297: in a 1v1 the start-of-turn hold is no excuse — a capture that opens another gate the next income
1085
+ // cannot hold is stopped even when this turn's other orders bring the total back under where it started.
1086
+ const gate = pc.profile.format === '1v1' ? gateStop(t) : null;
1087
+ if (f.holdCost <= start && !gate)
1050
1088
  return null;
1051
1089
  // #281: land a static seat left, which a live stack beside it takes free next turn: the border
1052
1090
  // comes either way, so the hold cost alone never refuses it (the capture still spends only what
@@ -1063,7 +1101,10 @@ export function bonusPasses(pc, ps, book, hd, tgt, prev) {
1063
1101
  denied.set(t, emptyEnemyLine(pc, t, e));
1064
1102
  return null;
1065
1103
  }
1066
- const why = `${stoppedLine(t)} and the frontier would then need ${f.holdCost} next turn to hold (${f.enemyBorders} enemy-facing borders), more than the next income of ${next} and more than the ${start} it needed at the start of the turn.`;
1104
+ // Only the 1v1 gate budget stops it (rule 4d's start-of-turn escape would have let it through): its own line.
1105
+ if (gate && f.holdCost <= start)
1106
+ return gate;
1107
+ const why = `${stoppedLine(t)} and the frontier would then need ${f.holdCost} next turn to hold (${f.enemyBorders} enemy-facing borders), more than the next income of ${next} and more than the ${start} it needed at the start of the turn.${gate ? ` In this 1v1 that is another gate${gateFoe(t)} (#297).` : ''}`;
1067
1108
  if (!stopped.some((x) => x.t === t))
1068
1109
  stopped.push({ t, holdCost: f.holdCost, income: next });
1069
1110
  return why;
@@ -1191,5 +1232,5 @@ export function bonusPasses(pc, ps, book, hd, tgt, prev) {
1191
1232
  if (closest)
1192
1233
  run(todo.filter((t) => leadSteps.has(t) && !captured.has(t)), true);
1193
1234
  };
1194
- return { snapshot, complete, unstaged, stage, stopped, stoppedLine, denied, outgrows, tryExpand, advance };
1235
+ return { snapshot, complete, unstaged, stage, stopped, stoppedLine, denied, outgrows, gateStop, tryExpand, advance };
1195
1236
  }
@@ -46,11 +46,22 @@ export function attackOutOfConceded(pc, ps, book, hd, tgt, caps) {
46
46
  }
47
47
  return { completes, advances };
48
48
  };
49
+ /**
50
+ * #286: rule 1c keeps `x` — a positive bonus containing it is completed by this turn's captures —
51
+ * so its armies would not withdraw: they are its garrison, not a free step. Live, a +2 member
52
+ * attacked out with 3 into an uneconomic bonus, was kept, and ended 1 army short of its hold.
53
+ */
54
+ const keptBy1c = (x) => g.map.bonuses.some((b) => {
55
+ if (b.value <= 0)
56
+ return false;
57
+ const ts = bonusTerritories(g, b.id);
58
+ return ts.includes(x) && ts.every(holding) && !ts.every((y) => mineSet.has(y));
59
+ });
49
60
  const tried = new Set();
50
61
  for (;;) {
51
62
  const cands = [];
52
63
  for (const x of [...conceded].sort(byNum)) {
53
- if (!mineSet.has(x) || myCommanders.has(x))
64
+ if (!mineSet.has(x) || myCommanders.has(x) || keptBy1c(x))
54
65
  continue;
55
66
  // #272 review: what tryCapture's forced source may spend: a covered exit (#179) keeps its cover
56
67
  // (No-Split sends the whole stack).
@@ -58,7 +69,7 @@ export function attackOutOfConceded(pc, ps, book, hd, tgt, caps) {
58
69
  if (n <= 0)
59
70
  continue;
60
71
  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))
72
+ if (mineSet.has(t) || captured.has(t) || spared.has(t) || tried.has(t) || pc.truce.noTarget(t) || tgt.droppedMembers.has(t))
62
73
  continue;
63
74
  const st = state.get(t);
64
75
  if (!st || st.armies === null || uncounted(t) || unitsAt(t) > 0)
@@ -1,9 +1,18 @@
1
+ // The estimates phase of a planning pass (#133): everything planTurn derives from its input before
2
+ // the first order — the opponents' deploy estimates and the fog prior (#119), the game profile and
3
+ // the goal it picks (rule 0p), the combat model and capture costs (S2, #126), what the board's
4
+ // territories are worth (#70, #85, #125), where I stand on armies (#167, #201, rule 0p.3) — and the
5
+ // rationale and warnings that state them. Pure: it reads the input and writes only
6
+ // `state.warnings` / `state.rationale`.
7
+ import { siegeFit, siegeOf } from './siege.js';
8
+ import { armiesForGold } from '../../commerce.js';
1
9
  import { holdsSeat } from '../../player-states.js';
2
10
  import { isTeamGame, teammatesOf } from '../../teams.js';
3
11
  import { bonusTerritories } from '../bonuses.js';
4
12
  import { CHAIN_MAX_STEPS } from '../chains.js';
5
13
  import { armiesForChance, armiesToTake, DEFAULT_DEFENSIVE_KILL_RATE, DEFAULT_OFFENSIVE_KILL_RATE, luckFraction, specialUnitStrength, straightKills, winChance, } from '../combat.js';
6
14
  import { neighborsOf } from '../graph.js';
15
+ import { incomeTrend } from '../income-trend.js';
7
16
  import { OUTLOOK_TURNS } from '../outlook.js';
8
17
  import { boardIncome, DEFAULT_BASE_INCOME } from '../player.js';
9
18
  import { AHEAD_PRESSURE_FACTOR, captureCost, combatSettings, DECIDED_PAYBACK_MIN, defaultMinWinChance, enemyDeployEstimates, HOLD_FALL_CHANCE, LUCK_WIN_CHANCE, MIN_ENEMY_DEPLOY, minWinChanceOf, ownerShown, PAYBACK_TURNS, PRESSURE_FACTOR, pressureMargin, SECOND_FRONT_LEAD, visibleState, } from './shared.js';
@@ -16,14 +25,16 @@ import { neutralizeSeats, staticSeats } from '../static-seats.js';
16
25
  import { commanderPlace } from './commander.js';
17
26
  /**
18
27
  * The fog prior to apply (#119, {@link EnemyIncomePrior}): only when the game says the start was
19
- * symmetric (`symmetricStart`), with no teams, and every seated player still playing — a 1v1 (one
20
- * opponent), or (#226) a free-for-all, where every opponent beside the fog gets the same prior. A
21
- * game with a player out (eliminated, booted, surrendered) gets none: a survivor may have absorbed
22
- * its territories, or I may have, so the start no longer says who earns what. Without a player list,
23
- * only one opponent in sight counts (a 1v1 as far as the board tells). #235: in a free-for-all with
24
- * no teams (two or more opponents seated) that gets none, `skipped` says why.
28
+ * symmetric (`symmetricStart`), with no teams — a 1v1 (one opponent), or (#226) a free-for-all, where
29
+ * every opponent beside the fog gets the same prior. #368: a player out (eliminated, booted,
30
+ * surrendered) whose seat no AI plays (`seats`, #270) no longer turns it off: its share of what the
31
+ * board hides goes to the opponents still playing (`opponents` counts them, `out` names it), so the
32
+ * prior is still at least my income, capped at an even share among the survivors. A seat an AI plays
33
+ * is an opponent like any other. Without a player list, only one opponent in sight counts (a 1v1 as
34
+ * far as the board tells). #235: in a free-for-all with no teams (two or more opponents seated) that
35
+ * gets none, `skipped` says why.
25
36
  */
26
- function fogPrior(board, me, ctx, myIncome) {
37
+ function fogPrior(board, me, ctx, myIncome, seats = new Map()) {
27
38
  const players = (ctx.players ?? []).filter((p) => holdsSeat(p.state));
28
39
  if (isTeamGame(players))
29
40
  return { prior: undefined };
@@ -31,18 +42,21 @@ function fogPrior(board, me, ctx, myIncome) {
31
42
  const why = (reason) => ({ prior: undefined, ...(ffa ? { skipped: reason } : {}) });
32
43
  if (ctx.symmetricStart !== true)
33
44
  return why(ctx.unevenStart ?? 'the game does not say every player started even');
34
- const out = players.filter((p) => (p.state ?? 'Playing') !== 'Playing' && p.id !== me).sort((a, b) => a.id - b.id);
35
- if (out.length)
36
- return why(`${out.map((p) => `player ${p.id} is out (${p.state})`).join(', ')}, and a survivor may have absorbed its territories, so the start no longer says who earns what`);
45
+ // #368: the players out whose seats stand still; their share is split among the rest.
46
+ const out = players
47
+ .filter((p) => p.id !== me && seats.has(p.id))
48
+ .sort((a, b) => a.id - b.id)
49
+ .map((p) => ({ id: p.id, state: p.state ?? 'Playing' }));
37
50
  const opponents = players.length
38
- ? players.filter((p) => p.id !== me).length
51
+ ? players.filter((p) => p.id !== me && !seats.has(p.id)).length
39
52
  : new Set(board.territories.flatMap((t) => (t.owner.kind === 'player' && t.owner.playerId !== me ? [t.owner.playerId] : []))).size;
40
53
  if (opponents < 1 || (!players.length && opponents !== 1))
41
54
  return { prior: undefined };
42
55
  return {
43
56
  prior: {
44
57
  myIncome: Math.max(0, myIncome),
45
- ...(opponents > 1 ? { format: 'ffa', opponents } : {}),
58
+ ...(opponents > 1 || out.length ? { format: 'ffa', opponents } : {}),
59
+ ...(out.length ? { out } : {}),
46
60
  ...(ctx.opening ? { opening: ctx.opening } : {}),
47
61
  },
48
62
  };
@@ -70,7 +84,7 @@ export function planEnemyEstimates(input) {
70
84
  const previousBoard = input.previousBoard ? neutralizeSeats(input.previousBoard, seats) : undefined;
71
85
  const tracks = input.tracks?.filter((t) => !seats.has(t.playerId));
72
86
  const capCut = input.incomeCap ? Math.max(0, Math.floor(input.incomeCap.uncapped - input.incomeCap.received)) : 0;
73
- const { prior, skipped } = fogPrior(board, input.me, ctx, input.income + capCut);
87
+ const { prior, skipped } = fogPrior(board, input.me, ctx, input.income + capCut, seats);
74
88
  const turn = input.turn ?? ctx.turn ?? null;
75
89
  const estimates = enemyDeployEstimates(input.graph, board, input.me, input.settings ?? {}, previousBoard, tracks, prior, {
76
90
  turn,
@@ -78,7 +92,41 @@ export function planEnemyEstimates(input) {
78
92
  reinforcement: ctx.reinforcement,
79
93
  ...(previousBoard && input.previousOrders ? { previousOrders: input.previousOrders } : {}),
80
94
  });
81
- return { estimates: applySanctions(estimates, input.sanctions ?? []), prior, ...(skipped ? { priorSkipped: skipped } : {}) };
95
+ const priced = applyKnown(applyArmyPrice(applySanctions(estimates, input.sanctions ?? []), input.settings?.armyCostMultiplier ?? 0), input.known ?? []);
96
+ return { estimates: priced, prior, ...(skipped ? { priorSkipped: skipped } : {}) };
97
+ }
98
+ /**
99
+ * #368: each estimate whose player the user gave a known income for (what it said in chat, say): that
100
+ * income replaces the estimate's, whatever its source; a Reinforcement card the clock adds stays on top.
101
+ * `known` keeps the income given and the one it replaced (`was`, card left out). Unchanged without.
102
+ */
103
+ export function applyKnown(estimates, known) {
104
+ if (!known.length)
105
+ return estimates;
106
+ const by = new Map(known.map((k) => [k.player, Math.max(0, Math.floor(k.income))]));
107
+ return estimates.map((e) => {
108
+ const income = by.get(e.playerId);
109
+ if (income === undefined)
110
+ return e;
111
+ const card = e.card?.armies ?? 0;
112
+ return { ...e, estimate: income + card, known: { income, was: e.estimate - card } };
113
+ });
114
+ }
115
+ /**
116
+ * #332: in a commerce game with a rising army price (multiplier m > 0), what each estimate read off the board
117
+ * (`visible`, `exact`: its base and bonuses, in gold) buys in armies, its Reinforcement card's armies kept on top.
118
+ * An observed, tracked or prior figure is already armies and is left as it is. Unchanged with m = 0.
119
+ */
120
+ export function applyArmyPrice(estimates, m) {
121
+ if (!(m > 0))
122
+ return estimates;
123
+ return estimates.map((e) => {
124
+ if (e.source !== 'visible' && e.source !== 'exact')
125
+ return e;
126
+ const card = e.card?.armies ?? 0;
127
+ const gold = e.estimate - card;
128
+ return { ...e, estimate: armiesForGold(gold, m) + card, armyPrice: { gold, multiplier: m } };
129
+ });
82
130
  }
83
131
  /**
84
132
  * G2 (PLAN-TEAMS D3): each estimate under the Sanctions on its player. A figure read off the board
@@ -135,6 +183,8 @@ function opponentsCtx(input) {
135
183
  game: ctx,
136
184
  turn: turnNow,
137
185
  ...(input.sanctions?.length ? { sanctions: input.sanctions } : {}),
186
+ // #368: a what-if enemyDeploy sizes every opponent itself, so a known income is left out under it.
187
+ ...(input.knownIncome?.length && opts.enemyDeploy === undefined ? { known: input.knownIncome } : {}),
138
188
  });
139
189
  const estimateList = allEstimates.filter((e) => notAlly(e.playerId));
140
190
  /** An opponent's income: its deploy estimate less the Reinforcement card the clock adds (#164). */
@@ -181,16 +231,22 @@ function opponentsCtx(input) {
181
231
  const behind = auto && profile.standing === 'behind';
182
232
  /** Rule 0p.3 (#72): behind on income in a 1v1 — strike (stay balanced, break first), never defend. */
183
233
  const strike = behind && profile.format === '1v1';
184
- const goal = opts.goal ?? (behind && !strike ? 'defend' : 'balanced');
185
- const balanced = goal === 'balanced';
234
+ // #382: a siege plans as balanced; `siege` below carries what differs.
235
+ // (`let`: the profile's siege, below, replaces the goal it picked.)
236
+ let goal = opts.goal === 'siege' ? 'balanced' : (opts.goal ?? (behind && !strike ? 'defend' : 'balanced'));
237
+ let balanced = goal === 'balanced';
186
238
  /** Rule 0p.3: behind — size attacks at the minimum (no pressure margin). */
187
239
  const minimal = behind;
240
+ /** #303: my income over the last turns, this one (what I deploy, card armies out) last. */
241
+ const trendNow = turnNow !== null && input.incomeHistory?.length
242
+ ? incomeTrend(input.incomeHistory, { turn: turnNow, income: Math.max(0, income - Math.max(0, Math.floor(input.cardArmies ?? 0))) })
243
+ : undefined;
188
244
  /** Rule 0p.3: ahead in a 1v1 — pressure allowed at {@link AHEAD_PRESSURE_FACTOR}. */
189
245
  const pressureFactor = auto && profile.format === '1v1' && profile.standing === 'ahead' ? AHEAD_PRESSURE_FACTOR : PRESSURE_FACTOR;
190
246
  /** The pressure margin over an estimated deploy: none when sizing at the minimum. */
191
247
  const marginFor = (d) => (minimal ? 0 : pressureMargin(d));
192
248
  /** Goals that refuse to complete a bonus they cannot hold (R3); the others only warn. */
193
- const guarded = balanced || goal === 'defend';
249
+ let guarded = balanced || goal === 'defend';
194
250
  const focus = new Set(opts.focusBonusIds ?? []);
195
251
  const reserve = Math.min(income, Math.max(0, Math.floor(opts.reserve ?? 0)));
196
252
  const custom = opts.enemyDeploy !== undefined;
@@ -226,6 +282,48 @@ function opponentsCtx(input) {
226
282
  guardedByHeld.add(t);
227
283
  }
228
284
  const untrustedAt = (player, t) => (guardedByHeld.has(t) ? (untrusted.get(player) ?? 0) : 0);
285
+ // ---- #382: the siege (plan/siege.ts) ----
286
+ const siegeArgs = {
287
+ g,
288
+ state: new Map(board.territories.map((t) => [t.territoryId, t])),
289
+ mineAtStart,
290
+ foe,
291
+ incomeOfPlayer,
292
+ deployOf,
293
+ myIncome: Math.max(0, earnedIncome - Math.max(0, Math.floor(input.cardArmies ?? 0))),
294
+ tracks: input.tracks,
295
+ settings: s,
296
+ ...(input.turn !== undefined ? { turn: input.turn } : {}),
297
+ ...(input.siegeMemory ? { memory: input.siegeMemory } : {}),
298
+ };
299
+ const sieged = opts.goal === 'siege' ? siegeOf({ ...siegeArgs, target: opts.siegeTarget }) : undefined;
300
+ // #382 item 2: adapting with no goal, the profile picks the siege when it fits (siegeFit), and hands back
301
+ // once its assault trigger fires or the fit is gone.
302
+ let siege = sieged && 'siege' in sieged ? sieged.siege : undefined;
303
+ let siegeHandBack;
304
+ if (auto && opts.siegeAuto !== false && (profile.format === '1v1' || profile.format === 'ffa') && (profile.phase === 'contact' || profile.phase === 'late')) {
305
+ const c = siegeOf({ ...siegeArgs, target: undefined });
306
+ if ('siege' in c) {
307
+ const fit = siegeFit(c.siege, { format: profile.format, phase: profile.phase, standing: profile.standing, leader: profile.ranking?.commonThreat });
308
+ if (fit.fits) {
309
+ siege = { ...c.siege, auto: fit.fit };
310
+ // The siege wins over the profile's own goal (a `defend` it picked included): it plans as balanced.
311
+ goal = 'balanced';
312
+ balanced = true;
313
+ guarded = true;
314
+ }
315
+ else if (fit.handBack)
316
+ siegeHandBack = `A siege on player ${c.siege.target} would fit (#382), but its assault trigger has fired (${fit.handBack}): the profile hands back to its own goal for the assault.`;
317
+ }
318
+ }
319
+ // Until the trigger fires, no pass attacks the target's territories but its breakable bonuses' members.
320
+ const held = siege && !siege.ready ? siege : undefined;
321
+ const heldLand = new Set(held
322
+ ? board.territories.flatMap((t) => t.owner.kind === 'player' && t.owner.playerId === held.target && !held.breakMembers.has(t.territoryId) ? [t.territoryId] : [])
323
+ : []);
324
+ const truceNow = held
325
+ ? { ...truce, siegeHeld: (t) => heldLand.has(t), noTarget: (t) => truce.noTarget(t) || heldLand.has(t) }
326
+ : truce;
229
327
  /**
230
328
  * #201: the planning horizon. Once the outlook (#178) says the game is decided — winning or losing
231
329
  * for OUTLOOK_TURNS turns running — every payback test counts the turns the game has left instead
@@ -266,7 +364,7 @@ function opponentsCtx(input) {
266
364
  allies,
267
365
  foe,
268
366
  teamFocus: teamFocusOf(board, allies, foe),
269
- truce,
367
+ truce: truceNow,
270
368
  turnNow,
271
369
  incomePrior,
272
370
  incomePriorSkipped,
@@ -278,7 +376,11 @@ function opponentsCtx(input) {
278
376
  strike,
279
377
  goal,
280
378
  balanced,
379
+ ...(siege ? { siege } : {}),
380
+ ...(sieged && 'warning' in sieged ? { siegeWarning: sieged.warning } : {}),
381
+ ...(siegeHandBack ? { siegeHandBack } : {}),
281
382
  minimal,
383
+ ...(trendNow ? { incomeTrend: trendNow } : {}),
282
384
  pressureFactor,
283
385
  marginFor,
284
386
  guarded,
@@ -640,23 +742,30 @@ export function planContext(input) {
640
742
  * every plan, in this order.
641
743
  */
642
744
  export function noteEstimates(ctx, state) {
643
- const { board, s, opts, earnedIncome: income, estimateList, profile, auto, strike, goal, minimal, pressureFactor, decidedGame } = ctx;
745
+ const { board, s, opts, earnedIncome: income, estimateList, profile, auto, strike, minimal, pressureFactor, decidedGame, siege } = ctx;
644
746
  const { rates, minWin, exactCombat, bombOn, luck, weightedRounding, noSplit, armiesBehindVs } = ctx;
645
747
  const { warnings, rationale } = state;
646
748
  const profileText = `${profile.format}, ${profile.phase}, ${profile.standing}`;
647
749
  if (opts.adapt && opts.goal !== undefined) {
648
- rationale.push(`Goal ${goal} was given explicitly, so it overrides the game profile (${profileText}): none of the profile's rules apply.`);
750
+ // #385: under `siege` the planner runs as `balanced`, so name the goal the caller gave.
751
+ rationale.push(`Goal ${opts.goal} was given explicitly, so it overrides the game profile (${profileText}): none of the profile's rules apply.`);
649
752
  // Also a warning: live, a script that always passed `goal: balanced` switched the 1v1 rules
650
753
  // (strike stack, breaks before expansion) off for two whole games, and nobody noticed.
651
- warnings.push(`Goal ${goal} was given explicitly, so none of the game-profile rules for ${profile.format === 'ffa' ? 'an FFA' : profile.format === 'teams' ? 'a team game' : 'a 1v1'} apply this turn (standing ${profile.standing}): leave the goal out to let the profile choose it and apply them.`);
754
+ warnings.push(`Goal ${opts.goal} was given explicitly, so none of the game-profile rules for ${profile.format === 'ffa' ? 'an FFA' : profile.format === 'teams' ? 'a team game' : 'a 1v1'} apply this turn (standing ${profile.standing}): leave the goal out to let the profile choose it and apply them.`);
652
755
  }
653
756
  else if (auto) {
654
757
  const strongest = estimateList.reduce((m, e) => Math.max(m, e.estimate), 0);
655
- rationale.push(strike
656
- ? `Goal balanced from the game profile (${profileText}): behind on income (${income} against ~${strongest}) in a 1v1 — strike: break the opponent's bonuses with minimal attacks before expansion that completes nothing (holds of my own bonuses that pay for themselves still come first), sized at the minimum (no extra margin beyond what the rules require).`
657
- : minimal
658
- ? `Goal defend from the game profile (${profileText}): behind on income (${income} against ~${strongest}), so defend first and size attacks at the minimum (no extra margin beyond what the rules require).`
659
- : `Goal balanced from the game profile (${profileText}): the base goal.`);
758
+ // #287: a 1v1 can read behind on the armies in view alone; then the incomes are not why.
759
+ const behindWhy = income <= BEHIND_RATIO * strongest
760
+ ? `behind on income (${income} against ~${strongest})`
761
+ : `behind on the board, not on income (${income} against ~${strongest}: the standing says why)`;
762
+ rationale.push(siege?.auto
763
+ ? `Goal siege from the game profile (${profileText}): it plans as balanced against player ${siege.target}, its cheap bonus breaks first and its other territories held back until the assault trigger fires${minimal ? `; ${behindWhy}, attacks are sized at the minimum (no extra margin beyond what the rules require)` : ''}.`
764
+ : strike
765
+ ? `Goal balanced from the game profile (${profileText}): ${behindWhy} in a 1v1 — strike: break the opponent's bonuses with minimal attacks before expansion that completes nothing (holds of my own bonuses that pay for themselves still come first), sized at the minimum (no extra margin beyond what the rules require).`
766
+ : minimal
767
+ ? `Goal defend from the game profile (${profileText}): ${behindWhy}, so defend first and size attacks at the minimum (no extra margin beyond what the rules require).`
768
+ : `Goal balanced from the game profile (${profileText}): the base goal.`);
660
769
  if (pressureFactor !== PRESSURE_FACTOR)
661
770
  rationale.push(`Ahead in a 1v1 (${income} against ~${strongest}): keep attacking — pressure on an opponent next to the fog is allowed when each capture costs up to ${pressureFactor}× a typical neutral capture (instead of ${PRESSURE_FACTOR}×).`);
662
771
  }
@@ -8,6 +8,7 @@ import { bonusTerritories } from '../bonuses.js';
8
8
  import { bfsDistances, neighborsOf } from '../graph.js';
9
9
  import { chargeDeploys } from '../local-deploy.js';
10
10
  import { twoStepReaches } from '../lookahead.js';
11
+ import { opensBehind } from '../opens.js';
11
12
  import { BREACH_WEIGHT, CITE_CLOSE, CITE_OPEN, CITE_SEP, CONCEDE_FACTOR, nearMissMargin, } from './shared.js';
12
13
  import { capRoom, relaxedFor } from './relations.js';
13
14
  import { byNum } from './util.js';
@@ -264,7 +265,23 @@ export function twoStepHolds(pc, ps, book, threats, hb, pass, prev) {
264
265
  }
265
266
  return v;
266
267
  };
267
- const guardsTwoStep = (t) => myCommanders.has(t) || heldBonusValue(t) > 0;
268
+ /**
269
+ * #291: my `t` is the only way in to held bonuses (they are not its own): behind a conceded border it is the next
270
+ * gate, not interior, so it guards against a stack two steps away too. Judged on the start of the turn, as the
271
+ * reaches are (found once per plan).
272
+ */
273
+ const opensMemo = new Map();
274
+ const source = (x) => {
275
+ const o = state.get(x)?.owner;
276
+ return o === undefined || o.kind === 'unknown' || (o.kind === 'player' && foe(o.playerId));
277
+ };
278
+ const opensHeld = (t) => {
279
+ let v = opensMemo.get(t);
280
+ if (v === undefined)
281
+ opensMemo.set(t, (v = opensBehind(g, heldAtStart, source, t, new Set()).income > 0));
282
+ return v;
283
+ };
284
+ const guardsTwoStep = (t) => myCommanders.has(t) || heldBonusValue(t) > 0 || opensHeld(t);
268
285
  /**
269
286
  * Every two-step reach to a territory of mine worth guarding (lookahead.ts, as check_plan), by
270
287
  * territory: found once per {@link planTurn} (it depends only on the start board) and shared by
@@ -444,7 +461,7 @@ export function twoStepHolds(pc, ps, book, threats, hb, pass, prev) {
444
461
  export function holdOrConcede(pc, ps, book, threats, hb, prev) {
445
462
  const { goal, paybackTurns, label, unitsAt, bombOn, toTake, myCommanders } = pc;
446
463
  const { warnings, rationale, locked } = ps;
447
- const { deploy, valueOf, stakeAt, cutOff, breachAt } = book;
464
+ const { deploy, valueOf, stakeAt, cutOff, breachAt, opensAt } = book;
448
465
  const { borders, recentlyTakenFrom } = threats;
449
466
  const { threatened, conceded } = hb;
450
467
  const { stayAt } = prev;
@@ -456,6 +473,8 @@ export function holdOrConcede(pc, ps, book, threats, hb, prev) {
456
473
  const cutNoted = new Set();
457
474
  /** #275: the borders whose breach is already named. */
458
475
  const breachNoted = new Set();
476
+ /** #291: the gates whose opened value is already named. */
477
+ const opensNoted = new Set();
459
478
  /** Rule 1a's pre-deploy threat warning per border, restated once the deploys are known. */
460
479
  const threatWarnings = new Map();
461
480
  const assessThreats = () => {
@@ -493,6 +512,14 @@ export function holdOrConcede(pc, ps, book, threats, hb, prev) {
493
512
  const more = breach.ids.length > MAX_CUT_NAMED ? ` and ${breach.ids.length - MAX_CUT_NAMED} more` : '';
494
513
  rationale.push(`${label(b.id)} alone shields ${named}${more} within two moves behind it (+${breach.income} income): with the guard off a breach walks straight in, so its value counts ${BREACH_WEIGHT * 100}% of that (+${breach.worth}) (#275).`);
495
514
  }
515
+ // #291: a gate whose loss opens held bonuses to the enemy says so.
516
+ const opens = opensAt(b.id);
517
+ if (opens && !opensNoted.has(b.id)) {
518
+ opensNoted.add(b.id);
519
+ const named = opens.ids.slice(0, MAX_CUT_NAMED).map(label).join(', ');
520
+ const more = opens.ids.length > MAX_CUT_NAMED ? ` and ${opens.ids.length - MAX_CUT_NAMED} more` : '';
521
+ rationale.push(`${label(b.id)} is the only way in to ${named}${more} (+${opens.income} income): losing it opens them to the enemy, so its value counts half of that (+${opens.worth}) (#291).`);
522
+ }
496
523
  const from = recentlyTakenFrom(b.id);
497
524
  threatened.push({
498
525
  id: b.id,
@@ -1512,7 +1539,7 @@ export function withdrawals(pc, ps, book, threats, hb, prev) {
1512
1539
  export function reconsiderAndGarrison(pc, ps, book, threats, hb, prev) {
1513
1540
  const { g, guarded, reserve, paybackTurns, label, bonusName, mine, mineSet, unitsAt, toTake, myCommanders } = pc;
1514
1541
  const { warnings, rationale, deployed, locked, captured, moves } = ps;
1515
- const { orderOf, deploy, pools, valueCache, cutCache, breachCache, valueOf } = book;
1542
+ const { orderOf, deploy, pools, valueCache, cutCache, breachCache, opensCache, valueOf } = book;
1516
1543
  const local = pools !== null && pools.bonuses.length > 0;
1517
1544
  const { borders } = threats;
1518
1545
  const { conceded, kept, garrisoned } = hb;
@@ -1529,6 +1556,7 @@ export function reconsiderAndGarrison(pc, ps, book, threats, hb, prev) {
1529
1556
  valueCache.clear();
1530
1557
  cutCache.clear();
1531
1558
  breachCache.clear();
1559
+ opensCache.clear();
1532
1560
  if (!conceded.size)
1533
1561
  return;
1534
1562
  for (const t of [...conceded].sort(byNum)) {
@@ -0,0 +1,113 @@
1
+ // Single-army jabs (#361). At 0% luck under straight rounding one attacking army kills
2
+ // round(1 × the offensive kill rate) defenders: at a 60% rate that is 1 (seen live: 75 → 74, 19 → 18),
3
+ // and the defenders kill it back. A one-for-one trade, the best rate an attack gets under these rules
4
+ // (10 attackers kill only 6). It captures nothing and earns no card piece, so its only use is
5
+ // attrition, and attrition pays only against an opponent I out-earn or out-army.
6
+ //
7
+ // Once every other order is sized (after the #226 margin), the armies still idle on a territory of
8
+ // mine beyond what holds it (`spareBeyondHold`: never a hold's own armies, a conceded border's or my
9
+ // commander's; never a step's saving source, where rule 5's leftover went to stay, or the strike stack
10
+ // but for a siege's break member) jab enemy stacks beside it, one army each, at most one jab per enemy stack, filler orders:
11
+ // 1. the siege target's breakable bonus members (#382), its cheapest break first: each jab is one
12
+ // defender fewer for next turn's break;
13
+ // 2. a member of a bonus an opponent holds in full in view (wearing down a bonus edge);
14
+ // 3. any other stack of an opponent I out-earn or out-army.
15
+ // On under `goal: 'siege'`, opt-in otherwise (`PlanOptions.jabs`), until measured further (#361).
16
+ // Never a territory another order of this plan attacks, a truce's or the held siege's (`noTarget`), a
17
+ // #240 repulsed one, a
18
+ // territory with a special unit, or a stack of fewer than 2 (a lone defender and the jab destroy
19
+ // each other and the territory keeps one: nothing traded).
20
+ import { straightKills } from '../combat.js';
21
+ import { neighborsOf } from '../graph.js';
22
+ import { breakableBonuses } from './siege.js';
23
+ /** Whether jabs trade one for one in this game: 0% luck, straight rounding, a lone army kills one. */
24
+ export function jabsTrade(pc) {
25
+ return pc.luck === 0 && !pc.weightedRounding && straightKills(1, pc.rates.offensiveKillRate) >= 1;
26
+ }
27
+ /**
28
+ * Plans the jabs and adds them to `ps.moves` (1 army, `winChance` 0), spending `spare` (the armies a
29
+ * source has beyond its hold; read once per source, then counted down here). `skip`: sources kept
30
+ * whole (the strike stack, a step's saving source); `strike`, the strike stack, jabs only the siege
31
+ * target's break members (a siege's stack grows or breaks, #382). `refused`: targets no jab goes to (#240's repulsed
32
+ * ones, attacked only at their sure size).
33
+ */
34
+ export function planJabs(pc, ps, spare, skip, refused = () => false, strike) {
35
+ const { g, territories: state, label, mineSet, foe, noSplit, unitsAt, defenceAt } = pc;
36
+ const { moves, avail, captured, rationale } = ps;
37
+ if (noSplit || !jabsTrade(pc))
38
+ return [];
39
+ const kills = straightKills(1, pc.rates.offensiveKillRate);
40
+ // Who the trade favours: an opponent I out-earn, or whose armies in view are fewer than mine.
41
+ const armiesOf = new Map();
42
+ let myArmies = 0;
43
+ for (const st of state.values()) {
44
+ if (st.owner.kind !== 'player' || st.armies === null)
45
+ continue;
46
+ if (mineSet.has(st.territoryId))
47
+ myArmies += st.armies;
48
+ else
49
+ armiesOf.set(st.owner.playerId, (armiesOf.get(st.owner.playerId) ?? 0) + st.armies);
50
+ }
51
+ const favours = (p) => pc.income > pc.incomeOfPlayer(p) || myArmies > (armiesOf.get(p) ?? 0);
52
+ const siegeRank = new Map();
53
+ if (pc.siege)
54
+ pc.siege.breaks.forEach((b, i) => {
55
+ for (const t of pc.bonusTs.get(b.bonusId) ?? [])
56
+ if (!siegeRank.has(t))
57
+ siegeRank.set(t, i);
58
+ });
59
+ const edge = new Set(breakableBonuses(g, state, foe, undefined)
60
+ .filter((b) => !b.probable)
61
+ .flatMap((b) => pc.bonusTs.get(b.bonusId) ?? []));
62
+ const attacked = new Set(moves.filter((m) => m.kind === 'attack').map((m) => m.to));
63
+ const left = new Map();
64
+ const spareAt = (x) => {
65
+ if (!left.has(x))
66
+ left.set(x, (skip.has(x) && x !== strike) || ps.leftoverKept.has(x) ? 0 : Math.max(0, spare(x)));
67
+ return left.get(x);
68
+ };
69
+ const cands = [];
70
+ for (const [t, st] of state) {
71
+ if (st.owner.kind !== 'player' || st.armies === null || mineSet.has(t))
72
+ continue;
73
+ const p = st.owner.playerId;
74
+ if (!foe(p) || attacked.has(t) || captured.has(t) || refused(t) || pc.truce.noTarget(t) || unitsAt(t) > 0)
75
+ continue;
76
+ const d = defenceAt(t);
77
+ if (d < 2 || !neighborsOf(g, t).some((n) => mineSet.has(n)))
78
+ continue;
79
+ const why = siegeRank.has(t) && pc.siege?.target === p ? 'siege-break' : edge.has(t) ? 'bonus-edge' : 'attrition';
80
+ if (why !== 'siege-break' && !favours(p))
81
+ continue;
82
+ // Before its trigger a siege attacks nothing of its target but the break members (noTarget says so).
83
+ cands.push({ t, player: p, d, why, rank: why === 'siege-break' ? siegeRank.get(t) : why === 'bonus-edge' ? 1000 : 2000 });
84
+ }
85
+ cands.sort((a, b) => a.rank - b.rank || a.d - b.d || a.t - b.t);
86
+ const jabs = [];
87
+ for (const c of cands) {
88
+ const from = neighborsOf(g, c.t)
89
+ .filter((x) => mineSet.has(x) && (x !== strike || (c.why === 'siege-break' && skip.has(x))) && spareAt(x) >= 1)
90
+ .sort((a, b) => spareAt(b) - spareAt(a) || a - b)[0];
91
+ if (from === undefined)
92
+ continue;
93
+ left.set(from, spareAt(from) - 1);
94
+ avail.set(from, avail.get(from) - 1);
95
+ const what = c.why === 'siege-break'
96
+ ? `one defender fewer on player ${c.player}'s bonus member for the siege's break (#382)`
97
+ : c.why === 'bonus-edge'
98
+ ? `wearing down an edge of a bonus player ${c.player} holds`
99
+ : `attrition against player ${c.player}, whom I out-earn or out-army`;
100
+ moves.push({
101
+ from,
102
+ to: c.t,
103
+ armies: 1,
104
+ kind: 'attack',
105
+ reason: `jab (#361): 1 army kills ${kills} of the ${c.d} at 0% luck and straight rounding, a one-for-one trade — ${what}; it takes nothing`,
106
+ winChance: 0,
107
+ });
108
+ jabs.push({ from, to: c.t, player: c.player, defenders: c.d, kills, loses: 1, why: c.why });
109
+ }
110
+ if (jabs.length)
111
+ rationale.push(`Jab (#361): ${jabs.map((j) => `1 from ${label(j.from)} into ${label(j.to)} (${j.defenders})`).join(', ')} — each lone army kills ${kills} and dies (0% luck, straight rounding), from armies beyond what holds their source: attrition, never a capture.`);
112
+ return jabs;
113
+ }