@chrischall/warapp-mcp 0.9.0 → 0.11.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.
@@ -7,7 +7,7 @@
7
7
  },
8
8
  "metadata": {
9
9
  "description": "MCP server for war.app (Warzone) — your games, players, settings, map bonuses and chokepoints, board analysis and route planning through war.app's per-player GameFeed API, plus the live board, territory picks, cards, turn planning and submission, turn notifications and game chat through your signed-in war.app tab (joining, leaving or surrendering a game, accepting another player's surrender, Begin on a speed first turn, picks, turn orders, withdrawing them, chat sends, marking notifications and chat read, deleting notifications, importing local history and linking a session are confirm-gated).",
10
- "version": "0.9.0"
10
+ "version": "0.11.0"
11
11
  },
12
12
  "plugins": [
13
13
  {
@@ -15,7 +15,7 @@
15
15
  "displayName": "war.app (Warzone)",
16
16
  "source": "./",
17
17
  "description": "war.app (Warzone) game advisor for Claude — games, maps, bonuses, routes, live board, picks, turns, cards and chat",
18
- "version": "0.9.0",
18
+ "version": "0.11.0",
19
19
  "author": {
20
20
  "name": "Chris Hall"
21
21
  },
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "warapp-mcp",
3
3
  "displayName": "war.app (Warzone)",
4
- "version": "0.9.0",
4
+ "version": "0.11.0",
5
5
  "description": "war.app (Warzone) game advisor for Claude — games, maps, bonuses, routes, live board, picks, turns, cards and chat",
6
6
  "author": {
7
7
  "name": "Chris Hall",
@@ -0,0 +1,91 @@
1
+ import { planCloseness, planTurn } from './planner.js';
2
+ import { boardIncome } from './player.js';
3
+ import { simulateTurn } from './turn-sim.js';
4
+ /** The last turn the check runs on without #319 firing. */
5
+ export const BONUS_DELAY_LAST_TURN = 4;
6
+ const simSettingsOf = (s) => ({
7
+ ...(s.offensiveKillRate !== undefined ? { offensiveKillRate: s.offensiveKillRate } : {}),
8
+ ...(s.defensiveKillRate !== undefined ? { defensiveKillRate: s.defensiveKillRate } : {}),
9
+ ...(s.luckModifier !== undefined ? { luckModifier: s.luckModifier } : {}),
10
+ ...(s.roundingMode !== undefined ? { roundingMode: s.roundingMode } : {}),
11
+ ...(s.oneArmyStandsGuard !== undefined ? { oneArmyStandsGuard: s.oneArmyStandsGuard } : {}),
12
+ ...(s.multiAttack !== undefined ? { multiAttack: s.multiAttack } : {}),
13
+ });
14
+ const ownerOf = (owner) => typeof owner === 'number' ? { kind: 'player', playerId: owner } : owner === 'neutral' ? { kind: 'neutral' } : { kind: 'unknown' };
15
+ const landOf = (b, me) => new Set(b.territories.flatMap((t) => (t.owner.kind === 'player' && t.owner.playerId === me ? [t.territoryId] : [])));
16
+ /**
17
+ * The turn `orders` finish `bonusId` on: this turn when it is held in full after them, else this turn
18
+ * plus rule 4f's turns to finish on the board they leave (planned at the income they leave); `undefined`
19
+ * when the next plan has no figure for it.
20
+ */
21
+ function finishTurn(input, turn, bonusId, orders, plan) {
22
+ const r = simulateTurn({
23
+ graph: input.graph,
24
+ board: input.board,
25
+ deploys: orders.deploys.map((d) => ({ player: input.me, territoryId: d.territoryId, armies: d.armies })),
26
+ orders: [{ player: input.me, orders: orders.moves.map((m) => ({ from: m.from, to: m.to, armies: m.armies })) }],
27
+ moveOrder: [input.me],
28
+ settings: simSettingsOf(input.settings ?? {}),
29
+ });
30
+ const after = {
31
+ source: input.board.source,
32
+ verified: false,
33
+ territories: input.board.territories.map((t) => {
34
+ const s = r.territories.get(t.territoryId);
35
+ return s ? { ...t, owner: ownerOf(s.owner), armies: s.owner === 'unknown' ? t.armies : s.armies } : t;
36
+ }),
37
+ };
38
+ const members = input.graph.map.bonuses.find((b) => b.id === bonusId)?.territoryIds ?? [];
39
+ const held = landOf(after, input.me);
40
+ if (members.length && members.every((t) => held.has(t)))
41
+ return turn;
42
+ const rules = { base: input.settings?.baseIncome ?? 0, per: 0 };
43
+ const gain = boardIncome(input.graph, held, rules).total - boardIncome(input.graph, landOf(input.board, input.me), rules).total;
44
+ const next = plan({
45
+ ...input,
46
+ board: after,
47
+ previousBoard: input.board,
48
+ income: Math.max(0, input.income + gain),
49
+ turn: turn + 1,
50
+ ...(input.game ? { game: { ...input.game, turn: turn + 1 } } : {}),
51
+ });
52
+ const turns = planCloseness(next)?.turns.get(bonusId);
53
+ return turns === undefined ? undefined : turn + Math.max(1, turns);
54
+ }
55
+ /**
56
+ * #505: whether `given` drops a capture `plan` (the default plan on `input`) makes toward rule 4f's
57
+ * nearest bonus, on turns 1–{@link BONUS_DELAY_LAST_TURN} or while #319 fires, and finishes that bonus
58
+ * later for it; `undefined` otherwise (no such capture dropped, no later finish, or no figure). Pure.
59
+ */
60
+ export function bonusDelay(a) {
61
+ const { input, plan, given } = a;
62
+ const turn = input.turn ?? input.game?.turn;
63
+ const c = planCloseness(plan);
64
+ if (turn === undefined || turn === null || !c || c.nearest === undefined)
65
+ return undefined;
66
+ if (!(turn >= 1 && turn <= BONUS_DELAY_LAST_TURN) && !c.spread)
67
+ return undefined;
68
+ const missing = new Set(c.remaining.get(c.nearest) ?? []);
69
+ const sent = new Set(given.moves.filter((m) => !landOf(input.board, input.me).has(m.to)).map((m) => m.to));
70
+ const toward = new Set(plan.expected.captures.filter((t) => missing.has(t)));
71
+ const dropped = [...new Set(plan.moves.filter((m) => toward.has(m.to) && !sent.has(m.to)).map((m) => m.to))].sort((x, y) => x - y);
72
+ if (!dropped.length)
73
+ return undefined;
74
+ const planner = a.planner ?? planTurn;
75
+ const planned = finishTurn(input, turn, c.nearest, { deploys: plan.deploys, moves: plan.moves }, planner);
76
+ const givenTurn = finishTurn(input, turn, c.nearest, given, planner);
77
+ if (planned === undefined || givenTurn === undefined || givenTurn <= planned)
78
+ return undefined;
79
+ const bonus = input.graph.map.bonuses.find((b) => b.id === c.nearest)?.name ?? `#${c.nearest}`;
80
+ return { bonusId: c.nearest, bonus, dropped, plannedTurn: planned, givenTurn, spread: c.spread };
81
+ }
82
+ /** #505: the warning for a {@link BonusDelay}; none without one. Advice only, no names but the bonus's. */
83
+ export function bonusDelayWarning(d) {
84
+ if (!d)
85
+ return undefined;
86
+ const ts = d.dropped.map((t) => `territory ${t}`).join(', ');
87
+ return (`These orders finish bonus ${d.bonus} on turn ${d.givenTurn} instead of turn ${d.plannedTurn} (#505): they drop the default plan's ` +
88
+ `capture${d.dropped.length === 1 ? '' : 's'} of ${ts} toward it, the nearest bonus to complete (rule 4f` +
89
+ `${d.spread ? "; #319's opening warning fires" : ''}). Each turn is rule 4f's turns to finish on the board each set of orders ` +
90
+ 'leaves, the rest of the board standing still. Advice only: the orders are sent as given.');
91
+ }
@@ -205,6 +205,11 @@ export function openingBenchmark(input) {
205
205
  return { turns, exact };
206
206
  }
207
207
  const mean = (xs) => r3(xs.reduce((a, b) => a + b, 0) / xs.length);
208
+ const median = (xs) => {
209
+ const s = [...xs].sort((a, b) => a - b);
210
+ const m = Math.floor(s.length / 2);
211
+ return r3(s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2);
212
+ };
208
213
  /** Many {@link Benchmark}s aggregated. A turn where I held nothing in the real game counts the real income as 0. Pure. */
209
214
  export function aggregateBenchmarks(results) {
210
215
  const byTurn = new Map();
@@ -221,12 +226,16 @@ export function aggregateBenchmarks(results) {
221
226
  .sort(([a], [b]) => a - b)
222
227
  .map(([afterTurn, ts]) => {
223
228
  const winners = ts.flatMap((t) => (t.winner === null ? [] : [t.winner]));
229
+ const replay = ts.map((t) => t.replay.income);
230
+ const real = ts.map((t) => t.real?.income ?? 0);
224
231
  return {
225
232
  afterTurn,
226
233
  n: ts.length,
227
- replay: mean(ts.map((t) => t.replay.income)),
228
- real: mean(ts.map((t) => t.real?.income ?? 0)),
234
+ replay: mean(replay),
235
+ real: mean(real),
229
236
  winner: winners.length ? mean(winners) : null,
237
+ winners: winners.length,
238
+ median: { replay: median(replay), real: median(real), winner: winners.length ? median(winners) : null },
230
239
  replayAhead: ts.filter((t) => t.replay.income > (t.real?.income ?? 0)).length,
231
240
  replayBehind: ts.filter((t) => t.replay.income < (t.real?.income ?? 0)).length,
232
241
  };
@@ -238,3 +247,86 @@ export function aggregateBenchmarks(results) {
238
247
  },
239
248
  };
240
249
  }
250
+ // ---- #503: the opening benchmark by era ----
251
+ /** Rule 4f (#105) merged: openings played from here on are the current era. */
252
+ export const PRE_RULE_4F_AT = '2026-11-13T08:24:00Z';
253
+ /**
254
+ * Without a turn-1 time, the era boundary by game id (ids are assigned when a game is created, so this
255
+ * approximates the time): the first-bonus research of 2026-11-23 split its games here.
256
+ */
257
+ export const PRE_RULE_4F_GAME_ID = 45_690_000;
258
+ /** The opening window the flags read: turns 1 to this. */
259
+ export const OPENING_WINDOW = 4;
260
+ /**
261
+ * A finished game's opening era: by its turn-1 time where known, else by its game id; with neither, the
262
+ * game is `pre-tool` (no local cache of it was ever kept, so this server never played it) — `basis`
263
+ * says `not planned` when the record also keeps no outlook line, `no game id` when it does. Pure.
264
+ */
265
+ export function openingEra(g) {
266
+ if (g.turn1At !== undefined && Number.isFinite(Date.parse(g.turn1At)))
267
+ return { era: Date.parse(g.turn1At) < Date.parse(PRE_RULE_4F_AT) ? 'pre-rule-4f' : 'current', basis: 'turn-1 time' };
268
+ if (g.gameId !== undefined)
269
+ return { era: g.gameId < PRE_RULE_4F_GAME_ID ? 'pre-rule-4f' : 'current', basis: 'game id' };
270
+ return { era: 'pre-tool', basis: g.planned ? 'no game id' : 'not planned' };
271
+ }
272
+ /**
273
+ * The opening window's turns with no orders of mine, and a boot of my seat in it. A turn n (history boards
274
+ * n − 1 and n both kept, land of mine on n − 1) shows orders when I hold a territory I did not hold before,
275
+ * a failed attack of mine is recorded that turn, or this server sent orders for it; else it reads as a turn
276
+ * with no orders. Army growth alone is not read as orders: a missed turn's board shows it too (the
277
+ * first-bonus research's missed turns all look so). Inferred from the boards: a deploy-and-transfer turn
278
+ * with no capture reads as no orders. Pure.
279
+ */
280
+ export function openingFlags(input) {
281
+ const window = input.window ?? OPENING_WINDOW;
282
+ const boards = new Map(input.history.map((b) => [b.turn, b.board]));
283
+ const sent = new Set([...(input.sentTurns ?? []), ...(input.failedAttackTurns ?? [])]);
284
+ const noOrderTurns = [];
285
+ for (let n = 1; n <= window; n++) {
286
+ const before = boards.get(n - 1);
287
+ const after = boards.get(n);
288
+ if (!before || !after || sent.has(n))
289
+ continue;
290
+ const was = landOf(before, input.me);
291
+ if (!was.size)
292
+ continue;
293
+ if (![...landOf(after, input.me)].some((id) => !was.has(id)))
294
+ noOrderTurns.push(n);
295
+ }
296
+ const bt = input.booted?.turn ?? null;
297
+ return { noOrderTurns, bootedTurn: bt !== null && bt >= 1 && bt <= window ? bt : null };
298
+ }
299
+ /** A map this many times the median map's territories or more is counted as large. */
300
+ export const LARGE_MAP_FACTOR = 5;
301
+ /** The benchmarks grouped by era, then format; flagged games apart; how many eras were read from which basis. Pure. */
302
+ export function benchmarkByEra(entries) {
303
+ const basis = {};
304
+ for (const e of entries)
305
+ basis[e.basis] = (basis[e.basis] ?? 0) + 1;
306
+ const sizes = entries.map((e) => e.territories).filter((n) => n > 0);
307
+ const large = sizes.length ? LARGE_MAP_FACTOR * median(sizes) : Number.POSITIVE_INFINITY;
308
+ const eras = {};
309
+ for (const era of ['pre-tool', 'pre-rule-4f', 'current']) {
310
+ const of = entries.filter((e) => e.era === era);
311
+ if (!of.length)
312
+ continue;
313
+ const isFlagged = (e) => e.flags.noOrderTurns.length > 0 || e.flags.bootedTurn !== null;
314
+ const clean = of.filter((e) => !isFlagged(e));
315
+ const flagged = of.filter(isFlagged);
316
+ const byFormat = {};
317
+ for (const f of [...new Set(clean.map((e) => e.format))].sort())
318
+ byFormat[f] = aggregateBenchmarks(clean.filter((e) => e.format === f).map((e) => e.bench));
319
+ eras[era] = {
320
+ all: aggregateBenchmarks(clean.map((e) => e.bench)),
321
+ byFormat,
322
+ largeMaps: clean.filter((e) => e.territories >= large).length,
323
+ flagged: {
324
+ games: flagged.length,
325
+ noOrderTurns: flagged.reduce((a, e) => a + e.flags.noOrderTurns.length, 0),
326
+ boots: flagged.filter((e) => e.flags.bootedTurn !== null).length,
327
+ benchmark: flagged.length ? aggregateBenchmarks(flagged.map((e) => e.bench)) : null,
328
+ },
329
+ };
330
+ }
331
+ return { basis, eras };
332
+ }
@@ -650,6 +650,10 @@ export function reportTruce(pc, ps, tp, freedOn) {
650
650
  ? `; the card lasts until turn ${r.enforcedUntil}.`
651
651
  : '.')
652
652
  : `${name}${notice}: none of its ${r.coveredTheirs.length} covered ${r.coveredTheirs.length === 1 ? 'territory is' : 'territories are'} a target this turn (T1), and player ${r.player} is no front for the no-second-front rule or the idle armies (T4).`);
653
+ for (const e of r.exceptions ?? [])
654
+ rationale.push(e.direction === 'mine'
655
+ ? `${name}: player ${r.player} agreed to an exception this turn, so ${e.territories.map(label).join(', ')} ${e.territories.length === 1 ? 'is a normal target' : 'are normal targets'} — no break.`
656
+ : `${name}: I agreed to an exception this turn, so player ${r.player} may attack ${e.territories.map(label).join(', ')}: ${e.territories.length === 1 ? 'it is' : 'they are'} held as against any opponent.`);
653
657
  if (mineRelaxed.length)
654
658
  rationale.push(`${name}: ${mineRelaxed.map(label).join(', ')} ${mineRelaxed.length === 1 ? 'faces' : 'face'} only player ${r.player}, so ${mineRelaxed.length === 1 ? 'it is' : 'they are'} held against its visible stacks there attacking with no deploy (T2) — a break needs a visible build-up first; ${freed} ${freed === 1 ? 'army' : 'armies'} freed this turn.`);
655
659
  const why = { commander: 'my commander stands there', value: `it protects more than ${TRUCE_RELAX_VALUE} × my income`, watch: `the trust is watch (${flags.join(', ') || 'a flag'})` };
@@ -677,6 +681,7 @@ export function reportTruce(pc, ps, tp, freedOn) {
677
681
  armiesFreed: freed,
678
682
  ...(tp?.capMoved.get(i)?.length ? { capMoved: tp.capMoved.get(i) } : {}),
679
683
  ...(r.breach ? { breach: r.breach } : {}),
684
+ ...(r.exceptions?.length ? { exceptions: r.exceptions } : {}),
680
685
  // T6: filled in once the plan's orders are final (truceBreakLosses).
681
686
  lossIfBroken: null,
682
687
  };
@@ -1936,6 +1936,11 @@ function planAttempts(input) {
1936
1936
  }
1937
1937
  /** #421: per plan, the strike share its pass held out of captures (absent when none). */
1938
1938
  const shareOutcome = new WeakMap();
1939
+ const closenessOutcome = new WeakMap();
1940
+ /** #505: rule 4f's nearest bonus and turns to finish for a plan `planTurn` made; `undefined` for any other object. */
1941
+ export function planCloseness(plan) {
1942
+ return closenessOutcome.get(plan);
1943
+ }
1939
1944
  /**
1940
1945
  * #421 (owner decision, 2026-11-20): the strike share is held out of captures, ahead of comfort margins,
1941
1946
  * but never at the cost of next income — when the plan without it earns more next turn (a completion the
@@ -3453,6 +3458,16 @@ function planPass(input, pass) {
3453
3458
  allInOutcome.set(plan, tgt.allInTries);
3454
3459
  if (pc.strikeShare > 0)
3455
3460
  shareOutcome.set(plan, pc.strikeShare);
3461
+ {
3462
+ const nearest = tgt.committing ? (tgt.byCloseness.find((p) => !p.focus) ?? tgt.byCloseness[0]) : undefined;
3463
+ const near = tgt.spreadNearest ?? nearest;
3464
+ closenessOutcome.set(plan, {
3465
+ ...(near ? { nearest: near.bonusId } : {}),
3466
+ spread: tgt.spreadNearest !== undefined || plan.warnings.some((w) => w.endsWith('(#319).')),
3467
+ turns: new Map(tgt.plans.map((p) => [p.bonusId, tgt.turnsOf(p)])),
3468
+ remaining: new Map(tgt.plans.map((p) => [p.bonusId, [...p.remaining].sort((a, b) => a - b)])),
3469
+ });
3470
+ }
3456
3471
  // #421: on a stockpile, the contested bonuses this plan does not complete that an all-in push could (planPushed).
3457
3472
  if (pc.pile && !input.stockpileAllIn) {
3458
3473
  const done = new Set(plan.expected.bonusesCompleted);
@@ -8,6 +8,8 @@
8
8
  // terms, the outcome (kept, ended with notice and whether it was honoured, broken by them or by
9
9
  // me), the break turn and the strongest breach flag my boards showed, the context at the break
10
10
  // (endgame, who led, outgrowing), whether they retaliated and whether they proposed again;
11
+ // - partner-approved exceptions (attacks the partner agreed to, either way) are no break: counted apart
12
+ // (`exceptionsMine` / `exceptionsTheirs`, and per entry), never in the outcome;
11
13
  // - tallies (`RecordCounts`), each moved once by the recorded transition that earns it
12
14
  // (`recordDelta`), so recording the same agreement again never counts it twice, and an entry
13
15
  // dropped past the bound still counts.
@@ -59,6 +61,7 @@ export function recordEntryFor(a, input, previous) {
59
61
  ...outcomeOf(a),
60
62
  ...(previous?.proposedAgain ? { proposedAgain: true } : {}),
61
63
  ...(a.retaliated !== undefined ? { retaliated: a.retaliated } : {}),
64
+ ...(a.exceptions?.length ? { exceptions: exceptionCounts(a) } : {}),
62
65
  updated: input.now,
63
66
  };
64
67
  if (a.status === 'broken-by-them' || a.status === 'broken-by-me') {
@@ -76,8 +79,23 @@ export function upsertEntry(entries, entry) {
76
79
  const rest = entries.filter((e) => e.key !== entry.key);
77
80
  return [...rest, entry].sort(byUpdated).slice(-MAX_RECORD_ENTRIES);
78
81
  }
79
- export const ZERO_COUNTS = Object.freeze({ made: 0, kept: 0, endedWithNotice: 0, brokenByThem: 0, brokenByMe: 0 });
82
+ export const ZERO_COUNTS = Object.freeze({
83
+ made: 0,
84
+ kept: 0,
85
+ endedWithNotice: 0,
86
+ brokenByThem: 0,
87
+ brokenByMe: 0,
88
+ exceptionsMine: 0,
89
+ exceptionsTheirs: 0,
90
+ });
80
91
  export const COUNT_KEYS = Object.keys(ZERO_COUNTS);
92
+ /** The tallies every stored version carries; the exception tallies came later and read as 0 when absent. */
93
+ export const CORE_COUNT_KEYS = ['made', 'kept', 'endedWithNotice', 'brokenByThem', 'brokenByMe'];
94
+ /** `a`'s exceptions counted by direction. */
95
+ function exceptionCounts(a) {
96
+ const list = a.exceptions ?? [];
97
+ return { mine: list.filter((e) => e.direction === 'mine').length, theirs: list.filter((e) => e.direction === 'theirs').length };
98
+ }
81
99
  const OUTCOME_COUNT = {
82
100
  kept: 'kept',
83
101
  'ended-with-notice': 'endedWithNotice',
@@ -98,6 +116,16 @@ export function recordDelta(before, after) {
98
116
  if (key)
99
117
  delta[key] = 1;
100
118
  }
119
+ // Each exception once, by its id: one already on `before` is not counted again.
120
+ const had = new Set((before?.exceptions ?? []).map((e) => e.id));
121
+ for (const e of after.exceptions ?? []) {
122
+ if (had.has(e.id))
123
+ continue;
124
+ if (e.direction === 'mine')
125
+ delta.exceptionsMine++;
126
+ else
127
+ delta.exceptionsTheirs++;
128
+ }
101
129
  return delta;
102
130
  }
103
131
  export const isZero = (c) => COUNT_KEYS.every((k) => c[k] === 0);
@@ -116,6 +144,8 @@ export function talliesOf(entries) {
116
144
  const key = OUTCOME_COUNT[e.outcome];
117
145
  if (key)
118
146
  out[key]++;
147
+ out.exceptionsMine += e.exceptions?.mine ?? 0;
148
+ out.exceptionsTheirs += e.exceptions?.theirs ?? 0;
119
149
  }
120
150
  return out;
121
151
  }
@@ -44,6 +44,36 @@ export const TACIT_QUIET_TURNS = 3;
44
44
  * and the partner's. The partner no longer needs me from there on.
45
45
  */
46
46
  export const TRUCE_ENDGAME_RATIO = 0.5;
47
+ /**
48
+ * Who an exception lets attack: `mine` — the partner agreed I may attack its covered territories;
49
+ * `theirs` — I agreed the partner may attack (or take) covered territories of mine.
50
+ */
51
+ export const EXCEPTION_DIRECTIONS = ['mine', 'theirs'];
52
+ /** Exceptions kept per agreement (the newest). */
53
+ export const MAX_EXCEPTIONS = 50;
54
+ /** The longest note an exception keeps (the owner's own words, names scrubbed). */
55
+ export const MAX_EXCEPTION_NOTE = 200;
56
+ /** The next exception id on `a`: `e1`, `e2`, … */
57
+ export function nextExceptionId(a) {
58
+ const n = (a.exceptions ?? []).reduce((m, e) => Math.max(m, Number(/^e(\d+)$/.exec(e.id)?.[1] ?? 0)), 0);
59
+ return `e${n + 1}`;
60
+ }
61
+ /** `a` with `exceptions` appended (fresh ids), at most {@link MAX_EXCEPTIONS} kept (the newest). */
62
+ export function withExceptions(a, exceptions) {
63
+ let next = a;
64
+ for (const e of exceptions)
65
+ next = { ...next, exceptions: [...(next.exceptions ?? []), { id: nextExceptionId(next), ...e }] };
66
+ return next.exceptions && next.exceptions.length > MAX_EXCEPTIONS ? { ...next, exceptions: next.exceptions.slice(-MAX_EXCEPTIONS) } : next;
67
+ }
68
+ /** The territories `a`'s exceptions in `direction` open on `turn` (the turn's orders), ascending. */
69
+ export function exceptedOn(a, turn, direction) {
70
+ const out = new Set();
71
+ for (const e of a.exceptions ?? [])
72
+ if (e.direction === direction && e.fromTurn <= turn && turn <= e.toTurn)
73
+ for (const t of e.territories)
74
+ out.add(t);
75
+ return out;
76
+ }
47
77
  const byNum = (a, b) => a - b;
48
78
  const alive = (p) => p !== undefined && (p.state === undefined || p.state === 'Playing');
49
79
  const turnedAI = (p) => p.isAI === true || p.humanTurnedIntoAI === true;
@@ -234,7 +264,8 @@ function fedByHitSource(t, orders, mine, was, now, me) {
234
264
  * leaves ambiguous;
235
265
  * - `outgrowing`: its income passed {@link TRUCE_OUTGROW_RATIO} × mine;
236
266
  * - `kept`: the consecutive quiet turns up to the newest board (when nothing broke).
237
- * A proposal that was never agreed has no flags.
267
+ * A covered territory under a `theirs` exception on a turn (the partner may attack it by agreement) raises
268
+ * nothing that turn. A proposal that was never agreed has no flags.
238
269
  */
239
270
  export function breachWatch(input) {
240
271
  const { agreement: a, graph, me } = input;
@@ -261,7 +292,11 @@ export function breachWatch(input) {
261
292
  const taken = [];
262
293
  const attacked = [];
263
294
  const ambiguous = [];
295
+ // A `theirs` exception on this turn: the partner may attack or take these by agreement — no event.
296
+ const allowed = exceptedOn(a, from.turn, 'theirs');
264
297
  for (const c of covered) {
298
+ if (allowed.has(c))
299
+ continue;
265
300
  const after = now.get(c);
266
301
  const shown = ownerShown(after);
267
302
  const neighbours = neighborsOf(graph, c);
@@ -518,7 +553,8 @@ const WATCH_KINDS = ['broken', 'cap-exceeded', 'massing', 'outgrowing'];
518
553
  /**
519
554
  * B2 (warapp_submit_turn): the active or in-notice agreements that `moves` would break — an order that
520
555
  * attacks a territory the partner holds on `board` and the terms cover (a transfer-only order attacks
521
- * nothing), or a Bomb (`bombs`, the targets) on such a territory. By agreement id; empty when nothing binds. Pure; reads only the ledger's own agreements and
556
+ * nothing), or a Bomb (`bombs`, the targets) on such a territory — except one a `mine` exception opens on `turn`
557
+ * (the partner agreed to it). By agreement id; empty when nothing binds. Pure; reads only the ledger's own agreements and
522
558
  * the board (the breach watch is not consulted: a break by them is recorded as broken-by-them first).
523
559
  */
524
560
  export function truceBreaksIn(input) {
@@ -530,7 +566,9 @@ export function truceBreaksIn(input) {
530
566
  if (state.phase !== 'active' && state.phase !== 'notice')
531
567
  continue;
532
568
  const held = new Set(input.board.territories.filter((t) => ownerShown(t) && ownerOn(t) === a.with).map((t) => t.territoryId));
533
- const covered = new Set(coveredTerritories(input.graph, a.terms.scope, held));
569
+ // A `mine` exception on this turn: the partner agreed to these attacks — no break.
570
+ const allowed = exceptedOn(a, input.turn, 'mine');
571
+ const covered = new Set(coveredTerritories(input.graph, a.terms.scope, held).filter((t) => !allowed.has(t)));
534
572
  const moves = input.moves.flatMap((m, index) => (m.mode !== 'transfer-only' && covered.has(m.to) ? [{ index, from: m.from, to: m.to }] : []));
535
573
  const bombs = (input.bombs ?? []).flatMap((target, index) => (covered.has(target) ? [{ index, target }] : []));
536
574
  if (moves.length || bombs.length)
@@ -566,10 +604,21 @@ export function planRelationsFrom(input) {
566
604
  if (endgame)
567
605
  watch.push('endgame');
568
606
  const broke = flags.find((f) => f.kind === 'broken' && !f.ambiguous);
607
+ // Partner-approved exceptions on this turn: those territories are no longer covered (normal targets
608
+ // for me, or open to the partner), and the plan lists them.
609
+ const exceptMine = exceptedOn(a, turn, 'mine');
610
+ const exceptTheirs = exceptedOn(a, turn, 'theirs');
611
+ const coveredMine = coveredTerritories(graph, a.terms.scope, mine);
612
+ const coveredTheirs = coveredTerritories(graph, a.terms.scope, holding(a.with));
613
+ const exceptions = [
614
+ { direction: 'mine', territories: coveredTheirs.filter((t) => exceptMine.has(t)) },
615
+ { direction: 'theirs', territories: coveredMine.filter((t) => exceptTheirs.has(t)) },
616
+ ].filter((e) => e.territories.length);
569
617
  relations.push({
570
618
  player: a.with,
571
- coveredMine: coveredTerritories(graph, a.terms.scope, mine),
572
- coveredTheirs: coveredTerritories(graph, a.terms.scope, holding(a.with)),
619
+ coveredMine: coveredMine.filter((t) => !exceptTheirs.has(t)),
620
+ coveredTheirs: coveredTheirs.filter((t) => !exceptMine.has(t)),
621
+ ...(exceptions.length ? { exceptions } : {}),
573
622
  state: broke ? 'broken' : state.phase,
574
623
  ...(state.endsTurn !== undefined ? { endsTurn: state.endsTurn } : {}),
575
624
  ...(a.terms.borderCap !== undefined ? { borderCap: a.terms.borderCap } : {}),