@chrischall/warapp-mcp 0.13.1 → 0.15.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 (58) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +9 -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/income-calibration.js +280 -0
  12. package/dist/analysis/intel.js +1 -1
  13. package/dist/analysis/lookahead.js +4 -0
  14. package/dist/analysis/opponents.js +52 -3
  15. package/dist/analysis/plan/deploy-estimates.js +1 -1
  16. package/dist/analysis/plan/estimates.js +40 -6
  17. package/dist/analysis/plan/relations.js +57 -8
  18. package/dist/analysis/plan/threats.js +1 -1
  19. package/dist/analysis/player-record.js +1 -0
  20. package/dist/analysis/relations.js +40 -0
  21. package/dist/analysis/stress.js +42 -2
  22. package/dist/analysis/turn-sim.js +62 -0
  23. package/dist/bundle.js +24486 -21811
  24. package/dist/card-state.js +157 -0
  25. package/dist/decision-log.js +44 -5
  26. package/dist/local-time.js +142 -0
  27. package/dist/relations-store.js +30 -5
  28. package/dist/tools/airlift-readback.js +87 -0
  29. package/dist/tools/alternative-orders.js +21 -0
  30. package/dist/tools/begin-turn.js +19 -5
  31. package/dist/tools/calibration-harness.js +102 -0
  32. package/dist/tools/calibration.js +110 -0
  33. package/dist/tools/card-advice.js +5 -4
  34. package/dist/tools/card-plays.js +32 -20
  35. package/dist/tools/card-state-view.js +26 -0
  36. package/dist/tools/card-support-advice.js +25 -8
  37. package/dist/tools/chat-inbox.js +1 -1
  38. package/dist/tools/chat.js +1 -1
  39. package/dist/tools/check-plan.js +113 -9
  40. package/dist/tools/common.js +14 -0
  41. package/dist/tools/decision-capture.js +14 -1
  42. package/dist/tools/game.js +11 -2
  43. package/dist/tools/index.js +13 -1
  44. package/dist/tools/notifications.js +1 -1
  45. package/dist/tools/opponents.js +2 -0
  46. package/dist/tools/player-card-readback.js +45 -0
  47. package/dist/tools/relations.js +146 -14
  48. package/dist/tools/sanctions-played.js +51 -0
  49. package/dist/tools/stress-opponents.js +8 -4
  50. package/dist/tools/turn-history.js +214 -0
  51. package/dist/tools/turn.js +504 -20
  52. package/dist/turn-orders.js +64 -0
  53. package/dist/version.js +1 -1
  54. package/manifest.json +17 -2
  55. package/mint.yaml +7 -0
  56. package/package.json +1 -1
  57. package/server.json +8 -2
  58. package/skills/warapp-mcp/SKILL.md +9 -1
@@ -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
+ }
@@ -0,0 +1,280 @@
1
+ import { CALIBRATION_HIGH, CALIBRATION_LOW, COVERAGE_BUCKETS, coverageBucket } from './game-lessons.js';
2
+ /** A true income jump at least this many times the turn before starts a catch-up count. */
3
+ export const JUMP_FACTOR = 1.5;
4
+ /** The estimate has caught up once it reaches this share of the truth. */
5
+ export const CATCH_UP_SHARE = 2 / 3;
6
+ /** The largest misses listed. */
7
+ export const WORST_LISTED = 10;
8
+ /** The phases a turn falls in. */
9
+ export const PHASES = ['turns-1-4', 'turns-5-10', 'turns-11-up'];
10
+ /** Seat-count bands. */
11
+ export const SEAT_BANDS = ['2', '3-6', '7-16', '17-up'];
12
+ export function phaseOf(turn) {
13
+ return turn <= 4 ? 'turns-1-4' : turn <= 10 ? 'turns-5-10' : 'turns-11-up';
14
+ }
15
+ export function seatBand(seats) {
16
+ if (seats === null || seats < 2)
17
+ return 'unknown';
18
+ return seats === 2 ? '2' : seats <= 6 ? '3-6' : seats <= 16 ? '7-16' : '17-up';
19
+ }
20
+ const r3 = (x) => Math.round(x * 1000) / 1000;
21
+ export function errorView(samples) {
22
+ const n = samples.length;
23
+ if (!n)
24
+ return null;
25
+ const ratios = samples.map((s) => s.ratio).sort((a, b) => a - b);
26
+ const mid = n >> 1;
27
+ const median = n % 2 ? ratios[mid] : (ratios[mid - 1] + ratios[mid]) / 2;
28
+ return {
29
+ n,
30
+ mean: r3(ratios.reduce((s, r) => s + r, 0) / n),
31
+ median: r3(median),
32
+ geoMean: r3(Math.exp(ratios.reduce((s, r) => s + Math.log(Math.max(r, 1e-6)), 0) / n)),
33
+ under: r3(ratios.filter((r) => r < CALIBRATION_LOW).length / n),
34
+ over: r3(ratios.filter((r) => r > CALIBRATION_HIGH).length / n),
35
+ meanError: r3(samples.reduce((s, x) => s + x.error, 0) / n),
36
+ };
37
+ }
38
+ const turnKeys = (turns) => Object.keys(turns)
39
+ .filter((k) => /^\d+$/.test(k))
40
+ .map(Number)
41
+ .sort((a, b) => a - b);
42
+ /** Every scored estimate of every game, in game then turn then opponent order. Pure. */
43
+ export function incomeSamples(games) {
44
+ const out = [];
45
+ games.forEach((g, i) => {
46
+ for (const turn of turnKeys(g.turns)) {
47
+ const e = g.turns[String(turn)];
48
+ const acc = e.accuracy?.estimates;
49
+ if (!acc?.length)
50
+ continue;
51
+ const truths = e.truth?.opponents ?? [];
52
+ const top = truths.length ? Math.max(...truths.map((o) => o.income)) : null;
53
+ const logged = new Map((e.decision?.estimates ?? []).map((x) => [x.player, x]));
54
+ for (const a of [...acc].sort((x, y) => x.player - y.player)) {
55
+ if (a.truth <= 0)
56
+ continue;
57
+ const ratio = a.estimate / a.truth;
58
+ out.push({
59
+ game: i + 1,
60
+ turn,
61
+ format: g.format,
62
+ seats: g.seats,
63
+ phase: phaseOf(turn),
64
+ estimate: a.estimate,
65
+ truth: a.truth,
66
+ ratio: r3(ratio),
67
+ error: a.estimate - a.truth,
68
+ source: a.source ?? 'unknown',
69
+ coverage: a.coverage,
70
+ band: coverageBucket(a.coverage),
71
+ thin: a.thin,
72
+ method: logged.get(a.player)?.method ?? null,
73
+ leader: top !== null && a.truth >= top,
74
+ stages: logged.get(a.player)?.stages ?? null,
75
+ });
76
+ }
77
+ }
78
+ });
79
+ return out;
80
+ }
81
+ /**
82
+ * Per game and opponent, a turn whose true income is at least {@link JUMP_FACTOR} × the turn before (both
83
+ * read, the earlier above 0) is a jump; its lag is the turns from it to the first logged estimate of that
84
+ * opponent at or after it that reaches {@link CATCH_UP_SHARE} of that turn's truth. Pure.
85
+ */
86
+ export function catchUp(games) {
87
+ const lagsList = [];
88
+ let censored = 0;
89
+ for (const g of games) {
90
+ const turns = turnKeys(g.turns);
91
+ const truth = new Map(); // player → turn → income
92
+ const est = new Map(); // player → turn → estimate
93
+ for (const t of turns) {
94
+ const e = g.turns[String(t)];
95
+ for (const o of e.truth?.opponents ?? [])
96
+ (truth.get(o.player) ?? truth.set(o.player, new Map()).get(o.player)).set(t, o.income);
97
+ for (const a of e.accuracy?.estimates ?? [])
98
+ (est.get(a.player) ?? est.set(a.player, new Map()).get(a.player)).set(t, a.estimate);
99
+ }
100
+ for (const [player, series] of [...truth].sort((a, b) => a[0] - b[0])) {
101
+ const estimates = est.get(player);
102
+ if (!estimates?.size)
103
+ continue;
104
+ const last = Math.max(...estimates.keys());
105
+ for (const [t, income] of [...series].sort((a, b) => a[0] - b[0])) {
106
+ const before = series.get(t - 1);
107
+ if (before === undefined || before <= 0 || income < JUMP_FACTOR * before || t > last)
108
+ continue;
109
+ let lag = null;
110
+ for (const u of [...estimates.keys()].filter((u) => u >= t).sort((a, b) => a - b)) {
111
+ const truthU = series.get(u) ?? income;
112
+ if (estimates.get(u) >= CATCH_UP_SHARE * truthU) {
113
+ lag = u - t;
114
+ break;
115
+ }
116
+ }
117
+ if (lag === null)
118
+ censored++;
119
+ else
120
+ lagsList.push(lag);
121
+ }
122
+ }
123
+ }
124
+ const sorted = [...lagsList].sort((a, b) => a - b);
125
+ const n = sorted.length;
126
+ const lags = {};
127
+ for (const l of sorted)
128
+ lags[String(l)] = (lags[String(l)] ?? 0) + 1;
129
+ return {
130
+ jumps: n + censored,
131
+ caught: n,
132
+ meanLag: n ? r3(sorted.reduce((s, x) => s + x, 0) / n) : null,
133
+ medianLag: n ? (n % 2 ? sorted[n >> 1] : (sorted[(n >> 1) - 1] + sorted[n >> 1]) / 2) : null,
134
+ lags,
135
+ censored,
136
+ };
137
+ }
138
+ export function consequences(games) {
139
+ const c = { turns: 0, underTurns: 0, underWithLoss: 0, otherTurns: 0, otherWithLoss: 0 };
140
+ for (const g of games)
141
+ for (const t of turnKeys(g.turns)) {
142
+ const e = g.turns[String(t)];
143
+ const acc = e.accuracy?.estimates;
144
+ if (!acc?.length || !e.next || !e.decision)
145
+ continue;
146
+ const conceded = new Set(e.decision.conceded ?? []);
147
+ const loss = e.next.lost.some((id) => !conceded.has(id));
148
+ const under = acc.some((a) => a.ratio !== null && a.ratio < CALIBRATION_LOW);
149
+ c.turns++;
150
+ if (under) {
151
+ c.underTurns++;
152
+ if (loss)
153
+ c.underWithLoss++;
154
+ }
155
+ else {
156
+ c.otherTurns++;
157
+ if (loss)
158
+ c.otherWithLoss++;
159
+ }
160
+ }
161
+ return c;
162
+ }
163
+ /** #568: the stages scored, in pipeline order (`card` is armies on top of an income, not scored alone). */
164
+ export const STAGES = ['visible', 'observed', 'tracked', 'prior', 'stated', 'blend', 'thin', 'known'];
165
+ /**
166
+ * #568: each stage's figure ÷ the truth, over the samples that logged it and where the stage applied (a figure
167
+ * above 0; the truth is the income, card armies apart, so the card is left out). Pure.
168
+ */
169
+ export function stageErrors(samples) {
170
+ const out = {};
171
+ for (const stage of STAGES) {
172
+ const rows = samples.flatMap((s) => {
173
+ const v = s.stages?.[stage];
174
+ return typeof v === 'number' && v > 0 ? [{ ratio: r3(v / s.truth), error: v - s.truth }] : [];
175
+ });
176
+ const view = errorView(rows);
177
+ if (view)
178
+ out[stage] = view;
179
+ }
180
+ return out;
181
+ }
182
+ /** #568: the dampings the what-if tries (0: no correction; 1: the full band factor). */
183
+ export const WHAT_IF_DAMPINGS = [0, 0.25, 0.5, 0.75, 1];
184
+ /** #568: a band's factor counts only from this many samples of the other games. */
185
+ export const WHAT_IF_MIN_SAMPLES = 5;
186
+ /**
187
+ * #568: what dividing the tracked figure by its coverage band's geometric mean of tracked ÷ truth, to each
188
+ * damping in {@link WHAT_IF_DAMPINGS}, would have read. Leave one game out: a game's samples are corrected by
189
+ * the bands of the other games only (at least {@link WHAT_IF_MIN_SAMPLES} samples, a band under 1×), so a game
190
+ * never calibrates itself. Only ever raises, as the draft rule does. The tracked stage alone, not the whole
191
+ * pipeline (the prior, its blend and thin evidence would move with it). Pure.
192
+ */
193
+ export function trackedWhatIf(samples) {
194
+ const rows = samples.flatMap((s) => (typeof s.stages?.tracked === 'number' && s.stages.tracked > 0 ? [{ s, tracked: s.stages.tracked }] : []));
195
+ const sums = new Map();
196
+ const key = (game, band) => `${game}|${band}`;
197
+ for (const { s, tracked } of rows) {
198
+ const k = key(s.game, s.band);
199
+ const v = sums.get(k) ?? { n: 0, log: 0 };
200
+ v.n++;
201
+ v.log += Math.log(tracked / s.truth);
202
+ sums.set(k, v);
203
+ }
204
+ const bandTotals = new Map();
205
+ for (const [k, v] of sums) {
206
+ const band = k.slice(k.indexOf('|') + 1);
207
+ const t = bandTotals.get(band) ?? { n: 0, log: 0 };
208
+ bandTotals.set(band, { n: t.n + v.n, log: t.log + v.log });
209
+ }
210
+ const factorFor = (game, band) => {
211
+ const all = bandTotals.get(band);
212
+ const own = sums.get(key(game, band)) ?? { n: 0, log: 0 };
213
+ const n = (all?.n ?? 0) - own.n;
214
+ if (n < WHAT_IF_MIN_SAMPLES)
215
+ return undefined;
216
+ const g = Math.exp(((all?.log ?? 0) - own.log) / n);
217
+ return g < 1 ? g : undefined;
218
+ };
219
+ return WHAT_IF_DAMPINGS.map((damping) => {
220
+ let raised = 0;
221
+ const scored = rows.map(({ s, tracked }) => {
222
+ const g = factorFor(s.game, s.band);
223
+ const v = g === undefined ? tracked : Math.max(tracked, Math.round(tracked / g ** damping));
224
+ if (v > tracked)
225
+ raised++;
226
+ return { band: s.band, ratio: r3(v / s.truth), error: v - s.truth };
227
+ });
228
+ const byBand = {};
229
+ for (const band of COVERAGE_BUCKETS) {
230
+ const view = errorView(scored.filter((x) => x.band === band));
231
+ if (view)
232
+ byBand[band] = view;
233
+ }
234
+ return { damping, error: errorView(scored), raised, byBand };
235
+ });
236
+ }
237
+ function groupBy(samples, key, order) {
238
+ const groups = new Map();
239
+ for (const s of samples) {
240
+ const k = key(s);
241
+ (groups.get(k) ?? groups.set(k, []).get(k)).push(s);
242
+ }
243
+ const keys = order ? order.filter((k) => groups.has(k)) : [...groups.keys()].sort();
244
+ const out = {};
245
+ for (const k of keys)
246
+ out[k] = errorView(groups.get(k));
247
+ return out;
248
+ }
249
+ /** The report over `games` (each finished game's log, in a stable order). Pure. */
250
+ export function incomeCalibration(games) {
251
+ const samples = incomeSamples(games);
252
+ const byPhaseAndCoverage = {};
253
+ for (const p of PHASES) {
254
+ const of = samples.filter((s) => s.phase === p);
255
+ if (of.length)
256
+ byPhaseAndCoverage[p] = groupBy(of, (s) => s.band, COVERAGE_BUCKETS);
257
+ }
258
+ const worst = [...samples]
259
+ .sort((a, b) => Math.abs(Math.log(Math.max(b.ratio, 1e-6))) - Math.abs(Math.log(Math.max(a.ratio, 1e-6))) || a.game - b.game || a.turn - b.turn)
260
+ .slice(0, WORST_LISTED);
261
+ return {
262
+ games: games.filter((g) => turnKeys(g.turns).some((t) => g.turns[String(t)].accuracy?.estimates.length)).length,
263
+ samples: samples.length,
264
+ all: errorView(samples),
265
+ byFormat: groupBy(samples, (s) => s.format),
266
+ bySeats: groupBy(samples, (s) => seatBand(s.seats), [...SEAT_BANDS, 'unknown']),
267
+ byPhase: groupBy(samples, (s) => s.phase, PHASES),
268
+ byCoverage: groupBy(samples, (s) => s.band, COVERAGE_BUCKETS),
269
+ bySource: groupBy(samples, (s) => s.source),
270
+ byThin: groupBy(samples, (s) => (s.thin ? 'thin' : 'solid')),
271
+ byMethod: groupBy(samples, (s) => s.method ?? 'unlogged'),
272
+ byLeader: groupBy(samples, (s) => (s.leader ? 'leader' : 'trailer')),
273
+ byPhaseAndCoverage,
274
+ catchUp: catchUp(games),
275
+ consequences: consequences(games),
276
+ worst,
277
+ byStage: stageErrors(samples),
278
+ trackedWhatIf: trackedWhatIf(samples),
279
+ };
280
+ }