@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
@@ -8,11 +8,12 @@ import { breachBehind } from '../breach.js';
8
8
  import { neighborsOf } from '../graph.js';
9
9
  import { chargeDeploys, deployPools } from '../local-deploy.js';
10
10
  import { territoryIncome } from '../player.js';
11
- import { BREACH_WEIGHT, WASTELAND_FACTOR } from './shared.js';
11
+ import { opensBehind } from '../opens.js';
12
+ import { BREACH_WEIGHT, OPENS_WEIGHT, WASTELAND_FACTOR, visibleState } from './shared.js';
12
13
  import { byNum } from './util.js';
13
14
  import { secondLineOf } from './guard-off.js';
14
15
  /** Open the deploy book of one pass: sets `ps.budget`, `ps.holdings` and the starting `avail`. */
15
- export function deployBook(ctx, ps) {
16
+ export function deployBook(ctx, ps, previousBoard) {
16
17
  const { g, territories: state, s, mine, mineSet, myCommanders, foe, guard, noSplit, armiesOf, incomeGain, label, income, reserve, econCostAt, paybackTurns, baseIncome, unitsAt, deployOf, untrustedAt, } = ctx;
17
18
  const { warnings, rationale, deployed, avail, coverKeep, captured, moves } = ps;
18
19
  // ---- mutable plan state ----
@@ -139,6 +140,53 @@ export function deployBook(ctx, ps) {
139
140
  }
140
141
  return cost <= paybackTurns * value && worst <= WASTELAND_FACTOR * value;
141
142
  };
143
+ /**
144
+ * #298: a foe's stack arrived on `x` since `previousBoard`: it took `x` from me, or its armies there
145
+ * grew, both read only where that board showed `x` (owner and armies). No previous board: none.
146
+ */
147
+ const before = new Map(previousBoard?.territories.map((t) => [t.territoryId, t]));
148
+ const arrived = (x, armiesNow) => {
149
+ const was = visibleState(before.get(x));
150
+ if (!was)
151
+ return false;
152
+ if (was.owner.kind !== 'player')
153
+ return false;
154
+ return was.owner.playerId === ctx.me || (foe(was.owner.playerId) && armiesNow > (was.armies ?? 0));
155
+ };
156
+ /**
157
+ * #298: an enemy stack roams inside bonus `ts`, beside my member `t`. Every missing member is a
158
+ * visible neutral or a visible foe's territory, at least one of them a foe's beside `t` whose stack
159
+ * arrived since the previous board (it took the member from me, or grew there: {@link arrived}), and
160
+ * finishing it passes #122's economy tests on what stands there now. My members within that stack's
161
+ * reach are garrisoned like those of a bonus I am building, so the bonus is not lost one member at a
162
+ * time while I retake the one it left.
163
+ */
164
+ const roamedBy = (t, ts, value) => {
165
+ let cost = 0;
166
+ let worst = 0;
167
+ let reach = false;
168
+ for (const x of ts) {
169
+ if (ps.holdings.has(x))
170
+ continue;
171
+ const st = state.get(x);
172
+ if (st === undefined || st.armies === null)
173
+ return false;
174
+ const o = st.owner;
175
+ if (o.kind === 'player') {
176
+ if (!foe(o.playerId))
177
+ return false;
178
+ // A stack: armies that can move (an empty or guard-only member roams nowhere).
179
+ if (st.armies > (guard ? 1 : 0) && neighborsOf(g, t).includes(x) && arrived(x, st.armies))
180
+ reach = true;
181
+ }
182
+ else if (o.kind !== 'neutral')
183
+ return false;
184
+ const c = econCostAt(x);
185
+ cost += c;
186
+ worst = Math.max(worst, c);
187
+ }
188
+ return reach && cost <= paybackTurns * value && worst <= WASTELAND_FACTOR * value;
189
+ };
142
190
  /**
143
191
  * #235: what losing my `t` cuts off from the rest of my holdings (`ps.holdings` without `t`): when
144
192
  * its neighbours of mine fall into two or more parts, every part but the largest (most territories,
@@ -233,11 +281,32 @@ export function deployBook(ctx, ps) {
233
281
  return out;
234
282
  };
235
283
  const breachCache = new Map();
284
+ /** #291: an enemy's territory or a hidden one: where a route into my land can start. */
285
+ const source = (x) => {
286
+ const o = state.get(x)?.owner;
287
+ return o === undefined || o.kind === 'unknown' || (o.kind === 'player' && foe(o.playerId));
288
+ };
289
+ /**
290
+ * #291: what losing my `t` opens to the enemy ({@link opensBehind}): the held bonuses every route from an enemy
291
+ * or the fog reaches only through it, less what its cut (#235) and its breach (#275) already count, with
292
+ * `worth` = {@link OPENS_WEIGHT} of their income. `null` when it opens nothing that earns.
293
+ */
294
+ const opensAt = (t) => {
295
+ if (opensCache.has(t))
296
+ return opensCache.get(t);
297
+ const skip = new Set([...(cutOff(t)?.ids ?? []), ...(breachAt(t)?.ids ?? [])]);
298
+ const o = opensBehind(g, ps.holdings, source, t, skip);
299
+ const out = o.income > 0 ? { ...o, worth: Math.round(OPENS_WEIGHT * o.income * 10) / 10 } : null;
300
+ opensCache.set(t, out);
301
+ return out;
302
+ };
303
+ const opensCache = new Map();
236
304
  const protectedValue = (t) => {
237
305
  // Each bonus is visited once, so it counts once however many of its borders are threatened.
238
306
  // #235: plus the income of what losing it cuts off from the rest of my holdings.
239
307
  // #275: plus, with the guard off, BREACH_WEIGHT × what a breach of it opens behind it.
240
- let v = (cutOff(t)?.income ?? 0) + (breachAt(t)?.worth ?? 0);
308
+ // #291: plus OPENS_WEIGHT × what its loss opens to the enemy (a gate cuts nothing off yet shields it all).
309
+ let v = (cutOff(t)?.income ?? 0) + (breachAt(t)?.worth ?? 0) + (opensAt(t)?.worth ?? 0);
241
310
  const mineWithout = (x) => x !== t && ps.holdings.has(x);
242
311
  for (const b of g.map.bonuses) {
243
312
  const ts = bonusTerritories(g, b.id);
@@ -266,7 +335,8 @@ export function deployBook(ctx, ps) {
266
335
  // foothold) was worth the whole bonus. Being built: every missing member is a visible
267
336
  // neutral, and finishing it passes rule 4's economy tests (a bonus behind an enemy, the
268
337
  // fog or a wasteland is not being built).
269
- if (building(ts, b.value)) {
338
+ // #298: so does a member an enemy stack roaming inside the bonus can reach (`roamedBy`).
339
+ if (building(ts, b.value) || roamedBy(t, ts, b.value)) {
270
340
  const held = ts.filter((x) => ps.holdings.has(x) || x === t).length;
271
341
  v += Math.round(((b.value * held) / ts.length) * 10) / 10;
272
342
  }
@@ -312,6 +382,8 @@ export function deployBook(ctx, ps) {
312
382
  cutCache,
313
383
  breachAt,
314
384
  breachCache,
385
+ opensAt,
386
+ opensCache,
315
387
  stakeAt,
316
388
  };
317
389
  }
@@ -39,7 +39,8 @@
39
39
  import { bonusTerritories } from '../bonuses.js';
40
40
  import { bfsDistances, neighborsOf } from '../graph.js';
41
41
  import { simTerritories, simulateTurn } from '../turn-sim.js';
42
- import { CONCEDE_FACTOR, } from './shared.js';
42
+ import { armiesToTake, DEFAULT_DEFENSIVE_KILL_RATE, straightKills } from '../combat.js';
43
+ import { captureCost, CONCEDE_FACTOR, } from './shared.js';
43
44
  import { byNum } from './util.js';
44
45
  /** T3: a covered border protecting more than this share of my income keeps its full hold. */
45
46
  export const TRUCE_RELAX_VALUE = 0.25;
@@ -52,6 +53,7 @@ const NONE = {
52
53
  enforced: new Set(),
53
54
  lookAheadFoes: new Set(),
54
55
  noTarget: () => false,
56
+ avoided: () => false,
55
57
  noFront: () => false,
56
58
  format: 'ffa',
57
59
  };
@@ -60,6 +62,94 @@ const NONE = {
60
62
  * and the territories none of my passes may attack. `notFoe` says who is me or a teammate.
61
63
  */
62
64
  export function truceOf(input, o) {
65
+ return withAvoid(truceFrom(input, o), input);
66
+ }
67
+ /** #375: a territory the caller asked to avoid, or one an avoided player holds, is never a target either. */
68
+ export function avoidedBy(input) {
69
+ const territories = new Set(input.options?.avoid?.territories ?? []);
70
+ const players = new Set(input.options?.avoid?.players ?? []);
71
+ if (!territories.size && !players.size)
72
+ return () => false;
73
+ const owner = new Map();
74
+ for (const t of input.board.territories)
75
+ if (t.owner.kind === 'player')
76
+ owner.set(t.territoryId, t.owner.playerId);
77
+ return (t) => territories.has(t) || players.has(owner.get(t) ?? Number.NaN);
78
+ }
79
+ /**
80
+ * #441: the neutrals an avoided player is visibly collecting — its only enemy neighbour is that player, or it
81
+ * sits in a bonus whose members that player visibly holds more than half of — which the plan skips like the
82
+ * player's own territories: taking one beside its stack reads as a provocation and is conceded next turn.
83
+ * Not skipped: a neutral whose capture completes a bonus of mine on its own (every other member mine at the
84
+ * start), or one the capture would hold next turn with what it leaves there alone (the fewest attackers that
85
+ * take it, less the defenders' kills) against every enemy stack beside it plus its owner's deploy.
86
+ * #457: a truce partner's (`truce`, `Truce.keptWith`) the same way — its enemy neighbours counting the partner
87
+ * even when a card makes it no foe — except that holding is no reason to take one: to the partner it reads as a
88
+ * breach either way; only completing a bonus of mine is (`truce: true` on the skirt). Empty with no avoided
89
+ * player and no truce partner, so every other plan is unchanged.
90
+ */
91
+ export function skirtedNeutrals(input, o) {
92
+ const out = new Map();
93
+ const avoid = new Set(input.options?.avoid?.players ?? []);
94
+ const partners = o.truce ?? new Set();
95
+ if (!avoid.size && !partners.size)
96
+ return out;
97
+ const watched = [...new Set([...avoid, ...partners])].sort(byNum);
98
+ const { graph: g, board, me } = input;
99
+ const state = new Map(board.territories.map((t) => [t.territoryId, t]));
100
+ const ownerOf = (t) => {
101
+ const st = state.get(t);
102
+ return st?.owner.kind === 'player' ? st.owner.playerId : undefined;
103
+ };
104
+ const rates = o.settings;
105
+ for (const st of [...board.territories].sort((a, b) => a.territoryId - b.territoryId)) {
106
+ const n = st.territoryId;
107
+ if (st.owner.kind !== 'neutral' || !g.territoryById.has(n))
108
+ continue;
109
+ const bonuses = g.map.bonuses.filter((b) => bonusTerritories(g, b.id).includes(n));
110
+ // It completes a bonus of mine: always worth taking.
111
+ if (bonuses.some((b) => b.value > 0 && bonusTerritories(g, b.id).every((x) => x === n || ownerOf(x) === me)))
112
+ continue;
113
+ const foes = [...new Set(neighborsOf(g, n).flatMap((x) => {
114
+ const p = ownerOf(x);
115
+ return p !== undefined && (o.foe(p) || partners.has(p)) ? [p] : [];
116
+ }))];
117
+ const of = (player, why) => ({ player, why, ...(partners.has(player) ? { truce: true } : {}) });
118
+ let skirt;
119
+ if (foes.length === 1 && (avoid.has(foes[0]) || partners.has(foes[0])))
120
+ skirt = of(foes[0], 'stack');
121
+ else
122
+ for (const b of [...bonuses].sort((x, y) => x.id - y.id)) {
123
+ const ts = bonusTerritories(g, b.id);
124
+ const p = watched.find((a) => ts.filter((x) => ownerOf(x) === a).length * 2 > ts.length);
125
+ if (p !== undefined) {
126
+ skirt = of(p, 'bonus');
127
+ break;
128
+ }
129
+ }
130
+ if (!skirt)
131
+ continue;
132
+ // #457: a truce partner's is skipped whether or not the capture would hold.
133
+ if (skirt.truce) {
134
+ out.set(n, skirt);
135
+ continue;
136
+ }
137
+ // It holds next turn with its survivors alone: no provocation that costs it.
138
+ const defenders = st.armies ?? 0;
139
+ const sent = captureCost(defenders, o.settings);
140
+ const survivors = sent === null ? 0 : sent - straightKills(defenders, rates.defensiveKillRate ?? DEFAULT_DEFENSIVE_KILL_RATE);
141
+ const threat = Math.max(0, ...foes.map((p) => neighborsOf(g, n).reduce((sum, x) => sum + (ownerOf(x) === p ? Math.max(0, (state.get(x).armies ?? 0) - 1) : 0), 0) + o.deployOf(p)));
142
+ if (survivors > 0 && (armiesToTake(survivors, rates) ?? Number.POSITIVE_INFINITY) > threat)
143
+ continue;
144
+ out.set(n, skirt);
145
+ }
146
+ return out;
147
+ }
148
+ function withAvoid(truce, input) {
149
+ const avoided = avoidedBy(input);
150
+ return { ...truce, avoided, noTarget: (t) => avoided(t) || truce.noTarget(t) };
151
+ }
152
+ function truceFrom(input, o) {
63
153
  const given = input.relations ?? [];
64
154
  if (!given.length)
65
155
  return NONE;
@@ -96,11 +186,15 @@ export function truceOf(input, o) {
96
186
  const partners = new Set();
97
187
  const enforced = new Set();
98
188
  const lookAheadFoes = new Set();
189
+ /** #457: the players an agreement (not only a card) binds this turn, in any format. */
190
+ const keptWith = new Set();
99
191
  /** Per partner whose agreement binds (in any format), the territories of theirs covered. */
100
192
  const theirs = new Map();
101
193
  given.forEach((r, i) => {
102
194
  if (!kept[i])
103
195
  return;
196
+ if (!r.card)
197
+ keptWith.add(r.player);
104
198
  // T2–T5 and T9 only in a free-for-all; T1 (never a surprise break, D3) wherever the agreement binds.
105
199
  if (binds[i]) {
106
200
  partners.add(r.player);
@@ -133,7 +227,19 @@ export function truceOf(input, o) {
133
227
  if (binds[i] && enforcedNow[i] && (r.enforcedUntil === undefined || (o.turnNow !== null && r.enforcedUntil > o.turnNow + 1)))
134
228
  lookAheadFoes.delete(r.player);
135
229
  });
136
- return { given, status, binds, partners, enforced, lookAheadFoes, noTarget, noFront, format: o.format };
230
+ return {
231
+ given,
232
+ status,
233
+ binds,
234
+ partners,
235
+ ...(keptWith.size ? { keptWith } : {}),
236
+ enforced,
237
+ lookAheadFoes,
238
+ noTarget,
239
+ avoided: () => false,
240
+ noFront,
241
+ format: o.format,
242
+ };
137
243
  }
138
244
  /**
139
245
  * T4 for rule 0p.2: the binding partners the game profile counts among my opponents — on the
@@ -678,6 +784,33 @@ export function truceBreakLosses(pc, plan) {
678
784
  return best;
679
785
  });
680
786
  }
787
+ /**
788
+ * #457: a neutral the plan's final orders attack beside a territory (at the start) of a player an agreement binds
789
+ * (`Truce.keptWith`): a warning per neutral that it may read as a breach to that player, so the owner can tell it
790
+ * first. Ascending territory id; nothing with no such agreement.
791
+ */
792
+ export function warnTruceNeutrals(pc, plan) {
793
+ const kept = pc.truce.keptWith;
794
+ if (!kept?.size)
795
+ return;
796
+ const ownerOf = (t) => {
797
+ const o = pc.territories.get(t)?.owner;
798
+ return o?.kind === 'player' ? o.playerId : undefined;
799
+ };
800
+ const taken = [...new Set(plan.moves.filter((m) => m.kind === 'attack').map((m) => m.to))].sort(byNum);
801
+ for (const t of taken) {
802
+ if (pc.territories.get(t)?.owner.kind !== 'neutral')
803
+ continue;
804
+ const beside = [...new Set(neighborsOf(pc.g, t).flatMap((x) => {
805
+ const p = ownerOf(x);
806
+ return p !== undefined && kept.has(p) ? [p] : [];
807
+ }))].sort(byNum);
808
+ if (!beside.length)
809
+ continue;
810
+ const who = beside.map((p) => `player ${p}`).join(' and ');
811
+ plan.warnings.push(`Taking ${pc.label(t)}, a neutral beside ${beside.map((p) => `player ${p}'s`).join(' and ')} land, may read as a breach to ${who} (a truce binds you): tell ${who} first (#457).`);
812
+ }
813
+ }
681
814
  /**
682
815
  * T6's report: each binding truce's {@link truceBreakLosses} on its view, and a rationale line that
683
816
  * says what a break would take. Nothing with no relations.
@@ -7,7 +7,9 @@
7
7
  // (#167) and the turns to eliminate each opponent (#179). planPass runs them where they ran before:
8
8
  // the expected outcome and the offence report after Order Priority for a strike, the plan last,
9
9
  // after the move order (plan/move-order.ts).
10
+ import { siegeFitLine, siegeLines, siegeReport } from './siege.js';
10
11
  import { bonusTerritories } from '../bonuses.js';
12
+ import { DEFAULT_DEFENSIVE_KILL_RATE, DEFAULT_OFFENSIVE_KILL_RATE, straightKills } from '../combat.js';
11
13
  import { classifyExchange } from '../exchange.js';
12
14
  import { neighborsOf } from '../graph.js';
13
15
  import { bonusesAtRisk, captureCost, CITE_OPEN, CITE_RE, ETA_HORIZON, NOT_ATTACKING_REASONS, SECOND_FRONT_LEAD, SLOT_NAMES, } from './shared.js';
@@ -67,6 +69,31 @@ export function reportExpected(pc, ps, book, threats, hd, tgt, caps) {
67
69
  ...frontierOf(after, (x) => (mineSet.has(x) ? stayAt(x) : (survivorsAt.get(x) ?? 0))),
68
70
  income: keptIncome(after),
69
71
  };
72
+ // #297: in a 1v1, the gates — every border of mine facing the opponent — against its one floating deploy.
73
+ const gates = (() => {
74
+ if (pc.profile.format !== '1v1')
75
+ return undefined;
76
+ const have = (x) => (mineSet.has(x) ? stayAt(x) : (survivorsAt.get(x) ?? 0)) + (mineSet.has(x) ? unitsAt(x) : 0);
77
+ const list = [];
78
+ let player;
79
+ for (const x of [...after].sort(byNum)) {
80
+ const th = threats.nextTurnAt(x, (n) => after.has(n));
81
+ if (!th)
82
+ continue;
83
+ player ??= th.player;
84
+ list.push({ id: x, needs: threats.holdArmies(th.threat), armies: have(x), ...(conceded.has(x) ? { conceded: true } : {}) });
85
+ }
86
+ if (player === undefined || !list.length)
87
+ return undefined;
88
+ const need = list.reduce((n, g) => n + g.needs, 0);
89
+ const onGates = list.reduce((n, g) => n + g.armies, 0);
90
+ const deficit = list.reduce((n, g) => n + Math.max(0, g.needs - g.armies), 0);
91
+ return { player, gates: list, need, onGates, deficit, income: frontier.income, short: Math.max(0, deficit - frontier.income) };
92
+ })();
93
+ // Warned only when this plan's own captures open a gate the budget cannot pay for (the shortfall alone is in the report).
94
+ const opened = gates ? gates.gates.filter((x) => captured.has(x.id)).map((x) => x.id) : [];
95
+ if (gates && gates.short > 0 && opened.length)
96
+ warnings.push(`Gate budget (#297): this plan's capture of ${opened.map(label).join(', ')} opens ${opened.length === 1 ? 'a gate' : 'gates'} the income cannot hold — ${gates.gates.length} gates facing player ${gates.player}${gates.gates.some((x) => x.conceded) ? ` (${gates.gates.filter((x) => x.conceded).length} conceded)` : ''} need ${gates.need} against its one floating deploy; ${gates.onGates} stand on them, ${gates.deficit} short across them, and the next income is ${gates.income}: ${gates.short} short.`);
70
97
  const startCost = startHold();
71
98
  const outgrown = frontier.holdCost > frontier.income && frontier.holdCost > startCost;
72
99
  // A capture stopped by one pass but taken by a later one (the next income grew in between) is
@@ -230,7 +257,7 @@ export function reportExpected(pc, ps, book, threats, hd, tgt, caps) {
230
257
  }
231
258
  if (noSplit && moves.length && guard)
232
259
  warnings.push('No-Split is on: each order sends its territory\'s whole stack less the one army that stands guard; whether war.app leaves that army behind under No-Split is unverified (a live turn with the guard off left every source at 0).');
233
- return { completed, nextIncome, atRisk, ifFall, reportRisk, frontier };
260
+ return { completed, nextIncome, atRisk, ifFall, reportRisk, frontier, ...(gates ? { gates } : {}) };
234
261
  }
235
262
  /** The offence report (#72), the warnings that follow the deploys, and the "Not attacking" line (#167). */
236
263
  export function reportOffence(pc, ps, book, threats, hd, tgt, holdLocked, leadSpareFor) {
@@ -424,6 +451,10 @@ export function reportOffence(pc, ps, book, threats, hd, tgt, holdLocked, leadSp
424
451
  const p = st.owner.playerId;
425
452
  if (uncounted(n))
426
453
  return `it holds ${uncountedKind(n)}, whose strength the board does not carry`;
454
+ if (pc.truce.avoided(n))
455
+ return 'the plan was told to avoid it (#375)';
456
+ if (pc.truce.siegeHeld?.(n))
457
+ return `the siege holds the assault on player ${p} until its trigger fires: only its bonus members are attacked (#382)`;
427
458
  // B2 (T1): the truce covers it.
428
459
  if (pc.truce.noTarget(n))
429
460
  return `my truce with player ${p} covers it (T1)`;
@@ -524,7 +555,7 @@ export function finishPlan(pc, ps, pass, threats, hd, tgt, expected, sentAt, slo
524
555
  const { reinforcementAt, borders, ownedBy, ownerOf, fogEdge } = threats;
525
556
  const { conceded, stayAt } = hd;
526
557
  const { offence, offenceSkip } = tgt;
527
- const { completed, nextIncome, atRisk, ifFall, reportRisk, frontier } = expected;
558
+ const { completed, nextIncome, atRisk, ifFall, reportRisk, frontier, gates } = expected;
528
559
  const offenceList = [...offence.values()].map(({ bonusId, ...o }) => {
529
560
  // A strike attack's cost is what the final orders send (a top-up can raise it).
530
561
  // The strike stack's own entry is final as built.
@@ -612,6 +643,29 @@ export function finishPlan(pc, ps, pass, threats, hd, tgt, expected, sentAt, slo
612
643
  return `${label(e.to)} from ${label(e.from)} with ${e.armies}: ${e.label} (${at(now)}, ${at(est)} after the estimated deploy, ${at(whole)} after the whole income)`;
613
644
  })
614
645
  .join('; ')}.`);
646
+ // ---- #314: a hold that survives by a handful ----
647
+ // What stays on a held border against its threat (the stack beside it plus its owner's deploy, one
648
+ // attack), luck-free: when that attack fails but leaves so little of mine that its own survivors
649
+ // take it next turn with nothing more deployed, the border is lost anyway. Only a contested big stack
650
+ // (mine at least a turn's income, facing a stack): a small border is re-sized every turn. Report only.
651
+ for (const b of [...borders.values()].sort((a, c) => a.id - c.id)) {
652
+ if (conceded.has(b.id) || b.movable <= 0)
653
+ continue;
654
+ const have = stayAt(b.id) + unitsAt(b.id);
655
+ if (have < income)
656
+ continue;
657
+ const take = toTake(have);
658
+ if (take === null || take <= b.threat)
659
+ continue;
660
+ const mineAfter = Math.max(0, have - straightKills(b.threat, rates.offensiveKillRate ?? DEFAULT_OFFENSIVE_KILL_RATE));
661
+ const hisAfter = Math.max(0, b.threat - straightKills(have, rates.defensiveKillRate ?? DEFAULT_DEFENSIVE_KILL_RATE));
662
+ const next = toTake(mineAfter);
663
+ if (next === null || next > hisAfter)
664
+ continue;
665
+ warnings.push(`${label(b.id)} holds by a handful (#314): an attack of ${b.threat} (its stacks beside it plus player ${b.player}'s deploy) ` +
666
+ `leaves ${mineAfter} of mine against ${hisAfter} of player ${b.player}'s, which take it next turn with nothing more there: ` +
667
+ 'it holds this turn only, so add to it or plan for losing the stack.');
668
+ }
615
669
  // ---- #179: turns to eliminate each visible opponent ----
616
670
  const eliminateEta = {};
617
671
  {
@@ -640,8 +694,19 @@ export function finishPlan(pc, ps, pass, threats, hd, tgt, expected, sentAt, slo
640
694
  eliminateEta[p] = { turns, atLeast: fogEdge(p).length > 0, distance, armies: Number.isFinite(armies) ? armies : null };
641
695
  }
642
696
  }
697
+ // #382: the siege's state and rationale, first.
698
+ if (pc.siegeWarning)
699
+ warnings.push(pc.siegeWarning);
700
+ if (pc.siege)
701
+ rationale.unshift(...siegeLines(pc.siege, label, pc.bonusName));
702
+ const chose = pc.siege ? siegeFitLine(pc.siege, pc.bonusName) : undefined;
703
+ if (chose)
704
+ rationale.unshift(chose);
705
+ if (pc.siegeHandBack)
706
+ rationale.push(pc.siegeHandBack);
643
707
  return {
644
- goal,
708
+ goal: pc.opts.goal === 'siege' || pc.siege ? 'siege' : goal,
709
+ ...(pc.siege ? { siege: siegeReport(pc.siege, g, captured, pc.bonusName) } : {}),
645
710
  profile,
646
711
  // Deploys interleave like moves, and the order they land in shows the opponent my income and
647
712
  // the move order: next to a visible enemy first, in the back after (ascending id within each).
@@ -663,6 +728,7 @@ export function finishPlan(pc, ps, pass, threats, hd, tgt, expected, sentAt, slo
663
728
  cardAdvice: ps.cardAdvice,
664
729
  multiSourceCaptures: [...combined].sort(byNum),
665
730
  frontier,
731
+ ...(gates ? { gates } : {}),
666
732
  offence: offenceList,
667
733
  moveSlots: moves.map((m) => SLOT_NAMES[slotOf(m)]),
668
734
  ...(exchanges.length ? { exchanges } : {}),
@@ -0,0 +1,133 @@
1
+ import { lateArrivals } from './holds.js';
2
+ /** What a held bonus's border lacks to hold once every order is planned (#215: the worse move order). */
3
+ function shortAt(pc, ps, threats, hd, id) {
4
+ const b = threats.borderAt(id, (x) => ps.captured.has(x));
5
+ if (!b)
6
+ return 0;
7
+ const need = Math.max(0, threats.holdArmies(b.threat) - pc.unitsAt(id));
8
+ return Math.max(0, need - (hd.stayAt(id) - lateArrivals(pc, ps, id)));
9
+ }
10
+ export function fundFromSecondSizing(pc, ps, book, threats, hd, caps) {
11
+ if (pc.noSplit || book.local)
12
+ return;
13
+ const { label, bonusName, territories: state, defenceAt, costAt, chanceOf } = pc;
14
+ const { moves, combined, deployed, avail, rationale, warnings } = ps;
15
+ const { worstCase, strikes } = caps;
16
+ // ---- the attacks each sized for their owner's whole deploy, by owner ----
17
+ const byOwner = new Map();
18
+ for (const m of moves) {
19
+ if (m.kind !== 'attack' || combined.has(m.to) || strikes.has(m.to))
20
+ continue;
21
+ const st = state.get(m.to);
22
+ if (st?.owner.kind !== 'player')
23
+ continue;
24
+ const extra = threats.reinforcementAt(m.to);
25
+ const d = defenceAt(m.to);
26
+ const full = costAt(m.to, d + extra);
27
+ if (extra <= 0 || full === null || m.armies < full || (worstCase.get(m.to) ?? 0) < d + extra)
28
+ continue;
29
+ const list = byOwner.get(st.owner.playerId) ?? [];
30
+ list.push(m);
31
+ byOwner.set(st.owner.playerId, list);
32
+ }
33
+ /** Each attack that may give armies up, with what it may give and the one that keeps its size. */
34
+ const spare = new Map();
35
+ const keepOf = new Map();
36
+ const ownerOf = (m) => state.get(m.to).owner.playerId;
37
+ /** What each source's deploy still has to give (two attacks from one source share it). */
38
+ const deployLeft = new Map();
39
+ for (const [owner, list] of [...byOwner].sort((a, b) => a[0] - b[0])) {
40
+ if (list.length < 2)
41
+ continue;
42
+ const keep = [...list].sort((a, b) => b.armies - a.armies || moves.indexOf(a) - moves.indexOf(b))[0];
43
+ keepOf.set(owner, keep);
44
+ for (const m of list) {
45
+ if (m === keep)
46
+ continue;
47
+ const bare = costAt(m.to, defenceAt(m.to));
48
+ if (bare === null)
49
+ continue;
50
+ const free = deployLeft.get(m.from) ?? deployed.get(m.from) ?? 0;
51
+ const room = Math.min(m.armies - bare, free);
52
+ if (room <= 0)
53
+ continue;
54
+ deployLeft.set(m.from, free - room);
55
+ spare.set(m, { room, owner, extra: threats.reinforcementAt(m.to) });
56
+ }
57
+ }
58
+ if (!spare.size)
59
+ return;
60
+ // ---- the held bonuses those armies make hold, most valuable first ----
61
+ const units = [...hd.units].sort((a, b) => b.value - a.value || a.bonusId - b.bonusId);
62
+ for (const u of units) {
63
+ if (u.value <= 0)
64
+ continue;
65
+ const ids = u.members.map((m) => m.id);
66
+ // A border an order leaves (a withdrawal, an attack out) is not one this restores.
67
+ if (moves.some((mv) => ids.includes(mv.from) && (mv.armies > 0 || mv.commander)))
68
+ continue;
69
+ const short = new Map(ids.map((id) => [id, shortAt(pc, ps, threats, hd, id)]));
70
+ const need = [...short.values()].reduce((n, x) => n + x, 0);
71
+ const pool = [...spare.values()].reduce((n, x) => n + x.room, 0);
72
+ if (need <= 0 || need > pool || need > pc.paybackTurns * u.value)
73
+ continue;
74
+ // Take it from the attacks with the most to give first (ties: the later order).
75
+ const takes = [];
76
+ let left = need;
77
+ for (const [m, x] of [...spare].sort((a, b) => b[1].room - a[1].room || moves.indexOf(b[0]) - moves.indexOf(a[0]))) {
78
+ if (left <= 0)
79
+ break;
80
+ const n = Math.min(left, x.room);
81
+ left -= n;
82
+ x.room -= n;
83
+ if (x.room <= 0)
84
+ spare.delete(m);
85
+ takes.push({ m, n, before: m.armies });
86
+ m.armies -= n;
87
+ avail.set(m.from, avail.get(m.from) + n);
88
+ book.undeploy(m.from, n);
89
+ const d = defenceAt(m.to);
90
+ m.winChance = chanceOf(m.armies, d);
91
+ if (ps.survivorsAt.has(m.to))
92
+ ps.survivorsAt.set(m.to, ps.survivorsAt.get(m.to) - n);
93
+ // What its owner could still deploy there first and lose it to this attack.
94
+ let covered = 0;
95
+ while (covered < x.extra && (costAt(m.to, d + covered + 1) ?? Infinity) <= m.armies)
96
+ covered++;
97
+ worstCase.set(m.to, d + covered);
98
+ }
99
+ const given = [];
100
+ for (const id of [...ids].sort((a, b) => a - b)) {
101
+ const n = short.get(id);
102
+ if (n > 0) {
103
+ book.deploy(id, n);
104
+ given.push(`${n} to ${label(id)}`);
105
+ }
106
+ ps.locked.add(id);
107
+ hd.heldBorders.add(id);
108
+ if (!hd.conceded.delete(id))
109
+ continue;
110
+ const conceding = `${label(id)} cannot be held `;
111
+ for (let i = warnings.length - 1; i >= 0; i--)
112
+ if (warnings[i].startsWith(conceding) && warnings[i].endsWith(': conceded'))
113
+ warnings.splice(i, 1);
114
+ }
115
+ u.conceded = false;
116
+ u.contested = false;
117
+ const conceding = `conceding bonus ${bonusName(u.bonusId)} (+${u.value}):`;
118
+ for (let i = warnings.length - 1; i >= 0; i--)
119
+ if (warnings[i].startsWith(conceding))
120
+ warnings.splice(i, 1);
121
+ const from = takes
122
+ .map(({ m, n, before }) => `${n} from the attack on ${label(m.to)} from ${label(m.from)} (${before} down to ${m.armies}: still sure against the ${defenceAt(m.to)} there now, and against up to ${worstCase.get(m.to) - defenceAt(m.to)} deployed there first)`)
123
+ .join(' and ');
124
+ const kept = [...new Map(takes.map(({ m }) => [ownerOf(m), m])).keys()]
125
+ .sort((a, b) => a - b)
126
+ .map((o) => {
127
+ const keep = keepOf.get(o);
128
+ return `player ${o}'s ~${threats.reinforcementAt(keep.to)} deploy reinforces one of its targets, not two, and the attack on ${label(keep.to)} keeps its size for it`;
129
+ })
130
+ .join('; ');
131
+ rationale.push(`Fund held bonus ${bonusName(u.bonusId)} (+${u.value}) (#277): deploy ${given.join(', ')} so each of its borders holds, ${from}. ${kept[0].toUpperCase()}${kept.slice(1)}.`);
132
+ }
133
+ }