@chrischall/warapp-mcp 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +99 -6
  4. package/dist/analysis/accept-surrender.js +20 -2
  5. package/dist/analysis/calibrate.js +1 -0
  6. package/dist/analysis/card-support.js +175 -16
  7. package/dist/analysis/card-threats.js +68 -3
  8. package/dist/analysis/chat-advice.js +182 -0
  9. package/dist/analysis/chat-blocks.js +106 -0
  10. package/dist/analysis/chat-intent.js +559 -0
  11. package/dist/analysis/chat-read.js +159 -0
  12. package/dist/analysis/decision-replay.js +279 -0
  13. package/dist/analysis/decision-truth.js +146 -0
  14. package/dist/analysis/finished-game.js +62 -3
  15. package/dist/analysis/game-lessons.js +12 -6
  16. package/dist/analysis/opponent-profile.js +46 -3
  17. package/dist/analysis/opponents.js +245 -19
  18. package/dist/analysis/outlook.js +323 -17
  19. package/dist/analysis/plan/after-leftover.js +4 -1
  20. package/dist/analysis/plan/captures.js +4 -3
  21. package/dist/analysis/plan/estimates.js +70 -6
  22. package/dist/analysis/plan/guard-off.js +2 -1
  23. package/dist/analysis/plan/holds.js +79 -6
  24. package/dist/analysis/plan/leftover.js +145 -5
  25. package/dist/analysis/plan/relations.js +115 -2
  26. package/dist/analysis/plan/shared.js +201 -11
  27. package/dist/analysis/plan/stand-still.js +2 -2
  28. package/dist/analysis/plan/stockpile.js +104 -0
  29. package/dist/analysis/plan/strike.js +34 -7
  30. package/dist/analysis/plan/targets.js +168 -53
  31. package/dist/analysis/plan/threats.js +108 -5
  32. package/dist/analysis/plan/transfers.js +11 -0
  33. package/dist/analysis/plan/two-move.js +70 -0
  34. package/dist/analysis/plan/vacated.js +124 -2
  35. package/dist/analysis/planner.js +302 -42
  36. package/dist/analysis/since-last.js +18 -5
  37. package/dist/board.js +36 -2
  38. package/dist/build-id.js +106 -0
  39. package/dist/bundle.js +14943 -10146
  40. package/dist/chat-automation.js +22 -0
  41. package/dist/client.js +14 -0
  42. package/dist/decision-log.js +1093 -0
  43. package/dist/finished-store.js +5 -1
  44. package/dist/lessons-store.js +322 -21
  45. package/dist/open-games.js +36 -16
  46. package/dist/outlook-log.js +42 -1
  47. package/dist/protocol/methods.js +4 -2
  48. package/dist/review-export.js +198 -0
  49. package/dist/state-bundle.js +62 -3
  50. package/dist/state-cli.js +5 -3
  51. package/dist/strategy/notes.js +56 -0
  52. package/dist/tools/accept-surrender.js +23 -9
  53. package/dist/tools/award.js +5 -1
  54. package/dist/tools/card-advice.js +77 -23
  55. package/dist/tools/card-support-advice.js +36 -7
  56. package/dist/tools/chat-advice.js +330 -0
  57. package/dist/tools/chat-inbox.js +15 -4
  58. package/dist/tools/chat.js +41 -11
  59. package/dist/tools/check-plan.js +14 -2
  60. package/dist/tools/decision-capture.js +459 -0
  61. package/dist/tools/end-of-game.js +146 -18
  62. package/dist/tools/game-kind.js +92 -0
  63. package/dist/tools/how-lost.js +7 -2
  64. package/dist/tools/index.js +3 -0
  65. package/dist/tools/join-game.js +10 -4
  66. package/dist/tools/live-context.js +6 -0
  67. package/dist/tools/live.js +10 -1
  68. package/dist/tools/map-curves.js +73 -0
  69. package/dist/tools/notifications.js +4 -3
  70. package/dist/tools/opponents.js +2 -0
  71. package/dist/tools/past-games.js +74 -8
  72. package/dist/tools/picks.js +49 -10
  73. package/dist/tools/profile-hook.js +62 -3
  74. package/dist/tools/profile-opponents.js +2 -0
  75. package/dist/tools/push.js +2 -2
  76. package/dist/tools/relations.js +2 -0
  77. package/dist/tools/scout.js +16 -2
  78. package/dist/tools/state.js +6 -1
  79. package/dist/tools/strategy.js +3 -3
  80. package/dist/tools/stress-opponents.js +2 -0
  81. package/dist/tools/surrender-pending.js +10 -1
  82. package/dist/tools/surrender.js +18 -3
  83. package/dist/tools/turn.js +313 -18
  84. package/dist/tools/where.js +3 -1
  85. package/dist/version.js +1 -1
  86. package/manifest.json +23 -2
  87. package/mint.yaml +23 -0
  88. package/package.json +1 -1
  89. package/server.json +20 -2
  90. package/skills/warapp-mcp/SKILL.md +42 -8
@@ -0,0 +1,159 @@
1
+ // #415 task 3: another player's chat message read for the views — its intent, and for an unread one the advice.
2
+ //
3
+ // `readChatMessage` puts the classifier (chat-intent.ts) and the stance (chat-advice.ts) together for one message,
4
+ // from what a tool can read cheaply: the game's seats (who is a teammate, who is out, the format), my standing as the
5
+ // caller read it (this turn's plan, or the outlook log of the last turn planned; absent → `unknown`, said in the
6
+ // reasons), and the truces of the agreement ledger (`chatTruces`). The label and the advice are hints, not the judge:
7
+ // the views carry the message itself beside them, as other players' text. Nothing here sends, marks or writes
8
+ // anything. Pure and deterministic; never throws.
9
+ import { carriesTeam, isTeamGame } from '../teams.js';
10
+ import { adviseReply } from './chat-advice.js';
11
+ import { classifyMessage } from './chat-intent.js';
12
+ import { agreementState } from './relations.js';
13
+ /** What the reasons say when no standing could be read. */
14
+ export const NO_STANDING_REASON = 'My standing is unknown here (no plan of this game is logged): the stance is worked out with standing `unknown`.';
15
+ /** What the reasons say with the automation gate off. */
16
+ export const AUTOMATION_OFF_REASON = 'Automated chat is off (WARAPP_CHAT_AUTOMATION): the owner sends any reply; nothing here is sent.';
17
+ /** What the reasons say with the gate on and a `send` block. */
18
+ const AUTOMATION_ON_REASON = 'Automated chat is on (WARAPP_CHAT_AUTOMATION): `send` holds the warapp_send_chat arguments for the draft, still to be confirmed (every send is confirm-gated).';
19
+ /**
20
+ * Where a reply to a message goes: the sender privately, my team, or the whole game; null when the channel it came
21
+ * on is unknown (a public reply could carry a private answer to everyone).
22
+ */
23
+ function replyRoute(channel, senderId) {
24
+ if (channel === 'private')
25
+ return { to: senderId };
26
+ if (channel === 'team')
27
+ return { channel: 'team' };
28
+ if (channel === 'public')
29
+ return {};
30
+ return null;
31
+ }
32
+ /** States of a player out of the game. */
33
+ const OUT = new Set(['Eliminated', 'SurrenderAccepted', 'Booted', 'EndedByVote', 'Declined', 'RemovedByHost']);
34
+ const playing = (p) => (p.state ?? 'Playing') === 'Playing';
35
+ /** The game's format from its seats: teams, a 1v1 (one opponent still playing), else a free-for-all. */
36
+ export function chatFormat(players, meId) {
37
+ try {
38
+ if (!Array.isArray(players) || !players.length)
39
+ return 'unknown';
40
+ if (isTeamGame(players))
41
+ return 'teams';
42
+ const opponents = players.filter((p) => p.id !== meId && playing(p)).length - (meId === undefined ? 1 : 0);
43
+ return opponents <= 1 ? '1v1' : 'ffa';
44
+ }
45
+ catch {
46
+ return 'unknown';
47
+ }
48
+ }
49
+ const TRUCE_RANK = { active: 3, 'in-notice': 2, proposed: 1 };
50
+ /**
51
+ * Each partner's truce from the agreement ledger: `active`, `in-notice`, or `proposed` (one I proposed, unanswered);
52
+ * the strongest when there are several. A Diplomacy card's (enforced) is no promise, and an agreement over is none.
53
+ * With the turn unknown, read from the status alone. Never throws.
54
+ */
55
+ export function chatTruces(agreements, turn, players) {
56
+ const out = new Map();
57
+ if (!Array.isArray(agreements))
58
+ return out;
59
+ for (const a of agreements) {
60
+ try {
61
+ if (!a || typeof a !== 'object' || a.enforced === true || typeof a.with !== 'number')
62
+ continue;
63
+ let truce = null;
64
+ if (turn !== null) {
65
+ const st = agreementState(a, turn, players);
66
+ if (st.phase === 'active')
67
+ truce = 'active';
68
+ else if (st.phase === 'notice')
69
+ truce = 'in-notice';
70
+ else if (st.phase === 'proposed' && a.status === 'proposed-by-me')
71
+ truce = 'proposed';
72
+ }
73
+ else if (a.status === 'agreed')
74
+ truce = 'active';
75
+ else if (a.status === 'notice-by-me' || a.status === 'notice-by-them')
76
+ truce = 'in-notice';
77
+ else if (a.status === 'proposed-by-me')
78
+ truce = 'proposed';
79
+ if (!truce)
80
+ continue;
81
+ const was = out.get(a.with);
82
+ if (!was || TRUCE_RANK[truce] > TRUCE_RANK[was])
83
+ out.set(a.with, truce);
84
+ }
85
+ catch {
86
+ // Skip what cannot be read.
87
+ }
88
+ }
89
+ return out;
90
+ }
91
+ const STANDING_INTENTS = new Set(['income-check', 'position-check']);
92
+ /** Label one message and, with `advise`, say how to answer it. Never throws. */
93
+ export function readChatMessage(msg, ctx, opts) {
94
+ try {
95
+ const c = ctx && typeof ctx === 'object' ? ctx : { players: [] };
96
+ const players = Array.isArray(c.players) ? c.players : [];
97
+ const seats = players.map((p) => ({ id: p.id, name: p.name, isMe: p.id === c.meId, team: p.team ?? null }));
98
+ const classified = classifyMessage(typeof msg?.text === 'string' ? msg.text : '', {
99
+ players: seats,
100
+ ...(c.territories ? { territories: c.territories } : {}),
101
+ ...(c.bonuses ? { bonuses: c.bonuses } : {}),
102
+ ...(msg?.myRecent ? { myRecentMessages: msg.myRecent } : {}),
103
+ ...(msg?.toMe ? { toMe: true } : {}),
104
+ });
105
+ const intent = { intents: classified.intents, confidence: classified.confidence };
106
+ if (!opts?.advise || typeof msg?.senderId !== 'number')
107
+ return { intent };
108
+ const senderId = msg.senderId;
109
+ const sender = players.find((p) => p.id === senderId);
110
+ const me = players.find((p) => p.id === c.meId);
111
+ const s = c.standing ?? null;
112
+ const truce = c.truces?.get(senderId) ?? null;
113
+ const game = {
114
+ format: c.format ?? chatFormat(players, c.meId),
115
+ standing: s?.standing ?? 'unknown',
116
+ ...(s?.iLead !== undefined ? { iLead: s.iLead } : {}),
117
+ ...(s && s.myIncome !== undefined ? { myIncome: s.myIncome } : {}),
118
+ // The leader's name is never put in a draft: it is another player's words.
119
+ ...(s?.strongest ? { strongest: { playerId: s.strongest.playerId, income: s.strongest.income, ...(s.strongest.thin !== undefined ? { thin: s.strongest.thin } : {}) } } : {}),
120
+ ...(s && s.leaderId !== undefined ? { leaderId: s.leaderId } : {}),
121
+ ...(c.meId !== undefined ? { meId: c.meId } : {}),
122
+ sender: {
123
+ id: senderId,
124
+ ...(s?.leaderId != null && s.leaderId === senderId ? { isLeader: true } : {}),
125
+ ...(me && sender && carriesTeam(me.team) && sender.team === me.team ? { teammate: true } : {}),
126
+ ...(sender && OUT.has(sender.state ?? 'Playing') ? { out: true } : {}),
127
+ truce,
128
+ },
129
+ channel: msg.channel,
130
+ };
131
+ const automation = c.automation === 'on' ? 'on' : 'off';
132
+ const advice = { ...adviseReply(classified, game), automation };
133
+ if (!s)
134
+ advice.reasons.push(NO_STANDING_REASON);
135
+ else if (classified.intents.some((i) => STANDING_INTENTS.has(i)))
136
+ advice.reasons.push(`My standing as read from ${s.basis}.`);
137
+ if (automation === 'off')
138
+ advice.reasons.push(AUTOMATION_OFF_REASON);
139
+ else if (advice.draft !== undefined) {
140
+ const route = replyRoute(msg.channel, senderId);
141
+ if (route === null)
142
+ advice.reasons.push('The channel this message came on is unknown, so no `send` is offered: the owner picks where a reply goes.');
143
+ else if (typeof c.gameId !== 'number')
144
+ advice.reasons.push('The game is unknown here, so no `send` is offered.');
145
+ else {
146
+ advice.send = { game_id: c.gameId, message: advice.draft, ...route, automated: true };
147
+ advice.reasons.push(AUTOMATION_ON_REASON);
148
+ }
149
+ }
150
+ return { intent, advice };
151
+ }
152
+ catch {
153
+ return { intent: { intents: [], confidence: 'low' } };
154
+ }
155
+ }
156
+ /** The compact view of an advice: the stance and its first reason. */
157
+ export function compactAdvice(a) {
158
+ return { stance: a.stance, ...(a.reasons[0] !== undefined ? { reason: a.reasons[0] } : {}) };
159
+ }
@@ -0,0 +1,279 @@
1
+ import { boardAt, decodeInput, interestingTurns } from '../decision-log.js';
2
+ import { ratioView } from './decision-truth.js';
3
+ import { COVERAGE_BUCKETS, coverageBucket } from './game-lessons.js';
4
+ import { buildGraph } from './graph.js';
5
+ import { applyBonusOverrides } from './overrides.js';
6
+ import { alliesOf, planEnemyEstimates } from './plan/estimates.js';
7
+ import { planningInput, planTurn } from './planner.js';
8
+ const sameJson = (a, b) => JSON.stringify(a) === JSON.stringify(b);
9
+ const deploysOf = (ds) => ds.map((d) => [d.territoryId, d.armies]);
10
+ const movesOf = (ms) => ms.map((m) => [m.from, m.to, m.armies, m.kind ?? null, !!m.commander]);
11
+ /** `input` under `scenario`; the same object without one. Pure: `input` is not changed. */
12
+ export function applyScenario(input, scenario) {
13
+ if (!scenario)
14
+ return input;
15
+ const options = {
16
+ ...input.options,
17
+ ...scenario.options,
18
+ ...(scenario.goal !== undefined ? { goal: scenario.goal } : {}),
19
+ ...(scenario.enemyDeploy !== undefined ? { enemyDeploy: scenario.enemyDeploy } : {}),
20
+ };
21
+ const known = new Map((input.knownIncome ?? []).map((k) => [k.player, k]));
22
+ for (const k of scenario.estimates ?? [])
23
+ known.set(k.player, { player: k.player, income: k.income });
24
+ return {
25
+ ...input,
26
+ options,
27
+ ...(scenario.settings ? { settings: { ...input.settings, ...scenario.settings } } : {}),
28
+ ...(known.size ? { knownIncome: [...known.values()] } : {}),
29
+ };
30
+ }
31
+ /**
32
+ * The opponents' deploy estimates `input` gives, as the planner reads them (static seats out, card
33
+ * armies out of my income, a known income in place of an estimate); under `options.enemyDeploy` every
34
+ * opponent is sized at that figure, so that is its estimate (`source: 'scenario'`).
35
+ */
36
+ export function estimatesOf(input) {
37
+ const pi = planningInput(input);
38
+ const ctx = pi.game ?? {};
39
+ const capCut = pi.incomeCap ? Math.max(0, Math.floor(pi.incomeCap.uncapped - pi.incomeCap.received)) : 0;
40
+ const allies = alliesOf(pi.me, ctx.players);
41
+ const enemyDeploy = pi.options?.enemyDeploy;
42
+ const { estimates } = planEnemyEstimates({
43
+ graph: pi.graph,
44
+ board: pi.board,
45
+ me: pi.me,
46
+ income: Math.max(0, Math.floor(pi.income)) + capCut - Math.max(0, Math.floor(pi.cardArmies ?? 0)),
47
+ ...(pi.settings ? { settings: pi.settings } : {}),
48
+ ...(pi.previousBoard ? { previousBoard: pi.previousBoard } : {}),
49
+ ...(pi.previousOrders ? { previousOrders: pi.previousOrders } : {}),
50
+ ...(pi.tracks ? { tracks: pi.tracks } : {}),
51
+ game: ctx,
52
+ turn: pi.turn ?? ctx.turn ?? null,
53
+ ...(pi.sanctions?.length ? { sanctions: pi.sanctions } : {}),
54
+ ...(pi.knownIncome?.length && enemyDeploy === undefined ? { known: pi.knownIncome } : {}),
55
+ });
56
+ return estimates
57
+ .filter((e) => e.playerId !== pi.me && !allies.has(e.playerId))
58
+ .sort((a, b) => a.playerId - b.playerId)
59
+ .map((e) => enemyDeploy !== undefined
60
+ ? { player: e.playerId, estimate: enemyDeploy, source: 'scenario', coverage: e.coverage?.share ?? null }
61
+ : { player: e.playerId, estimate: e.estimate, source: e.source, coverage: e.coverage?.share ?? null });
62
+ }
63
+ /** The graph a replay plans on: the stored map with the game's bonus overrides. */
64
+ export function replayGraph(src) {
65
+ return src.map ? buildGraph(applyBonusOverrides(src.map, src.settings)) : undefined;
66
+ }
67
+ function score(decision, next, plan) {
68
+ const expected = decision.expected?.nextIncome;
69
+ const held = new Set([...next.capturesMade, ...next.gained]);
70
+ const missed = new Set(next.capturesMissed);
71
+ const caps = plan?.expected.captures ?? [];
72
+ return {
73
+ incomeHeld: typeof next.income === 'number' && typeof expected === 'number' ? next.income >= expected : null,
74
+ capturesHeld: next.capturesMissed.length === 0,
75
+ eliminated: next.eliminated,
76
+ replayedCaptures: {
77
+ backed: caps.filter((id) => held.has(id)),
78
+ failed: caps.filter((id) => !held.has(id) && missed.has(id)),
79
+ untested: caps.filter((id) => !held.has(id) && !missed.has(id)),
80
+ },
81
+ };
82
+ }
83
+ /** The decided turns of `log`, ascending. */
84
+ const decidedTurns = (log) => Object.entries(log.turns)
85
+ .filter(([k, e]) => /^\d+$/.test(k) && !!e.decision)
86
+ .map(([k, e]) => [Number(k), e])
87
+ .sort((a, b) => a[0] - b[0]);
88
+ /** One logged turn planned again (see {@link replayDecisions}). */
89
+ export function replayTurn(log, turn, graph, scenario) {
90
+ const e = log.turns[String(turn)];
91
+ const d = e.decision;
92
+ const base = { turn, status: 'compared', goal: { logged: d.goal }, nextIncome: { logged: d.expected?.nextIncome } };
93
+ const scoreOnly = (status) => ({ ...base, status, ...(e.next ? { score: score(d, e.next, undefined) } : {}) });
94
+ if (!graph)
95
+ return scoreOnly('no-map');
96
+ if (!e.input)
97
+ return scoreOnly('no-input');
98
+ const board = boardAt(log, turn);
99
+ if (!board)
100
+ return scoreOnly('no-board');
101
+ let input;
102
+ let plan;
103
+ try {
104
+ input = applyScenario(decodeInput(e.input, board, graph), scenario);
105
+ plan = planTurn(input);
106
+ }
107
+ catch {
108
+ return scoreOnly('failed');
109
+ }
110
+ const sameDeploys = sameJson(deploysOf(d.deploys), deploysOf(plan.deploys));
111
+ const sameMoves = sameJson(movesOf(d.moves), movesOf(plan.moves));
112
+ let estimates;
113
+ try {
114
+ estimates = estimatesOf(input);
115
+ }
116
+ catch {
117
+ estimates = undefined;
118
+ }
119
+ return {
120
+ ...base,
121
+ same: sameDeploys && sameMoves,
122
+ sameDeploys,
123
+ sameMoves,
124
+ goal: { logged: d.goal, replayed: plan.goal },
125
+ nextIncome: { logged: d.expected?.nextIncome, replayed: plan.expected.nextIncome },
126
+ ...(e.next ? { score: score(d, e.next, plan) } : {}),
127
+ ...(estimates ? { estimates } : {}),
128
+ };
129
+ }
130
+ /** Every decided turn of `log` planned again on `src`'s map, under `scenario` when given. Pure; never throws. */
131
+ export function replayDecisions(log, src, scenario) {
132
+ let graph;
133
+ try {
134
+ graph = replayGraph(src);
135
+ }
136
+ catch {
137
+ graph = undefined;
138
+ }
139
+ return { gameId: log.gameId, turns: decidedTurns(log).map(([turn]) => replayTurn(log, turn, graph, scenario)) };
140
+ }
141
+ const round = (x) => Math.round(x * 1e4) / 1e4;
142
+ /** The replays summed: ids never appear. */
143
+ export function replayAggregate(games) {
144
+ const out = {
145
+ games: games.length,
146
+ turns: 0,
147
+ compared: 0,
148
+ identical: 0,
149
+ identicalShare: null,
150
+ goalChanged: 0,
151
+ byGoal: {},
152
+ skipped: {},
153
+ expectations: { scored: 0, incomeHeld: 0, capturesHeld: 0 },
154
+ replayedCaptures: { backed: 0, failed: 0, untested: 0 },
155
+ };
156
+ for (const g of games)
157
+ for (const t of g.turns) {
158
+ out.turns++;
159
+ if (t.score) {
160
+ if (t.score.incomeHeld !== null) {
161
+ out.expectations.scored++;
162
+ if (t.score.incomeHeld)
163
+ out.expectations.incomeHeld++;
164
+ if (t.score.capturesHeld)
165
+ out.expectations.capturesHeld++;
166
+ }
167
+ if (t.status === 'compared') {
168
+ out.replayedCaptures.backed += t.score.replayedCaptures.backed.length;
169
+ out.replayedCaptures.failed += t.score.replayedCaptures.failed.length;
170
+ out.replayedCaptures.untested += t.score.replayedCaptures.untested.length;
171
+ }
172
+ }
173
+ if (t.status !== 'compared') {
174
+ out.skipped[t.status] = (out.skipped[t.status] ?? 0) + 1;
175
+ continue;
176
+ }
177
+ out.compared++;
178
+ if (t.same)
179
+ out.identical++;
180
+ if (t.goal.replayed !== t.goal.logged)
181
+ out.goalChanged++;
182
+ const b = (out.byGoal[t.goal.logged] ??= { compared: 0, different: 0 });
183
+ b.compared++;
184
+ if (!t.same)
185
+ b.different++;
186
+ }
187
+ out.identicalShare = out.compared ? round(out.identical / out.compared) : null;
188
+ return out;
189
+ }
190
+ function view(samples) {
191
+ const byCoverage = {};
192
+ for (const b of COVERAGE_BUCKETS) {
193
+ const v = ratioView(samples.filter((s) => coverageBucket(s.coverage) === b).map((s) => s.ratio));
194
+ if (v)
195
+ byCoverage[b] = v;
196
+ }
197
+ const bySource = {};
198
+ for (const src of [...new Set(samples.map((s) => s.source))].sort())
199
+ bySource[src] = ratioView(samples.filter((s) => s.source === src).map((s) => s.ratio));
200
+ return { estimates: ratioView(samples.map((s) => s.ratio)), byCoverage, bySource };
201
+ }
202
+ /**
203
+ * The estimate accuracy over `games` (each log beside its replay): the logged turns' `accuracy` blocks
204
+ * by coverage band and estimate source, outlook right/wrong — and the replayed estimates (under the
205
+ * replay's scenario) against each turn's `truth`. Pure.
206
+ */
207
+ export function accuracyReport(games) {
208
+ const all = [];
209
+ const scen = [];
210
+ const outlook = { right: 0, wrong: 0 };
211
+ const perGame = [];
212
+ let withTruth = 0;
213
+ let replayed = false;
214
+ for (const { log, replay } of games) {
215
+ const mine = [];
216
+ const o = { right: 0, wrong: 0 };
217
+ let truthSeen = false;
218
+ for (const e of Object.values(log.turns)) {
219
+ if (e.truth)
220
+ truthSeen = true;
221
+ const a = e.accuracy;
222
+ if (!a)
223
+ continue;
224
+ for (const x of a.estimates)
225
+ if (x.ratio !== null)
226
+ mine.push({ ratio: x.ratio, coverage: x.coverage, source: x.source ?? 'unknown' });
227
+ if (a.outlook.right === true)
228
+ o.right++;
229
+ if (a.outlook.right === false)
230
+ o.wrong++;
231
+ }
232
+ for (const t of replay?.turns ?? []) {
233
+ const truth = log.turns[String(t.turn)]?.truth;
234
+ if (!t.estimates || !truth)
235
+ continue;
236
+ replayed = true;
237
+ for (const x of t.estimates) {
238
+ const real = truth.opponents.find((p) => p.player === x.player)?.income;
239
+ if (typeof real === 'number' && real > 0)
240
+ scen.push({ ratio: x.estimate / real, coverage: x.coverage, source: x.source });
241
+ }
242
+ }
243
+ if (!truthSeen)
244
+ continue;
245
+ withTruth++;
246
+ all.push(...mine);
247
+ outlook.right += o.right;
248
+ outlook.wrong += o.wrong;
249
+ perGame.push({ ...view(mine), outlook: o });
250
+ }
251
+ return { games: withTruth, logged: { ...view(all), outlook }, perGame, ...(replayed ? { scenario: view(scen) } : {}) };
252
+ }
253
+ /** Each interesting turn of `log` (Task 3's rule, `interestingTurns`) that keeps its input and board, as a fixture. Pure. */
254
+ export function decisionFixtures(log, src) {
255
+ const keep = interestingTurns(log);
256
+ const out = [];
257
+ for (const [turn, e] of decidedTurns(log)) {
258
+ if (!keep.has(turn) || !e.input)
259
+ continue;
260
+ const board = boardAt(log, turn);
261
+ if (!board)
262
+ continue;
263
+ out.push({
264
+ version: 1,
265
+ mapId: src.map?.id ?? src.settings?.mapId,
266
+ turn,
267
+ plannerVersion: e.planner?.version,
268
+ board,
269
+ input: e.input,
270
+ decision: e.decision,
271
+ ...(e.sent ? { sent: e.sent } : {}),
272
+ ...(e.override ? { override: e.override } : {}),
273
+ ...(e.next ? { next: e.next } : {}),
274
+ ...(e.truth ? { truth: e.truth } : {}),
275
+ ...(e.accuracy ? { accuracy: e.accuracy } : {}),
276
+ });
277
+ }
278
+ return JSON.parse(JSON.stringify(out));
279
+ }
@@ -0,0 +1,146 @@
1
+ import { COVERAGE_BUCKETS, CALIBRATION_HIGH, CALIBRATION_LOW, coverageBucket } from './game-lessons.js';
2
+ import { turnIncomes } from './finished-game.js';
3
+ import { gameOutlook, OUTLOOK_TURNS, readingOf } from './outlook.js';
4
+ import { visibleState } from './plan/shared.js';
5
+ const round = (x) => Math.round(x * 1e6) / 1e6;
6
+ const ownerOf = (t) => (t.owner.kind === 'player' ? t.owner.playerId : undefined);
7
+ /** The ratio view of estimate ÷ truth samples (truth > 0); `null` with none. */
8
+ export function ratioView(ratios) {
9
+ if (!ratios.length)
10
+ return null;
11
+ const n = ratios.length;
12
+ return {
13
+ n,
14
+ mean: round(ratios.reduce((s, r) => s + r, 0) / n),
15
+ geoMean: round(Math.exp(ratios.reduce((s, r) => s + Math.log(Math.max(r, 1e-6)), 0) / n)),
16
+ under: round(ratios.filter((r) => r < CALIBRATION_LOW).length / n),
17
+ over: round(ratios.filter((r) => r > CALIBRATION_HIGH).length / n),
18
+ };
19
+ }
20
+ /** The outlook the true figures give on turn T: `gameOutlook` over the history boards up to T − 1, each as the turn played on it. */
21
+ function trueOutlook(input, byBoard, turn) {
22
+ const boards = [];
23
+ // The outlook reads the latest run of consecutive turns; a few more boards than that give the tracker its window.
24
+ for (let b = turn - 1; b >= 0 && boards.length < OUTLOOK_TURNS + 3; b--) {
25
+ const board = byBoard.get(b);
26
+ if (!board)
27
+ break;
28
+ boards.unshift({ turn: b + 1, board });
29
+ }
30
+ if (!boards.length)
31
+ return null;
32
+ try {
33
+ // #454: the finer reading, as the decision log keeps it.
34
+ return readingOf(gameOutlook({
35
+ graph: input.graph,
36
+ me: input.me,
37
+ boards,
38
+ ...(input.plannerSettings ? { settings: input.plannerSettings } : {}),
39
+ ...(input.game ? { game: input.game } : {}),
40
+ }));
41
+ }
42
+ catch {
43
+ return null;
44
+ }
45
+ }
46
+ /**
47
+ * Every turn's truth (turns 1 … the game's last, and any logged turn), every logged turn's accuracy, and
48
+ * the game's summary. A turn whose history board the history lacks is `missing`. Pure.
49
+ */
50
+ export function decisionTruth(input) {
51
+ const byBoard = new Map(input.history.map((b) => [b.turn, b.board]));
52
+ const last = input.numberOfTurns ?? Math.max(0, ...input.history.map((b) => b.turn));
53
+ const turns = new Set();
54
+ for (let t = 1; t <= last; t++)
55
+ turns.add(t);
56
+ for (const t of input.logged.keys())
57
+ if (t >= 1)
58
+ turns.add(t);
59
+ const players = [...new Set(input.opponents)].filter((p) => p !== input.me).sort((a, b) => a - b);
60
+ const truth = new Map();
61
+ const accuracy = new Map();
62
+ const missing = [];
63
+ const samples = [];
64
+ const outlook = { right: 0, wrong: 0 };
65
+ let withHidden = 0;
66
+ for (const turn of [...turns].sort((a, b) => a - b)) {
67
+ const real = byBoard.get(turn - 1);
68
+ if (!real) {
69
+ missing.push(turn);
70
+ continue;
71
+ }
72
+ const logged = input.logged.get(turn);
73
+ const seen = new Map((logged?.board?.territories ?? []).map((t) => [t.territoryId, t]));
74
+ const hiddenOnMine = (id) => !!logged?.board && !visibleState(seen.get(id));
75
+ const incomes = turnIncomes(input.graph, real, [input.me, ...players], input.incomeSettings);
76
+ const mine = incomes.get(input.me);
77
+ const opponents = players.map((p) => {
78
+ const x = incomes.get(p);
79
+ const hidden = real.territories
80
+ .filter((t) => ownerOf(t) === p && t.armies !== null && hiddenOnMine(t.territoryId))
81
+ .map((t) => [t.territoryId, t.armies])
82
+ .sort((a, b) => a[0] - b[0]);
83
+ return {
84
+ player: p,
85
+ income: x.income,
86
+ armies: x.armies,
87
+ ...(x.armiesUnread ? { armiesUnread: x.armiesUnread } : {}),
88
+ ...(x.commanders ? { commanders: x.commanders } : {}),
89
+ territories: x.territories,
90
+ bonuses: x.bonuses,
91
+ hidden,
92
+ };
93
+ });
94
+ const myUnread = mine.armiesUnread ? { armiesUnread: mine.armiesUnread } : {};
95
+ const myCommanders = mine.commanders ? { commanders: mine.commanders } : {};
96
+ truth.set(turn, {
97
+ board: turn - 1,
98
+ mine: { income: mine.income, armies: mine.armies, territories: mine.territories, ...myUnread, ...myCommanders },
99
+ opponents,
100
+ });
101
+ if (!logged)
102
+ continue;
103
+ const myIncome = logged.myIncome ?? mine.income;
104
+ const hiddenStacks = logged.board ? opponents.reduce((s, o) => s + o.hidden.filter(([, a]) => a >= myIncome && a > 0).length, 0) : null;
105
+ if (hiddenStacks)
106
+ withHidden++;
107
+ const estimates = [...logged.estimates]
108
+ .filter((e) => players.includes(e.player))
109
+ .sort((a, b) => a.player - b.player)
110
+ .map((e) => {
111
+ const t = opponents.find((o) => o.player === e.player).income;
112
+ const ratio = t > 0 ? round(e.estimate / t) : null;
113
+ if (ratio !== null)
114
+ samples.push({ turn, opponent: e.player, estimate: e.estimate, truth: t, coverage: e.coverage, source: e.source ?? null });
115
+ return { player: e.player, estimate: e.estimate, truth: t, ratio, source: e.source ?? null, coverage: e.coverage, thin: e.thin };
116
+ });
117
+ const trueState = logged.outlook !== null ? trueOutlook(input, byBoard, turn) : null;
118
+ const right = logged.outlook !== null && trueState !== null ? logged.outlook === trueState : null;
119
+ if (right === true)
120
+ outlook.right++;
121
+ if (right === false)
122
+ outlook.wrong++;
123
+ accuracy.set(turn, { estimates, outlook: { logged: logged.outlook, truth: trueState, right }, myIncome, hiddenStacks });
124
+ }
125
+ const ratios = (xs) => xs.map((s) => s.estimate / s.truth);
126
+ const byCoverage = {};
127
+ for (const b of COVERAGE_BUCKETS) {
128
+ const v = ratioView(ratios(samples.filter((s) => coverageBucket(s.coverage) === b)));
129
+ if (v)
130
+ byCoverage[b] = v;
131
+ }
132
+ const bySource = {};
133
+ for (const src of [...new Set(samples.map((s) => s.source ?? 'unknown'))].sort()) {
134
+ bySource[src] = ratioView(ratios(samples.filter((s) => (s.source ?? 'unknown') === src)));
135
+ }
136
+ return {
137
+ truth,
138
+ accuracy,
139
+ summary: { estimates: ratioView(ratios(samples)), byCoverage, bySource, outlook, turns: truth.size, turnsWithHiddenStacks: withHidden },
140
+ missing,
141
+ };
142
+ }
143
+ /** Whether a turn's accuracy shows an estimate off by more than 1.5× or under 0.5× (#412 compaction's rule). */
144
+ export function estimateOff(a) {
145
+ return !!a?.estimates.some((e) => e.ratio !== null && (e.ratio > CALIBRATION_HIGH || e.ratio < CALIBRATION_LOW));
146
+ }