@chrischall/warapp-mcp 0.4.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 (92) hide show
  1. package/.claude-plugin/marketplace.json +3 -3
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +41 -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 +48009 -39350
  40. package/dist/cards.js +7 -5
  41. package/dist/chat.js +46 -4
  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/my-games.js +1 -1
  47. package/dist/normalize.js +17 -0
  48. package/dist/profile-store.js +12 -2
  49. package/dist/protocol/bundle.js +28 -10
  50. package/dist/protocol/codec.js +1 -1
  51. package/dist/protocol/dialect.js +371 -0
  52. package/dist/protocol/interp.js +143 -66
  53. package/dist/protocol/methods.js +95 -34
  54. package/dist/protocol/rpc.js +35 -3
  55. package/dist/push/socketio.js +2 -2
  56. package/dist/relations-store.js +38 -4
  57. package/dist/siege-store.js +49 -0
  58. package/dist/state-bundle.js +525 -0
  59. package/dist/state-cli.js +69 -0
  60. package/dist/surrender-pending.js +4 -4
  61. package/dist/team-cards.js +25 -0
  62. package/dist/tools/award.js +15 -1
  63. package/dist/tools/card-advice.js +16 -5
  64. package/dist/tools/card-plays.js +2 -2
  65. package/dist/tools/card-support-advice.js +2 -1
  66. package/dist/tools/chat-inbox.js +36 -3
  67. package/dist/tools/chat-read-mark.js +3 -1
  68. package/dist/tools/chat.js +65 -6
  69. package/dist/tools/check-plan.js +54 -10
  70. package/dist/tools/commerce-deploy.js +33 -0
  71. package/dist/tools/common.js +31 -0
  72. package/dist/tools/end-of-game.js +5 -3
  73. package/dist/tools/index.js +7 -0
  74. package/dist/tools/my-games.js +10 -3
  75. package/dist/tools/notifications.js +2 -2
  76. package/dist/tools/picks.js +12 -0
  77. package/dist/tools/profile-opponents.js +2 -0
  78. package/dist/tools/push.js +2 -1
  79. package/dist/tools/relations.js +137 -0
  80. package/dist/tools/state.js +227 -0
  81. package/dist/tools/stress-opponents.js +5 -2
  82. package/dist/tools/surrender-pending.js +11 -6
  83. package/dist/tools/survival.js +11 -3
  84. package/dist/tools/team-brief.js +2 -2
  85. package/dist/tools/team.js +12 -3
  86. package/dist/tools/turn.js +332 -60
  87. package/dist/version.js +1 -1
  88. package/manifest.json +10 -2
  89. package/mint.yaml +14 -4
  90. package/package.json +4 -4
  91. package/server.json +2 -2
  92. package/skills/warapp-mcp/SKILL.md +31 -9
@@ -921,10 +921,15 @@ export function chooseStrikeStack(pc, ps, book, threats, open, stays) {
921
921
  };
922
922
  /** The stack on `x` a strike could send: what stays, plus a small expansion's armies (No-Split). */
923
923
  const stackAt = (x) => stays(x) + (smallExpansion(x)?.armies ?? 0);
924
- if (auto && profile.format === '1v1' && goal !== 'defend' && facing.size) {
925
- const player = [...facing]
926
- .map((p) => ({ p, e: estimates.get(p) }))
927
- .sort((a, b) => (b.e?.estimate ?? 0) - (a.e?.estimate ?? 0) || a.p - b.p)[0];
924
+ // #382: a siege builds the stack facing its target in any format (its attacks held until the trigger:
925
+ // the target's other territories are no targets then, so the stack only grows or breaks).
926
+ const siege = pc.siege && facing.has(pc.siege.target) ? pc.siege : undefined;
927
+ if ((auto && profile.format === '1v1' && goal !== 'defend' && facing.size) || siege) {
928
+ const player = siege
929
+ ? { p: siege.target, e: estimates.get(siege.target) }
930
+ : [...facing]
931
+ .map((p) => ({ p, e: estimates.get(p) }))
932
+ .sort((a, b) => (b.e?.estimate ?? 0) - (a.e?.estimate ?? 0) || a.p - b.p)[0];
928
933
  /** The opponent's territories next to `x` a strike could aim at. */
929
934
  const aims = (x) => neighborsOf(g, x).filter((n) => {
930
935
  const st = state.get(n);
@@ -1306,7 +1311,7 @@ export function spendStrikeStack(pc, ps, input, book, threats, tgt, cap, strikeS
1306
1311
  why: `not made from the strike stack ${label(S)} — ${refused.get(c.id) ?? 'not worth it'}${effect ? `: ${effect}` : ''}`,
1307
1312
  });
1308
1313
  }
1309
- const builds = `the spare deploys build one strike stack facing player ${strikeStack.player}, the strongest opponent (~${strikeStack.income} income, ${strikeStack.source})`;
1314
+ const builds = `the spare deploys build one strike stack facing player ${strikeStack.player}, ${pc.siege?.target === strikeStack.player ? 'the siege target' : 'the strongest opponent'} (~${strikeStack.income} income, ${strikeStack.source})`;
1310
1315
  if (!taken.length) {
1311
1316
  const held = candidates.length
1312
1317
  ? candidates.map((c) => `${label(c.id)}: ${refused.get(c.id) ?? 'not worth it'}`).join('; ')
@@ -1,10 +1,13 @@
1
1
  import { analyzeBonus, bonusTerritories } from '../bonuses.js';
2
2
  import { straightKills } from '../combat.js';
3
3
  import { bfsDistances, neighborsOf } from '../graph.js';
4
- import { DEFENSE_DISCOUNT, HIDDEN_POOL_INCOMES, NEUTRAL_BORDER_COST, ownerShown, TRACKED_MIN_TURNS, visibleState, WASTELAND_FACTOR, } from './shared.js';
4
+ import { DEFAULT_BASE_INCOME } from '../player.js';
5
+ import { DEFENSE_DISCOUNT, HIDDEN_POOL_INCOMES, NEUTRAL_BORDER_COST, visibleState, WASTELAND_FACTOR, } from './shared.js';
5
6
  import { teammateAt } from './state.js';
6
7
  import { byNum } from './util.js';
7
8
  import { denialsOf, emptyEnemiesOf } from './vacated.js';
9
+ import { breakableBonuses } from './siege.js';
10
+ import { ALL_IN_VALUE_TURNS } from './bonus-attempts.js';
8
11
  /** The targets, the frontier costs and the bonus plans, in the order planPass defined them. */
9
12
  export function targetsPhase(pc, ps, input, threats, hd) {
10
13
  const c0 = breakTargets(pc, input);
@@ -28,62 +31,8 @@ export function breakTargets(pc, input) {
28
31
  // opponent's income gap (all of them listed), or in its single best fit (the first listed, with
29
32
  // fewer bonuses than the next), and on this board every member
30
33
  // is that opponent's or hidden. Such a break is "probable".
31
- const breakable = [];
32
- const breakMember = new Set();
33
- if (balanced) {
34
- for (const b of [...g.map.bonuses].sort((x, y) => x.id - y.id)) {
35
- const ts = bonusTerritories(g, b.id);
36
- if (b.value <= 0 || !ts.length)
37
- continue;
38
- const owners = new Set();
39
- let visible = true;
40
- for (const t of ts) {
41
- const st = state.get(t);
42
- if (st?.owner.kind !== 'player' || !foe(st.owner.playerId) || st.armies === null)
43
- visible = false;
44
- else
45
- owners.add(st.owner.playerId);
46
- }
47
- if (visible && owners.size === 1) {
48
- breakable.push({ bonusId: b.id, value: b.value, player: [...owners][0] });
49
- for (const t of ts)
50
- breakMember.add(t);
51
- continue;
52
- }
53
- // Inferred (#72): one opponent's visible members, the rest hidden, and its track fits it.
54
- if (owners.size !== 1)
55
- continue;
56
- const player = [...owners][0];
57
- const hiddenOrTheirs = ts.every((t) => {
58
- const st = ownerShown(state.get(t));
59
- return st === undefined || (st.owner.kind === 'player' && st.owner.playerId === player);
60
- });
61
- if (!hiddenOrTheirs)
62
- continue;
63
- const tr = input.tracks?.find((x) => x.playerId === player);
64
- const fits = tr && tr.income !== null && tr.turns.length >= TRACKED_MIN_TURNS ? tr.inferred?.candidates : undefined;
65
- if (!fits?.length)
66
- continue;
67
- // "Every" only when the tracker listed every fit (no "and N more"). The best fit must be
68
- // strictly smaller than the next: equal-sized fits are ordered only by bonus id.
69
- const more = tr.inferred.more;
70
- const inEvery = more === 0 && fits.every((c) => c.bonusIds.includes(b.id));
71
- const single = fits.length === 1 && more === 0;
72
- const inBest = fits[0].bonusIds.includes(b.id) && (single || (fits[1] !== undefined && fits[0].bonusIds.length < fits[1].bonusIds.length));
73
- if (!inEvery && !inBest)
74
- continue;
75
- breakable.push({
76
- bonusId: b.id,
77
- value: b.value,
78
- player,
79
- probable: inEvery
80
- ? 'in every combination of bonuses that fits its income gap'
81
- : 'in the best fit of its income gap',
82
- });
83
- for (const t of ts)
84
- breakMember.add(t);
85
- }
86
- }
34
+ const breakable = balanced ? breakableBonuses(g, state, foe, input.tracks) : [];
35
+ const breakMember = new Set(breakable.flatMap((b) => bonusTerritories(g, b.bonusId)));
87
36
  // ---- counter-attacks (under `balanced`, #72) ----
88
37
  // An enemy stack next to me that shrank since the previous board by attacking me: visible on
89
38
  // both boards under the same owner (F1, #69), every neighbour visible on both, one of them a
@@ -147,6 +96,12 @@ export function captureTargets(pc, ps, input, threats, prev) {
147
96
  const { breakMember, counterAt } = prev;
148
97
  // ---- 2. targets ----
149
98
  const targets = new Map();
99
+ /**
100
+ * #298: the missing members of the bonuses dropped after repeated failed attempts
101
+ * (`input.bonusPush.dropped`): no bonus step (rule 4e's contact fallback, #203's lead steps) goes into one.
102
+ */
103
+ const bonusDropped = input.bonusPush?.dropped ?? new Set();
104
+ const droppedMembers = new Set([...bonusDropped].flatMap((id) => (g.bonusById.has(id) ? bonusTerritories(g, id).filter((t) => !mineSet.has(t)) : [])));
150
105
  /**
151
106
  * #240: territories my attacks failed on repeatedly while their owner reinforced them
152
107
  * (`input.repulsed`, {@link repulsedAttacks}): still that opponent's, armies in view, next to mine,
@@ -192,6 +147,51 @@ export function captureTargets(pc, ps, input, threats, prev) {
192
147
  .map((a) => `${a.armies} against ${a.before}, ${a.after} after`)
193
148
  .join('; ')}): a further attack is sized for ${size}.`);
194
149
  }
150
+ /**
151
+ * #298: a bonus pushed all-in (`input.bonusPush.allIn`, after two failed attempts): every missing
152
+ * member must be in view and beside a territory of mine; one another player holds is sized for its
153
+ * defenders plus its owner's deploy (#368's middle figure, `reinforcementAt`), like #240's sure size
154
+ * (taken at that size or not at all), a neutral at its capture cost. The push fits when the whole is at
155
+ * most ALL_IN_VALUE_TURNS × the bonus's value and at most my income; planTurn drops it otherwise.
156
+ */
157
+ const allInTries = new Map();
158
+ for (const bonusId of [...(input.bonusPush?.allIn ?? [])].sort(byNum)) {
159
+ const b = g.bonusById.get(bonusId);
160
+ if (!b)
161
+ continue;
162
+ const cap = Math.max(0, Math.min(ALL_IN_VALUE_TURNS * b.value, pc.income));
163
+ const sized = [];
164
+ let why;
165
+ for (const t of bonusTerritories(g, bonusId).filter((x) => !mineSet.has(x))) {
166
+ const st = state.get(t);
167
+ if (!st || st.owner.kind === 'unknown' || st.armies === null)
168
+ why ??= `${label(t)} is out of view`;
169
+ else if (!neighborsOf(g, t).some((n) => mineSet.has(n)))
170
+ why ??= `${label(t)} is out of reach this turn`;
171
+ else if (uncounted(t))
172
+ why ??= `${label(t)} holds a special unit`;
173
+ else if (st.owner.kind === 'player' && !foe(st.owner.playerId))
174
+ why ??= `${label(t)} is my teammate's`;
175
+ else {
176
+ const defenders = defenceAt(t);
177
+ const extra = st.owner.kind === 'player' ? reinforcementAt(t) : 0;
178
+ const cost = costAt(t, defenders + extra);
179
+ if (cost === null)
180
+ why ??= `${label(t)} cannot be taken`;
181
+ else
182
+ sized.push({ t, ...(st.owner.kind === 'player' ? { player: st.owner.playerId } : {}), defenders, extra, cost });
183
+ }
184
+ }
185
+ const cost = sized.reduce((n, x) => n + x.cost, 0);
186
+ if (!why && cost > cap)
187
+ why = `the push needs ${cost} armies, over the cap of ${cap} (${ALL_IN_VALUE_TURNS} × its +${b.value}, at most my income ${pc.income})`;
188
+ allInTries.set(bonusId, { feasible: !why, cost, cap, ...(why ? { detail: why } : {}) });
189
+ if (why)
190
+ continue;
191
+ for (const x of sized)
192
+ if (x.player !== undefined && x.extra > 0)
193
+ repulsed.set(x.t, { player: x.player, defenders: x.defenders, extra: x.extra, cost: x.cost, sure: true });
194
+ }
195
195
  /** A capture's cost of `t` (its ordinary sizing), or #240's sure one for a repulsed territory. */
196
196
  const costFor = (t) => repulsed.get(t)?.cost ?? costAt(t);
197
197
  /**
@@ -261,7 +261,7 @@ export function captureTargets(pc, ps, input, threats, prev) {
261
261
  }
262
262
  const enemy = st.owner.kind === 'player';
263
263
  if (enemy && goal !== 'complete-bonus' && !(balanced && (breakMember.has(t) || counterAt.has(t)))) {
264
- if (!leadStepsOn || unitsAt(t) > 0 || !g.map.bonuses.some((b) => b.value > 0 && bonusTs.get(b.id).includes(t)))
264
+ if (!leadStepsOn || unitsAt(t) > 0 || droppedMembers.has(t) || !g.map.bonuses.some((b) => b.value > 0 && bonusTs.get(b.id).includes(t)))
265
265
  continue;
266
266
  const defenders = defenceAt(t);
267
267
  const extra = reinforcementAt(t);
@@ -281,7 +281,7 @@ export function captureTargets(pc, ps, input, threats, prev) {
281
281
  // Bonus passes work toward my own bonuses; under `balanced` enemy targets are only break candidates.
282
282
  // #203: a lead step is a bonus target too.
283
283
  const bonusTarget = (t) => targets.has(t) && !(balanced && targets.get(t).enemy && !leadSteps.has(t));
284
- return { targets, leadSteps, leadStepsOn, leadTry, leadNote, bonusTarget, repulsed, costFor, sizeOf };
284
+ return { targets, leadSteps, leadStepsOn, leadTry, leadNote, bonusTarget, repulsed, costFor, sizeOf, allInTries, bonusDropped, droppedMembers };
285
285
  }
286
286
  /** Rule 4d: what a capture adds to the frontier (#71), and the offence report (#72). */
287
287
  export function frontierCosts(pc, threats, hd, prev) {
@@ -427,6 +427,12 @@ export function bonusScoring(pc, ps, threats, prev) {
427
427
  continue;
428
428
  if (!remaining.length)
429
429
  continue;
430
+ // #298: a bonus dropped after repeated failed attempts is not funded: its members are no bonus step.
431
+ if (prev.bonusDropped.has(b.id)) {
432
+ for (const t of remaining)
433
+ uneconomicMember.add(t);
434
+ continue;
435
+ }
430
436
  // PLAN-TEAMS C3.3: a bonus pays only the player holding every member, so one with a member my
431
437
  // teammate visibly holds is not mine to complete (plan/team.ts reports the shared ones).
432
438
  const mates = remaining.filter((t) => teammateAt(pc, t));
@@ -567,7 +573,13 @@ export function bonusScoring(pc, ps, threats, prev) {
567
573
  plans.sort((a, b) => Number(b.focus) - Number(a.focus) || ratio(b) - ratio(a) || a.borders - b.borders || a.bonusId - b.bonusId);
568
574
  return { fogNote, toFinish, plans, wasteShare, wasteCost, wasteLoss, finishCost, economicMember, uneconomicMember, negativeMember, rememberedSaid, ratio };
569
575
  }
570
- /** #101: commit to the bonus closest to completion; a break's retake check. */
576
+ /** #319: the opening warning's bound: at least this many territories held with no bonus. */
577
+ export const SPREAD_TERRITORIES = 10;
578
+ /** #319: the last turn the opening warning runs on (from turn 2). */
579
+ export const SPREAD_LAST_TURN = 6;
580
+ /** #319: "near base": an income at most this much above the base income. */
581
+ export const SPREAD_INCOME_SLACK = 3;
582
+ /** #101: commit to the bonus closest to completion; a break's retake check; #319's spread warning. */
571
583
  export function closestBonus(pc, ps, input, prev) {
572
584
  const { g, me, income, profile, territories: state, label, bonusName, mine, mineSet, bonusTs, toTake } = pc;
573
585
  const { rationale } = ps;
@@ -636,6 +648,25 @@ export function closestBonus(pc, ps, input, prev) {
636
648
  rationale.push(`${bonusName(p.bonusId)}, advanced last turn, gives way to ${bonusName(top.bonusId)}: it is strictly closer to completion (${turnsText(top)} to finish against ${turnsText(p)}).`);
637
649
  }
638
650
  }
651
+ // #319: in the opening (turns 2–6), many territories on an income near base means the captures are
652
+ // spread over bonuses and none completed (six lost games held 11–20 territories on 8 or less after
653
+ // turn 4). A warning only, naming rule 4f's nearest bonus with its armies and turns: no order changes.
654
+ const turnNow = pc.game.turn ?? null;
655
+ const base = Math.max(0, Math.floor(input.settings?.baseIncome ?? DEFAULT_BASE_INCOME));
656
+ if (turnNow !== null &&
657
+ turnNow >= 2 &&
658
+ turnNow <= SPREAD_LAST_TURN &&
659
+ !holdsBonus &&
660
+ mine.length >= SPREAD_TERRITORIES &&
661
+ income <= base + SPREAD_INCOME_SLACK) {
662
+ const nearest = committing ? byCloseness.find((p) => !p.focus) ?? byCloseness[0] : undefined;
663
+ ps.warnings.push(`${mine.length} territories, no bonus: the captures are spread (income ${income}, base ${base}). ` +
664
+ (nearest
665
+ ? `Nearest bonus to complete: ${bonusName(nearest.bonusId)}, ${nearest.cost} armies to finish${fogNote(nearest.fogged, nearest.fogEach)}, ` +
666
+ `${turnsText(nearest)}${income > 0 ? ` at income ${income}` : ''} (rule 4f).`
667
+ : 'No bonus is worth completing from here.') +
668
+ ' Complete one before taking more territories outside it (#319).');
669
+ }
639
670
  /**
640
671
  * A break's retake check, by its target: the warning it raised (if any) and what it was
641
672
  * judged on, so a top-up that adds survivors re-judges it.
@@ -32,6 +32,8 @@ export function threatsPhase(pc, ps, input) {
32
32
  return {
33
33
  ...seen,
34
34
  growthOf,
35
+ /** #290: the previous board as given (the leftover reads which enemy stacks grew since). */
36
+ previousBoard: input.previousBoard,
35
37
  deployReaching,
36
38
  reinforcementAt,
37
39
  holdArmies,
@@ -824,6 +826,10 @@ export function borderThreats(pc, ps, input, src, forces) {
824
826
  const fogged = [...estimates.values()].filter((e) => foe(e.playerId) && e.fogBeside && !out.has(e.playerId)).map((e) => e.playerId).sort(byNum);
825
827
  if (incomePriorSkipped && fogged.length)
826
828
  warnings.push(`No fog prior for the opponents beside the fog (${fogged.length === 1 ? 'player' : 'players'} ${fogged.join(', ')}) in this free-for-all: ${incomePriorSkipped}; their estimates rest on what the board shows, each a lower bound under fog.`);
829
+ // #368: a known income given for a player with no estimate (none of its territories in view).
830
+ for (const k of input.knownIncome ?? [])
831
+ if (!estimates.has(k.player) && foe(k.player))
832
+ warnings.push(`known_income for player ${k.player} is not used: none of its territories is in view, so the plan has no border it threatens.`);
827
833
  for (const p of [...estimated].sort(byNum)) {
828
834
  const e = estimates.get(p);
829
835
  const visible = `base ${e.base} + visible bonuses +${e.bonusIncome} = ${e.base + e.bonusIncome}`;
@@ -898,11 +904,6 @@ export function borderThreats(pc, ps, input, src, forces) {
898
904
  const used = track.turns.filter((x) => e.trackedTurns.includes(x.from));
899
905
  rationale.push(`Tracked income for player ${p}: ~${e.tracked}/turn (${incomeBasis(track)}): ${used.map((x) => `turn ${x.from} +${x.observed}`).join(', ')}, each observed deploy a lower bound under fog${e.coverage ? `, read from ${coverageText(e.coverage)}` : ''}; at least its visible base + bonuses ${track.visibleIncome}; used in place of the single-turn observed figure (warapp_track_opponents has the details).`);
900
906
  }
901
- // #294: a tracked figure read from little of its frontier keeps a floor above it.
902
- if (e.coverageFloor) {
903
- const f = e.coverageFloor;
904
- warnings.push(`Player ${p}'s tracked ~${f.tracked} was read from ${coverageText({ ...e.coverage, hiddenBonuses: 0 }).replace(/\)$/, `, under ${Math.round(LOW_COVERAGE * 100)}%)`)}: the estimate is at least ~${f.tracked} × ${f.factor} = ${f.figure} (the factor is unmeasured), since the fog hid most of where it deploys.`);
905
- }
906
907
  // #164: a Reinforcement card the clock says it may hold, on top of its income.
907
908
  if (e.card)
908
909
  warnings.push(`Player ${p} may hold a Reinforcement card from turn ${e.card.due} (the card clock${e.cardPlayed !== null ? `; it last played one on turn ${e.cardPlayed}` : ''}): +${e.card.armies} added to its deploy, ~${e.estimate} in all, until a deployment above its income is seen; one card at most is counted, though more may be in hand after a long time due.`);
@@ -920,12 +921,42 @@ export function borderThreats(pc, ps, input, src, forces) {
920
921
  ? `Player ${p} is under Sanctions (${pct}, until turn ${z.untilTurn}, read from the board by an unverified decoder): its estimate is cut from ~${z.before} to ~${income} by the client's rule.`
921
922
  : `Player ${p} is under Sanctions (${pct}, until turn ${z.untilTurn}, read from the board by an unverified decoder), but its estimate ~${income} is not cut: ${e.source === 'prior' ? 'it is a prior, a floor guessed from what it could earn, not its income' : `it is ${e.source} from its deploys, which may already carry the cut`}.`);
922
923
  }
924
+ // #332: a commerce game's rising army price, applied to a figure read off the board.
925
+ if (e.armyPrice)
926
+ warnings.push(`Player ${p} earns ~${e.armyPrice.gold} gold, which buys ~${income} armies at the army cost multiplier ${e.armyPrice.multiplier} (commerce).`);
923
927
  const withCard = e.card ? `, plus +${e.card.armies} from its Reinforcement card (~${e.estimate} in all)` : '';
924
928
  // #235 1c: the track's newest turn read more with the armies beside the fog as deploys: a label,
925
929
  // never income (#123 lesson 5); the higher figure is the caller's to test.
926
930
  const cut = e.newestCut;
927
931
  if (cut && e.source !== 'exact' && cut.reading > income)
928
932
  warnings.push(`Player ${p}'s newest turn (turn ${cut.from} → turn ${cut.to}) reads up to +${cut.reading} if the armies that arrived beside the fog were deploys (+${cut.observed} with those beyond twice the ~${cut.expected ?? '?'} it was expected to deploy read as moves); the estimate keeps ~${income} (${e.source === 'tracked' ? 'tracked' : e.source === 'prior' ? 'the fog prior' : 'its visible base + bonuses'}) because a stack walking in is not income (#123). To test the higher figure, pass enemy_deploy ${cut.reading} to warapp_check_plan.`);
933
+ // #368: an income the user supplied replaces the estimate.
934
+ if (e.known) {
935
+ warnings.push(`Enemy deploy estimate for player ${p}: ~${income} (the known income you supplied (known_income), in place of the estimate ~${e.known.was})${withCard}; a figure supplied is taken as it is, not checked against the board.`);
936
+ continue;
937
+ }
938
+ // #368: thin evidence sizes it between its lower bound and its upper (owner decision of
939
+ // 2026-11-19: the middle until we learn otherwise).
940
+ if (e.thinEvidence) {
941
+ const t = e.thinEvidence;
942
+ const thin = t.coverage !== null && t.coverage < LOW_COVERAGE;
943
+ const why = [
944
+ ...(thin
945
+ ? [`its tracked income was read from ${e.coverage ? coverageText(e.coverage) : `${Math.round(t.coverage * 100)}% of its frontier`}, under ${Math.round(LOW_COVERAGE * 100)}%`]
946
+ : []),
947
+ ...(t.rising ? [`its tracked income rose two turns running (${t.rising.join(', ')})`] : []),
948
+ ];
949
+ const lowerIs = t.trend !== null && t.lower === t.trend && t.trend > t.tracked
950
+ ? `the trend's next step ~${t.lower} (the tracked ~${t.tracked})`
951
+ : t.lower === t.tracked
952
+ ? `~${t.lower} (the tracked figure)`
953
+ : `~${t.lower} (its visible income; the tracked ~${t.tracked})`;
954
+ const sized = thin
955
+ ? `it is sized between the lower bound ${lowerIs} and the upper bound ~${t.upper} (${t.prior !== null && t.upper === Math.min(e.couldEarn, t.prior) ? 'the fog prior, not shrunk toward the track' : 'the most it could earn'}): the midpoint ~${t.midpoint}, moved toward what the evidence gives, ~${t.toward}, as more of its frontier is read (${Math.round(t.weight * 100)}% of the way from that to the midpoint)`
956
+ : `its lower bound is ${lowerIs.startsWith('~') ? lowerIs.slice(1) : lowerIs}, read from enough of its frontier to plan on it`;
957
+ warnings.push(`Enemy deploy estimate for player ${p}: ~${income} (thin evidence: ${why.join(' and ')}, so ${sized})${withCard}; it could deploy more.`);
958
+ continue;
959
+ }
929
960
  if (e.source === 'exact') {
930
961
  warnings.push(`Enemy deploy estimate for player ${p}: ~${income} (exact: under ${ctx.fog} every territory's owner shows, so its income is ${visible}${e.observed !== null && e.observed > income ? `; the +${e.observed} observed above it is a card or armies the board misread, not income` : ''}); only the army cap, Sanctions and a Reinforcement card are unknown.`);
931
962
  continue;
@@ -933,7 +964,11 @@ export function borderThreats(pc, ps, input, src, forces) {
933
964
  if (e.source === 'prior') {
934
965
  warnings.push(`Enemy deploy estimate for player ${p}: ~${income} (a prior, not an observation: ${(incomePrior.opening?.get(p) ?? -1) > incomePrior.myIncome
935
966
  ? `its opening simulated from the starts the award of picks proved earns ${incomePrior.opening.get(p)} this turn`
936
- : `in ${incomePrior.format === 'ffa' ? 'a free-for-all that started even (no teams, every player still in)' : 'a 1v1 that started even'}, an opponent bordering the fog is assumed to earn at least my own income ${incomePrior.myIncome}`}, ${e.priorCap !== null
967
+ : `in ${incomePrior.format === 'ffa'
968
+ ? incomePrior.out?.length
969
+ ? `a free-for-all that started even (no teams; ${incomePrior.out.map((o) => `player ${o.id} is out (${o.state})`).join(', ')}, ${incomePrior.out.length === 1 ? 'its' : 'their'} share of what the board hides split among the ${incomePrior.opponents} ${incomePrior.opponents === 1 ? 'opponent' : 'opponents'} still playing)`
970
+ : 'a free-for-all that started even (no teams, every player still in)'
971
+ : 'a 1v1 that started even'}, an opponent bordering the fog is assumed to earn at least my own income ${incomePrior.myIncome}`}, ${e.priorCap !== null
937
972
  ? `capped at an even share (1 of ${incomePrior.opponents} opponents) of what the board hides, ${e.priorCap} (all of it would be ${e.couldEarn})`
938
973
  : `capped at the most it could earn on this board, ${e.couldEarn}`}${e.priorBlend
939
974
  ? ` — shrunk toward its ${e.priorBlend.toward === e.tracked ? `tracked ~${e.tracked}` : `visible ${e.priorBlend.toward}`} by the evidence: ${e.priorBlend.turns} observed ${e.priorBlend.turns === 1 ? 'turn' : 'turns'} with ${Math.round(e.priorBlend.share * 100)}% of its ${e.coverage ? 'frontier read' : 'edge in view'} keep ${Math.round(e.priorBlend.weight * 100)}% of the gap from ${e.priorBlend.prior}`
@@ -14,6 +14,8 @@
14
14
  // and never from a stack beside a visible enemy at the start of the turn (interior only once a
15
15
  // strike lands).
16
16
  // When those steps together make the border hold, it is held after all, never left reported conceded.
17
+ // #367: heading for an enemy front, a step must also bring the stack strictly nearer it measured through
18
+ // the conceded borders, so a stack behind one waits where the front will be instead of walking away and back.
17
19
  import { bfsDistances, neighborsOf } from '../graph.js';
18
20
  import { teammateAt } from './state.js';
19
21
  import { capStepRoom, truceKeep } from './relations.js';
@@ -41,7 +43,11 @@ export function transfers(pc, ps, book, threats, hd, caps, staging) {
41
43
  * it may fail, #172's two-step hold, an exit's cover (#179), the leftover kept central (#218) and a
42
44
  * truce's hold (B2).
43
45
  */
44
- const keepOf = (t) => {
46
+ /**
47
+ * `t`'s keeps. `through`: a conceded border `t` is about to make hold (#257) — a two-step reach through it is cut
48
+ * by that very move (#291: else the gate behind a conceded border would keep its armies from the border itself).
49
+ */
50
+ const keepOf = (t, through) => {
45
51
  // #128: interior only if this turn's attacks on players beside it land. Until they do, it
46
52
  // keeps what holds against the threat there as if they failed (its neighbours' owners'
47
53
  // stacks and deploy as they stand): a +12 bonus was left on 1 beside a capture.
@@ -50,7 +56,7 @@ export function transfers(pc, ps, book, threats, hd, caps, staging) {
50
56
  const keep128 = ifFail ? Math.max(0, holdArmies(ifFail.threat) - unitsAt(t)) : 0;
51
57
  // #172: or it is interior now, but a stack two steps away can take the territory in between
52
58
  // this turn and attack it next. The larger hold binds (never the two added together).
53
- const far = twoStepHold(t);
59
+ const far = twoStepHold(t, through !== undefined ? (n) => n === through : undefined);
54
60
  const twoStep = far !== null && far.stay > keep128 ? far : null;
55
61
  const truceHold = truceKeep(pc, threats, t);
56
62
  const keep = Math.max(keep128, twoStep?.stay ?? 0, coverKeep.has(t) ? coverKeep.get(t) + guardAt(t) : 0,
@@ -101,7 +107,7 @@ export function transfers(pc, ps, book, threats, hd, caps, staging) {
101
107
  .filter((t) => !neighborsOf(g, t).some((x) => isEnemy(x)))
102
108
  .map((t) => {
103
109
  const n = avail.get(t);
104
- const part = Math.min(n, Math.max(0, stayAt(t) - keepOf(t).keep), capStepRoom(pc, ps, t, id));
110
+ const part = Math.min(n, Math.max(0, stayAt(t) - keepOf(t, id).keep), capStepRoom(pc, ps, t, id));
105
111
  return { t, n, part: noSplit && part < n ? 0 : part };
106
112
  })
107
113
  .filter((x) => x.part >= c.k)
@@ -161,6 +167,26 @@ export function transfers(pc, ps, book, threats, hd, caps, staging) {
161
167
  const withdrawn = new Set(moves.filter((m) => m.kind === 'transfer' && conceded.has(m.from)).map((m) => m.from));
162
168
  const viaOk = (id) => !conceded.has(id) || (!withdrawn.has(id) && attacksFrom(id).length > 0);
163
169
  const distEnemyVia = bfsDistances(g, enemyFront, { passable: (id) => held.has(id) && viaOk(id) });
170
+ // #367: the enemy front measured through every territory held, conceded borders included. A border the
171
+ // plan concedes falls to the stack beside it, and the front is then right where it stood; measured only
172
+ // around it (distEnemy), the front jumped to a farther one and an idle stack behind it walked away, to
173
+ // walk straight back the next turn once the border had fallen (live: 649 armies, twice). So a step toward
174
+ // an enemy front must also bring the stack strictly nearer it measured this way: one board, no memory.
175
+ const distEnemyThrough = bfsDistances(g, enemyFront, { passable: (id) => held.has(id) });
176
+ /** The conceded border on the way from `t` to the enemy front nearest it through conceded borders, and that front. */
177
+ const pastConceded = (t) => {
178
+ let at = t;
179
+ let border;
180
+ while ((distEnemyThrough.get(at) ?? 0) > 0) {
181
+ const d = distEnemyThrough.get(at);
182
+ at = neighborsOf(g, at)
183
+ .filter((x) => distEnemyThrough.get(x) === d - 1)
184
+ .sort((a, b) => Number(conceded.has(b)) - Number(conceded.has(a)) || a - b)[0];
185
+ if (border === undefined && conceded.has(at))
186
+ border = at;
187
+ }
188
+ return border === undefined ? undefined : { border, front: at };
189
+ };
164
190
  // #125: staging. Idle armies on a territory facing no visible enemy — a border beside neutrals
165
191
  // included — walk one step toward the source of the capture the leftover saved toward, when
166
192
  // it is no farther than the enemy front; once there they help take it.
@@ -240,14 +266,28 @@ export function transfers(pc, ps, book, threats, hd, caps, staging) {
240
266
  // Only into a territory held at the start of the turn: a planned capture is
241
267
  // not mine yet, and a "transfer" into it would execute as an attack.
242
268
  // B2 (T5): never onto a truce's capped border past its cap, nor back along a transfer.
243
- const step = neighborsOf(g, t)
269
+ const steps = neighborsOf(g, t)
244
270
  .filter((x) => mineSet.has(x) &&
245
271
  (via ? viaOk(x) : !conceded.has(x)) &&
246
272
  (dist.get(x) ?? Infinity) < d &&
247
273
  capStepRoom(pc, ps, t, x) > 0)
248
- .sort((a, b) => dist.get(a) - dist.get(b) || a - b)[0];
249
- if (step === undefined)
274
+ .sort((a, b) => dist.get(a) - dist.get(b) || a - b);
275
+ // #367: heading for an enemy front, never a step that does not bring the stack strictly nearer it
276
+ // through the conceded borders (a #260 via step already goes through one, and a neutral edge is
277
+ // another target: both as before).
278
+ const through = !via && dist === distEnemy ? distEnemyThrough.get(t) : undefined;
279
+ const step = steps.find((x) => through === undefined || (distEnemyThrough.get(x) ?? Infinity) < through);
280
+ if (step === undefined) {
281
+ const past = steps.length ? pastConceded(t) : undefined;
282
+ if (past) {
283
+ rationale.push(`Keep the ${n} idle armies on ${label(t)}: the enemy front nearest them, ${label(past.front)}, lies past ${label(past.border)}, a border the plan concedes (#367); once it falls the front is here, so they do not walk away toward a farther front only to walk back.`);
284
+ // #291: what a stack two steps away needs them to hold here, said as when the keep alone stops them.
285
+ const { twoStep } = keepOf(t);
286
+ if (twoStep)
287
+ rationale.push(twoStepCite(t, twoStep, (c) => `Keep the ${n} idle armies on ${label(t)}: ${c}.`, `Keep the ${n} idle armies on ${label(t)}.`));
288
+ }
250
289
  continue;
290
+ }
251
291
  const { pending, ifFail, twoStep, truceHold, keep } = keepOf(t);
252
292
  // No-Split (#124): a transfer sends the whole stack, so one that must keep some sends none.
253
293
  const room = capStepRoom(pc, ps, t, step);