@chrischall/warapp-mcp 0.1.0 → 0.2.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.
- package/.claude-plugin/marketplace.json +3 -3
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +28 -17
- package/dist/analysis/accept-surrender.js +56 -0
- package/dist/analysis/calibrate.js +239 -0
- package/dist/analysis/finished-game.js +136 -0
- package/dist/analysis/game-lessons.js +217 -0
- package/dist/analysis/local-deploy.js +37 -17
- package/dist/analysis/opponent-profile.js +6 -5
- package/dist/analysis/opponents.js +10 -2
- package/dist/analysis/outlook.js +63 -1
- package/dist/analysis/plan/shared.js +194 -7
- package/dist/analysis/plan/threats.js +103 -29
- package/dist/analysis/planner.js +10 -5
- package/dist/analysis/stress.js +14 -7
- package/dist/analysis/whereabouts.js +3 -0
- package/dist/bundle.js +12392 -9245
- package/dist/calibration-source.js +75 -0
- package/dist/chat.js +73 -0
- package/dist/client.js +85 -7
- package/dist/finished-store.js +357 -0
- package/dist/index.js +1 -1
- package/dist/lessons-store.js +356 -0
- package/dist/live.js +9 -0
- package/dist/map-details.js +127 -0
- package/dist/map-stats.js +14 -6
- package/dist/map-store.js +44 -6
- package/dist/my-games.js +44 -6
- package/dist/normalize.js +34 -2
- package/dist/notifications.js +143 -0
- package/dist/outlook-log.js +28 -1
- package/dist/player-record-store.js +2 -0
- package/dist/profile-store.js +61 -11
- package/dist/protocol/methods.js +86 -2
- package/dist/replay.js +16 -4
- package/dist/stats.js +26 -4
- package/dist/strategy/notes.js +64 -9
- package/dist/surrender-pending.js +126 -0
- package/dist/tools/accept-surrender.js +311 -0
- package/dist/tools/chat-inbox.js +17 -5
- package/dist/tools/chat-read-mark.js +179 -0
- package/dist/tools/chat.js +50 -8
- package/dist/tools/check-plan.js +1 -0
- package/dist/tools/commander-check.js +1 -0
- package/dist/tools/end-of-game.js +384 -0
- package/dist/tools/game.js +31 -6
- package/dist/tools/index.js +15 -5
- package/dist/tools/live-context.js +1 -1
- package/dist/tools/map-details.js +88 -0
- package/dist/tools/map-stats.js +15 -2
- package/dist/tools/map.js +10 -2
- package/dist/tools/my-games.js +77 -7
- package/dist/tools/notifications.js +484 -0
- package/dist/tools/opponents.js +14 -2
- package/dist/tools/past-games.js +94 -0
- package/dist/tools/picks.js +15 -2
- package/dist/tools/profile-opponents.js +1 -1
- package/dist/tools/profile-reads.js +3 -3
- package/dist/tools/push.js +72 -12
- package/dist/tools/strategy.js +65 -8
- package/dist/tools/stress-opponents.js +1 -1
- package/dist/tools/surrender-pending.js +74 -0
- package/dist/tools/surrender.js +10 -3
- package/dist/tools/team.js +1 -5
- package/dist/tools/turn.js +79 -15
- package/dist/tools/where.js +42 -17
- package/dist/tools/write-kit.js +6 -0
- package/dist/trend.js +145 -20
- package/dist/version.js +1 -1
- package/manifest.json +22 -2
- package/mint.yaml +14 -9
- package/package.json +1 -1
- package/server.json +2 -2
- package/skills/warapp-mcp/SKILL.md +141 -14
|
@@ -0,0 +1,356 @@
|
|
|
1
|
+
// What finished games teach, kept across games (#312 E2; owner decisions P2–P4 of 2026-11-16), name-free:
|
|
2
|
+
//
|
|
3
|
+
// - `<dataDir>/maps-record/<mapId>.json` (version 1), one per map I finished a game on: the games
|
|
4
|
+
// kept and their outcomes, and per game (at most `MAX_MAP_ENTRIES`, the oldest dropped first, its
|
|
5
|
+
// counts kept) the format, seats, my result, my start region (territories and the bonuses they
|
|
6
|
+
// touch) and income curve, and each winner's start region and income after turns 4 and 8 (the pace
|
|
7
|
+
// to beat). At most `MAX_MAP_RECORDS` maps, the least recently written dropped first.
|
|
8
|
+
// - `<dataDir>/lessons.json` (version 1): per format the games, outcomes, how each lost game was lost
|
|
9
|
+
// (a cause, never who), the turn my income first went flat, and the tracker's estimates scored
|
|
10
|
+
// against the true incomes by frontier coverage (#294): aggregates only — a game's entry (at most
|
|
11
|
+
// `MAX_LESSON_ENTRIES`) holds the same counts for that game alone, so processing it again replaces
|
|
12
|
+
// its share, never adds it twice; a dropped entry's counts stay in the totals.
|
|
13
|
+
//
|
|
14
|
+
// Every game is keyed by `finishedGameKey` (an HMAC of my account and the game under the one shared
|
|
15
|
+
// salt): no game or player id, no name, no clock. Territory, bonus and map ids are the map's own,
|
|
16
|
+
// public data. 0600 files in 0700 folders, atomic writes under the in-process path lock; a file that
|
|
17
|
+
// exists but does not parse (not JSON, not an object, another version, a malformed total) is never
|
|
18
|
+
// overwritten (`failed`). Off with `WARAPP_PLAYER_PROFILE=off` (the end-of-game pass does not run).
|
|
19
|
+
// Profiles and lessons INFORM ONLY (P1): no planner decision reads any of this.
|
|
20
|
+
import { readdir, readFile, stat, unlink } from 'node:fs/promises';
|
|
21
|
+
import { join } from 'node:path';
|
|
22
|
+
import { addCalibration, COVERAGE_BUCKETS, } from './analysis/game-lessons.js';
|
|
23
|
+
import { PROFILE_FORMATS } from './analysis/opponent-profile.js';
|
|
24
|
+
import { writeJsonAtomic } from './map-store.js';
|
|
25
|
+
import { withPathLock } from './path-lock.js';
|
|
26
|
+
export const MAX_MAP_ENTRIES = 50;
|
|
27
|
+
export const MAX_MAP_RECORDS = 200;
|
|
28
|
+
export const MAX_LESSON_ENTRIES = 500;
|
|
29
|
+
export const mapRecordDir = (dir) => join(dir, 'maps-record');
|
|
30
|
+
export const mapRecordPath = (dir, mapId) => join(mapRecordDir(dir), `${mapId}.json`);
|
|
31
|
+
export const lessonsPath = (dir) => join(dir, 'lessons.json');
|
|
32
|
+
const isRec = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
33
|
+
const isInt = (v) => typeof v === 'number' && Number.isInteger(v);
|
|
34
|
+
const num = (v) => typeof v === 'number' && Number.isFinite(v);
|
|
35
|
+
const ints = (v) => Array.isArray(v) && v.every(isInt);
|
|
36
|
+
const intOrNull = (v) => v === null || isInt(v);
|
|
37
|
+
const HASH = /^[0-9a-f]{32}$/;
|
|
38
|
+
const isFormat = (v) => PROFILE_FORMATS.includes(v);
|
|
39
|
+
const RESULTS = ['won', 'lost', 'surrendered', 'eliminated', 'booted', 'ended-by-vote', 'unknown'];
|
|
40
|
+
const isResult = (v) => RESULTS.includes(v);
|
|
41
|
+
const CAUSES = ['commander', 'last-territories', 'unknown', 'surrendered', 'booted', 'still-holding'];
|
|
42
|
+
/** Read a store: `missing`, the parsed object, or `unreadable` (exists, not JSON or not an object). */
|
|
43
|
+
async function readStore(path) {
|
|
44
|
+
let text;
|
|
45
|
+
try {
|
|
46
|
+
text = await readFile(path, 'utf8');
|
|
47
|
+
}
|
|
48
|
+
catch (e) {
|
|
49
|
+
return e.code === 'ENOENT' ? 'missing' : 'unreadable';
|
|
50
|
+
}
|
|
51
|
+
try {
|
|
52
|
+
const v = JSON.parse(text);
|
|
53
|
+
return isRec(v) ? v : 'unreadable';
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
return 'unreadable';
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
const countsOf = (v) => isRec(v) && Object.values(v).every(isInt) ? Object.fromEntries(Object.entries(v)) : undefined;
|
|
60
|
+
const bumpCount = (c, k, by) => {
|
|
61
|
+
const n = (c[k] ?? 0) + by;
|
|
62
|
+
if (n)
|
|
63
|
+
c[k] = n;
|
|
64
|
+
else
|
|
65
|
+
delete c[k];
|
|
66
|
+
};
|
|
67
|
+
const regionOf = (v) => (isRec(v) && ints(v.territories) && ints(v.bonuses) ? { territories: v.territories, bonuses: v.bonuses } : undefined);
|
|
68
|
+
function mapEntryOf(v) {
|
|
69
|
+
if (!isRec(v) || typeof v.key !== 'string' || !HASH.test(v.key) || !isFormat(v.format) || !isInt(v.seats) || !isResult(v.result) || !intOrNull(v.turns))
|
|
70
|
+
return undefined;
|
|
71
|
+
const m = v.me;
|
|
72
|
+
const mine = regionOf(m);
|
|
73
|
+
if (!mine || !isRec(m) || !Array.isArray(m.income) || !m.income.every(intOrNull) || !intOrNull(m.income4) || !intOrNull(m.income8))
|
|
74
|
+
return undefined;
|
|
75
|
+
if (!Array.isArray(v.winners))
|
|
76
|
+
return undefined;
|
|
77
|
+
const winners = [];
|
|
78
|
+
for (const w of v.winners) {
|
|
79
|
+
const r = regionOf(w);
|
|
80
|
+
if (!r || !isRec(w) || !intOrNull(w.income4) || !intOrNull(w.income8))
|
|
81
|
+
return undefined;
|
|
82
|
+
winners.push({ ...r, income4: w.income4, income8: w.income8 });
|
|
83
|
+
}
|
|
84
|
+
return {
|
|
85
|
+
key: v.key,
|
|
86
|
+
format: v.format,
|
|
87
|
+
seats: v.seats,
|
|
88
|
+
result: v.result,
|
|
89
|
+
turns: v.turns,
|
|
90
|
+
me: { ...mine, income: m.income, income4: m.income4, income8: m.income8 },
|
|
91
|
+
winners,
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
/** The record of `mapId`: an empty one when missing, `unreadable` when it cannot be parsed. Never throws. */
|
|
95
|
+
export async function readMapRecord(dir, mapId) {
|
|
96
|
+
try {
|
|
97
|
+
const v = await readStore(mapRecordPath(dir, mapId));
|
|
98
|
+
if (v === 'unreadable')
|
|
99
|
+
return v;
|
|
100
|
+
if (v === 'missing')
|
|
101
|
+
return { version: 1, mapId, games: 0, outcomes: {}, entries: [] };
|
|
102
|
+
const outcomes = countsOf(v.outcomes);
|
|
103
|
+
if (v.version !== 1 || v.mapId !== mapId || !isInt(v.games) || !outcomes)
|
|
104
|
+
return 'unreadable';
|
|
105
|
+
const entries = (Array.isArray(v.entries) ? v.entries : []).map(mapEntryOf).filter((e) => e !== undefined);
|
|
106
|
+
return { version: 1, mapId, games: v.games, outcomes, entries };
|
|
107
|
+
}
|
|
108
|
+
catch {
|
|
109
|
+
return 'unreadable';
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Keep one finished game in its map's record: a game already there (by key) is replaced, its outcome
|
|
114
|
+
* moved; a new one counted. `kept`, or `failed` (an unreadable record is never overwritten; a failed
|
|
115
|
+
* write). Never throws.
|
|
116
|
+
*/
|
|
117
|
+
export async function recordMapGame(dir, mapId, entry, keep = MAX_MAP_RECORDS) {
|
|
118
|
+
const path = mapRecordPath(dir, mapId);
|
|
119
|
+
try {
|
|
120
|
+
const r = await withPathLock(path, async () => {
|
|
121
|
+
const rec = await readMapRecord(dir, mapId);
|
|
122
|
+
if (rec === 'unreadable')
|
|
123
|
+
return 'failed';
|
|
124
|
+
const old = rec.entries.find((e) => e.key === entry.key);
|
|
125
|
+
if (old)
|
|
126
|
+
bumpCount(rec.outcomes, old.result, -1);
|
|
127
|
+
else
|
|
128
|
+
rec.games++;
|
|
129
|
+
bumpCount(rec.outcomes, entry.result, 1);
|
|
130
|
+
rec.entries = [...rec.entries.filter((e) => e.key !== entry.key), entry].slice(-MAX_MAP_ENTRIES);
|
|
131
|
+
await writeJsonAtomic(path, mapRecordDir(dir), rec);
|
|
132
|
+
return 'kept';
|
|
133
|
+
});
|
|
134
|
+
if (r === 'kept')
|
|
135
|
+
await pruneMapRecords(dir, keep, path).catch(() => undefined);
|
|
136
|
+
return r;
|
|
137
|
+
}
|
|
138
|
+
catch {
|
|
139
|
+
return 'failed';
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
async function pruneMapRecords(dir, keep, protect) {
|
|
143
|
+
const folder = mapRecordDir(dir);
|
|
144
|
+
const files = [];
|
|
145
|
+
for (const name of await readdir(folder)) {
|
|
146
|
+
if (!/^\d+\.json$/.test(name))
|
|
147
|
+
continue;
|
|
148
|
+
const path = join(folder, name);
|
|
149
|
+
try {
|
|
150
|
+
files.push({ path, at: (await stat(path)).mtimeMs });
|
|
151
|
+
}
|
|
152
|
+
catch {
|
|
153
|
+
// Gone already.
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
if (files.length <= keep)
|
|
157
|
+
return;
|
|
158
|
+
files.sort((a, b) => a.at - b.at || a.path.localeCompare(b.path));
|
|
159
|
+
let over = files.length - keep;
|
|
160
|
+
for (const f of files) {
|
|
161
|
+
if (over <= 0)
|
|
162
|
+
break;
|
|
163
|
+
if (f.path === protect)
|
|
164
|
+
continue;
|
|
165
|
+
await unlink(f.path).catch(() => undefined);
|
|
166
|
+
over--;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
const median = (xs) => {
|
|
170
|
+
if (!xs.length)
|
|
171
|
+
return null;
|
|
172
|
+
const s = [...xs].sort((a, b) => a - b);
|
|
173
|
+
const m = Math.floor(s.length / 2);
|
|
174
|
+
return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;
|
|
175
|
+
};
|
|
176
|
+
/** What a map's record says in short: games, my results, and the winners' pace beside mine (medians over the kept games). Pure. */
|
|
177
|
+
export function mapRecordSummary(rec) {
|
|
178
|
+
const of = (xs) => median(xs.filter((x) => x !== null));
|
|
179
|
+
const winners = rec.entries.flatMap((e) => e.winners);
|
|
180
|
+
return {
|
|
181
|
+
games: rec.games,
|
|
182
|
+
outcomes: rec.outcomes,
|
|
183
|
+
pace: {
|
|
184
|
+
winners: { income4: of(winners.map((w) => w.income4)), income8: of(winners.map((w) => w.income8)) },
|
|
185
|
+
mine: { income4: of(rec.entries.map((e) => e.me.income4)), income8: of(rec.entries.map((e) => e.me.income8)) },
|
|
186
|
+
},
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
/** My results per bonus my start touched, and how often each bonus held a winner's start (#312 E3), most games first then by id. Pure. */
|
|
190
|
+
export function mapRecordStarts(rec) {
|
|
191
|
+
const mine = new Map();
|
|
192
|
+
const winners = new Map();
|
|
193
|
+
for (const e of rec.entries) {
|
|
194
|
+
for (const b of e.me.bonuses) {
|
|
195
|
+
const x = mine.get(b) ?? { games: 0, outcomes: {} };
|
|
196
|
+
x.games++;
|
|
197
|
+
bumpCount(x.outcomes, e.result, 1);
|
|
198
|
+
mine.set(b, x);
|
|
199
|
+
}
|
|
200
|
+
// A bonus counts once per game, however many winners started in it.
|
|
201
|
+
for (const b of new Set(e.winners.flatMap((w) => w.bonuses)))
|
|
202
|
+
winners.set(b, (winners.get(b) ?? 0) + 1);
|
|
203
|
+
}
|
|
204
|
+
const order = (a, b) => b.games - a.games || a.bonusId - b.bonusId;
|
|
205
|
+
return {
|
|
206
|
+
mine: [...mine].map(([bonusId, x]) => ({ bonusId, ...x })).sort(order),
|
|
207
|
+
winners: [...winners].map(([bonusId, games]) => ({ bonusId, games })).sort(order),
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
function statsOf(v) {
|
|
211
|
+
if (!isRec(v) || !isInt(v.n) || !num(v.sum) || !num(v.sq) || !num(v.logSum) || !isInt(v.under) || !isInt(v.over))
|
|
212
|
+
return undefined;
|
|
213
|
+
return { n: v.n, sum: v.sum, sq: v.sq, logSum: v.logSum, under: v.under, over: v.over };
|
|
214
|
+
}
|
|
215
|
+
function calibrationOf(v) {
|
|
216
|
+
if (!isRec(v))
|
|
217
|
+
return undefined;
|
|
218
|
+
const out = {};
|
|
219
|
+
for (const [k, s] of Object.entries(v)) {
|
|
220
|
+
if (!COVERAGE_BUCKETS.includes(k))
|
|
221
|
+
return undefined;
|
|
222
|
+
const x = statsOf(s);
|
|
223
|
+
if (!x)
|
|
224
|
+
return undefined;
|
|
225
|
+
out[k] = x;
|
|
226
|
+
}
|
|
227
|
+
return out;
|
|
228
|
+
}
|
|
229
|
+
function lossOf(v) {
|
|
230
|
+
if (v === null)
|
|
231
|
+
return null;
|
|
232
|
+
if (!isRec(v) || !CAUSES.includes(v.cause) || !intOrNull(v.turn))
|
|
233
|
+
return undefined;
|
|
234
|
+
return { cause: v.cause, turn: v.turn };
|
|
235
|
+
}
|
|
236
|
+
function lessonEntryOf(v) {
|
|
237
|
+
if (!isRec(v) || typeof v.key !== 'string' || !HASH.test(v.key) || !isFormat(v.format) || !isInt(v.seats) || !isResult(v.result) || !intOrNull(v.flatAfterTurn))
|
|
238
|
+
return undefined;
|
|
239
|
+
const loss = lossOf(v.howLost);
|
|
240
|
+
const calibration = calibrationOf(v.calibration);
|
|
241
|
+
if (loss === undefined || !calibration)
|
|
242
|
+
return undefined;
|
|
243
|
+
return { key: v.key, format: v.format, seats: v.seats, result: v.result, flatAfterTurn: v.flatAfterTurn, howLost: loss, calibration };
|
|
244
|
+
}
|
|
245
|
+
function totalsOf(v) {
|
|
246
|
+
if (!isRec(v) || !isInt(v.games))
|
|
247
|
+
return undefined;
|
|
248
|
+
const outcomes = countsOf(v.outcomes);
|
|
249
|
+
const lost = countsOf(v.howLost);
|
|
250
|
+
const calibration = calibrationOf(v.calibration);
|
|
251
|
+
const f = v.flat;
|
|
252
|
+
if (!outcomes || !lost || !calibration || !isRec(f) || !isInt(f.n) || !num(f.sum))
|
|
253
|
+
return undefined;
|
|
254
|
+
return { games: v.games, outcomes, howLost: lost, flat: { n: f.n, sum: f.sum }, calibration };
|
|
255
|
+
}
|
|
256
|
+
/** The lessons store: empty when missing, `unreadable` when it cannot be parsed (a malformed total too). Never throws. */
|
|
257
|
+
export async function readLessons(dir) {
|
|
258
|
+
try {
|
|
259
|
+
const v = await readStore(lessonsPath(dir));
|
|
260
|
+
if (v === 'unreadable')
|
|
261
|
+
return v;
|
|
262
|
+
if (v === 'missing')
|
|
263
|
+
return { version: 1, byFormat: {}, entries: [] };
|
|
264
|
+
if (v.version !== 1 || !isRec(v.byFormat))
|
|
265
|
+
return 'unreadable';
|
|
266
|
+
const byFormat = {};
|
|
267
|
+
for (const [k, t] of Object.entries(v.byFormat)) {
|
|
268
|
+
const totals = totalsOf(t);
|
|
269
|
+
if (!isFormat(k) || !totals)
|
|
270
|
+
return 'unreadable';
|
|
271
|
+
byFormat[k] = totals;
|
|
272
|
+
}
|
|
273
|
+
const entries = (Array.isArray(v.entries) ? v.entries : []).map(lessonEntryOf).filter((e) => e !== undefined);
|
|
274
|
+
return { version: 1, byFormat, entries };
|
|
275
|
+
}
|
|
276
|
+
catch {
|
|
277
|
+
return 'unreadable';
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
const emptyTotals = () => ({ games: 0, outcomes: {}, howLost: {}, flat: { n: 0, sum: 0 }, calibration: {} });
|
|
281
|
+
/** Move `t` by one entry's share, `scale` +1 (add) or −1 (take back). */
|
|
282
|
+
function applyEntry(t, e, scale) {
|
|
283
|
+
t.games += scale;
|
|
284
|
+
bumpCount(t.outcomes, e.result, scale);
|
|
285
|
+
if (e.howLost)
|
|
286
|
+
bumpCount(t.howLost, e.howLost.cause, scale);
|
|
287
|
+
if (e.flatAfterTurn !== null)
|
|
288
|
+
t.flat = { n: t.flat.n + scale, sum: t.flat.sum + scale * e.flatAfterTurn };
|
|
289
|
+
t.calibration = addCalibration(t.calibration, e.calibration, scale);
|
|
290
|
+
}
|
|
291
|
+
/**
|
|
292
|
+
* Keep one finished game's lessons: its totals moved by the difference from the entry stored for it
|
|
293
|
+
* (so processing a game again replaces its share), the entry kept (at most {@link MAX_LESSON_ENTRIES}).
|
|
294
|
+
* `kept`, or `failed` (an unreadable store is never overwritten; a failed write). Never throws.
|
|
295
|
+
*/
|
|
296
|
+
export async function recordLessons(dir, entry) {
|
|
297
|
+
const path = lessonsPath(dir);
|
|
298
|
+
try {
|
|
299
|
+
return await withPathLock(path, async () => {
|
|
300
|
+
const file = await readLessons(dir);
|
|
301
|
+
if (file === 'unreadable')
|
|
302
|
+
return 'failed';
|
|
303
|
+
const old = file.entries.find((e) => e.key === entry.key);
|
|
304
|
+
if (old) {
|
|
305
|
+
const t = file.byFormat[old.format];
|
|
306
|
+
if (t) {
|
|
307
|
+
applyEntry(t, old, -1);
|
|
308
|
+
if (t.games <= 0)
|
|
309
|
+
delete file.byFormat[old.format];
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
const t = file.byFormat[entry.format] ?? emptyTotals();
|
|
313
|
+
applyEntry(t, entry, 1);
|
|
314
|
+
file.byFormat[entry.format] = t;
|
|
315
|
+
file.entries = [...file.entries.filter((e) => e.key !== entry.key), entry].slice(-MAX_LESSON_ENTRIES);
|
|
316
|
+
await writeJsonAtomic(path, dir, file);
|
|
317
|
+
return 'kept';
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
catch {
|
|
321
|
+
return 'failed';
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
const r2 = (x) => Math.round(x * 100) / 100;
|
|
325
|
+
/** A calibration's bands summarized ({@link RatioSummary}); a band with no sample is left out. Pure. */
|
|
326
|
+
export function calibrationSummary(c) {
|
|
327
|
+
const out = {};
|
|
328
|
+
for (const k of COVERAGE_BUCKETS) {
|
|
329
|
+
const x = c[k];
|
|
330
|
+
if (!x || x.n <= 0)
|
|
331
|
+
continue;
|
|
332
|
+
out[k] = { n: x.n, mean: r2(x.sum / x.n), geoMean: r2(Math.exp(x.logSum / x.n)), low: r2(x.under / x.n), high: r2(x.over / x.n) };
|
|
333
|
+
}
|
|
334
|
+
return out;
|
|
335
|
+
}
|
|
336
|
+
/** The lessons store summarized (#312 E3): per format, and the calibration of every format together. Aggregates only. Pure. */
|
|
337
|
+
export function lessonsSummary(file) {
|
|
338
|
+
const byFormat = {};
|
|
339
|
+
let games = 0;
|
|
340
|
+
let all = {};
|
|
341
|
+
for (const f of PROFILE_FORMATS) {
|
|
342
|
+
const t = file.byFormat[f];
|
|
343
|
+
if (!t || t.games <= 0)
|
|
344
|
+
continue;
|
|
345
|
+
games += t.games;
|
|
346
|
+
all = addCalibration(all, t.calibration);
|
|
347
|
+
byFormat[f] = {
|
|
348
|
+
games: t.games,
|
|
349
|
+
outcomes: t.outcomes,
|
|
350
|
+
howLost: t.howLost,
|
|
351
|
+
flatAfterTurn: t.flat.n > 0 ? { games: t.flat.n, mean: r2(t.flat.sum / t.flat.n) } : null,
|
|
352
|
+
calibration: calibrationSummary(t.calibration),
|
|
353
|
+
};
|
|
354
|
+
}
|
|
355
|
+
return { games, byFormat, calibration: calibrationSummary(all) };
|
|
356
|
+
}
|
package/dist/live.js
CHANGED
|
@@ -217,6 +217,15 @@ export function inGameId(player) {
|
|
|
217
217
|
}
|
|
218
218
|
return Number(text.slice(2, -2));
|
|
219
219
|
}
|
|
220
|
+
/** {@link inGameId}, or `undefined` for a player whose id is not a GameFeed id (e.g. an AI slot). */
|
|
221
|
+
export function inGameOf(player) {
|
|
222
|
+
try {
|
|
223
|
+
return inGameId(player);
|
|
224
|
+
}
|
|
225
|
+
catch {
|
|
226
|
+
return undefined;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
220
229
|
/** In-game id → GameFeed player, for the players whose ids can be derived. */
|
|
221
230
|
export function playersByInGameId(players) {
|
|
222
231
|
const out = new Map();
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
// A map's distribution modes and the territories each lets a player start on (#328): the GetMapDetails
|
|
2
|
+
// reply (method 73, no auth, the int32 map id), decoded by the client bundle's own readers by stable type
|
|
3
|
+
// name, like GetMyGames — fields by read order, checked by type, never by their minified names
|
|
4
|
+
// (docs/WEB-PROTOCOL.md, "Map details: distribution modes"). GameFeed's map names its modes but not their
|
|
5
|
+
// territories; the client's map preview reads them from here.
|
|
6
|
+
//
|
|
7
|
+
// `MapDetails` reads its modes fourth, an int32-count dict of mode id → `DistributionMode`, which the
|
|
8
|
+
// bundle reads by a byte tag: a `NormalDistribution` (its territory ids, then the description, the id and
|
|
9
|
+
// the name) or a `ScenarioDistribution` (its slot names, its territory → slot dict, then the same three).
|
|
10
|
+
// UNVERIFIED live beyond what #328's trace shows (a normal mode's bytes, and its ids against GameFeed's map).
|
|
11
|
+
import { McpToolError } from '@chrischall/mcp-utils';
|
|
12
|
+
import { fields, isObj } from './protocol/decoded.js';
|
|
13
|
+
export const MAP_DETAILS = 'warlight.shared.MapDetails';
|
|
14
|
+
export const NORMAL_DISTRIBUTION = 'warlight.shared.NormalDistribution';
|
|
15
|
+
export const SCENARIO_DISTRIBUTION = 'warlight.shared.ScenarioDistribution';
|
|
16
|
+
/** MapDetails: the position of its mode dict in read order, and its whole field count. */
|
|
17
|
+
const MD = { modes: 3 };
|
|
18
|
+
export const MAP_DETAILS_FIELDS = 14;
|
|
19
|
+
/** NormalDistribution: its territory list, then the base fields (description, id, name). */
|
|
20
|
+
const ND = { territories: 0, id: 2 };
|
|
21
|
+
export const NORMAL_DISTRIBUTION_FIELDS = 4;
|
|
22
|
+
/** ScenarioDistribution: its slot names, its territory → slot dict, then the base fields. */
|
|
23
|
+
const SD = { territories: 1, id: 3 };
|
|
24
|
+
export const SCENARIO_DISTRIBUTION_FIELDS = 5;
|
|
25
|
+
/** The GetMapDetails reply arrived in a shape this server does not understand. */
|
|
26
|
+
export class MapDetailsFormatError extends McpToolError {
|
|
27
|
+
constructor(detail) {
|
|
28
|
+
super(`war.app's map details arrived in an unexpected shape (${detail}).`, {
|
|
29
|
+
kind: 'unknown',
|
|
30
|
+
hint: "The war.app client may have changed; the distribution modes' territories stay unknown.",
|
|
31
|
+
});
|
|
32
|
+
this.name = 'MapDetailsFormatError';
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
const isInt = (v) => typeof v === 'number' && Number.isInteger(v);
|
|
36
|
+
const isIntList = (v) => Array.isArray(v) && v.every(isInt);
|
|
37
|
+
/** A decoded dict: `[key, value]` pairs. */
|
|
38
|
+
const isPairs = (v) => Array.isArray(v) && v.every((e) => Array.isArray(e) && e.length === 2);
|
|
39
|
+
/** One mode's territory ids (`null`: the reply lists none), checked against the dict's key. */
|
|
40
|
+
function territoriesOf(key, mode) {
|
|
41
|
+
if (mode === null)
|
|
42
|
+
return null;
|
|
43
|
+
if (!isObj(mode))
|
|
44
|
+
throw new MapDetailsFormatError(`mode ${key} is not a record`);
|
|
45
|
+
const f = fields(mode);
|
|
46
|
+
let id;
|
|
47
|
+
let ids;
|
|
48
|
+
if (mode.$type === NORMAL_DISTRIBUTION) {
|
|
49
|
+
if (f.length !== NORMAL_DISTRIBUTION_FIELDS)
|
|
50
|
+
throw new MapDetailsFormatError(`a NormalDistribution has ${f.length} fields`);
|
|
51
|
+
const list = f[ND.territories];
|
|
52
|
+
if (list !== null && !isIntList(list))
|
|
53
|
+
throw new MapDetailsFormatError(`mode ${key}'s territories are not ids`);
|
|
54
|
+
id = f[ND.id];
|
|
55
|
+
ids = list;
|
|
56
|
+
}
|
|
57
|
+
else if (mode.$type === SCENARIO_DISTRIBUTION) {
|
|
58
|
+
if (f.length !== SCENARIO_DISTRIBUTION_FIELDS)
|
|
59
|
+
throw new MapDetailsFormatError(`a ScenarioDistribution has ${f.length} fields`);
|
|
60
|
+
const dict = f[SD.territories];
|
|
61
|
+
if (dict !== null && !(isPairs(dict) && dict.every(([t, s]) => isInt(t) && isInt(s)))) {
|
|
62
|
+
throw new MapDetailsFormatError(`mode ${key}'s territories are not ids`);
|
|
63
|
+
}
|
|
64
|
+
id = f[SD.id];
|
|
65
|
+
ids = dict === null ? null : dict.map(([t]) => t);
|
|
66
|
+
}
|
|
67
|
+
else {
|
|
68
|
+
throw new MapDetailsFormatError(`mode ${key} is neither a normal nor a scenario distribution`);
|
|
69
|
+
}
|
|
70
|
+
if (id !== key)
|
|
71
|
+
throw new MapDetailsFormatError(`mode ${key} names itself ${String(id)}`);
|
|
72
|
+
return ids;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Read a GetMapDetails result (the body positioned at the result-present flag): mode id → its territory
|
|
76
|
+
* ids, `null` for a mode the reply lists none for. `null` when there is no result.
|
|
77
|
+
*/
|
|
78
|
+
export function readMapDetailsModes(bundle, body) {
|
|
79
|
+
if (!body.bool())
|
|
80
|
+
return null;
|
|
81
|
+
const details = bundle.readClass(MAP_DETAILS, body);
|
|
82
|
+
if (!isObj(details) || details.$type !== MAP_DETAILS)
|
|
83
|
+
throw new MapDetailsFormatError('no MapDetails');
|
|
84
|
+
const f = fields(details);
|
|
85
|
+
if (f.length !== MAP_DETAILS_FIELDS)
|
|
86
|
+
throw new MapDetailsFormatError(`a MapDetails has ${f.length} fields, not ${MAP_DETAILS_FIELDS}`);
|
|
87
|
+
const modes = f[MD.modes];
|
|
88
|
+
const out = new Map();
|
|
89
|
+
if (modes === null)
|
|
90
|
+
return out;
|
|
91
|
+
if (!isPairs(modes))
|
|
92
|
+
throw new MapDetailsFormatError('no mode list');
|
|
93
|
+
for (const [key, mode] of modes) {
|
|
94
|
+
if (!isInt(key))
|
|
95
|
+
throw new MapDetailsFormatError('a mode id is not an integer');
|
|
96
|
+
out.set(key, territoriesOf(key, mode));
|
|
97
|
+
}
|
|
98
|
+
return out;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Lay the territories read (`byMode`) on `map`'s modes, a copy: each mode's ids that are territories of the
|
|
102
|
+
* map, in order, once each (an id the map lacks is dropped, with a warning); a mode the reply leaves out, or
|
|
103
|
+
* lists none for (or whose every id is dropped), is `null` — unknown, never empty. A mode the reply has but the map does not is ignored.
|
|
104
|
+
*/
|
|
105
|
+
export function applyModeTerritories(map, byMode) {
|
|
106
|
+
const land = new Set(map.territories.map((t) => t.id));
|
|
107
|
+
const found = new Map();
|
|
108
|
+
const warnings = [];
|
|
109
|
+
const distributionModes = map.distributionModes.map((d) => {
|
|
110
|
+
const ids = byMode.get(d.id);
|
|
111
|
+
if (!ids)
|
|
112
|
+
return { ...d, territories: null };
|
|
113
|
+
const kept = [...new Set(ids.filter((id) => land.has(id)))];
|
|
114
|
+
const dropped = [...new Set(ids.filter((id) => !land.has(id)))];
|
|
115
|
+
if (dropped.length) {
|
|
116
|
+
const one = dropped.length === 1;
|
|
117
|
+
warnings.push(`Distribution mode ${d.id}: ${dropped.length} territory id${one ? '' : 's'} war.app listed ${one ? 'is' : 'are'} not ` +
|
|
118
|
+
`${one ? 'a territory' : 'territories'} of map ${map.id} and ${one ? 'was' : 'were'} dropped (${dropped.join(', ')}).`);
|
|
119
|
+
}
|
|
120
|
+
// Every id dropped (or none listed) says nothing about the mode: unknown, never known-empty.
|
|
121
|
+
if (!kept.length)
|
|
122
|
+
return { ...d, territories: null };
|
|
123
|
+
found.set(d.id, kept);
|
|
124
|
+
return { ...d, territories: kept };
|
|
125
|
+
});
|
|
126
|
+
return { map: { ...map, distributionModes }, found, warnings };
|
|
127
|
+
}
|
package/dist/map-stats.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { historyBoards } from './trend.js';
|
|
1
|
+
import { historyBoards, historyReport } from './trend.js';
|
|
2
2
|
/** Below this many games a rate is reported only with a warning. */
|
|
3
3
|
export const MIN_SAMPLE = 5;
|
|
4
4
|
/**
|
|
@@ -6,6 +6,12 @@ export const MIN_SAMPLE = 5;
|
|
|
6
6
|
* 4 wins (80%) is as consistent with a coin flip as with a strong start (#132).
|
|
7
7
|
*/
|
|
8
8
|
export const MIN_RATE_SAMPLE = 10;
|
|
9
|
+
/**
|
|
10
|
+
* History layouts whose records are no longer trusted (#302): a record read under one is not
|
|
11
|
+
* readable, so it is never cached and a cached one is deleted and fetched again. Empty until the
|
|
12
|
+
* live check of GameFeed's finished-game history says which numbering is wrong.
|
|
13
|
+
*/
|
|
14
|
+
export const RETIRED_LAYOUTS = new Set();
|
|
9
15
|
const byId = (a, b) => a - b;
|
|
10
16
|
const ownedBy = (board, playerId) => new Set(board.territories
|
|
11
17
|
.filter((t) => t.owner.kind === 'player' && t.owner.playerId === playerId)
|
|
@@ -14,7 +20,7 @@ const ownedBy = (board, playerId) => new Set(board.territories
|
|
|
14
20
|
const scoringBonuses = (map) => map.bonuses.filter((b) => b.value > 0 && b.territoryIds.length > 0).sort((a, b) => a.id - b.id);
|
|
15
21
|
/** Reduce a finished game (with `GetHistory`) to its stats record. Never throws on a bad history. */
|
|
16
22
|
export function recordFromGame(game, map) {
|
|
17
|
-
const boards = historyBoards(game.history, game.players);
|
|
23
|
+
const boards = historyBoards(game.history, game.players, game.numberOfTurns !== undefined ? { numberOfTurns: game.numberOfTurns } : {});
|
|
18
24
|
const start = boards.find(({ board }) => board.territories.some((t) => t.owner.kind === 'player'));
|
|
19
25
|
const later = start ? boards.filter((b) => b.turn >= start.turn) : [];
|
|
20
26
|
const bonuses = scoringBonuses(map);
|
|
@@ -44,7 +50,9 @@ export function recordFromGame(game, map) {
|
|
|
44
50
|
}
|
|
45
51
|
return { playerId: p.id, won: p.state === 'Won', starts, anchorBonusId, startBonusIds, firstBonusTurn };
|
|
46
52
|
});
|
|
47
|
-
|
|
53
|
+
const report = boards.length ? historyReport(game) : undefined;
|
|
54
|
+
const layout = report && 'read' in report ? { layout: report.read.layout } : {};
|
|
55
|
+
return { gameId: game.id, mapId: map.id, turnsSeen: boards.length, ...layout, players };
|
|
48
56
|
}
|
|
49
57
|
const round2 = (n) => Math.round(n * 100) / 100;
|
|
50
58
|
function median(xs) {
|
|
@@ -54,10 +62,10 @@ function median(xs) {
|
|
|
54
62
|
const mid = Math.floor(s.length / 2);
|
|
55
63
|
return s.length % 2 ? s[mid] : (s[mid - 1] + s[mid]) / 2;
|
|
56
64
|
}
|
|
57
|
-
/** A record the stats can use: its history parsed
|
|
58
|
-
export const readableRecord = (r) => r.turnsSeen > 0 && r.players.some((p) => p.starts.length > 0);
|
|
65
|
+
/** A record the stats can use: its history parsed, some player's starts were read, and its layout is not retired. */
|
|
66
|
+
export const readableRecord = (r, retired = RETIRED_LAYOUTS) => r.turnsSeen > 0 && r.players.some((p) => p.starts.length > 0) && (r.layout === undefined || !retired.has(r.layout));
|
|
59
67
|
function statsFor(mapId, all, top) {
|
|
60
|
-
const games = all.filter(readableRecord);
|
|
68
|
+
const games = all.filter((r) => readableRecord(r));
|
|
61
69
|
const unreadable = all.length - games.length;
|
|
62
70
|
const picks = new Map();
|
|
63
71
|
const anchors = new Map();
|
package/dist/map-store.js
CHANGED
|
@@ -6,6 +6,12 @@
|
|
|
6
6
|
// and applied by `mapOf`). Maps are public data. At most MAX_STORED_MAPS files; the least recently
|
|
7
7
|
// used (file mtime, touched on every read and on every memory hit in `MapCache`) is evicted on a
|
|
8
8
|
// write.
|
|
9
|
+
// A mode may carry `territories` (#328: the ids war.app's map details list for it, src/map-details.ts),
|
|
10
|
+
// added by `writeStoredModeTerritories` with the map's `storedAt` unchanged; a mode without them reads
|
|
11
|
+
// as not read yet (never as empty), and a file written before them reads as it did (same version).
|
|
12
|
+
// `MapCache.store` carries them onto a fresh download of the map (src/client.ts) under the stored copy's
|
|
13
|
+
// `storedAt`, so ids read from war.app never gain a new 30 days; a mode whose ids are not all territories
|
|
14
|
+
// of the fresh map is not carried (it is read again).
|
|
9
15
|
// A map maker can publish an edit under the same map id and GameFeed sends no map version, so a
|
|
10
16
|
// stored map is trusted for MAX_MAP_AGE_MS after `storedAt` (the download time, epoch ms) and then
|
|
11
17
|
// reads as absent: the game is fetched with its map again and the fresh copy replaces it (sooner when
|
|
@@ -73,6 +79,9 @@ function modeOf(d) {
|
|
|
73
79
|
const out = { id: d.id, name: d.name };
|
|
74
80
|
if (typeof d.type === 'string')
|
|
75
81
|
out.type = d.type;
|
|
82
|
+
// #328: only a non-empty list of ids is kept knowledge; anything else (absent, null, [], junk) reads as not read yet.
|
|
83
|
+
if (isIntArray(d.territories) && d.territories.length)
|
|
84
|
+
out.territories = d.territories;
|
|
76
85
|
return out;
|
|
77
86
|
}
|
|
78
87
|
/** Every element of `xs` read by `f`, or `undefined` when any is unreadable. */
|
|
@@ -112,14 +121,20 @@ function storedMapOf(raw, mapId, now, maxAgeMs) {
|
|
|
112
121
|
* than `maxAgeMs` ({@link MAX_MAP_AGE_MS} by default). Never throws.
|
|
113
122
|
*/
|
|
114
123
|
export async function readStoredMap(dir, mapId, opts = {}) {
|
|
124
|
+
return (await readStoredMapEntry(dir, mapId, opts))?.map;
|
|
125
|
+
}
|
|
126
|
+
/** {@link readStoredMap} with the copy's `storedAt`. Never throws. */
|
|
127
|
+
export async function readStoredMapEntry(dir, mapId, opts = {}) {
|
|
115
128
|
const path = mapStorePath(dir, mapId);
|
|
116
129
|
try {
|
|
117
|
-
const
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
130
|
+
const raw = JSON.parse(await readFile(path, 'utf8'));
|
|
131
|
+
const map = storedMapOf(raw, mapId, opts.now ?? Date.now(), opts.maxAgeMs ?? MAX_MAP_AGE_MS);
|
|
132
|
+
if (!map)
|
|
133
|
+
return undefined;
|
|
134
|
+
const now = new Date();
|
|
135
|
+
await utimes(path, now, now).catch(() => { });
|
|
136
|
+
const at = isRec(raw) ? raw.storedAt : undefined;
|
|
137
|
+
return { map, storedAt: typeof at === 'number' && Number.isFinite(at) ? at : undefined };
|
|
123
138
|
}
|
|
124
139
|
catch {
|
|
125
140
|
return undefined;
|
|
@@ -157,6 +172,29 @@ export async function writeStoredMap(dir, map, storedAt = Date.now()) {
|
|
|
157
172
|
return false;
|
|
158
173
|
}
|
|
159
174
|
}
|
|
175
|
+
/**
|
|
176
|
+
* Keep the territories read for the stored map's distribution modes (#328, by mode id) in its file,
|
|
177
|
+
* leaving its `storedAt` alone: they came from war.app's map details for the same map, so they age out
|
|
178
|
+
* with the GameFeed copy (a fresh download replaces the file, and they are read again). Only a stored
|
|
179
|
+
* map still trusted is updated; a mode not in `byMode` keeps what it had. `true` when written; never throws.
|
|
180
|
+
*/
|
|
181
|
+
export async function writeStoredModeTerritories(dir, mapId, byMode) {
|
|
182
|
+
const path = mapStorePath(dir, mapId);
|
|
183
|
+
try {
|
|
184
|
+
return await withPathLock(path, async () => {
|
|
185
|
+
const raw = JSON.parse(await readFile(path, 'utf8'));
|
|
186
|
+
if (!storedMapOf(raw, mapId, Date.now(), MAX_MAP_AGE_MS) || !isRec(raw) || !isRec(raw.map) || !Array.isArray(raw.map.distributionModes)) {
|
|
187
|
+
return false;
|
|
188
|
+
}
|
|
189
|
+
raw.map.distributionModes = raw.map.distributionModes.map((d) => isRec(d) && isInt(d.id) && byMode.get(d.id)?.length ? { ...d, territories: [...byMode.get(d.id)] } : d);
|
|
190
|
+
await writeJsonAtomic(path, mapsDir(dir), raw);
|
|
191
|
+
return true;
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
catch {
|
|
195
|
+
return false;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
160
198
|
/**
|
|
161
199
|
* Mark the stored copy of `map` recently used, storing it when its file has gone. A map served from
|
|
162
200
|
* memory is otherwise never read from disk, so the map of a game played all session long would age
|