@chrischall/warapp-mcp 0.6.0 → 0.8.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 (111) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +100 -7
  4. package/dist/analysis/accept-surrender.js +20 -2
  5. package/dist/analysis/calibrate.js +1 -0
  6. package/dist/analysis/card-support.js +187 -20
  7. package/dist/analysis/card-threats.js +68 -3
  8. package/dist/analysis/chat-advice.js +182 -0
  9. package/dist/analysis/chat-blocks.js +106 -0
  10. package/dist/analysis/chat-intent.js +559 -0
  11. package/dist/analysis/chat-read.js +159 -0
  12. package/dist/analysis/coalition.js +55 -0
  13. package/dist/analysis/decision-replay.js +279 -0
  14. package/dist/analysis/decision-truth.js +146 -0
  15. package/dist/analysis/finished-game.js +62 -3
  16. package/dist/analysis/game-lessons.js +12 -6
  17. package/dist/analysis/local-deploy.js +14 -0
  18. package/dist/analysis/opponent-profile.js +46 -3
  19. package/dist/analysis/opponents.js +246 -19
  20. package/dist/analysis/outlook.js +323 -17
  21. package/dist/analysis/picks.js +270 -37
  22. package/dist/analysis/plan/after-leftover.js +28 -3
  23. package/dist/analysis/plan/captures.js +80 -16
  24. package/dist/analysis/plan/completed.js +8 -1
  25. package/dist/analysis/plan/conceded-out.js +16 -11
  26. package/dist/analysis/plan/deploy-estimates.js +513 -0
  27. package/dist/analysis/plan/doomed-out.js +135 -0
  28. package/dist/analysis/plan/estimates.js +73 -7
  29. package/dist/analysis/plan/free-capture.js +34 -0
  30. package/dist/analysis/plan/guard-off.js +2 -1
  31. package/dist/analysis/plan/holds.js +85 -313
  32. package/dist/analysis/plan/horizon.js +42 -0
  33. package/dist/analysis/plan/leftover.js +188 -10
  34. package/dist/analysis/plan/observe.js +896 -0
  35. package/dist/analysis/plan/orders.js +35 -1
  36. package/dist/analysis/plan/relations.js +115 -2
  37. package/dist/analysis/plan/report.js +10 -4
  38. package/dist/analysis/plan/shared.js +7 -1189
  39. package/dist/analysis/plan/stand-still.js +7 -5
  40. package/dist/analysis/plan/state.js +12 -0
  41. package/dist/analysis/plan/stockpile.js +104 -0
  42. package/dist/analysis/plan/strike-stack.js +467 -0
  43. package/dist/analysis/plan/strike.js +8 -441
  44. package/dist/analysis/plan/targets.js +374 -72
  45. package/dist/analysis/plan/threats.js +120 -9
  46. package/dist/analysis/plan/transfers.js +35 -1
  47. package/dist/analysis/plan/two-move.js +70 -0
  48. package/dist/analysis/plan/vacated.js +124 -2
  49. package/dist/analysis/plan/withdraw.js +316 -0
  50. package/dist/analysis/planner.js +356 -53
  51. package/dist/analysis/player.js +4 -0
  52. package/dist/analysis/relations.js +8 -2
  53. package/dist/analysis/since-last.js +18 -5
  54. package/dist/analysis/stress.js +1 -1
  55. package/dist/board.js +36 -2
  56. package/dist/build-id.js +106 -0
  57. package/dist/bundle.js +15863 -10242
  58. package/dist/chat-automation.js +22 -0
  59. package/dist/client.js +14 -0
  60. package/dist/decision-log.js +1093 -0
  61. package/dist/finished-store.js +5 -1
  62. package/dist/lessons-store.js +322 -21
  63. package/dist/my-games.js +2 -0
  64. package/dist/open-games.js +122 -18
  65. package/dist/outlook-log.js +42 -1
  66. package/dist/protocol/methods.js +4 -2
  67. package/dist/review-export.js +198 -0
  68. package/dist/state-bundle.js +62 -3
  69. package/dist/state-cli.js +5 -3
  70. package/dist/strategy/notes.js +56 -0
  71. package/dist/tools/accept-surrender.js +23 -9
  72. package/dist/tools/award.js +5 -1
  73. package/dist/tools/card-advice.js +102 -33
  74. package/dist/tools/card-support-advice.js +53 -8
  75. package/dist/tools/chat-advice.js +330 -0
  76. package/dist/tools/chat-inbox.js +15 -4
  77. package/dist/tools/chat.js +41 -11
  78. package/dist/tools/check-plan.js +16 -3
  79. package/dist/tools/commander-check.js +2 -1
  80. package/dist/tools/decision-capture.js +461 -0
  81. package/dist/tools/end-of-game.js +146 -18
  82. package/dist/tools/game-kind.js +92 -0
  83. package/dist/tools/how-lost.js +7 -2
  84. package/dist/tools/index.js +3 -0
  85. package/dist/tools/join-game.js +51 -9
  86. package/dist/tools/live-context.js +6 -0
  87. package/dist/tools/live.js +43 -6
  88. package/dist/tools/map-curves.js +73 -0
  89. package/dist/tools/notifications.js +4 -3
  90. package/dist/tools/open-games.js +2 -2
  91. package/dist/tools/opponents.js +2 -0
  92. package/dist/tools/past-games.js +74 -8
  93. package/dist/tools/picks.js +169 -57
  94. package/dist/tools/profile-hook.js +62 -3
  95. package/dist/tools/profile-opponents.js +2 -0
  96. package/dist/tools/push.js +2 -2
  97. package/dist/tools/relations.js +2 -0
  98. package/dist/tools/scout.js +16 -2
  99. package/dist/tools/state.js +6 -1
  100. package/dist/tools/strategy.js +3 -3
  101. package/dist/tools/stress-opponents.js +2 -0
  102. package/dist/tools/surrender-pending.js +10 -1
  103. package/dist/tools/surrender.js +18 -3
  104. package/dist/tools/turn.js +353 -19
  105. package/dist/tools/where.js +3 -1
  106. package/dist/version.js +1 -1
  107. package/manifest.json +23 -2
  108. package/mint.yaml +23 -0
  109. package/package.json +1 -1
  110. package/server.json +20 -2
  111. package/skills/warapp-mcp/SKILL.md +42 -8
@@ -5,7 +5,7 @@ import { DEFAULT_BASE_INCOME } from '../player.js';
5
5
  import { DEFENSE_DISCOUNT, HIDDEN_POOL_INCOMES, NEUTRAL_BORDER_COST, visibleState, WASTELAND_FACTOR, } from './shared.js';
6
6
  import { teammateAt } from './state.js';
7
7
  import { byNum } from './util.js';
8
- import { denialsOf, emptyEnemiesOf } from './vacated.js';
8
+ import { denialsOf, emptyEnemiesOf, fogVacated, VACATED_FOG_ARMIES } from './vacated.js';
9
9
  import { breakableBonuses } from './siege.js';
10
10
  import { ALL_IN_VALUE_TURNS } from './bonus-attempts.js';
11
11
  /** The targets, the frontier costs and the bonus plans, in the order planPass defined them. */
@@ -14,13 +14,18 @@ export function targetsPhase(pc, ps, input, threats, hd) {
14
14
  const c1 = { ...c0, ...captureTargets(pc, ps, input, threats, c0) };
15
15
  const c2 = { ...c1, ...frontierCosts(pc, threats, hd, c1) };
16
16
  const c3 = { ...c2, ...bonusScoring(pc, ps, threats, c2) };
17
- const c4 = { ...c3, ...closestBonus(pc, ps, input, c3) };
17
+ const c4 = { ...c3, ...closestBonus(pc, ps, input, c3, hd) };
18
18
  // #281: the vacated land worth denying and (the owner's extension) the empty enemy territories
19
19
  // pass 3 may take, each judged once on the board as it stands.
20
20
  const denials = denialsOf(pc);
21
21
  const emptyEnemies = emptyEnemiesOf(pc, input.previousBoard, threats.reinforcementAt, (t) => c4.targets.has(t) || c4.repulsed.has(t) || pc.truce.noTarget(t));
22
22
  return { ...c4, denials, emptyEnemies };
23
23
  }
24
+ /**
25
+ * #430 (owner decision of 2026-11-22): a retake of a held bonus's lost members costs at most this many
26
+ * times the bonus's value — tighter than PAYBACK_TURNS (10), which the first draft used.
27
+ */
28
+ export const RETAKE_VALUE_TURNS = 5;
24
29
  /** The enemy bonuses I could break and the counter-attacks (under `balanced`, #72). */
25
30
  export function breakTargets(pc, input) {
26
31
  const { g, me, foe, balanced, territories: state, mineSet, unitsAt, costAt } = pc;
@@ -102,6 +107,59 @@ export function captureTargets(pc, ps, input, threats, prev) {
102
107
  */
103
108
  const bonusDropped = input.bonusPush?.dropped ?? new Set();
104
109
  const droppedMembers = new Set([...bonusDropped].flatMap((id) => (g.bonusById.has(id) ? bonusTerritories(g, id).filter((t) => !mineSet.has(t)) : [])));
110
+ /** #421: the missing members of the contested bonuses a stockpile pushes all-in: targets, an opponent's included. */
111
+ const pileMembers = new Set([...(input.stockpileAllIn ?? [])].flatMap((id) => (g.bonusById.has(id) ? bonusTerritories(g, id).filter((t) => !mineSet.has(t)) : [])));
112
+ /**
113
+ * #430: the opponents' territories that retake a bonus I held in full on `previousBoard`. Under
114
+ * `balanced` an enemy territory was only a break or counter target, so a held bonus that lost a
115
+ * member to a player was never retaken outside the 1v1 strike stack (0 of 166 breaks regained in
116
+ * planner-era games). Such a member is a bonus target, in every format, when the retake completes
117
+ * the bonus this turn (every missing member in view, beside mine, no special unit, a foe's or a
118
+ * neutral; none of #298's dropped members), its capture costs together are at most
119
+ * RETAKE_VALUE_TURNS (5) × the value, and the profile does not read me behind (behind, the turn goes to
120
+ * holds and strikes: the evidence's confound). It then competes as a completion in the bonus passes
121
+ * and rule 4a's greedy step, so a hold that scores higher is still funded first, and R3 still
122
+ * refuses a retake that cannot be held.
123
+ */
124
+ const retakeMembers = new Set();
125
+ if (balanced && input.previousBoard && profile.standing !== 'behind') {
126
+ const before = new Map(input.previousBoard.territories.map((t) => [t.territoryId, t]));
127
+ for (const b of [...g.map.bonuses].sort((x, y) => x.id - y.id)) {
128
+ const ts = bonusTs.get(b.id) ?? [];
129
+ if (b.value <= 0 || !ts.length || ts.every((t) => mineSet.has(t)) || bonusDropped.has(b.id))
130
+ continue;
131
+ const heldBefore = ts.every((t) => {
132
+ const was = visibleState(before.get(t));
133
+ return was?.owner.kind === 'player' && was.owner.playerId === pc.me;
134
+ });
135
+ if (!heldBefore)
136
+ continue;
137
+ const missing = ts.filter((t) => !mineSet.has(t));
138
+ let cost = 0;
139
+ const ok = missing.every((t) => {
140
+ const st = state.get(t);
141
+ if (!st || st.armies === null || st.owner.kind === 'unknown' || st.owner.kind === 'available')
142
+ return false;
143
+ if (st.owner.kind === 'player' && (!foe(st.owner.playerId) || pc.truce.noTarget(t)))
144
+ return false;
145
+ if (uncounted(t) || droppedMembers.has(t) || !neighborsOf(g, t).some((n) => mineSet.has(n)))
146
+ return false;
147
+ const c = costAt(t);
148
+ if (c === null)
149
+ return false;
150
+ cost += c;
151
+ return true;
152
+ });
153
+ if (!ok || cost > RETAKE_VALUE_TURNS * b.value)
154
+ continue;
155
+ const theirs = missing.filter((t) => state.get(t).owner.kind === 'player');
156
+ if (!theirs.length)
157
+ continue;
158
+ for (const t of theirs)
159
+ retakeMembers.add(t);
160
+ rationale.push(`Retake ${theirs.map(label).join(', ')}: ${theirs.length > 1 ? 'they complete' : 'it completes'} bonus ${b.name} (+${b.value}) again, which I held in full last turn, for ${cost} armies (at most ${RETAKE_VALUE_TURNS} × its value), so ${theirs.length > 1 ? 'they are' : 'it is'} a bonus target (#430).`);
161
+ }
162
+ }
105
163
  /**
106
164
  * #240: territories my attacks failed on repeatedly while their owner reinforced them
107
165
  * (`input.repulsed`, {@link repulsedAttacks}): still that opponent's, armies in view, next to mine,
@@ -159,7 +217,9 @@ export function captureTargets(pc, ps, input, threats, prev) {
159
217
  const b = g.bonusById.get(bonusId);
160
218
  if (!b)
161
219
  continue;
162
- const cap = Math.max(0, Math.min(ALL_IN_VALUE_TURNS * b.value, pc.income));
220
+ // #421: a stockpile's push spends armies already on the board: capped at the payback horizon × its value.
221
+ const pile = input.stockpileAllIn?.has(bonusId) === true;
222
+ const cap = pile ? Math.max(0, pc.capturePaybackTurns * b.value) : Math.max(0, Math.min(ALL_IN_VALUE_TURNS * b.value, pc.income));
163
223
  const sized = [];
164
224
  let why;
165
225
  for (const t of bonusTerritories(g, bonusId).filter((x) => !mineSet.has(x))) {
@@ -184,7 +244,9 @@ export function captureTargets(pc, ps, input, threats, prev) {
184
244
  }
185
245
  const cost = sized.reduce((n, x) => n + x.cost, 0);
186
246
  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})`;
247
+ why = pile
248
+ ? `the push needs ${cost} armies, over the cap of ${cap} (${pc.capturePaybackTurns} × its +${b.value}, #421)`
249
+ : `the push needs ${cost} armies, over the cap of ${cap} (${ALL_IN_VALUE_TURNS} × its +${b.value}, at most my income ${pc.income})`;
188
250
  allInTries.set(bonusId, { feasible: !why, cost, cap, ...(why ? { detail: why } : {}) });
189
251
  if (why)
190
252
  continue;
@@ -246,6 +308,16 @@ export function captureTargets(pc, ps, input, threats, prev) {
246
308
  warnings.push(`${label(t)} (player ${hiddenOwner}) borders my ${sources.map(label).join(', ')} and its armies are hidden by the fog: the threat from it counts ${bound} plus its deploy, and the win chance of an attack into it is unknown, so none is planned.`);
247
309
  continue;
248
310
  }
311
+ // #417, the breach force: land a static seat left, hidden now, is attacked at the 2-defender price
312
+ // (`defenceAt` reads it so), until it is taken or the fog shows another player there.
313
+ if (fogVacated(pc.vacated, st, t)) {
314
+ const cost = costAt(t);
315
+ if (cost !== null) {
316
+ targets.set(t, { id: t, cost, enemy: false, sources });
317
+ rationale.push(`${label(t)} is fogged and was player ${pc.vacated.get(t)}'s (out, no AI): its land behind the old border stands on ${VACATED_FOG_ARMIES} at most, so an attack into it is priced at ${VACATED_FOG_ARMIES} defenders (${cost} armies) (#417).`);
318
+ continue;
319
+ }
320
+ }
249
321
  if (!st || st.owner.kind === 'unknown' || st.armies === null) {
250
322
  warnings.push(`Fogged territory ${label(t)} borders my ${sources.map(label).join(', ')}: its armies are unknown (fog), so no attack is planned.`);
251
323
  continue;
@@ -260,7 +332,7 @@ export function captureTargets(pc, ps, input, threats, prev) {
260
332
  continue;
261
333
  }
262
334
  const enemy = st.owner.kind === 'player';
263
- if (enemy && goal !== 'complete-bonus' && !(balanced && (breakMember.has(t) || counterAt.has(t)))) {
335
+ if (enemy && goal !== 'complete-bonus' && !(balanced && (breakMember.has(t) || counterAt.has(t))) && !pileMembers.has(t) && !retakeMembers.has(t)) {
264
336
  if (!leadStepsOn || unitsAt(t) > 0 || droppedMembers.has(t) || !g.map.bonuses.some((b) => b.value > 0 && bonusTs.get(b.id).includes(t)))
265
337
  continue;
266
338
  const defenders = defenceAt(t);
@@ -280,7 +352,9 @@ export function captureTargets(pc, ps, input, threats, prev) {
280
352
  }
281
353
  // Bonus passes work toward my own bonuses; under `balanced` enemy targets are only break candidates.
282
354
  // #203: a lead step is a bonus target too.
283
- const bonusTarget = (t) => targets.has(t) && !(balanced && targets.get(t).enemy && !leadSteps.has(t));
355
+ // #421: a member of a contested bonus a stockpile pushes all-in is a bonus target too.
356
+ // #430: a member that retakes a bonus I held last turn is a bonus target too.
357
+ const bonusTarget = (t) => targets.has(t) && !(balanced && targets.get(t).enemy && !leadSteps.has(t) && !pileMembers.has(t) && !retakeMembers.has(t));
284
358
  return { targets, leadSteps, leadStepsOn, leadTry, leadNote, bonusTarget, repulsed, costFor, sizeOf, allInTries, bonusDropped, droppedMembers };
285
359
  }
286
360
  /** Rule 4d: what a capture adds to the frontier (#71), and the offence report (#72). */
@@ -381,25 +455,59 @@ export function frontierCosts(pc, threats, hd, prev) {
381
455
  }
382
456
  return { borders, enemyBorders, holdCost };
383
457
  };
458
+ /**
459
+ * #433: each border's share of {@link frontierOf}'s hold cost (the same borders: a conceded one only while its
460
+ * garrison stands), for the Local Deployment pools that can pay it.
461
+ */
462
+ const frontierNeeds = (held, haveOf) => {
463
+ const needs = new Map();
464
+ for (const x of [...held].sort(byNum)) {
465
+ const b = borderOf(x, held, haveOf(x));
466
+ if ((!conceded.has(x) || stood.has(x)) && b.need > 0)
467
+ needs.set(x, b.need);
468
+ }
469
+ return needs;
470
+ };
384
471
  /** The frontier's hold cost at the start of the turn (my armies then; today's concessions left out). */
385
472
  const startHold = () => frontierOf(mineSet, armiesOf).holdCost;
386
- return { survivorsOf, borderOf, borderCost, frontierDelta, edgeCost, scoreCost, targetScoreCost, landScoreCost, offence, offenceSkip, skipOffence, badTrades, frontierOf, startHold };
473
+ return { survivorsOf, borderOf, borderCost, frontierDelta, edgeCost, scoreCost, targetScoreCost, landScoreCost, offence, offenceSkip, skipOffence, badTrades, frontierOf, frontierNeeds, startHold };
387
474
  }
388
475
  /** Bonus scoring (rule 4, R3, #70, #101, #125, #167): the bonuses worth working toward, best first. */
389
476
  export function bonusScoring(pc, ps, threats, prev) {
390
- const { g, s, opts, guarded, focus, paybackTurns, territories: state, label, mineSet, armiesOf, defenceAt, completedOver, territoryShare, rates, costOf, costAt, econCostAt, } = pc;
477
+ const { g, s, opts, guarded, focus, capturePaybackTurns: paybackTurns, territories: state, label, mineSet, armiesOf, defenceAt, completedOver, territoryShare, rates, costOf, costAt, econCostAt, } = pc;
391
478
  const { rationale } = ps;
392
479
  const { exposure } = threats;
393
480
  const { targets, bonusTarget, survivorsOf, frontierDelta, scoreCost } = prev;
394
481
  // ---- bonus scoring ----
395
- /** "N armies to finish", naming the fogged members counted in it (#101). */
396
- const fogNote = (fogged, each) => fogged ? ` (${fogged} fogged member${fogged === 1 ? '' : 's'} counted at ${each} each)` : '';
397
- const toFinish = (cost, fogged, each) => `${cost} armies to finish${fogNote(fogged, each)}`;
482
+ /**
483
+ * "N armies to finish", naming the fogged members counted in it (#101): those at the costliest visible
484
+ * member, and (#428) those costed as the game's neutral size.
485
+ */
486
+ const fogNote = (f) => {
487
+ const parts = [
488
+ ...(f.fogged ? [`${f.fogged} fogged member${f.fogged === 1 ? '' : 's'} counted at ${f.fogEach} each`] : []),
489
+ ...(f.fogNeutral
490
+ ? [`${f.fogNeutral.count} fogged member${f.fogNeutral.count === 1 ? '' : 's'} counted at ${f.fogNeutral.each} each: the game's neutral size, ${f.fogNeutral.size}`]
491
+ : []),
492
+ ];
493
+ return parts.length ? ` (${parts.join('; ')})` : '';
494
+ };
495
+ const toFinish = (cost, f) => `${cost} armies to finish${fogNote(f)}`;
398
496
  const plans = [];
399
497
  /** #167: the share of the map's territories that started as wastelands, and what one costs to take and loses. */
400
498
  const wasteShare = s.wastelands && s.wastelands.count > 0 && s.wastelands.size > 0 && g.territoryById.size > 0
401
499
  ? Math.min(1, s.wastelands.count / g.territoryById.size)
402
500
  : 0;
501
+ /**
502
+ * #432: a visible neutral at the game's wasteland size or more, when the game has wastelands larger than its
503
+ * ordinary neutrals (`neutralArmies`, when the settings give it).
504
+ */
505
+ const isWasteland = (st) => s.wastelands !== undefined &&
506
+ s.wastelands.count > 0 &&
507
+ s.wastelands.size > (s.neutralArmies ?? 0) &&
508
+ st.owner.kind === 'neutral' &&
509
+ st.armies !== null &&
510
+ st.armies >= s.wastelands.size;
403
511
  const wasteCost = wasteShare > 0 ? (costOf(s.wastelands.size) ?? Infinity) : 0;
404
512
  const wasteLoss = wasteShare > 0 ? Math.min(wasteCost - 1, straightKills(s.wastelands.size, rates.defensiveKillRate)) + 1 : 0;
405
513
  /** Every positive bonus worth completing (net > 0) still missing members: its armies to finish (rule 4e). */
@@ -410,10 +518,30 @@ export function bonusScoring(pc, ps, threats, prev) {
410
518
  const negativeMember = new Set();
411
519
  /** #201: a remembered neutral's rationale line (its index) and the bonuses it names. */
412
520
  const rememberedSaid = new Map();
521
+ /** #428: the same for a member costed at its last sighting. */
522
+ const lastSeenSaid = new Map();
523
+ /** Says once per territory, naming every bonus it is costed in (#201, #428). */
524
+ const sayOnce = (said, t, b, tail) => {
525
+ const was = said.get(t);
526
+ if (was) {
527
+ was.bonuses.push(`${b.name} (#${b.id})`);
528
+ rationale[was.at] = `${was.bonuses.join(', ')}: ${tail}`;
529
+ }
530
+ else {
531
+ said.set(t, { at: rationale.length, bonuses: [`${b.name} (#${b.id})`] });
532
+ rationale.push(`${b.name} (#${b.id}): ${tail}`);
533
+ }
534
+ };
535
+ // #428: the game's neutral size, costed once: a fogged member no board showed, whose owner the fog hides.
536
+ const neutralSize = s.neutralArmies !== undefined && s.neutralArmies >= 0 ? s.neutralArmies : undefined;
537
+ const neutralCost = neutralSize !== undefined ? (costOf(neutralSize) ?? Infinity) : Infinity;
538
+ const neutralLoss = neutralSize !== undefined && Number.isFinite(neutralCost) ? Math.min(neutralCost - 1, straightKills(neutralSize, rates.defensiveKillRate)) + 1 : Infinity;
539
+ // #435: whether the Gift card is in play (the shared-bonus handover needs it).
540
+ const giftInPlay = pc.game.cardsInPlay?.includes('Gift') === true;
413
541
  for (const b of [...g.map.bonuses].sort((x, y) => x.id - y.id)) {
414
542
  const isFocus = focus.has(b.id);
415
543
  const ts = bonusTerritories(g, b.id);
416
- const remaining = ts.filter((t) => !mineSet.has(t));
544
+ let remaining = ts.filter((t) => !mineSet.has(t));
417
545
  if (b.value < 0 && !isFocus) {
418
546
  // Completing it would cut income: never plan into it (an economic
419
547
  // membership elsewhere still wins — see the pass-3 filter).
@@ -436,13 +564,26 @@ export function bonusScoring(pc, ps, threats, prev) {
436
564
  // PLAN-TEAMS C3.3: a bonus pays only the player holding every member, so one with a member my
437
565
  // teammate visibly holds is not mine to complete (plan/team.ts reports the shared ones).
438
566
  const mates = remaining.filter((t) => teammateAt(pc, t));
439
- if (mates.length) {
567
+ // #435 (proposed rule): one of us must work a shared bonus, or nobody does (45701358: four, +69,
568
+ // left to plain expansion). Whoever holds the most members (`nearer`, as team.sharedBonuses reads
569
+ // it) works it: when that is me, alone, its other members are scored as mine to take, and the
570
+ // teammate's members are theirs to hand over (a Gift) — never captured, never costed, and never
571
+ // a completion this turn (`completable` false while they stand), so no income is claimed for it.
572
+ // Owner decision 2026-11-22: only with the Gift card in play — the handover needs one; without it
573
+ // (or the cards unread) a shared bonus is skipped as before.
574
+ const handover = mates.length ? (giftInPlay && nearerMe(pc, ts) ? mates : undefined) : [];
575
+ if (handover === undefined) {
440
576
  if (remaining.some(bonusTarget) || isFocus)
441
577
  rationale.push(`Skip bonus ${b.name} (#${b.id}): my teammate holds ${mates.map(label).join(', ')}, and a bonus pays only the player holding all of it.`);
442
578
  if (isFocus)
443
579
  ps.warnings.push(`Focus on bonus ${b.name} (#${b.id}) ignored: my teammate holds ${mates.map(label).join(', ')} (one owner per bonus).`);
444
580
  continue;
445
581
  }
582
+ if (handover.length) {
583
+ remaining = remaining.filter((t) => !handover.includes(t));
584
+ if (!remaining.length)
585
+ continue;
586
+ }
446
587
  // Cluster as a unit (#70): the negative bonuses its missing members complete come off its
447
588
  // worth (on a map without negative bonuses, net = value).
448
589
  const rest = new Set(remaining);
@@ -460,83 +601,147 @@ export function bonusScoring(pc, ps, threats, prev) {
460
601
  rationale.push(`Skip bonus ${b.name} (#${b.id}): completing it costs more income than it pays (net ${net}).`);
461
602
  continue;
462
603
  }
463
- // Armies to finish (#101): every missing member's capture cost. A fogged member counts at its
464
- // bonus's costliest visible missing member (it cannot be costed, and counting it as free made
465
- // the figure jump when it came into view); with none visible, the bonus cannot be costed.
604
+ // Armies to finish (#101): every missing member's capture cost. A fogged member a static seat left
605
+ // is priced by #417 first (below); any other is costed from what is known of it (#428): its last sighting on my boards (unless the fog shows another owner
606
+ // now), else (#201) its size on the picking board, else the game's neutral size (when its owner is
607
+ // hidden too); only with none of those does it count at its bonus's costliest visible missing
608
+ // member (counting it as free made the figure jump when it came into view; 65 finished-game plans
609
+ // counted every one at 208); with none visible either, the bonus cannot be costed.
466
610
  let cost = 0;
467
611
  let worst = 0;
468
612
  let fogged = 0;
613
+ let foggedNeutral = 0;
469
614
  // #125: the economy test charges the armies lost, not the armies sent.
470
615
  let loss = 0;
471
616
  let worstLoss = 0;
617
+ /** #432: its missing members in view that are wastelands. */
618
+ const wastelands = [];
619
+ const known = (t, armies) => {
620
+ const c = costAt(t, armies) ?? Infinity;
621
+ cost += c;
622
+ worst = Math.max(worst, c);
623
+ const l = Math.min(c - 1, straightKills(armies, rates.defensiveKillRate)) + 1;
624
+ loss += l;
625
+ worstLoss = Math.max(worstLoss, l);
626
+ };
627
+ /** #417: the fogged members a static seat left, each with its cost and loss at VACATED_FOG_ARMIES. */
628
+ const vacatedFog = [];
472
629
  for (const t of remaining) {
473
630
  const st = state.get(t);
474
631
  if (!st || st.owner.kind === 'unknown' || st.armies === null) {
632
+ // #417 first: land a static seat left is thin behind its border stack: costed at most at
633
+ // VACATED_FOG_ARMIES defenders, and never raising what another fogged member counts at.
634
+ const left = pc.vacated.get(t);
635
+ if (left !== undefined) {
636
+ const c = costAt(t, VACATED_FOG_ARMIES) ?? Infinity;
637
+ vacatedFog.push({ t, left, c, l: Math.min(c - 1, straightKills(VACATED_FOG_ARMIES, rates.defensiveKillRate)) + 1 });
638
+ continue;
639
+ }
640
+ const shown = st?.owner.kind === 'player' ? st.owner.playerId : undefined;
641
+ // #428: its last sighting, under the owner the fog shows now (or any, when it shows none).
642
+ const seen = opts.lastSeen?.get(t);
643
+ if (seen && (shown === undefined || seen.owner === shown)) {
644
+ known(t, seen.armies);
645
+ if (remaining.some(bonusTarget))
646
+ sayOnce(lastSeenSaid, t, b, `${label(t)}, fogged now, was last seen at ${seen.armies} armies (#428): costed at that.`);
647
+ continue;
648
+ }
475
649
  // #201: a neutral the picking board showed keeps its size (an owner the fog shows is not one).
476
650
  const was = opts.rememberedNeutrals?.get(t);
477
- if (was === undefined || (st && st.owner.kind === 'player')) {
478
- fogged++;
651
+ if (was === undefined || shown !== undefined) {
652
+ // #428: a member whose owner is hidden too is costed as the game's neutral size, when known.
653
+ if (shown === undefined && Number.isFinite(neutralCost))
654
+ foggedNeutral++;
655
+ else
656
+ fogged++;
479
657
  continue;
480
658
  }
481
- const c = costAt(t, was) ?? Infinity;
482
- cost += c;
483
- worst = Math.max(worst, c);
484
- const l = Math.min(c - 1, straightKills(was, rates.defensiveKillRate)) + 1;
485
- loss += l;
486
- worstLoss = Math.max(worstLoss, l);
487
- if (remaining.some(bonusTarget)) {
488
- // Said once per territory, naming every bonus it is costed in.
489
- const said = rememberedSaid.get(t);
490
- const tail = `${label(t)}, fogged now, was a neutral of ${was} on the picking board (#201): costed at that.`;
491
- if (said) {
492
- said.bonuses.push(`${b.name} (#${b.id})`);
493
- rationale[said.at] = `${said.bonuses.join(', ')}: ${tail}`;
494
- }
495
- else {
496
- rememberedSaid.set(t, { at: rationale.length, bonuses: [`${b.name} (#${b.id})`] });
497
- rationale.push(`${b.name} (#${b.id}): ${tail}`);
498
- }
499
- }
659
+ known(t, was);
660
+ if (remaining.some(bonusTarget))
661
+ sayOnce(rememberedSaid, t, b, `${label(t)}, fogged now, was a neutral of ${was} on the picking board (#201): costed at that.`);
500
662
  continue;
501
663
  }
502
664
  const c = costAt(t) ?? Infinity;
503
665
  cost += c;
504
666
  worst = Math.max(worst, c);
667
+ if (isWasteland(st))
668
+ wastelands.push(t);
505
669
  const l = econCostAt(t);
506
670
  loss += l;
507
671
  worstLoss = Math.max(worstLoss, l);
508
672
  }
509
- let fogEach = fogged ? (fogged < remaining.length ? worst : Infinity) : 0;
510
- let fogLoss = fogged ? (fogged < remaining.length ? worstLoss : Infinity) : 0;
673
+ // #417: a member a static seat left counts at the lesser of its VACATED_FOG_ARMIES cost and the
674
+ // costliest member in view; with none in view (only fog), at that cost.
675
+ const inView = remaining.length - fogged - foggedNeutral - vacatedFog.length > 0;
676
+ for (const v of vacatedFog) {
677
+ const c = inView ? Math.min(v.c, worst) : v.c;
678
+ cost += c;
679
+ loss += inView ? Math.min(v.l, worstLoss) : v.l;
680
+ if (remaining.some(bonusTarget))
681
+ sayOnce(rememberedSaid, v.t, b, `${label(v.t)}, fogged now, was player ${v.left}'s (out, no AI): its land behind a border stack stands on ${VACATED_FOG_ARMIES} at most, so it is costed at ${c}, not at a stack in view (#417).`);
682
+ }
683
+ let fogEach = fogged ? (inView ? worst : Infinity) : 0;
684
+ let fogLoss = fogged ? (inView ? worstLoss : Infinity) : 0;
685
+ let neutralEach = foggedNeutral ? neutralCost : 0;
686
+ let neutralEachLoss = foggedNeutral ? neutralLoss : 0;
511
687
  // #167: with automatic Wastelands, a fogged member may be one: its expected surcharge over an
512
688
  // ordinary member is (wastelands ÷ territories on the map) × (a wasteland's cost − this one's).
513
- if (wasteShare > 0 && fogged && Number.isFinite(fogEach)) {
514
- const extra = Math.ceil(wasteShare * Math.max(0, wasteCost - fogEach));
515
- const extraLoss = Math.ceil(wasteShare * Math.max(0, wasteLoss - fogLoss));
516
- if (extra > 0) {
517
- fogEach += extra;
518
- fogLoss += extraLoss;
519
- if (remaining.some(bonusTarget))
520
- rationale.push(`${b.name} (#${b.id}): its ${fogged} fogged member${fogged === 1 ? '' : 's'} may be ${fogged === 1 ? 'a wasteland' : 'wastelands'} (${s.wastelands.count} of the map's ${g.territoryById.size} territories start at ${s.wastelands.size}): +${extra * fogged} armies expected.`);
521
- }
689
+ if (wasteShare > 0 && (fogged || foggedNeutral)) {
690
+ // The loss rises with the cost only (an expected surcharge of 0 adds no loss either).
691
+ const surcharge = (each, eachLoss) => {
692
+ const extra = Number.isFinite(each) ? Math.ceil(wasteShare * Math.max(0, wasteCost - each)) : 0;
693
+ return { extra, extraLoss: extra > 0 ? Math.ceil(wasteShare * Math.max(0, wasteLoss - eachLoss)) : 0 };
694
+ };
695
+ const a = fogged ? surcharge(fogEach, fogLoss) : { extra: 0, extraLoss: 0 };
696
+ const n = foggedNeutral ? surcharge(neutralEach, neutralEachLoss) : { extra: 0, extraLoss: 0 };
697
+ fogEach += a.extra;
698
+ fogLoss += a.extraLoss;
699
+ neutralEach += n.extra;
700
+ neutralEachLoss += n.extraLoss;
701
+ const count = (a.extra > 0 ? fogged : 0) + (n.extra > 0 ? foggedNeutral : 0);
702
+ const expected = a.extra * fogged + n.extra * foggedNeutral;
703
+ if (expected > 0 && remaining.some(bonusTarget))
704
+ rationale.push(`${b.name} (#${b.id}): its ${count} fogged member${count === 1 ? '' : 's'} may be ${count === 1 ? 'a wasteland' : 'wastelands'} (${s.wastelands.count} of the map's ${g.territoryById.size} territories start at ${s.wastelands.size}): +${expected} armies expected.`);
705
+ }
706
+ cost += fogged * fogEach + foggedNeutral * neutralEach;
707
+ loss += fogged * fogLoss + foggedNeutral * neutralEachLoss;
708
+ const fogNeutral = foggedNeutral ? { count: foggedNeutral, each: neutralEach, size: neutralSize } : undefined;
709
+ // #432: while the gate budget is short, no bonus is built through a wasteland: its armies go to the gates —
710
+ // unless this turn's captures can complete it (owner decision 2026-11-22: a completing wasteland is taken).
711
+ const wasteStop = !isFocus && pc.shortGates !== undefined && wastelands.length > 0 && !remaining.every(bonusTarget);
712
+ const economic = isFocus || (loss <= paybackTurns * net && worstLoss <= WASTELAND_FACTOR * net && !wasteStop);
713
+ // #435: a shared bonus I am nearer to but that is not worth working stays as C3.3 left it — skipped
714
+ // with its members plain expansion, never marked uneconomic (45701358 turn 1: a 344-member super-bonus,
715
+ // 6 members to my teammate's 5, would otherwise have stopped expansion into all its members).
716
+ if (handover.length && !economic) {
717
+ if (remaining.some(bonusTarget))
718
+ rationale.push(`Skip bonus ${b.name} (#${b.id}): my teammate holds ${handover.map(label).join(', ')}, and a bonus pays only the player holding all of it.`);
719
+ continue;
522
720
  }
523
- cost += fogged * fogEach;
524
- loss += fogged * fogLoss;
525
721
  if (b.value > 0)
526
- finishCost.set(b.id, { cost, value: b.value, net, fogged, fogEach });
527
- const economic = isFocus || (loss <= paybackTurns * net && worstLoss <= WASTELAND_FACTOR * net);
722
+ finishCost.set(b.id, { cost, value: b.value, net, fogged, fogEach, ...(fogNeutral ? { fogNeutral } : {}) });
528
723
  for (const t of remaining)
529
724
  (economic ? economicMember : uneconomicMember).add(t);
530
725
  if (!remaining.some(bonusTarget))
531
726
  continue;
727
+ if (!economic && wasteStop && loss <= paybackTurns * net && worstLoss <= WASTELAND_FACTOR * net) {
728
+ rationale.push(`Skip bonus ${b.name} (#${b.id}): finishing it means taking the wasteland${wastelands.length === 1 ? '' : 's'} ${wastelands.map(label).join(', ')} (${s.wastelands.size} armies or more) while the gates facing player ${pc.shortGates.player} are ${pc.shortGates.deficit} short (#432).`);
729
+ continue;
730
+ }
532
731
  if (!economic) {
533
- rationale.push(`Skip bonus ${b.name} (#${b.id}): uneconomic for +${net === b.value ? b.value : `${b.value} (net +${net})`} (${toFinish(cost, fogged, fogEach)}, losing ~${loss}; ${worstLoss} lost on its costliest territory).`);
732
+ rationale.push(`Skip bonus ${b.name} (#${b.id}): uneconomic for +${net === b.value ? b.value : `${b.value} (net +${net})`} (${toFinish(cost, { fogged, fogEach, fogNeutral })}, losing ~${loss}; ${worstLoss} lost on its costliest territory).`);
534
733
  continue;
535
734
  }
735
+ // #435: said once the bonus is worth working (an uneconomic one says only that).
736
+ if (handover.length) {
737
+ const mineN = ts.filter((t) => mineSet.has(t)).length;
738
+ rationale.push(`Bonus ${b.name} (#${b.id}): I hold ${mineN} of its ${ts.length} members, my teammate ${handover.length} — I am nearer, so it is mine to work ` +
739
+ `(#435); it pays only once my teammate hands over ${handover.map(label).join(', ')} (a Gift), so no capture here completes it.`);
740
+ }
536
741
  // R3: what holding the completed bonus's frontier would cost next turn (each
537
742
  // remaining member holding the survivors of its capture, mine their armies now).
538
743
  let defenseCost = 0;
539
- if (guarded && remaining.every(bonusTarget)) {
744
+ if (guarded && !handover.length && remaining.every(bonusTarget)) {
540
745
  const rem = new Set(remaining);
541
746
  const exposed = exposure(ts, (n) => rem.has(n), (m) => {
542
747
  if (!rem.has(m))
@@ -550,13 +755,14 @@ export function bonusScoring(pc, ps, threats, prev) {
550
755
  }
551
756
  // #71: the frontier its missing members add (their hold need left out when R3 judged it).
552
757
  const reach = remaining.filter((t) => targets.has(t));
553
- const frontier = frontierDelta(mineSet, reach, (x) => (mineSet.has(x) ? armiesOf(x) : survivorsOf(x)), !(guarded && remaining.every(bonusTarget))).armies;
758
+ const frontier = frontierDelta(mineSet, reach, (x) => (mineSet.has(x) ? armiesOf(x) : survivorsOf(x)), !(guarded && !handover.length && remaining.every(bonusTarget))).armies;
554
759
  plans.push({
555
760
  bonusId: b.id,
556
761
  value: b.value,
557
762
  focus: isFocus,
558
763
  remaining,
559
- completable: remaining.every(bonusTarget),
764
+ // #435: never complete while a teammate's member is still theirs.
765
+ completable: !handover.length && remaining.every(bonusTarget),
560
766
  cost,
561
767
  borders: analyzeBonus(g, b.id).borderTerritoryIds.length,
562
768
  defenseCost,
@@ -564,6 +770,7 @@ export function bonusScoring(pc, ps, threats, prev) {
564
770
  frontier,
565
771
  fogged,
566
772
  fogEach,
773
+ ...(fogNeutral ? { fogNeutral } : {}),
567
774
  });
568
775
  }
569
776
  const ratio = (p) => {
@@ -573,28 +780,53 @@ export function bonusScoring(pc, ps, threats, prev) {
573
780
  plans.sort((a, b) => Number(b.focus) - Number(a.focus) || ratio(b) - ratio(a) || a.borders - b.borders || a.bonusId - b.bonusId);
574
781
  return { fogNote, toFinish, plans, wasteShare, wasteCost, wasteLoss, finishCost, economicMember, uneconomicMember, negativeMember, rememberedSaid, ratio };
575
782
  }
783
+ /**
784
+ * #435: whether I alone hold the most members of `ts` among me and each teammate visibly holding one
785
+ * (the `nearer` of team.sharedBonuses, plan/team.ts); a tie is nobody's.
786
+ */
787
+ function nearerMe(pc, ts) {
788
+ const mine = ts.filter((t) => pc.mineSet.has(t)).length;
789
+ const per = new Map();
790
+ for (const t of ts) {
791
+ const o = pc.territories.get(t)?.owner;
792
+ if (o?.kind === 'player' && pc.allies.has(o.playerId))
793
+ per.set(o.playerId, (per.get(o.playerId) ?? 0) + 1);
794
+ }
795
+ return mine > Math.max(0, ...per.values());
796
+ }
576
797
  /** #319: the opening warning's bound: at least this many territories held with no bonus. */
577
798
  export const SPREAD_TERRITORIES = 10;
578
799
  /** #319: the last turn the opening warning runs on (from turn 2). */
579
800
  export const SPREAD_LAST_TURN = 6;
580
801
  /** #319: "near base": an income at most this much above the base income. */
581
802
  export const SPREAD_INCOME_SLACK = 3;
803
+ /** #416: the least value a bonus held in full needs to end rule 4f's commitment and #319's warning. */
804
+ export const HOLDS_BONUS_MIN_VALUE = 2;
582
805
  /** #101: commit to the bonus closest to completion; a break's retake check; #319's spread warning. */
583
- export function closestBonus(pc, ps, input, prev) {
584
- const { g, me, income, profile, territories: state, label, bonusName, mine, mineSet, bonusTs, toTake } = pc;
585
- const { rationale } = ps;
806
+ export function closestBonus(pc, ps, input, prev, hd) {
807
+ const { g, me, income, profile, territories: state, label, bonusName, mine, mineSet, bonusTs, toTake, armiesOf, guard } = pc;
808
+ const { rationale, avail } = ps;
586
809
  const { fogNote, plans } = prev;
587
810
  // ---- #101: commit to the closest bonus ----
588
811
  // While no bonus is held (and in the opening and expansion phases), expansion goes to the bonus
589
812
  // closest to completion — fewest turns to finish at this income (its armies to finish, counting
590
813
  // the members I hold, over the income) — then the next closest, instead of one capture into each
591
- // of several large bonuses by value per army. Bonuses as close as each other keep the score order
592
- // (value per army, rule 4), except that a bonus advanced last turn (a member captured since
593
- // `previousBoard`) keeps priority unless another is strictly closer. Focused bonuses come first.
594
- const holdsBonus = g.map.bonuses.some((b) => {
814
+ // of several large bonuses by value per army. Bonuses as close as each other go by the income per
815
+ // army of every bonus their capture completes (#438: a pair bonus on top of a single-territory one
816
+ // counts), then a bonus advanced last turn (a member captured since `previousBoard`) first, then the
817
+ // score order (value per army, rule 4). Focused bonuses come first.
818
+ // #416: a bonus held counts only from HOLDS_BONUS_MIN_VALUE up: one point of income is no base to build
819
+ // on, and holding a +1 silenced #319 in a live game while the captures stayed spread.
820
+ const heldValues = g.map.bonuses
821
+ .filter((b) => {
595
822
  const ts = bonusTs.get(b.id);
596
823
  return b.value > 0 && ts.length > 0 && ts.every((t) => mineSet.has(t));
597
- });
824
+ })
825
+ .map((b) => b.value);
826
+ const holdsBonus = heldValues.some((v) => v >= HOLDS_BONUS_MIN_VALUE);
827
+ /** #416: a bonus is held, but none worth HOLDS_BONUS_MIN_VALUE: the lines say so instead of "no bonus". */
828
+ const holdsSmallOnly = !holdsBonus && heldValues.length > 0;
829
+ const noBonusText = holdsSmallOnly ? `no bonus worth more than +${HOLDS_BONUS_MIN_VALUE - 1}` : 'no bonus';
598
830
  // #132: in an FFA, contact with one front still leaves neutrals to expand into: keep committing
599
831
  // while any neutral borders a territory of mine.
600
832
  const neutralsInReach = profile.format === 'ffa' && mine.some((t) => neighborsOf(g, t).some((n) => state.get(n)?.owner.kind === 'neutral'));
@@ -618,29 +850,99 @@ export function closestBonus(pc, ps, input, prev) {
618
850
  */
619
851
  const fromMine = bfsDistances(g, mine);
620
852
  const depthOf = (p) => Math.max(0, ...p.remaining.map((t) => fromMine.get(t) ?? 0));
621
- /** Turns to finish a bonus at this income, and at least its depth (with no income, its armies to finish). */
622
- const turnsOf = (p) => (income > 0 ? Math.max(Math.ceil(p.cost / income), depthOf(p)) : p.cost);
853
+ /**
854
+ * #416: the armies already standing beside a bonus's missing members — each territory of mine next to
855
+ * one, counted once, with what it can send beyond the guard and beyond what holds it (`keepFor`:
856
+ * exact holds come first). A start on 10 armies beside a bonus finishes it without waiting for the
857
+ * income, so counting only the income ranked it level with a bonus the deploys need two turns for.
858
+ */
859
+ const standing = new Map();
860
+ const standingBeside = (p) => {
861
+ const was = standing.get(p.bonusId);
862
+ if (was !== undefined)
863
+ return was;
864
+ const rest = new Set(p.remaining);
865
+ let n = 0;
866
+ for (const x of mine) {
867
+ if (!neighborsOf(g, x).some((t) => rest.has(t)))
868
+ continue;
869
+ const movable = Math.min(avail.get(x) ?? 0, armiesOf(x) - guard);
870
+ const keep = hd ? hd.keepFor(x, () => false) : 0;
871
+ n += Math.max(0, movable - keep);
872
+ }
873
+ const credit = Math.min(n, p.cost);
874
+ standing.set(p.bonusId, credit);
875
+ return credit;
876
+ };
877
+ /**
878
+ * Turns to finish a bonus at this income once the armies standing beside it are spent (#416), and at
879
+ * least its depth (with no income, its armies to finish less those).
880
+ */
881
+ const turnsOf = (p) => {
882
+ const left = Math.max(0, p.cost - standingBeside(p));
883
+ return income > 0 ? Math.max(Math.ceil(left / income), depthOf(p)) : left;
884
+ };
623
885
  const scoreRank = new Map(plans.map((p, i) => [p.bonusId, i]));
624
- /** Bonus plans closest to completion first (focus first; ties: advanced last turn, then the score order). */
886
+ /**
887
+ * #438: every bonus a plan's capture completes — each plan whose missing members are all among
888
+ * its own (a pair bonus beside a single-territory one) — with their net income added up.
889
+ */
890
+ const completesWith = (p) => plans.filter((q) => q.remaining.every((t) => p.remaining.includes(t)));
891
+ const incomeOf = (p) => completesWith(p).reduce((n, q) => n + q.net, 0);
892
+ /** #438: that income per army, on the score's cost (`ratio`, scaled from this bonus's net to the sum). */
893
+ const perArmy = (p) => {
894
+ const r = prev.ratio(p);
895
+ return Number.isFinite(r) && p.net > 0 ? (r * incomeOf(p)) / p.net : r;
896
+ };
897
+ /** #416: its missing members in the fog, however each is costed. */
898
+ const foggedOf = (p) => p.fogged + (p.fogNeutral?.count ?? 0);
899
+ /**
900
+ * Bonus plans closest to completion first (focus first; ties: the income per army of every bonus
901
+ * the capture completes, #438, then #416's fewer armies to finish and fewer fogged members — the
902
+ * figure least likely to be wrong —, then advanced last turn, then the score order). #416 asked for
903
+ * its keys first; ahead of #438 they ranked a cheap +3 over completing a bonus that lifts a −8
904
+ * penalty (negative-bonuses (c): next income 20 → lower), so they only split what #438 leaves even.
905
+ */
625
906
  const byCloseness = committing
626
907
  ? [...plans].sort((a, b) => Number(b.focus) - Number(a.focus) ||
627
908
  turnsOf(a) - turnsOf(b) ||
909
+ perArmy(b) - perArmy(a) ||
910
+ a.cost - b.cost ||
911
+ foggedOf(a) - foggedOf(b) ||
628
912
  Number(advancedLast.has(b.bonusId)) - Number(advancedLast.has(a.bonusId)) ||
629
913
  scoreRank.get(a.bonusId) - scoreRank.get(b.bonusId))
630
914
  : plans;
631
915
  const turnsText = (p) => {
632
916
  const n = turnsOf(p);
633
- const deep = n > Math.ceil(p.cost / income) ? ` (${n} layers deep)` : '';
917
+ const deep = n > Math.max(1, Math.ceil(Math.max(0, p.cost - standingBeside(p)) / income)) ? ` (${n} layers deep)` : '';
634
918
  return income > 0 ? `${n} turn${n === 1 ? '' : 's'}${deep}` : 'no income';
635
919
  };
920
+ /** #416: the armies standing beside it, when any count toward its turns. */
921
+ const standingNote = (p) => {
922
+ const n = standingBeside(p);
923
+ return n > 0 ? ` (${n} standing beside it)` : '';
924
+ };
636
925
  if (committing && byCloseness.length > 1) {
637
926
  const why = holdsBonus
638
927
  ? `${profile.phase[0].toUpperCase()}${profile.phase.slice(1)} phase${profile.phase === 'opening' || profile.phase === 'expansion' ? '' : ', neutrals in reach'}`
639
- : 'No bonus held';
928
+ : `${noBonusText[0].toUpperCase()}${noBonusText.slice(1)} held`;
640
929
  rationale.push(`${why}: expansion goes to the bonus closest to completion first — ${byCloseness
641
- .map((p, i) => `${bonusName(p.bonusId)} ${i ? p.cost : `${p.cost} armies to finish`}${fogNote(p.fogged, p.fogEach)}, ${turnsText(p)}${i || income <= 0 ? '' : ` at income ${income}`}`)
930
+ .map((p, i) => `${bonusName(p.bonusId)} ${i ? p.cost : `${p.cost} armies to finish`}${fogNote(p)}${standingNote(p)}, ${turnsText(p)}${i || income <= 0 ? '' : ` at income ${income}`}`)
642
931
  .join(', ')} — and a farther bonus gets only armies the closer ones cannot use.`);
643
932
  const top = byCloseness.find((p) => !p.focus);
933
+ // #438: a capture that completes more than one bonus says what they add up to per army.
934
+ const said = new Set();
935
+ for (const p of byCloseness) {
936
+ const all = completesWith(p);
937
+ const key = [...p.remaining].sort((x, y) => x - y).join(',');
938
+ // Only where it ranks: another bonus as close that this capture does not complete.
939
+ const rivals = byCloseness.some((q) => !all.includes(q) && !q.focus && turnsOf(q) === turnsOf(p));
940
+ if (all.length < 2 || !rivals || said.has(key))
941
+ continue;
942
+ said.add(key);
943
+ const names = all.map((q) => bonusName(q.bonusId));
944
+ rationale.push(`${names.slice(0, -1).join(', ')} and ${names.at(-1)} complete together for ${p.cost} armies: +${incomeOf(p)} next-turn income, ${(incomeOf(p) / p.cost).toFixed(2)} per army — ranked on that among bonuses as close (#438).`);
945
+ }
644
946
  for (const p of byCloseness.filter((x) => advancedLast.has(x.bonusId))) {
645
947
  if (p === top)
646
948
  rationale.push(`${bonusName(p.bonusId)} keeps priority: I advanced it last turn, and no bonus is strictly closer to completion.`);
@@ -660,9 +962,9 @@ export function closestBonus(pc, ps, input, prev) {
660
962
  mine.length >= SPREAD_TERRITORIES &&
661
963
  income <= base + SPREAD_INCOME_SLACK) {
662
964
  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}). ` +
965
+ ps.warnings.push(`${mine.length} territories, ${noBonusText}: the captures are spread (income ${income}, base ${base}). ` +
664
966
  (nearest
665
- ? `Nearest bonus to complete: ${bonusName(nearest.bonusId)}, ${nearest.cost} armies to finish${fogNote(nearest.fogged, nearest.fogEach)}, ` +
967
+ ? `Nearest bonus to complete: ${bonusName(nearest.bonusId)}, ${nearest.cost} armies to finish${fogNote(nearest)}${standingNote(nearest)}, ` +
666
968
  `${turnsText(nearest)}${income > 0 ? ` at income ${income}` : ''} (rule 4f).`
667
969
  : 'No bonus is worth completing from here.') +
668
970
  ' Complete one before taking more territories outside it (#319).');