@chrischall/warapp-mcp 0.13.1 → 0.14.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 (42) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +7 -6
  4. package/dist/analysis/airlift-plan.js +288 -0
  5. package/dist/analysis/blockade-plan.js +178 -0
  6. package/dist/analysis/bomb-plan.js +72 -0
  7. package/dist/analysis/card-threats.js +10 -9
  8. package/dist/analysis/cards-in-effect.js +20 -0
  9. package/dist/analysis/combat.js +5 -0
  10. package/dist/analysis/coordination.js +47 -0
  11. package/dist/analysis/lookahead.js +4 -0
  12. package/dist/analysis/plan/relations.js +57 -8
  13. package/dist/analysis/player-record.js +1 -0
  14. package/dist/analysis/relations.js +40 -0
  15. package/dist/analysis/stress.js +42 -2
  16. package/dist/analysis/turn-sim.js +62 -0
  17. package/dist/bundle.js +23219 -21662
  18. package/dist/card-state.js +157 -0
  19. package/dist/local-time.js +142 -0
  20. package/dist/relations-store.js +30 -5
  21. package/dist/tools/airlift-readback.js +87 -0
  22. package/dist/tools/alternative-orders.js +21 -0
  23. package/dist/tools/begin-turn.js +19 -5
  24. package/dist/tools/card-advice.js +5 -4
  25. package/dist/tools/card-plays.js +32 -20
  26. package/dist/tools/card-state-view.js +26 -0
  27. package/dist/tools/card-support-advice.js +25 -8
  28. package/dist/tools/chat-inbox.js +1 -1
  29. package/dist/tools/chat.js +1 -1
  30. package/dist/tools/check-plan.js +90 -8
  31. package/dist/tools/game.js +11 -2
  32. package/dist/tools/index.js +7 -1
  33. package/dist/tools/notifications.js +1 -1
  34. package/dist/tools/player-card-readback.js +45 -0
  35. package/dist/tools/relations.js +146 -14
  36. package/dist/tools/sanctions-played.js +51 -0
  37. package/dist/tools/turn.js +479 -13
  38. package/dist/version.js +1 -1
  39. package/manifest.json +9 -2
  40. package/mint.yaml +7 -0
  41. package/package.json +1 -1
  42. package/server.json +8 -2
@@ -0,0 +1,178 @@
1
+ // An Emergency Blockade plan beside the plain plan (owner request 2026-11-24, part B). When I hold an Emergency
2
+ // Blockade card, warapp_plan_turn also looks for a plan that walls off a border the plain plan concedes: the
3
+ // territory turns neutral at its armies × the card's multiplier (rounded with a half down) in phase 37 — after the
4
+ // deploys and Bombs, before every move (the client bundle's GameOrderPlayCardAbandonResult) — so the stack beside it
5
+ // must break through a wall instead of taking a thin border into what lies behind. The unchanged planner (`planTurn`)
6
+ // plans that board and the plans are compared by the plain plan's own measure (`scoreOf`, shared with the Airlift
7
+ // plan); the best one that beats the plain plan is returned ALONGSIDE it, the plain plan and its orders unchanged.
8
+ // Pure and deterministic.
9
+ //
10
+ // Candidates (the evacuation/denial case beside the Airlift's evacuate): a territory of mine the plain plan concedes,
11
+ // with armies on it, not my commander's (it would be lost with it); those whose fall would complete an opponent's
12
+ // bonus first (every other member visibly its own, a stack of its beside the territory), then the strongest wall.
13
+ //
14
+ // Owner-approved 2026-11-24: the plain plan's measure reads only my income, and a conceded border is lost either way,
15
+ // so a wall's worth is the bonus it denies: `denied` (that bonus's value) enters the two-turn score as a staging
16
+ // gain does (`scoreOf(plan, denied)`: × `STAGING_DISCOUNT`, ranked first), only for a wall the stack beside it does
17
+ // not break this turn (luck-free: its armies plus the plan's enemy deploy against the wall).
18
+ // The wall is built from the armies standing now: a deploy there would be multiplied too, but the planner does not
19
+ // deploy onto a neutral, so a plan sized on this board is never short for that reason.
20
+ //
21
+ // A Blockade (phase 60, after every move; owner decision 2026-11-24): the plain plan's orders stand unchanged and the
22
+ // card is added. Its candidates are territories of mine whose fall would complete an opponent's bonus (the same
23
+ // denial term), not my commander's; it is valued only when the stress-tested line keeps the territory mine through
24
+ // the attacks (no single-deploy reply `stressPlan` tries takes it — each opponent beside my land at the plan's enemy
25
+ // deploy), since the Blockade acts only on a territory still mine then. The wall is its armies after the plan × the
26
+ // multiplier. It is charged the positive bonuses of mine it gives up (every member mine after the plan), out of
27
+ // both incomes; the two-turn score is that plus 0.8 × the denied bonus.
28
+ import { compareScores, scoreOf } from './airlift-plan.js';
29
+ import { armiesToTake } from './combat.js';
30
+ import { neighborsOf } from './graph.js';
31
+ import { stressPlan } from './stress.js';
32
+ import { planTurn } from './planner.js';
33
+ import { roundHalfDown } from './turn-sim.js';
34
+ /** Most candidate walls tried (each one planner run). */
35
+ export const MAX_WALL_CANDIDATES = 6;
36
+ /** The board with `target` a neutral wall of `armies`. */
37
+ export function walledBoard(board, target, armies) {
38
+ return {
39
+ ...board,
40
+ territories: board.territories.map((t) => {
41
+ if (t.territoryId !== target)
42
+ return t;
43
+ const { specialUnits: _units, ...rest } = t;
44
+ return { ...rest, owner: { kind: 'neutral' }, armies };
45
+ }),
46
+ };
47
+ }
48
+ /** The bonus value the fall of `id` would complete for an opponent with a stack beside it, and that opponent. */
49
+ function denialOf(input, id) {
50
+ const { graph, board, me } = input;
51
+ const owner = new Map(board.territories.map((t) => [t.territoryId, t.owner.kind === 'player' && t.armies !== null ? t.owner.playerId : undefined]));
52
+ let best = { denied: 0 };
53
+ for (const p of new Set(neighborsOf(graph, id).map((n) => owner.get(n)).filter((x) => x !== undefined && x !== me))) {
54
+ const value = [...graph.bonusById.values()]
55
+ .filter((b) => b.value > 0 && b.territoryIds.includes(id) && b.territoryIds.every((x) => x === id || owner.get(x) === p))
56
+ .reduce((n, b) => n + b.value, 0);
57
+ if (value > best.denied)
58
+ best = { denied: value, deniedFrom: p };
59
+ }
60
+ return best;
61
+ }
62
+ /** The candidate walls, denials first, then the strongest (see the header). */
63
+ export function wallCandidates(input, plain, multiplier) {
64
+ const { board, me } = input;
65
+ const conceded = new Set(plain.conceded);
66
+ return board.territories
67
+ .filter((t) => conceded.has(t.territoryId) &&
68
+ t.owner.kind === 'player' &&
69
+ t.owner.playerId === me &&
70
+ t.armies !== null &&
71
+ t.armies > 0 &&
72
+ !t.specialUnits?.some((u) => u.kind === 'commander' && u.playerId === me))
73
+ .map((t) => ({ target: t.territoryId, armies: t.armies, wall: roundHalfDown(t.armies * multiplier), ...denialOf(input, t.territoryId) }))
74
+ .sort((a, b) => b.denied - a.denied || b.wall - a.wall || a.target - b.target);
75
+ }
76
+ /** The wall survives this turn: every enemy stack beside it (its movable armies) plus the enemy deploy, luck-free. */
77
+ function wallHolds(input, wall, enemyDeploy) {
78
+ const guard = input.settings?.oneArmyStandsGuard === false ? 0 : 1;
79
+ const attackers = neighborsOf(input.graph, wall.target).reduce((n, x) => {
80
+ const t = input.board.territories.find((y) => y.territoryId === x);
81
+ return n + (t?.owner.kind === 'player' && t.owner.playerId !== input.me && t.armies !== null ? Math.max(0, t.armies - guard) : 0);
82
+ }, 0) + enemyDeploy;
83
+ const need = armiesToTake(wall.wall, {
84
+ ...(input.settings?.offensiveKillRate !== undefined ? { offensiveKillRate: input.settings.offensiveKillRate } : {}),
85
+ ...(input.settings?.defensiveKillRate !== undefined ? { defensiveKillRate: input.settings.defensiveKillRate } : {}),
86
+ });
87
+ return need === null || attackers < need;
88
+ }
89
+ /** The best Emergency Blockade plan that beats the plain plan, or none. */
90
+ export function planWall(a) {
91
+ if (a.cards < 1 || !(a.multiplier > 0))
92
+ return { considered: 0 };
93
+ const plainScore = scoreOf(a.plain);
94
+ let best;
95
+ let considered = 0;
96
+ for (const wall of wallCandidates(a.input, a.plain, a.multiplier).slice(0, MAX_WALL_CANDIDATES)) {
97
+ considered++;
98
+ const plan = planTurn({ ...a.input, board: walledBoard(a.input.board, wall.target, wall.wall) });
99
+ const score = scoreOf(plan, wall.denied > 0 && wallHolds(a.input, wall, a.plain.enemyDeploy) ? wall.denied : 0);
100
+ if (compareScores(score, plainScore) >= 0)
101
+ continue;
102
+ if (!best || compareScores(score, best.score) < 0)
103
+ best = { plan, wall, score, plainScore, considered: 0 };
104
+ }
105
+ if (best)
106
+ best.considered = considered;
107
+ return best ? { best, considered } : { considered };
108
+ }
109
+ /** The best Blockade (phase 60) added to the plain plan's orders, or none (see the header). */
110
+ export function planBlockade(a) {
111
+ if (a.cards < 1 || !(a.multiplier > 0))
112
+ return { considered: 0 };
113
+ const { graph, board, me } = a.input;
114
+ const plainScore = scoreOf(a.plain);
115
+ const at = new Map(board.territories.map((t) => [t.territoryId, t]));
116
+ const isMine = (id) => {
117
+ const t = at.get(id);
118
+ return t?.owner.kind === 'player' && t.owner.playerId === me && t.armies !== null;
119
+ };
120
+ const deployed = new Map();
121
+ for (const d of a.plain.deploys)
122
+ deployed.set(d.territoryId, (deployed.get(d.territoryId) ?? 0) + d.armies);
123
+ const after = (id) => (at.get(id)?.armies ?? 0) +
124
+ (deployed.get(id) ?? 0) -
125
+ a.plain.moves.filter((m) => m.from === id).reduce((n, m) => n + m.armies, 0) +
126
+ a.plain.moves.filter((m) => m.to === id && m.kind === 'transfer').reduce((n, m) => n + m.armies, 0);
127
+ const candidates = board.territories
128
+ .filter((t) => isMine(t.territoryId) && !t.specialUnits?.some((u) => u.kind === 'commander' && u.playerId === me))
129
+ .map((t) => ({ target: t.territoryId, armies: after(t.territoryId), ...denialOf(a.input, t.territoryId) }))
130
+ .filter((c) => c.denied > 0 && c.armies > 0)
131
+ .map((c) => ({ ...c, wall: roundHalfDown(c.armies * a.multiplier) }))
132
+ .sort((x, y) => y.denied - x.denied || y.wall - x.wall || x.target - y.target)
133
+ .slice(0, MAX_WALL_CANDIDATES);
134
+ if (!candidates.length)
135
+ return { considered: 0 };
136
+ // The stress-tested line: the plain plan's orders against each opponent beside my land at the plan's enemy deploy.
137
+ const opponents = [
138
+ ...new Set(board.territories.flatMap((t) => t.owner.kind === 'player' && t.owner.playerId !== me && neighborsOf(graph, t.territoryId).some(isMine) ? [t.owner.playerId] : [])),
139
+ ].map((id) => ({ id, deploy: a.plain.enemyDeploy }));
140
+ const report = stressPlan({
141
+ graph,
142
+ board,
143
+ me,
144
+ deploys: a.plain.deploys,
145
+ moves: a.plain.moves.map((m) => ({ from: m.from, to: m.to, armies: m.armies, ...(m.commander ? { withCommander: true } : {}) })),
146
+ opponents,
147
+ ...(a.input.settings ? { settings: a.input.settings } : {}),
148
+ lookAhead: false,
149
+ });
150
+ const falls = new Set(report.atRisk.territories.map((t) => t.id));
151
+ const captured = new Set(a.plain.expected.captures);
152
+ const conceded = new Set(a.plain.conceded);
153
+ const mineAfter = (id) => (isMine(id) && !conceded.has(id)) || captured.has(id);
154
+ let best;
155
+ let considered = 0;
156
+ for (const c of candidates) {
157
+ considered++;
158
+ if (falls.has(c.target) || report.baseline.captured.includes(c.target))
159
+ continue;
160
+ const lost = [...graph.bonusById.values()]
161
+ .filter((b) => b.value > 0 && b.territoryIds.includes(c.target) && b.territoryIds.every(mineAfter))
162
+ .reduce((n, b) => n + b.value, 0);
163
+ const scored = scoreOf(a.plain, c.denied);
164
+ const score = {
165
+ ...scored,
166
+ twoTurn: scored.twoTurn - lost,
167
+ safeIncome: scored.safeIncome - lost,
168
+ nextIncome: scored.nextIncome - lost,
169
+ };
170
+ if (compareScores(score, plainScore) >= 0)
171
+ continue;
172
+ if (!best || compareScores(score, best.score) < 0)
173
+ best = { plan: a.plain, wall: c, score, plainScore, considered: 0 };
174
+ }
175
+ if (best)
176
+ best.considered = considered;
177
+ return best ? { best, considered } : { considered };
178
+ }
@@ -0,0 +1,72 @@
1
+ // A Bomb plan beside the plain plan (owner request 2026-11-24, part B). When I hold a Bomb card, warapp_plan_turn
2
+ // also looks for a plan that plays it: each candidate target is halved on the board the planner plans on (a Bomb
3
+ // runs in phase 30, after every deploy and before every move, and leaves half the armies rounded down — the client
4
+ // bundle's GameOrderPlayCardBombResult), the unchanged planner (`planTurn`) plans that board, and the plans are
5
+ // compared by the plain plan's own measure (`scoreOf`, shared with the Airlift plan). The best one that beats the
6
+ // plain plan is returned ALONGSIDE it; the plain plan and its orders never change. Pure and deterministic.
7
+ //
8
+ // Candidates: an opponent's territory beside mine (never a teammate's, never a player a truce or a Diplomacy card
9
+ // keeps at peace with me — the planner's own relations), first one that is a member of a bonus its owner visibly
10
+ // holds whole (a capture there breaks it), then the largest stacks (cutting a stack that presses my border).
11
+ // The halving here is of the armies standing now: the owner's deploy on the target lands before the Bomb and is
12
+ // halved with it, so a plan sized on this board is never short for that reason.
13
+ import { compareScores, scoreOf } from './airlift-plan.js';
14
+ import { bombLeaves } from './combat.js';
15
+ import { neighborsOf } from './graph.js';
16
+ import { planTurn } from './planner.js';
17
+ /** Most candidate targets tried (each one planner run). */
18
+ export const MAX_BOMB_CANDIDATES = 6;
19
+ export { bombLeaves };
20
+ /** The board with `target`'s armies halved. */
21
+ export function bombedBoard(board, target) {
22
+ return {
23
+ ...board,
24
+ territories: board.territories.map((t) => (t.territoryId === target && t.armies !== null ? { ...t, armies: bombLeaves(t.armies) } : t)),
25
+ };
26
+ }
27
+ /** The candidate targets, best first (see the header). */
28
+ export function bombCandidates(input) {
29
+ const { graph, board, me } = input;
30
+ const at = new Map(board.territories.map((t) => [t.territoryId, t]));
31
+ const ownerOf = (id) => {
32
+ const t = at.get(id);
33
+ return t?.owner.kind === 'player' && t.armies !== null ? t.owner.playerId : undefined;
34
+ };
35
+ const myTeam = input.game?.players?.find((p) => p.id === me)?.team;
36
+ const friend = (p) => p === me || (myTeam !== undefined && myTeam >= 0 && input.game?.players?.find((x) => x.id === p)?.team === myTeam);
37
+ const peace = new Set((input.relations ?? []).filter((r) => r.enforced === true || r.state === 'active' || r.state === 'notice').map((r) => r.player));
38
+ const out = [];
39
+ for (const t of board.territories) {
40
+ const owner = ownerOf(t.territoryId);
41
+ if (owner === undefined || friend(owner) || peace.has(owner))
42
+ continue;
43
+ if (!neighborsOf(graph, t.territoryId).some((n) => ownerOf(n) === me))
44
+ continue;
45
+ const armies = t.armies ?? 0;
46
+ if (armies < 2)
47
+ continue; // halving 0 or 1 changes nothing
48
+ const breaks = [...graph.bonusById.values()].some((b) => b.value > 0 && b.territoryIds.includes(t.territoryId) && b.territoryIds.every((x) => ownerOf(x) === owner));
49
+ out.push({ target: t.territoryId, kind: breaks ? 'break-bonus' : 'cut-stack', armies, left: bombLeaves(armies) });
50
+ }
51
+ return out.sort((a, b) => Number(b.kind === 'break-bonus') - Number(a.kind === 'break-bonus') || b.armies - a.armies || a.target - b.target);
52
+ }
53
+ /** The best Bomb plan that beats the plain plan, or none. */
54
+ export function planBomb(a) {
55
+ if (a.cards < 1)
56
+ return { considered: 0 };
57
+ const plainScore = scoreOf(a.plain);
58
+ let best;
59
+ let considered = 0;
60
+ for (const bomb of bombCandidates(a.input).slice(0, MAX_BOMB_CANDIDATES)) {
61
+ considered++;
62
+ const plan = planTurn({ ...a.input, board: bombedBoard(a.input.board, bomb.target) });
63
+ const score = scoreOf(plan);
64
+ if (compareScores(score, plainScore) >= 0)
65
+ continue;
66
+ if (!best || compareScores(score, best.score) < 0)
67
+ best = { plan, bomb, score, plainScore, considered: 0 };
68
+ }
69
+ if (best)
70
+ best.considered = considered;
71
+ return best ? { best, considered } : { considered };
72
+ }
@@ -10,10 +10,11 @@
10
10
  // territory next to one of mine after the deployments and before every move, and kills half its
11
11
  // armies — a commander is reported unharmed. An Emergency Blockade turns a territory into a
12
12
  // neutral of its armies (that turn's deploy included) times the multiplier, before the attacks;
13
- // special units count for nothing on it. UNVERIFIED: how war.app rounds the half (each side is
14
- // read in its worst case: a bombed enemy keeps the larger half, a bombed stack of mine the
15
- // smaller) and the wall (rounded to the nearest army here).
16
- import { armiesToTake, COMMANDER_STRENGTH, DEFAULT_DEFENSIVE_KILL_RATE, straightKills } from './combat.js';
13
+ // special units count for nothing on it. The Bomb's half is the client's rule (owner decision 2026-11-24, read
14
+ // from the bundle's GameOrderPlayCardBombResult: round(armies / 2) with a half rounded down): a bombed stack keeps
15
+ // floor(armies / 2), the same rule bombPlan and the stress test apply. UNVERIFIED: the wall (rounded to the nearest
16
+ // army here).
17
+ import { armiesToTake, bombLeaves, COMMANDER_STRENGTH, DEFAULT_DEFENSIVE_KILL_RATE, straightKills } from './combat.js';
17
18
  import { neighborsOf } from './graph.js';
18
19
  import { bonusTerritories } from './bonuses.js';
19
20
  import { opensBehind } from './opens.js';
@@ -45,9 +46,9 @@ export function reader(cb) {
45
46
  /**
46
47
  * Each opponent's stacks next to `t` plus its deploy (the strongest one), with `bombed` halved by
47
48
  * a bomb. The bomb lands after the deploys, so the worst case is taken: an owner with another
48
- * stack next to `t` deploys there, unhalved (d + ⌈a/2⌉ + the other stacks, less the guards); one
49
+ * stack next to `t` deploys there, unhalved (d + ⌊a/2⌋ + the other stacks, less the guards); one
49
50
  * whose only stack next to `t` is the bombed one deploys on it, and the deploy is halved with it
50
- * (⌈(a + d)/2⌉ less the guard).
51
+ * (⌊(a + d)/2⌋ less the guard).
51
52
  */
52
53
  const reachOf = (t, bombed) => {
53
54
  const by = new Map();
@@ -70,8 +71,8 @@ export function reader(cb) {
70
71
  const reach = e.bombed === undefined
71
72
  ? d + e.others
72
73
  : e.hasOther
73
- ? d + e.others + Math.max(0, Math.ceil(e.bombed / 2) - guard)
74
- : Math.max(0, Math.ceil((e.bombed + d) / 2) - guard);
74
+ ? d + e.others + Math.max(0, bombLeaves(e.bombed) - guard)
75
+ : Math.max(0, bombLeaves(e.bombed + d) - guard);
75
76
  if (!best || reach > best.reach)
76
77
  best = { player, reach };
77
78
  }
@@ -124,7 +125,7 @@ export function bombAdvice(cb) {
124
125
  continue;
125
126
  }
126
127
  const n = r.armiesOf(t) + cb.enemyDeploy;
127
- const left = Math.ceil(n / 2);
128
+ const left = bombLeaves(n);
128
129
  const cmd = r.commanderOf(t, (q) => q === p) ? COMMANDER_STRENGTH : 0;
129
130
  const planned = r.attacksOn(t);
130
131
  const free = planned + borders.reduce((a, b) => a + Math.max(0, r.after(b) - r.guard), 0);
@@ -46,6 +46,26 @@ function cardSettings(settings, card) {
46
46
  const raw = settings.raw?.[`${card}Card`];
47
47
  return typeof raw === 'object' && raw !== null && !Array.isArray(raw) ? raw : undefined;
48
48
  }
49
+ /** A setting's number: a JSON number, or a numeric string (GameFeed may send a scalar as either). */
50
+ const settingNumber = (v) => {
51
+ const n = typeof v === 'number' ? v : typeof v === 'string' && /^\s*-?\d+(\.\d+)?\s*$/.test(v) ? Number(v) : undefined;
52
+ return n !== undefined && Number.isFinite(n) ? n : undefined;
53
+ };
54
+ /** The Sanctions card's settings, or `undefined` when the game does not have it in play. */
55
+ export function sanctionsSettings(settings) {
56
+ const s = cardSettings(settings, 'Sanctions');
57
+ if (!s)
58
+ return undefined;
59
+ const p = settingNumber(s.Percentage);
60
+ const percentage = p !== undefined && p >= -1 && p <= 1 ? p : null;
61
+ const d = settingNumber(s.Duration);
62
+ const duration = d !== undefined && Number.isInteger(d) && d >= 1 ? d : null;
63
+ const effect = percentage === null ? 'unknown' : percentage > 0 ? 'cut' : percentage < 0 ? 'boost' : 'none';
64
+ const targets = { cut: 'opponents', boost: 'your side', none: 'anyone', unknown: 'unknown' }[effect];
65
+ return { percentage, duration, effect, targets };
66
+ }
67
+ /** A percentage as a person reads it: −0.3 → "−30%" (signed when negative). */
68
+ export const percentText = (p) => `${Math.round(p * 100)}%`;
49
69
  const durationOf = (s) => {
50
70
  const d = s?.Duration;
51
71
  return typeof d === 'number' && Number.isInteger(d) && d >= 1 ? d : undefined;
@@ -229,3 +229,8 @@ export function armiesForChance(defenders, minChance, settings = {}) {
229
229
  }
230
230
  return hi;
231
231
  }
232
+ /**
233
+ * What a Bomb leaves of `armies`: half, rounded down — the client bundle's GameOrderPlayCardBombResult,
234
+ * round(armies / 2) with a half rounded down. One rule for the turn simulator, the Bomb plan and the card advice.
235
+ */
236
+ export const bombLeaves = (armies) => Math.floor(armies / 2);
@@ -0,0 +1,47 @@
1
+ // Coordination notes (report only): a joint attack agreed with a partner — who hits what, and which
2
+ // territories I follow on, on a turn or while open — kept per game in the agreement ledger
3
+ // (warapp_record_agreement `coordination`), listed by warapp_get_relations and told by
4
+ // warapp_plan_turn on its turn. Name-free (player and territory ids, turns, a note with names
5
+ // scrubbed). Never read into an order.
6
+ /** Coordination notes kept per game (the newest). */
7
+ export const MAX_COORDINATION = 50;
8
+ /** The longest note a coordination keeps. */
9
+ export const MAX_COORDINATION_NOTE = 200;
10
+ const isRec = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
11
+ const isInt = (v) => typeof v === 'number' && Number.isInteger(v);
12
+ const ints = (v) => (Array.isArray(v) && v.every(isInt) ? [...v] : undefined);
13
+ const ID = /^k(\d{1,9})$/;
14
+ /** A coordination read back, or `undefined` when it is unusable. */
15
+ export function coordinationOf(v) {
16
+ if (!isRec(v) || typeof v.id !== 'string' || !ID.test(v.id) || !isInt(v.with) || !isInt(v.target) || !isInt(v.recordedTurn))
17
+ return undefined;
18
+ const mine = ints(v.mine);
19
+ const theirs = ints(v.theirs);
20
+ if (!mine || !theirs)
21
+ return undefined;
22
+ const c = { id: v.id, with: v.with, target: v.target, mine, theirs, recordedTurn: v.recordedTurn };
23
+ if (isInt(v.turn))
24
+ c.turn = v.turn;
25
+ if (isInt(v.doneTurn))
26
+ c.doneTurn = v.doneTurn;
27
+ if (typeof v.note === 'string' && v.note.length)
28
+ c.note = v.note.slice(0, MAX_COORDINATION_NOTE);
29
+ return c;
30
+ }
31
+ /** The next coordination id in `list`: `k1`, `k2`, … */
32
+ export function nextCoordinationId(list) {
33
+ const n = (list ?? []).reduce((m, c) => Math.max(m, Number(ID.exec(c.id)?.[1] ?? 0)), 0);
34
+ return `k${n + 1}`;
35
+ }
36
+ /** Whether `c` is still open and falls on `turn` (one with no turn falls on every turn while open). */
37
+ export const coordinationDue = (c, turn) => c.doneTurn === undefined && (c.turn === undefined || c.turn === turn);
38
+ /** The plan's line for `c`: who hits what and where I follow on. Report only. */
39
+ export function coordinationLine(c, label) {
40
+ const list = (ts) => ts.map(label).join(', ');
41
+ const parts = [
42
+ ...(c.theirs.length ? [`they hit ${list(c.theirs)}`] : []),
43
+ ...(c.mine.length ? [`you follow on ${list(c.mine)}`] : []),
44
+ ];
45
+ return (`Agreed with player ${c.with} (coordination ${c.id}, against player ${c.target}${c.turn !== undefined ? `, turn ${c.turn}` : ''}): ` +
46
+ `${parts.length ? parts.join(', ') : 'a joint attack'}. Report only: the orders are the plan's own; close it with coordination_done once it is over.`);
47
+ }
@@ -26,6 +26,10 @@ export function twoStepReaches(input) {
26
26
  graph,
27
27
  board,
28
28
  deploys: [...myDeploys, ...deploys],
29
+ ...(input.bombs?.length ? { bombs: input.bombs.map((target) => ({ player: me, target })) } : {}),
30
+ ...(input.abandons?.length ? { abandons: input.abandons.map((w) => ({ ...w, player: me })) } : {}),
31
+ ...(input.blockades?.length ? { blockades: input.blockades.map((w) => ({ ...w, player: me })) } : {}),
32
+ ...(input.airlifts?.length ? { airlifts: input.airlifts.map((a) => ({ ...a, player: me })) } : {}),
29
33
  orders: [{ player: me, orders: myOrders }, ...(theirs ? [theirs] : [])],
30
34
  moveOrder,
31
35
  ...(input.settings ? { settings: input.settings } : {}),
@@ -334,6 +334,7 @@ function capsOf(pc) {
334
334
  const { truce } = pc;
335
335
  const capped = new Map();
336
336
  const borderOf = new Map();
337
+ const promised = new Set();
337
338
  truce.given.forEach((r, i) => {
338
339
  if (!truce.binds[i] || r.borderCap === undefined || truce.enforced.has(r.player))
339
340
  return;
@@ -342,7 +343,26 @@ function capsOf(pc) {
342
343
  for (const t of ts)
343
344
  capped.set(t, Math.min(capped.get(t) ?? Infinity, Math.max(0, Math.floor(r.borderCap))));
344
345
  });
345
- const caps = { borderOf, capped };
346
+ // A territory cap I promised binds while the truce does, on a territory of mine, like a border cap.
347
+ truce.given.forEach((r, i) => {
348
+ if (!truce.binds[i] || !r.territoryCaps?.length)
349
+ return;
350
+ const ts = borderOf.get(i) ?? [];
351
+ for (const c of r.territoryCaps) {
352
+ if (!pc.mineSet.has(c.territory))
353
+ continue;
354
+ const max = Math.max(0, Math.floor(c.max));
355
+ if (max < (capped.get(c.territory) ?? Infinity)) {
356
+ capped.set(c.territory, max);
357
+ promised.add(c.territory);
358
+ }
359
+ if (!ts.includes(c.territory))
360
+ ts.push(c.territory);
361
+ }
362
+ if (ts.length)
363
+ borderOf.set(i, ts.sort(byNum));
364
+ });
365
+ const caps = { borderOf, capped, promised };
346
366
  capsMemo.set(pc, caps);
347
367
  return caps;
348
368
  }
@@ -399,7 +419,7 @@ export function applyBorderCaps(pc, ps, book, hd, tp, threats) {
399
419
  if (!tp)
400
420
  return;
401
421
  const { deployed, avail, moves, warnings, rationale, incoming } = ps;
402
- const { capped, borderOf } = capsOf(pc);
422
+ const { capped, borderOf, promised } = capsOf(pc);
403
423
  if (!capped.size)
404
424
  return;
405
425
  // Another front: a foe's territory no truce covers, else any territory not mine no truce covers.
@@ -415,6 +435,9 @@ export function applyBorderCaps(pc, ps, book, hd, tp, threats) {
415
435
  truce.given.forEach((r, i) => {
416
436
  for (const t of borderOf.get(i) ?? []) {
417
437
  const cap = capped.get(t);
438
+ // How the lines name it: a territory cap I promised, or the truce's border cap.
439
+ const capIs = promised.has(t) ? `cap of ${cap} on ${label(t)}` : `border cap ${cap}`;
440
+ const capWord = promised.has(t) ? 'cap' : 'border cap';
418
441
  const before = endsAt(pc, ps, t);
419
442
  let excess = before - cap;
420
443
  if (excess <= 0)
@@ -486,7 +509,7 @@ export function applyBorderCaps(pc, ps, book, hd, tp, threats) {
486
509
  to: step,
487
510
  armies: k,
488
511
  kind: 'transfer',
489
- reason: `keeps the truce's border cap of ${cap} with player ${r.player} on ${label(t)}`,
512
+ reason: `keeps the truce's ${capWord} of ${cap} with player ${r.player} on ${label(t)}`,
490
513
  });
491
514
  hd.arrived.set(step, (hd.arrived.get(step) ?? 0) + k);
492
515
  moved.push({ from: t, to: step, armies: k });
@@ -497,7 +520,7 @@ export function applyBorderCaps(pc, ps, book, hd, tp, threats) {
497
520
  if (moved.length)
498
521
  tp.capMoved.set(i, moved);
499
522
  if (said.length || trimmed.length)
500
- rationale.push(`Truce with player ${r.player} (border cap ${cap}): ${already ? `${label(t)} already stands above the cap with ${armiesOf(t)}, so` : `my orders would leave more than ${cap} on ${label(t)}, so`} ${[...trimmed, ...said].join(' and ')}${said.length && !facesOther ? ', toward another front' : ''} (T5).`);
523
+ rationale.push(`Truce with player ${r.player} (${capIs}): ${already ? `${label(t)} already stands above the cap with ${armiesOf(t)}, so` : `my orders would leave more than ${cap} on ${label(t)}, so`} ${[...trimmed, ...said].join(' and ')}${said.length && !facesOther ? ', toward another front' : ''} (T5).`);
501
524
  if (excess > 0) {
502
525
  const dep = deployed.get(t) ?? 0;
503
526
  const why = step === undefined && dep > 0
@@ -510,8 +533,8 @@ export function applyBorderCaps(pc, ps, book, hd, tp, threats) {
510
533
  ? ` (Local Deployment: the pools had room for only ${noRoom.shift} of the ${noRoom.off} deployed there on ${label(step)}, and the armies there cannot move again this turn)`
511
534
  : ' (the armies there cannot move again this turn)';
512
535
  warnings.push(why.endsWith('.')
513
- ? `Truce with player ${r.player}: my orders leave ${excess} above the agreed border cap of ${cap} on ${label(t)}${why}`
514
- : `Truce with player ${r.player}: my orders leave ${excess} above the agreed border cap of ${cap} on ${label(t)}${why}: that breaks a term of the truce.`);
536
+ ? `Truce with player ${r.player}: my orders leave ${excess} above the agreed ${capWord} of ${cap} on ${label(t)}${why}`
537
+ : `Truce with player ${r.player}: my orders leave ${excess} above the agreed ${capWord} of ${cap} on ${label(t)}${why}: that breaks a term of the truce.`);
515
538
  }
516
539
  if (facesOther) {
517
540
  // The cap's cost: what it leaves no longer holds the border against another opponent.
@@ -522,7 +545,7 @@ export function applyBorderCaps(pc, ps, book, hd, tp, threats) {
522
545
  const need = f && !truce.partners.has(f.player) ? Math.max(0, threats.holdArmies(f.threat) - unitsAt(t)) : 0;
523
546
  const left = endsAt(pc, ps, t);
524
547
  if (f && need > 0 && left < need && before >= need)
525
- warnings.push(`Truce with player ${r.player} (border cap ${cap}): ${label(t)} also faces player ${f.player}, and the ${left} the cap leaves there do not hold it — its hold needs ${need} against player ${f.player}'s ~${f.threat}. Keep the term, or give notice (notice-by-me) and ask the owner before exceeding the cap; never break it silently.`);
548
+ warnings.push(`Truce with player ${r.player} (${capIs}): ${label(t)} also faces player ${f.player}, and the ${left} the cap leaves there do not hold it — its hold needs ${need} against player ${f.player}'s ~${f.threat}. Keep the term, or give notice (notice-by-me) and ask the owner before exceeding the cap; never break it silently.`);
526
549
  }
527
550
  if (pc.myCommanders.has(t)) {
528
551
  // T3 keeps my commander's full hold against the partner; the cap may still thin it below that.
@@ -533,7 +556,7 @@ export function applyBorderCaps(pc, ps, book, hd, tp, threats) {
533
556
  const need = f ? Math.max(0, threats.holdArmies(f.threat) - unitsAt(t)) : 0;
534
557
  const left = endsAt(pc, ps, t);
535
558
  if (f && need > 0 && left < need && before >= need)
536
- warnings.push(`Truce with player ${r.player} (border cap ${cap}): my commander stands on ${label(t)}, and the ${left} the cap leaves there do not hold it against player ${r.player}'s full attack — its hold needs ${need} against ~${f.threat}. Keep the term, or give notice (notice-by-me) and ask the owner before exceeding the cap; never break it silently.`);
559
+ warnings.push(`Truce with player ${r.player} (${capIs}): my commander stands on ${label(t)}, and the ${left} the cap leaves there do not hold it against player ${r.player}'s full attack — its hold needs ${need} against ~${f.threat}. Keep the term, or give notice (notice-by-me) and ask the owner before exceeding the cap; never break it silently.`);
537
560
  }
538
561
  }
539
562
  });
@@ -848,3 +871,29 @@ export function reportBreakLosses(pc, views, plan) {
848
871
  plan.rationale.push(`${name}: if it broke this turn — its ~${loss.deploy} deploy on ${label(loss.from)} and an attack on ${label(loss.to)} with ${loss.attackers} — I would lose ${lost}${when} (T6).`);
849
872
  });
850
873
  }
874
+ /**
875
+ * The territory caps I promised (each binding relation's `territoryCaps`) that `deploys` and `moves`
876
+ * go over: per capped territory of mine, its armies now, plus the deploys there, less the armies moved
877
+ * out, plus those moved in from territories of mine (transfers). For warapp_check_plan's warning.
878
+ */
879
+ export function territoryCapOverruns(relations, o) {
880
+ const out = [];
881
+ for (const r of relations)
882
+ for (const c of r.territoryCaps ?? []) {
883
+ if (!o.mine.has(c.territory))
884
+ continue;
885
+ let n = o.armiesOf(c.territory);
886
+ for (const d of o.deploys)
887
+ if (d.territoryId === c.territory)
888
+ n += d.armies;
889
+ for (const m of o.moves) {
890
+ if (m.from === c.territory)
891
+ n -= m.armies;
892
+ if (m.to === c.territory && o.mine.has(m.from))
893
+ n += m.armies;
894
+ }
895
+ if (n > c.max)
896
+ out.push({ player: r.player, ...(r.agreement ? { agreement: r.agreement } : {}), territory: c.territory, max: c.max, armies: n });
897
+ }
898
+ return out.sort((a, b) => a.territory - b.territory || a.player - b.player);
899
+ }
@@ -55,6 +55,7 @@ export function recordEntryFor(a, input, previous) {
55
55
  scopeSize: scope === 'all' ? null : 'territories' in scope ? scope.territories.length : scope.bonuses.length,
56
56
  noticeTurns: a.terms.noticeTurns,
57
57
  cap: a.terms.borderCap ?? null,
58
+ ...(a.caps?.length ? { caps: a.caps.length } : {}),
58
59
  endCondition: endCondition(a.terms),
59
60
  against: a.terms.against !== undefined,
60
61
  },
@@ -44,6 +44,15 @@ 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
+ /** Territory caps kept per agreement. */
48
+ export const MAX_CAPS = 20;
49
+ /** `a` with `caps` set (one per territory: a new one replaces the old) and `remove` lifted; `caps` absent when none is left. */
50
+ export function withCaps(a, caps, remove = []) {
51
+ const gone = new Set([...remove, ...caps.map((c) => c.territory)]);
52
+ const next = [...(a.caps ?? []).filter((c) => !gone.has(c.territory)), ...caps].slice(-MAX_CAPS);
53
+ const { caps: _old, ...rest } = a;
54
+ return next.length ? { ...rest, caps: next } : rest;
55
+ }
47
56
  /**
48
57
  * Who an exception lets attack: `mine` — the partner agreed I may attack its covered territories;
49
58
  * `theirs` — I agreed the partner may attack (or take) covered territories of mine.
@@ -250,6 +259,36 @@ function fedByHitSource(t, orders, mine, was, now, me) {
250
259
  return nowArmies < expectedArmies(m.from, before, orders, mine);
251
260
  });
252
261
  }
262
+ /**
263
+ * A self-check of the territory caps I promised on `a` (its `caps`): on the newest board, each territory
264
+ * of mine holding more than its cap is one `cap-exceeded` flag `by: 'me'` — my breach, not the
265
+ * partner's, so it never feeds {@link trust}. Nothing for a proposal never agreed, or with no caps.
266
+ */
267
+ export function capSelfCheck(a, boards, me) {
268
+ if (!a.caps?.length || a.agreedTurn === undefined)
269
+ return [];
270
+ const newest = [...boards].sort((x, y) => x.turn - y.turn).at(-1);
271
+ if (!newest)
272
+ return [];
273
+ const at = territoryMap(newest.board);
274
+ const flags = [];
275
+ for (const c of [...a.caps].sort((x, y) => x.territory - y.territory)) {
276
+ const t = visibleState(at.get(c.territory));
277
+ const armies = t?.armies ?? 0;
278
+ if (!t || ownerOn(t) !== me || armies <= c.max)
279
+ continue;
280
+ flags.push({
281
+ kind: 'cap-exceeded',
282
+ by: 'me',
283
+ turn: newest.turn,
284
+ territories: [c.territory],
285
+ armies,
286
+ cap: c.max,
287
+ evidence: `my territory ${c.territory} holds ${armies}, over the cap of ${c.max} I agreed`,
288
+ });
289
+ }
290
+ return flags;
291
+ }
253
292
  /**
254
293
  * What my boards say about the partner keeping `agreement`, over the consecutive turns from the
255
294
  * one it was agreed (and before it ended), as flags with their turn and evidence:
@@ -622,6 +661,7 @@ export function planRelationsFrom(input) {
622
661
  state: broke ? 'broken' : state.phase,
623
662
  ...(state.endsTurn !== undefined ? { endsTurn: state.endsTurn } : {}),
624
663
  ...(a.terms.borderCap !== undefined ? { borderCap: a.terms.borderCap } : {}),
664
+ ...(a.caps?.length ? { territoryCaps: a.caps.map((c) => ({ territory: c.territory, max: c.max })) } : {}),
625
665
  trust: verdict.level,
626
666
  ...(watch.length ? { watch } : {}),
627
667
  // T9: `a.enforced` is never read in. No tool writes it, and only a Diplomacy card the decoder is