@chrischall/warapp-mcp 0.5.0 → 0.7.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 (125) hide show
  1. package/.claude-plugin/marketplace.json +3 -3
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +133 -8
  4. package/dist/analysis/accept-surrender.js +20 -2
  5. package/dist/analysis/calibrate.js +1 -0
  6. package/dist/analysis/card-support.js +177 -17
  7. package/dist/analysis/card-threats.js +126 -14
  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/decision-replay.js +279 -0
  13. package/dist/analysis/decision-truth.js +146 -0
  14. package/dist/analysis/finished-game.js +62 -3
  15. package/dist/analysis/game-lessons.js +15 -10
  16. package/dist/analysis/hold-diff.js +3 -1
  17. package/dist/analysis/income-trend.js +38 -0
  18. package/dist/analysis/intel.js +75 -0
  19. package/dist/analysis/opens.js +64 -0
  20. package/dist/analysis/opponent-profile.js +121 -10
  21. package/dist/analysis/opponents.js +246 -20
  22. package/dist/analysis/outlook.js +360 -15
  23. package/dist/analysis/picks.js +91 -12
  24. package/dist/analysis/plan/after-leftover.js +4 -1
  25. package/dist/analysis/plan/bonus-attempts.js +105 -0
  26. package/dist/analysis/plan/capture-instead.js +116 -0
  27. package/dist/analysis/plan/captures.js +49 -7
  28. package/dist/analysis/plan/conceded-out.js +13 -2
  29. package/dist/analysis/plan/estimates.js +203 -30
  30. package/dist/analysis/plan/guard-off.js +2 -1
  31. package/dist/analysis/plan/holds.js +110 -9
  32. package/dist/analysis/plan/jabs.js +113 -0
  33. package/dist/analysis/plan/leftover.js +393 -8
  34. package/dist/analysis/plan/orders.js +76 -4
  35. package/dist/analysis/plan/relations.js +135 -2
  36. package/dist/analysis/plan/report.js +69 -3
  37. package/dist/analysis/plan/second-sizing.js +133 -0
  38. package/dist/analysis/plan/shared.js +279 -27
  39. package/dist/analysis/plan/siege.js +303 -0
  40. package/dist/analysis/plan/stand-still.js +9 -5
  41. package/dist/analysis/plan/state.js +8 -0
  42. package/dist/analysis/plan/stockpile.js +104 -0
  43. package/dist/analysis/plan/strike.js +39 -7
  44. package/dist/analysis/plan/targets.js +256 -110
  45. package/dist/analysis/plan/threats.js +148 -10
  46. package/dist/analysis/plan/transfers.js +57 -6
  47. package/dist/analysis/plan/two-move.js +70 -0
  48. package/dist/analysis/plan/vacated.js +124 -2
  49. package/dist/analysis/planner.js +527 -49
  50. package/dist/analysis/profile.js +13 -2
  51. package/dist/analysis/since-last.js +18 -5
  52. package/dist/analysis/stress.js +8 -2
  53. package/dist/board.js +36 -2
  54. package/dist/bonus-attempt-store.js +55 -0
  55. package/dist/build-id.js +106 -0
  56. package/dist/bundle.js +54138 -41059
  57. package/dist/cards.js +7 -5
  58. package/dist/chat-automation.js +22 -0
  59. package/dist/chat.js +35 -1
  60. package/dist/client.js +14 -0
  61. package/dist/commerce.js +111 -0
  62. package/dist/decision-log.js +1093 -0
  63. package/dist/finished-store.js +5 -1
  64. package/dist/index.js +9 -1
  65. package/dist/lessons-store.js +322 -21
  66. package/dist/live.js +43 -0
  67. package/dist/move-order.js +64 -3
  68. package/dist/normalize.js +17 -0
  69. package/dist/open-games.js +36 -16
  70. package/dist/outlook-log.js +42 -1
  71. package/dist/profile-store.js +12 -2
  72. package/dist/protocol/methods.js +62 -5
  73. package/dist/protocol/rpc.js +8 -0
  74. package/dist/relations-store.js +38 -4
  75. package/dist/review-export.js +198 -0
  76. package/dist/siege-store.js +49 -0
  77. package/dist/state-bundle.js +584 -0
  78. package/dist/state-cli.js +71 -0
  79. package/dist/strategy/notes.js +56 -0
  80. package/dist/team-cards.js +25 -0
  81. package/dist/tools/accept-surrender.js +23 -9
  82. package/dist/tools/award.js +20 -2
  83. package/dist/tools/card-advice.js +93 -28
  84. package/dist/tools/card-plays.js +2 -2
  85. package/dist/tools/card-support-advice.js +37 -7
  86. package/dist/tools/chat-advice.js +330 -0
  87. package/dist/tools/chat-inbox.js +19 -4
  88. package/dist/tools/chat.js +106 -17
  89. package/dist/tools/check-plan.js +68 -12
  90. package/dist/tools/commerce-deploy.js +33 -0
  91. package/dist/tools/common.js +31 -0
  92. package/dist/tools/decision-capture.js +459 -0
  93. package/dist/tools/end-of-game.js +151 -21
  94. package/dist/tools/game-kind.js +92 -0
  95. package/dist/tools/how-lost.js +7 -2
  96. package/dist/tools/index.js +10 -0
  97. package/dist/tools/join-game.js +10 -4
  98. package/dist/tools/live-context.js +6 -0
  99. package/dist/tools/live.js +10 -1
  100. package/dist/tools/map-curves.js +73 -0
  101. package/dist/tools/notifications.js +4 -3
  102. package/dist/tools/opponents.js +2 -0
  103. package/dist/tools/past-games.js +74 -8
  104. package/dist/tools/picks.js +61 -10
  105. package/dist/tools/profile-hook.js +62 -3
  106. package/dist/tools/profile-opponents.js +4 -0
  107. package/dist/tools/push.js +2 -2
  108. package/dist/tools/relations.js +139 -0
  109. package/dist/tools/scout.js +16 -2
  110. package/dist/tools/state.js +232 -0
  111. package/dist/tools/strategy.js +3 -3
  112. package/dist/tools/stress-opponents.js +7 -2
  113. package/dist/tools/surrender-pending.js +10 -1
  114. package/dist/tools/surrender.js +18 -3
  115. package/dist/tools/survival.js +11 -3
  116. package/dist/tools/team-brief.js +2 -2
  117. package/dist/tools/team.js +12 -3
  118. package/dist/tools/turn.js +643 -76
  119. package/dist/tools/where.js +3 -1
  120. package/dist/version.js +1 -1
  121. package/manifest.json +32 -3
  122. package/mint.yaml +37 -4
  123. package/package.json +4 -4
  124. package/server.json +20 -2
  125. package/skills/warapp-mcp/SKILL.md +73 -17
@@ -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
- import { denialsOf, emptyEnemiesOf } from './vacated.js';
8
+ import { denialsOf, emptyEnemiesOf, fogVacated, VACATED_FOG_ARMIES } 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,14 @@ 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)) : [])));
105
+ /** #421: the missing members of the contested bonuses a stockpile pushes all-in: targets, an opponent's included. */
106
+ const pileMembers = new Set([...(input.stockpileAllIn ?? [])].flatMap((id) => (g.bonusById.has(id) ? bonusTerritories(g, id).filter((t) => !mineSet.has(t)) : [])));
150
107
  /**
151
108
  * #240: territories my attacks failed on repeatedly while their owner reinforced them
152
109
  * (`input.repulsed`, {@link repulsedAttacks}): still that opponent's, armies in view, next to mine,
@@ -192,6 +149,55 @@ export function captureTargets(pc, ps, input, threats, prev) {
192
149
  .map((a) => `${a.armies} against ${a.before}, ${a.after} after`)
193
150
  .join('; ')}): a further attack is sized for ${size}.`);
194
151
  }
152
+ /**
153
+ * #298: a bonus pushed all-in (`input.bonusPush.allIn`, after two failed attempts): every missing
154
+ * member must be in view and beside a territory of mine; one another player holds is sized for its
155
+ * defenders plus its owner's deploy (#368's middle figure, `reinforcementAt`), like #240's sure size
156
+ * (taken at that size or not at all), a neutral at its capture cost. The push fits when the whole is at
157
+ * most ALL_IN_VALUE_TURNS × the bonus's value and at most my income; planTurn drops it otherwise.
158
+ */
159
+ const allInTries = new Map();
160
+ for (const bonusId of [...(input.bonusPush?.allIn ?? [])].sort(byNum)) {
161
+ const b = g.bonusById.get(bonusId);
162
+ if (!b)
163
+ continue;
164
+ // #421: a stockpile's push spends armies already on the board: capped at the payback horizon × its value.
165
+ const pile = input.stockpileAllIn?.has(bonusId) === true;
166
+ const cap = pile ? Math.max(0, pc.paybackTurns * b.value) : Math.max(0, Math.min(ALL_IN_VALUE_TURNS * b.value, pc.income));
167
+ const sized = [];
168
+ let why;
169
+ for (const t of bonusTerritories(g, bonusId).filter((x) => !mineSet.has(x))) {
170
+ const st = state.get(t);
171
+ if (!st || st.owner.kind === 'unknown' || st.armies === null)
172
+ why ??= `${label(t)} is out of view`;
173
+ else if (!neighborsOf(g, t).some((n) => mineSet.has(n)))
174
+ why ??= `${label(t)} is out of reach this turn`;
175
+ else if (uncounted(t))
176
+ why ??= `${label(t)} holds a special unit`;
177
+ else if (st.owner.kind === 'player' && !foe(st.owner.playerId))
178
+ why ??= `${label(t)} is my teammate's`;
179
+ else {
180
+ const defenders = defenceAt(t);
181
+ const extra = st.owner.kind === 'player' ? reinforcementAt(t) : 0;
182
+ const cost = costAt(t, defenders + extra);
183
+ if (cost === null)
184
+ why ??= `${label(t)} cannot be taken`;
185
+ else
186
+ sized.push({ t, ...(st.owner.kind === 'player' ? { player: st.owner.playerId } : {}), defenders, extra, cost });
187
+ }
188
+ }
189
+ const cost = sized.reduce((n, x) => n + x.cost, 0);
190
+ if (!why && cost > cap)
191
+ why = pile
192
+ ? `the push needs ${cost} armies, over the cap of ${cap} (${pc.paybackTurns} × its +${b.value}, #421)`
193
+ : `the push needs ${cost} armies, over the cap of ${cap} (${ALL_IN_VALUE_TURNS} × its +${b.value}, at most my income ${pc.income})`;
194
+ allInTries.set(bonusId, { feasible: !why, cost, cap, ...(why ? { detail: why } : {}) });
195
+ if (why)
196
+ continue;
197
+ for (const x of sized)
198
+ if (x.player !== undefined && x.extra > 0)
199
+ repulsed.set(x.t, { player: x.player, defenders: x.defenders, extra: x.extra, cost: x.cost, sure: true });
200
+ }
195
201
  /** A capture's cost of `t` (its ordinary sizing), or #240's sure one for a repulsed territory. */
196
202
  const costFor = (t) => repulsed.get(t)?.cost ?? costAt(t);
197
203
  /**
@@ -246,6 +252,16 @@ export function captureTargets(pc, ps, input, threats, prev) {
246
252
  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
253
  continue;
248
254
  }
255
+ // #417, the breach force: land a static seat left, hidden now, is attacked at the 2-defender price
256
+ // (`defenceAt` reads it so), until it is taken or the fog shows another player there.
257
+ if (fogVacated(pc.vacated, st, t)) {
258
+ const cost = costAt(t);
259
+ if (cost !== null) {
260
+ targets.set(t, { id: t, cost, enemy: false, sources });
261
+ 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).`);
262
+ continue;
263
+ }
264
+ }
249
265
  if (!st || st.owner.kind === 'unknown' || st.armies === null) {
250
266
  warnings.push(`Fogged territory ${label(t)} borders my ${sources.map(label).join(', ')}: its armies are unknown (fog), so no attack is planned.`);
251
267
  continue;
@@ -260,8 +276,8 @@ export function captureTargets(pc, ps, input, threats, prev) {
260
276
  continue;
261
277
  }
262
278
  const enemy = st.owner.kind === 'player';
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)))
279
+ if (enemy && goal !== 'complete-bonus' && !(balanced && (breakMember.has(t) || counterAt.has(t))) && !pileMembers.has(t)) {
280
+ if (!leadStepsOn || unitsAt(t) > 0 || droppedMembers.has(t) || !g.map.bonuses.some((b) => b.value > 0 && bonusTs.get(b.id).includes(t)))
265
281
  continue;
266
282
  const defenders = defenceAt(t);
267
283
  const extra = reinforcementAt(t);
@@ -280,8 +296,9 @@ export function captureTargets(pc, ps, input, threats, prev) {
280
296
  }
281
297
  // Bonus passes work toward my own bonuses; under `balanced` enemy targets are only break candidates.
282
298
  // #203: a lead step is a bonus target too.
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 };
299
+ // #421: a member of a contested bonus a stockpile pushes all-in is a bonus target too.
300
+ const bonusTarget = (t) => targets.has(t) && !(balanced && targets.get(t).enemy && !leadSteps.has(t) && !pileMembers.has(t));
301
+ return { targets, leadSteps, leadStepsOn, leadTry, leadNote, bonusTarget, repulsed, costFor, sizeOf, allInTries, bonusDropped, droppedMembers };
285
302
  }
286
303
  /** Rule 4d: what a capture adds to the frontier (#71), and the offence report (#72). */
287
304
  export function frontierCosts(pc, threats, hd, prev) {
@@ -392,9 +409,20 @@ export function bonusScoring(pc, ps, threats, prev) {
392
409
  const { exposure } = threats;
393
410
  const { targets, bonusTarget, survivorsOf, frontierDelta, scoreCost } = prev;
394
411
  // ---- 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)}`;
412
+ /**
413
+ * "N armies to finish", naming the fogged members counted in it (#101): those at the costliest visible
414
+ * member, and (#428) those costed as the game's neutral size.
415
+ */
416
+ const fogNote = (f) => {
417
+ const parts = [
418
+ ...(f.fogged ? [`${f.fogged} fogged member${f.fogged === 1 ? '' : 's'} counted at ${f.fogEach} each`] : []),
419
+ ...(f.fogNeutral
420
+ ? [`${f.fogNeutral.count} fogged member${f.fogNeutral.count === 1 ? '' : 's'} counted at ${f.fogNeutral.each} each: the game's neutral size, ${f.fogNeutral.size}`]
421
+ : []),
422
+ ];
423
+ return parts.length ? ` (${parts.join('; ')})` : '';
424
+ };
425
+ const toFinish = (cost, f) => `${cost} armies to finish${fogNote(f)}`;
398
426
  const plans = [];
399
427
  /** #167: the share of the map's territories that started as wastelands, and what one costs to take and loses. */
400
428
  const wasteShare = s.wastelands && s.wastelands.count > 0 && s.wastelands.size > 0 && g.territoryById.size > 0
@@ -410,6 +438,24 @@ export function bonusScoring(pc, ps, threats, prev) {
410
438
  const negativeMember = new Set();
411
439
  /** #201: a remembered neutral's rationale line (its index) and the bonuses it names. */
412
440
  const rememberedSaid = new Map();
441
+ /** #428: the same for a member costed at its last sighting. */
442
+ const lastSeenSaid = new Map();
443
+ /** Says once per territory, naming every bonus it is costed in (#201, #428). */
444
+ const sayOnce = (said, t, b, tail) => {
445
+ const was = said.get(t);
446
+ if (was) {
447
+ was.bonuses.push(`${b.name} (#${b.id})`);
448
+ rationale[was.at] = `${was.bonuses.join(', ')}: ${tail}`;
449
+ }
450
+ else {
451
+ said.set(t, { at: rationale.length, bonuses: [`${b.name} (#${b.id})`] });
452
+ rationale.push(`${b.name} (#${b.id}): ${tail}`);
453
+ }
454
+ };
455
+ // #428: the game's neutral size, costed once: a fogged member no board showed, whose owner the fog hides.
456
+ const neutralSize = s.neutralArmies !== undefined && s.neutralArmies >= 0 ? s.neutralArmies : undefined;
457
+ const neutralCost = neutralSize !== undefined ? (costOf(neutralSize) ?? Infinity) : Infinity;
458
+ const neutralLoss = neutralSize !== undefined && Number.isFinite(neutralCost) ? Math.min(neutralCost - 1, straightKills(neutralSize, rates.defensiveKillRate)) + 1 : Infinity;
413
459
  for (const b of [...g.map.bonuses].sort((x, y) => x.id - y.id)) {
414
460
  const isFocus = focus.has(b.id);
415
461
  const ts = bonusTerritories(g, b.id);
@@ -427,6 +473,12 @@ export function bonusScoring(pc, ps, threats, prev) {
427
473
  continue;
428
474
  if (!remaining.length)
429
475
  continue;
476
+ // #298: a bonus dropped after repeated failed attempts is not funded: its members are no bonus step.
477
+ if (prev.bonusDropped.has(b.id)) {
478
+ for (const t of remaining)
479
+ uneconomicMember.add(t);
480
+ continue;
481
+ }
430
482
  // PLAN-TEAMS C3.3: a bonus pays only the player holding every member, so one with a member my
431
483
  // teammate visibly holds is not mine to complete (plan/team.ts reports the shared ones).
432
484
  const mates = remaining.filter((t) => teammateAt(pc, t));
@@ -454,43 +506,62 @@ export function bonusScoring(pc, ps, threats, prev) {
454
506
  rationale.push(`Skip bonus ${b.name} (#${b.id}): completing it costs more income than it pays (net ${net}).`);
455
507
  continue;
456
508
  }
457
- // Armies to finish (#101): every missing member's capture cost. A fogged member counts at its
458
- // bonus's costliest visible missing member (it cannot be costed, and counting it as free made
459
- // the figure jump when it came into view); with none visible, the bonus cannot be costed.
509
+ // Armies to finish (#101): every missing member's capture cost. A fogged member a static seat left
510
+ // 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
511
+ // now), else (#201) its size on the picking board, else the game's neutral size (when its owner is
512
+ // hidden too); only with none of those does it count at its bonus's costliest visible missing
513
+ // member (counting it as free made the figure jump when it came into view; 65 finished-game plans
514
+ // counted every one at 208); with none visible either, the bonus cannot be costed.
460
515
  let cost = 0;
461
516
  let worst = 0;
462
517
  let fogged = 0;
518
+ let foggedNeutral = 0;
463
519
  // #125: the economy test charges the armies lost, not the armies sent.
464
520
  let loss = 0;
465
521
  let worstLoss = 0;
522
+ const known = (t, armies) => {
523
+ const c = costAt(t, armies) ?? Infinity;
524
+ cost += c;
525
+ worst = Math.max(worst, c);
526
+ const l = Math.min(c - 1, straightKills(armies, rates.defensiveKillRate)) + 1;
527
+ loss += l;
528
+ worstLoss = Math.max(worstLoss, l);
529
+ };
530
+ /** #417: the fogged members a static seat left, each with its cost and loss at VACATED_FOG_ARMIES. */
531
+ const vacatedFog = [];
466
532
  for (const t of remaining) {
467
533
  const st = state.get(t);
468
534
  if (!st || st.owner.kind === 'unknown' || st.armies === null) {
535
+ // #417 first: land a static seat left is thin behind its border stack: costed at most at
536
+ // VACATED_FOG_ARMIES defenders, and never raising what another fogged member counts at.
537
+ const left = pc.vacated.get(t);
538
+ if (left !== undefined) {
539
+ const c = costAt(t, VACATED_FOG_ARMIES) ?? Infinity;
540
+ vacatedFog.push({ t, left, c, l: Math.min(c - 1, straightKills(VACATED_FOG_ARMIES, rates.defensiveKillRate)) + 1 });
541
+ continue;
542
+ }
543
+ const shown = st?.owner.kind === 'player' ? st.owner.playerId : undefined;
544
+ // #428: its last sighting, under the owner the fog shows now (or any, when it shows none).
545
+ const seen = opts.lastSeen?.get(t);
546
+ if (seen && (shown === undefined || seen.owner === shown)) {
547
+ known(t, seen.armies);
548
+ if (remaining.some(bonusTarget))
549
+ sayOnce(lastSeenSaid, t, b, `${label(t)}, fogged now, was last seen at ${seen.armies} armies (#428): costed at that.`);
550
+ continue;
551
+ }
469
552
  // #201: a neutral the picking board showed keeps its size (an owner the fog shows is not one).
470
553
  const was = opts.rememberedNeutrals?.get(t);
471
- if (was === undefined || (st && st.owner.kind === 'player')) {
472
- fogged++;
554
+ if (was === undefined || shown !== undefined) {
555
+ // #428: a member whose owner is hidden too is costed as the game's neutral size, when known.
556
+ if (shown === undefined && Number.isFinite(neutralCost))
557
+ foggedNeutral++;
558
+ else
559
+ fogged++;
473
560
  continue;
474
561
  }
475
- const c = costAt(t, was) ?? Infinity;
476
- cost += c;
477
- worst = Math.max(worst, c);
478
- const l = Math.min(c - 1, straightKills(was, rates.defensiveKillRate)) + 1;
479
- loss += l;
480
- worstLoss = Math.max(worstLoss, l);
481
- if (remaining.some(bonusTarget)) {
482
- // Said once per territory, naming every bonus it is costed in.
483
- const said = rememberedSaid.get(t);
484
- const tail = `${label(t)}, fogged now, was a neutral of ${was} on the picking board (#201): costed at that.`;
485
- if (said) {
486
- said.bonuses.push(`${b.name} (#${b.id})`);
487
- rationale[said.at] = `${said.bonuses.join(', ')}: ${tail}`;
488
- }
489
- else {
490
- rememberedSaid.set(t, { at: rationale.length, bonuses: [`${b.name} (#${b.id})`] });
491
- rationale.push(`${b.name} (#${b.id}): ${tail}`);
492
- }
493
- }
562
+ known(t, was);
563
+ if (remaining.some(bonusTarget))
564
+ sayOnce(rememberedSaid, t, b, `${label(t)}, fogged now, was a neutral of ${was} on the picking board (#201): costed at that.`);
494
565
  continue;
495
566
  }
496
567
  const c = costAt(t) ?? Infinity;
@@ -500,31 +571,51 @@ export function bonusScoring(pc, ps, threats, prev) {
500
571
  loss += l;
501
572
  worstLoss = Math.max(worstLoss, l);
502
573
  }
503
- let fogEach = fogged ? (fogged < remaining.length ? worst : Infinity) : 0;
504
- let fogLoss = fogged ? (fogged < remaining.length ? worstLoss : Infinity) : 0;
574
+ // #417: a member a static seat left counts at the lesser of its VACATED_FOG_ARMIES cost and the
575
+ // costliest member in view; with none in view (only fog), at that cost.
576
+ const inView = remaining.length - fogged - foggedNeutral - vacatedFog.length > 0;
577
+ for (const v of vacatedFog) {
578
+ const c = inView ? Math.min(v.c, worst) : v.c;
579
+ cost += c;
580
+ loss += inView ? Math.min(v.l, worstLoss) : v.l;
581
+ if (remaining.some(bonusTarget))
582
+ 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).`);
583
+ }
584
+ let fogEach = fogged ? (inView ? worst : Infinity) : 0;
585
+ let fogLoss = fogged ? (inView ? worstLoss : Infinity) : 0;
586
+ let neutralEach = foggedNeutral ? neutralCost : 0;
587
+ let neutralEachLoss = foggedNeutral ? neutralLoss : 0;
505
588
  // #167: with automatic Wastelands, a fogged member may be one: its expected surcharge over an
506
589
  // ordinary member is (wastelands ÷ territories on the map) × (a wasteland's cost − this one's).
507
- if (wasteShare > 0 && fogged && Number.isFinite(fogEach)) {
508
- const extra = Math.ceil(wasteShare * Math.max(0, wasteCost - fogEach));
509
- const extraLoss = Math.ceil(wasteShare * Math.max(0, wasteLoss - fogLoss));
510
- if (extra > 0) {
511
- fogEach += extra;
512
- fogLoss += extraLoss;
513
- if (remaining.some(bonusTarget))
514
- 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.`);
515
- }
590
+ if (wasteShare > 0 && (fogged || foggedNeutral)) {
591
+ // The loss rises with the cost only (an expected surcharge of 0 adds no loss either).
592
+ const surcharge = (each, eachLoss) => {
593
+ const extra = Number.isFinite(each) ? Math.ceil(wasteShare * Math.max(0, wasteCost - each)) : 0;
594
+ return { extra, extraLoss: extra > 0 ? Math.ceil(wasteShare * Math.max(0, wasteLoss - eachLoss)) : 0 };
595
+ };
596
+ const a = fogged ? surcharge(fogEach, fogLoss) : { extra: 0, extraLoss: 0 };
597
+ const n = foggedNeutral ? surcharge(neutralEach, neutralEachLoss) : { extra: 0, extraLoss: 0 };
598
+ fogEach += a.extra;
599
+ fogLoss += a.extraLoss;
600
+ neutralEach += n.extra;
601
+ neutralEachLoss += n.extraLoss;
602
+ const count = (a.extra > 0 ? fogged : 0) + (n.extra > 0 ? foggedNeutral : 0);
603
+ const expected = a.extra * fogged + n.extra * foggedNeutral;
604
+ if (expected > 0 && remaining.some(bonusTarget))
605
+ 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.`);
516
606
  }
517
- cost += fogged * fogEach;
518
- loss += fogged * fogLoss;
607
+ cost += fogged * fogEach + foggedNeutral * neutralEach;
608
+ loss += fogged * fogLoss + foggedNeutral * neutralEachLoss;
609
+ const fogNeutral = foggedNeutral ? { count: foggedNeutral, each: neutralEach, size: neutralSize } : undefined;
519
610
  if (b.value > 0)
520
- finishCost.set(b.id, { cost, value: b.value, net, fogged, fogEach });
611
+ finishCost.set(b.id, { cost, value: b.value, net, fogged, fogEach, ...(fogNeutral ? { fogNeutral } : {}) });
521
612
  const economic = isFocus || (loss <= paybackTurns * net && worstLoss <= WASTELAND_FACTOR * net);
522
613
  for (const t of remaining)
523
614
  (economic ? economicMember : uneconomicMember).add(t);
524
615
  if (!remaining.some(bonusTarget))
525
616
  continue;
526
617
  if (!economic) {
527
- 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).`);
618
+ 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).`);
528
619
  continue;
529
620
  }
530
621
  // R3: what holding the completed bonus's frontier would cost next turn (each
@@ -558,6 +649,7 @@ export function bonusScoring(pc, ps, threats, prev) {
558
649
  frontier,
559
650
  fogged,
560
651
  fogEach,
652
+ ...(fogNeutral ? { fogNeutral } : {}),
561
653
  });
562
654
  }
563
655
  const ratio = (p) => {
@@ -567,7 +659,13 @@ export function bonusScoring(pc, ps, threats, prev) {
567
659
  plans.sort((a, b) => Number(b.focus) - Number(a.focus) || ratio(b) - ratio(a) || a.borders - b.borders || a.bonusId - b.bonusId);
568
660
  return { fogNote, toFinish, plans, wasteShare, wasteCost, wasteLoss, finishCost, economicMember, uneconomicMember, negativeMember, rememberedSaid, ratio };
569
661
  }
570
- /** #101: commit to the bonus closest to completion; a break's retake check. */
662
+ /** #319: the opening warning's bound: at least this many territories held with no bonus. */
663
+ export const SPREAD_TERRITORIES = 10;
664
+ /** #319: the last turn the opening warning runs on (from turn 2). */
665
+ export const SPREAD_LAST_TURN = 6;
666
+ /** #319: "near base": an income at most this much above the base income. */
667
+ export const SPREAD_INCOME_SLACK = 3;
668
+ /** #101: commit to the bonus closest to completion; a break's retake check; #319's spread warning. */
571
669
  export function closestBonus(pc, ps, input, prev) {
572
670
  const { g, me, income, profile, territories: state, label, bonusName, mine, mineSet, bonusTs, toTake } = pc;
573
671
  const { rationale } = ps;
@@ -576,9 +674,10 @@ export function closestBonus(pc, ps, input, prev) {
576
674
  // While no bonus is held (and in the opening and expansion phases), expansion goes to the bonus
577
675
  // closest to completion — fewest turns to finish at this income (its armies to finish, counting
578
676
  // the members I hold, over the income) — then the next closest, instead of one capture into each
579
- // of several large bonuses by value per army. Bonuses as close as each other keep the score order
580
- // (value per army, rule 4), except that a bonus advanced last turn (a member captured since
581
- // `previousBoard`) keeps priority unless another is strictly closer. Focused bonuses come first.
677
+ // of several large bonuses by value per army. Bonuses as close as each other go by the income per
678
+ // army of every bonus their capture completes (#438: a pair bonus on top of a single-territory one
679
+ // counts), then a bonus advanced last turn (a member captured since `previousBoard`) first, then the
680
+ // score order (value per army, rule 4). Focused bonuses come first.
582
681
  const holdsBonus = g.map.bonuses.some((b) => {
583
682
  const ts = bonusTs.get(b.id);
584
683
  return b.value > 0 && ts.length > 0 && ts.every((t) => mineSet.has(t));
@@ -609,10 +708,25 @@ export function closestBonus(pc, ps, input, prev) {
609
708
  /** Turns to finish a bonus at this income, and at least its depth (with no income, its armies to finish). */
610
709
  const turnsOf = (p) => (income > 0 ? Math.max(Math.ceil(p.cost / income), depthOf(p)) : p.cost);
611
710
  const scoreRank = new Map(plans.map((p, i) => [p.bonusId, i]));
612
- /** Bonus plans closest to completion first (focus first; ties: advanced last turn, then the score order). */
711
+ /**
712
+ * #438: every bonus a plan's capture completes — each plan whose missing members are all among
713
+ * its own (a pair bonus beside a single-territory one) — with their net income added up.
714
+ */
715
+ const completesWith = (p) => plans.filter((q) => q.remaining.every((t) => p.remaining.includes(t)));
716
+ const incomeOf = (p) => completesWith(p).reduce((n, q) => n + q.net, 0);
717
+ /** #438: that income per army, on the score's cost (`ratio`, scaled from this bonus's net to the sum). */
718
+ const perArmy = (p) => {
719
+ const r = prev.ratio(p);
720
+ return Number.isFinite(r) && p.net > 0 ? (r * incomeOf(p)) / p.net : r;
721
+ };
722
+ /**
723
+ * Bonus plans closest to completion first (focus first; ties: the income per army of every bonus
724
+ * the capture completes, #438, then advanced last turn, then the score order).
725
+ */
613
726
  const byCloseness = committing
614
727
  ? [...plans].sort((a, b) => Number(b.focus) - Number(a.focus) ||
615
728
  turnsOf(a) - turnsOf(b) ||
729
+ perArmy(b) - perArmy(a) ||
616
730
  Number(advancedLast.has(b.bonusId)) - Number(advancedLast.has(a.bonusId)) ||
617
731
  scoreRank.get(a.bonusId) - scoreRank.get(b.bonusId))
618
732
  : plans;
@@ -626,9 +740,22 @@ export function closestBonus(pc, ps, input, prev) {
626
740
  ? `${profile.phase[0].toUpperCase()}${profile.phase.slice(1)} phase${profile.phase === 'opening' || profile.phase === 'expansion' ? '' : ', neutrals in reach'}`
627
741
  : 'No bonus held';
628
742
  rationale.push(`${why}: expansion goes to the bonus closest to completion first — ${byCloseness
629
- .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}`}`)
743
+ .map((p, i) => `${bonusName(p.bonusId)} ${i ? p.cost : `${p.cost} armies to finish`}${fogNote(p)}, ${turnsText(p)}${i || income <= 0 ? '' : ` at income ${income}`}`)
630
744
  .join(', ')} — and a farther bonus gets only armies the closer ones cannot use.`);
631
745
  const top = byCloseness.find((p) => !p.focus);
746
+ // #438: a capture that completes more than one bonus says what they add up to per army.
747
+ const said = new Set();
748
+ for (const p of byCloseness) {
749
+ const all = completesWith(p);
750
+ const key = [...p.remaining].sort((x, y) => x - y).join(',');
751
+ // Only where it ranks: another bonus as close that this capture does not complete.
752
+ const rivals = byCloseness.some((q) => !all.includes(q) && !q.focus && turnsOf(q) === turnsOf(p));
753
+ if (all.length < 2 || !rivals || said.has(key))
754
+ continue;
755
+ said.add(key);
756
+ const names = all.map((q) => bonusName(q.bonusId));
757
+ 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).`);
758
+ }
632
759
  for (const p of byCloseness.filter((x) => advancedLast.has(x.bonusId))) {
633
760
  if (p === top)
634
761
  rationale.push(`${bonusName(p.bonusId)} keeps priority: I advanced it last turn, and no bonus is strictly closer to completion.`);
@@ -636,6 +763,25 @@ export function closestBonus(pc, ps, input, prev) {
636
763
  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
764
  }
638
765
  }
766
+ // #319: in the opening (turns 2–6), many territories on an income near base means the captures are
767
+ // spread over bonuses and none completed (six lost games held 11–20 territories on 8 or less after
768
+ // turn 4). A warning only, naming rule 4f's nearest bonus with its armies and turns: no order changes.
769
+ const turnNow = pc.game.turn ?? null;
770
+ const base = Math.max(0, Math.floor(input.settings?.baseIncome ?? DEFAULT_BASE_INCOME));
771
+ if (turnNow !== null &&
772
+ turnNow >= 2 &&
773
+ turnNow <= SPREAD_LAST_TURN &&
774
+ !holdsBonus &&
775
+ mine.length >= SPREAD_TERRITORIES &&
776
+ income <= base + SPREAD_INCOME_SLACK) {
777
+ const nearest = committing ? byCloseness.find((p) => !p.focus) ?? byCloseness[0] : undefined;
778
+ ps.warnings.push(`${mine.length} territories, no bonus: the captures are spread (income ${income}, base ${base}). ` +
779
+ (nearest
780
+ ? `Nearest bonus to complete: ${bonusName(nearest.bonusId)}, ${nearest.cost} armies to finish${fogNote(nearest)}, ` +
781
+ `${turnsText(nearest)}${income > 0 ? ` at income ${income}` : ''} (rule 4f).`
782
+ : 'No bonus is worth completing from here.') +
783
+ ' Complete one before taking more territories outside it (#319).');
784
+ }
639
785
  /**
640
786
  * A break's retake check, by its target: the warning it raised (if any) and what it was
641
787
  * judged on, so a top-up that adds survivors re-judges it.