@chrischall/warapp-mcp 0.26.0 → 0.27.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 +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/dist/analysis/fog-view.js +35 -0
- package/dist/bundle.js +506 -152
- package/dist/calibration-source.js +39 -4
- package/dist/fog-history.js +246 -0
- package/dist/history-window.js +85 -0
- package/dist/protocol/methods.js +8 -0
- package/dist/tools/calibration-harness.js +26 -11
- package/dist/tools/fog-capture.js +35 -0
- package/dist/tools/game.js +49 -6
- package/dist/tools/turn.js +7 -0
- package/dist/version.js +1 -1
- package/manifest.json +1 -1
- package/package.json +1 -1
- package/server.json +2 -2
|
@@ -4,8 +4,34 @@ import { readStoredMap } from './map-store.js';
|
|
|
4
4
|
import { playerRecordSalt } from './player-record-store.js';
|
|
5
5
|
import { gamesDir, loadReplay } from './replay.js';
|
|
6
6
|
import { readCachedOrders } from './trend.js';
|
|
7
|
+
import { buildGraph } from './analysis/graph.js';
|
|
8
|
+
import { fogView } from './analysis/fog-view.js';
|
|
9
|
+
import { fogBoards, readFogHistory, wallMultipliers } from './fog-history.js';
|
|
7
10
|
import { readdir, readFile } from 'node:fs/promises';
|
|
8
11
|
import { join } from 'node:path';
|
|
12
|
+
/**
|
|
13
|
+
* #568: `cached` with the turns it lacks taken from the fogged view captured while the game was played (exact), and,
|
|
14
|
+
* with no board at all, the history's boards seen through the fog rule (`fogView`; an approximation). Pure.
|
|
15
|
+
*/
|
|
16
|
+
export function boardsFor(input) {
|
|
17
|
+
const have = new Set(input.cached.map((b) => b.turn));
|
|
18
|
+
const lastTruth = Math.max(-1, ...input.history.boards.map((b) => b.turn));
|
|
19
|
+
// A captured board for turn T is my view of history board T − 1: none past the history's end.
|
|
20
|
+
const fill = input.captured.filter((b) => !have.has(b.turn) && b.turn - 1 <= lastTruth);
|
|
21
|
+
if (fill.length) {
|
|
22
|
+
const cached = [...input.cached, ...fill.map((b) => ({ turn: b.turn, board: b.board }))].sort((a, b) => a.turn - b.turn);
|
|
23
|
+
return { cached, boards: input.cached.length ? 'cache+capture' : 'capture', capturedTurns: fill.length };
|
|
24
|
+
}
|
|
25
|
+
if (input.cached.length)
|
|
26
|
+
return { cached: input.cached, boards: 'cache', capturedTurns: 0 };
|
|
27
|
+
if (!input.history.boards.length)
|
|
28
|
+
return { cached: [], boards: 'none', capturedTurns: 0 };
|
|
29
|
+
const graph = buildGraph(input.map);
|
|
30
|
+
const me = input.history.players.find((p) => p.id === input.history.me);
|
|
31
|
+
const allies = new Set(input.history.players.filter((p) => p.id !== input.history.me && typeof me?.team === 'number' && me.team >= 0 && p.team === me.team).map((p) => p.id));
|
|
32
|
+
const cached = input.history.boards.map((b) => ({ turn: b.turn + 1, board: fogView(graph, b.board, input.history.me, input.fog, allies) }));
|
|
33
|
+
return { cached, boards: 'rebuilt', capturedTurns: 0 };
|
|
34
|
+
}
|
|
9
35
|
const count = (o, k) => {
|
|
10
36
|
o[k] = (o[k] ?? 0) + 1;
|
|
11
37
|
};
|
|
@@ -88,7 +114,7 @@ export async function calibrationSources(dir) {
|
|
|
88
114
|
count(out.skipped, 'no-map');
|
|
89
115
|
continue;
|
|
90
116
|
}
|
|
91
|
-
const
|
|
117
|
+
const seenCached = fromReplay && replay.playerId === history.me
|
|
92
118
|
? replay.boards.map((b) => {
|
|
93
119
|
const o = replay.orders.get(b.turn);
|
|
94
120
|
return { turn: b.turn, board: b.board, ...(o ? { orders: o } : {}) };
|
|
@@ -96,8 +122,17 @@ export async function calibrationSources(dir) {
|
|
|
96
122
|
: [];
|
|
97
123
|
const recovered = fromReplay ? undefined : named.get(path);
|
|
98
124
|
const gameId = fromReplay ? replay.game.id : recovered?.gameId;
|
|
99
|
-
|
|
100
|
-
|
|
125
|
+
// #568: the fogged view captured while the game was played (real ids: only with the settings record's players).
|
|
126
|
+
const fog = fromReplay && replay.playerId === history.me ? await readFogHistory(dir, replay.game.id, replay.playerId) : undefined;
|
|
127
|
+
const { cached, boards, capturedTurns } = boardsFor({
|
|
128
|
+
cached: seenCached,
|
|
129
|
+
captured: fog ? fogBoards(fog, replay.game.players, wallMultipliers(settings.raw)) : [],
|
|
130
|
+
history,
|
|
131
|
+
map,
|
|
132
|
+
fog: settings.fog,
|
|
133
|
+
});
|
|
134
|
+
const sentTurns = seenCached.length
|
|
135
|
+
? seenCached.flatMap((b) => (b.orders ? [b.turn] : []))
|
|
101
136
|
: recovered
|
|
102
137
|
? [...(await readCachedOrders(dir, recovered.gameId, recovered.playerId)).keys()]
|
|
103
138
|
: [];
|
|
@@ -108,7 +143,7 @@ export async function calibrationSources(dir) {
|
|
|
108
143
|
failedAttackTurns: [...new Set((rec.failedAttacks ?? []).map((f) => f.turn))].sort((a, b) => a - b),
|
|
109
144
|
sentTurns: [...new Set(sentTurns)].sort((a, b) => a - b),
|
|
110
145
|
};
|
|
111
|
-
out.inputs.push({ source: fromReplay ? 'settings-record' : 'record-only', history, settings, map, cached, opening });
|
|
146
|
+
out.inputs.push({ source: fromReplay ? 'settings-record' : 'record-only', history, settings, map, cached, boards, capturedTurns, opening });
|
|
112
147
|
}
|
|
113
148
|
// A settings record whose game has no record: its pass has not run (or the record was pruned).
|
|
114
149
|
for (const path of byPath.keys())
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
// #568 (owner decision 2026-12-01): my fogged view of every turn of a game, captured while it is played. war.app's
|
|
2
|
+
// history slider (`GetTurns`, method 83) answers, for a game in play, the starting board as I saw it and each resolved
|
|
3
|
+
// turn's visible orders, every one carrying the territory standings it changed or revealed for me (the base order's
|
|
4
|
+
// standing updates), which the client replays to show any past turn. Once the game ends war.app lifts the fog (a
|
|
5
|
+
// finished game's GetTurns shows every territory `Visible`), so this view can only be kept while the game is played.
|
|
6
|
+
// The board cache keeps the newest ten turns this server planned; this keeps every turn, so the calibration harness can
|
|
7
|
+
// replay the tracker over the whole game. Ids and counts only, by in-game id as war.app sends them; never a name.
|
|
8
|
+
// 0600 in a 0700 directory, written atomically under the path lock. Never throws.
|
|
9
|
+
import { randomUUID } from 'node:crypto';
|
|
10
|
+
import { mkdir, readdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
|
|
11
|
+
import { join } from 'node:path';
|
|
12
|
+
import { inGameOf } from './live.js';
|
|
13
|
+
import { withPathLock } from './path-lock.js';
|
|
14
|
+
import { fields, isObj } from './protocol/decoded.js';
|
|
15
|
+
import { decodeOrder } from './team-orders.js';
|
|
16
|
+
import { roundHalfDown } from './analysis/turn-sim.js';
|
|
17
|
+
export const FOG_HISTORY_VERSION = 1;
|
|
18
|
+
/** Games kept at most (the least recently written dropped). */
|
|
19
|
+
export const MAX_FOG_HISTORIES = 200;
|
|
20
|
+
/** Turns one capture asks for at most (the client asks 1,000; a turn's updates are small). */
|
|
21
|
+
export const FOG_CAPTURE_TURNS = 200;
|
|
22
|
+
export const fogHistoryDir = (dir) => join(dir, 'fog-history');
|
|
23
|
+
export const fogHistoryPath = (dir, gameId, playerId) => join(fogHistoryDir(dir), `${gameId}-${playerId}.json`);
|
|
24
|
+
const isInt = (v) => typeof v === 'number' && Number.isInteger(v);
|
|
25
|
+
const TERRITORY_STANDING = /\.TerritoryStanding$/;
|
|
26
|
+
const ARMIES = /\.Armies$/;
|
|
27
|
+
const GAME_TURN = /\.GameTurn$/;
|
|
28
|
+
const GAME_STANDING = /\.GameStanding$/;
|
|
29
|
+
/** A TerritoryStanding record (read order: fog level, territory, Armies, owner, then an optional dict) as a cell. */
|
|
30
|
+
export function cellOf(v) {
|
|
31
|
+
if (!isObj(v) || typeof v.$type !== 'string' || !TERRITORY_STANDING.test(v.$type))
|
|
32
|
+
return undefined;
|
|
33
|
+
const [fog, territory, armies, owner] = fields(v);
|
|
34
|
+
const level = isInt(fog) ? fog : isObj(fog) ? fields(fog).find(isInt) : undefined;
|
|
35
|
+
if (level === undefined || !isInt(territory) || !isInt(owner) || !isObj(armies) || typeof armies.$type !== 'string' || !ARMIES.test(armies.$type))
|
|
36
|
+
return undefined;
|
|
37
|
+
// Armies: a "fogged" flag, then the count (then the special units).
|
|
38
|
+
const af = fields(armies);
|
|
39
|
+
const hidden = af.find((x) => typeof x === 'boolean') === true;
|
|
40
|
+
const count = af.find(isInt);
|
|
41
|
+
return [territory, level, owner, hidden || count === undefined ? null : count];
|
|
42
|
+
}
|
|
43
|
+
/** The territories of a GameStanding record: its dict of territory → TerritoryStanding (read as pairs or a Map). */
|
|
44
|
+
function standingCells(s) {
|
|
45
|
+
const out = [];
|
|
46
|
+
for (const f of fields(s)) {
|
|
47
|
+
const entries = f instanceof Map ? [...f.entries()] : Array.isArray(f) ? f : [];
|
|
48
|
+
for (const e of entries) {
|
|
49
|
+
const v = Array.isArray(e) ? e[1] : e;
|
|
50
|
+
const c = cellOf(v);
|
|
51
|
+
if (c)
|
|
52
|
+
out.push(c);
|
|
53
|
+
}
|
|
54
|
+
if (out.length)
|
|
55
|
+
break;
|
|
56
|
+
}
|
|
57
|
+
return out.sort((a, b) => a[0] - b[0]);
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* A decoded GetTurnsReturn as what to keep: the starting board (the last standing it sends: the client takes it as
|
|
61
|
+
* turn 0's), and per turn (1-based) the standing updates of its orders, in order. `undefined` when it is not one.
|
|
62
|
+
*/
|
|
63
|
+
export function readTurnsReturn(ret) {
|
|
64
|
+
if (!isObj(ret))
|
|
65
|
+
return undefined;
|
|
66
|
+
const lists = fields(ret).filter((v) => Array.isArray(v));
|
|
67
|
+
const standings = lists.flat().filter((v) => isObj(v) && typeof v.$type === 'string' && GAME_STANDING.test(v.$type));
|
|
68
|
+
const gameTurns = lists.flat().filter((v) => isObj(v) && typeof v.$type === 'string' && GAME_TURN.test(v.$type));
|
|
69
|
+
if (!standings.length && !gameTurns.length)
|
|
70
|
+
return undefined;
|
|
71
|
+
const turns = {};
|
|
72
|
+
for (const t of gameTurns) {
|
|
73
|
+
const own = fields(t);
|
|
74
|
+
const index = own.find(isInt);
|
|
75
|
+
const orders = own.filter((v) => Array.isArray(v)).at(-1) ?? [];
|
|
76
|
+
if (index === undefined)
|
|
77
|
+
continue;
|
|
78
|
+
const cells = [];
|
|
79
|
+
for (const o of orders) {
|
|
80
|
+
if (!isObj(o))
|
|
81
|
+
continue;
|
|
82
|
+
const d = decodeOrder(o);
|
|
83
|
+
if (d?.kind === 'deploy') {
|
|
84
|
+
cells.push(['d', d.territoryId, d.armies]);
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
const card = cardEntry(o);
|
|
88
|
+
if (card) {
|
|
89
|
+
cells.push(card);
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
// The base order's standing updates: its last list of TerritoryStanding records.
|
|
93
|
+
for (const f of fields(o))
|
|
94
|
+
if (Array.isArray(f))
|
|
95
|
+
for (const x of f) {
|
|
96
|
+
const c = cellOf(x);
|
|
97
|
+
if (c)
|
|
98
|
+
cells.push(c);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
turns[String(index + 1)] = cells;
|
|
102
|
+
}
|
|
103
|
+
const start = standings.length ? standingCells(standings.at(-1)) : undefined;
|
|
104
|
+
return { ...(start?.length ? { start } : {}), turns };
|
|
105
|
+
}
|
|
106
|
+
const CARD_PLAY = /\.GameOrderPlayCard(Airlift|Blockade|Abandon|Bomb)$/;
|
|
107
|
+
/** A board-changing card play with no standing update of its own, as an entry; `undefined` for any other order. */
|
|
108
|
+
function cardEntry(o) {
|
|
109
|
+
const m = typeof o.$type === 'string' ? CARD_PLAY.exec(o.$type) : null;
|
|
110
|
+
if (!m)
|
|
111
|
+
return undefined;
|
|
112
|
+
const f = fields(o);
|
|
113
|
+
// The order's own fields come before its card GUID (a string), then the base's player.
|
|
114
|
+
const guid = f.findIndex((v) => typeof v === 'string');
|
|
115
|
+
const own = guid >= 0 ? f.slice(0, guid) : f;
|
|
116
|
+
const ints = own.filter(isInt);
|
|
117
|
+
if (m[1] === 'Airlift') {
|
|
118
|
+
// Requested Armies, from, a flag, to; the result's first Armies is what flew.
|
|
119
|
+
const result = f.find((v) => isObj(v) && typeof v.$type === 'string' && /AirliftResult$/.test(v.$type));
|
|
120
|
+
const flew = result ? fields(result).find((v) => isObj(v) && typeof v.$type === 'string' && ARMIES.test(v.$type)) : undefined;
|
|
121
|
+
const n = flew ? fields(flew).find(isInt) : undefined;
|
|
122
|
+
return ints.length >= 2 && n !== undefined ? ['a', ints[0], ints.at(-1), n] : undefined;
|
|
123
|
+
}
|
|
124
|
+
if (!ints.length)
|
|
125
|
+
return undefined;
|
|
126
|
+
return [m[1] === 'Blockade' ? 'b' : m[1] === 'Abandon' ? 'e' : 'h', ints[0]];
|
|
127
|
+
}
|
|
128
|
+
/** The game's wall multipliers, from the settings' card rules: `BlockadeCard` / `EmergencyBlockadeCard` `MultiplyAmount`. */
|
|
129
|
+
export function wallMultipliers(raw) {
|
|
130
|
+
const of = (key) => {
|
|
131
|
+
const r = raw?.[key];
|
|
132
|
+
const m = typeof r === 'object' && r !== null ? Number(r.MultiplyAmount) : Number.NaN;
|
|
133
|
+
return Number.isFinite(m) && m > 0 ? m : undefined;
|
|
134
|
+
};
|
|
135
|
+
const blockade = of('BlockadeCard');
|
|
136
|
+
const abandon = of('EmergencyBlockadeCard');
|
|
137
|
+
return { ...(blockade !== undefined ? { blockade } : {}), ...(abandon !== undefined ? { abandon } : {}) };
|
|
138
|
+
}
|
|
139
|
+
/** Every turn's board as I saw it: the start for turn 1, then each turn's updates applied for the next. Pure. */
|
|
140
|
+
export function fogBoards(h, players, walls = {}) {
|
|
141
|
+
const byInGame = new Map();
|
|
142
|
+
for (const p of players) {
|
|
143
|
+
const g = inGameOf(p);
|
|
144
|
+
if (g !== undefined)
|
|
145
|
+
byInGame.set(g, p.id);
|
|
146
|
+
}
|
|
147
|
+
const cur = new Map(h.start.map((c) => [c[0], c]));
|
|
148
|
+
const out = [];
|
|
149
|
+
const snapshot = (turn) => out.push({ turn, board: { source: 'browser', verified: true, territories: [...cur.values()].sort((a, b) => a[0] - b[0]).map((c) => stateOf(c, byInGame)) } });
|
|
150
|
+
snapshot(1);
|
|
151
|
+
const numbers = Object.keys(h.turns).map(Number).filter((n) => n >= 1).sort((a, b) => a - b);
|
|
152
|
+
for (let n = 1; n <= (numbers.at(-1) ?? 0); n++) {
|
|
153
|
+
const updates = h.turns[String(n)];
|
|
154
|
+
if (!updates)
|
|
155
|
+
break; // a gap: later boards would be wrong
|
|
156
|
+
const add = (t, n) => {
|
|
157
|
+
const was = cur.get(t);
|
|
158
|
+
if (was && was[3] !== null)
|
|
159
|
+
cur.set(t, [was[0], was[1], was[2], Math.max(0, was[3] + n)]);
|
|
160
|
+
};
|
|
161
|
+
const wall = (t, m) => {
|
|
162
|
+
const was = cur.get(t);
|
|
163
|
+
// The multiplier unknown: neutral, its armies unknown.
|
|
164
|
+
if (was)
|
|
165
|
+
cur.set(t, [was[0], was[1], 0, was[3] === null || m === undefined ? null : roundHalfDown(was[3] * m)]);
|
|
166
|
+
};
|
|
167
|
+
for (const c of updates) {
|
|
168
|
+
if (c[0] === 'd')
|
|
169
|
+
add(c[1], c[2]);
|
|
170
|
+
else if (c[0] === 'a') {
|
|
171
|
+
add(c[1], -c[3]);
|
|
172
|
+
add(c[2], c[3]);
|
|
173
|
+
}
|
|
174
|
+
else if (c[0] === 'b')
|
|
175
|
+
wall(c[1], walls.blockade);
|
|
176
|
+
else if (c[0] === 'e')
|
|
177
|
+
wall(c[1], walls.abandon);
|
|
178
|
+
else if (c[0] === 'h') {
|
|
179
|
+
const was = cur.get(c[1]);
|
|
180
|
+
if (was && was[3] !== null)
|
|
181
|
+
cur.set(c[1], [was[0], was[1], was[2], Math.floor(was[3] / 2)]);
|
|
182
|
+
}
|
|
183
|
+
else if (typeof c[0] === 'number')
|
|
184
|
+
cur.set(c[0], c);
|
|
185
|
+
}
|
|
186
|
+
snapshot(n + 1);
|
|
187
|
+
}
|
|
188
|
+
return out;
|
|
189
|
+
}
|
|
190
|
+
const FOG_NAMES = { 1: 'You', 2: 'Visible', 3: 'OwnerOnly', 4: 'Fogged' };
|
|
191
|
+
function stateOf([territoryId, fog, owner, armies], byInGame) {
|
|
192
|
+
const fogLevel = FOG_NAMES[fog] ?? String(fog);
|
|
193
|
+
if (fog >= 4)
|
|
194
|
+
return { territoryId, owner: { kind: 'unknown' }, armies: null, fogLevel };
|
|
195
|
+
const o = owner === 0 ? { kind: 'neutral' } : owner > 0 && byInGame.has(owner) ? { kind: 'player', playerId: byInGame.get(owner) } : { kind: 'unknown' };
|
|
196
|
+
return { territoryId, owner: o, armies: fog >= 3 ? null : armies, fogLevel };
|
|
197
|
+
}
|
|
198
|
+
export async function readFogHistory(dir, gameId, playerId) {
|
|
199
|
+
try {
|
|
200
|
+
const v = JSON.parse(await readFile(fogHistoryPath(dir, gameId, playerId), 'utf8'));
|
|
201
|
+
return v && v.version === FOG_HISTORY_VERSION && v.gameId === gameId && v.playerId === playerId && Array.isArray(v.start) && v.turns && typeof v.turns === 'object' ? v : undefined;
|
|
202
|
+
}
|
|
203
|
+
catch {
|
|
204
|
+
return undefined;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
/** Merge a capture into the game's file (a turn read again replaces its updates). `true` when written; never throws. */
|
|
208
|
+
export async function mergeFogHistory(dir, gameId, playerId, got) {
|
|
209
|
+
const path = fogHistoryPath(dir, gameId, playerId);
|
|
210
|
+
try {
|
|
211
|
+
return await withPathLock(path, async () => {
|
|
212
|
+
const was = await readFogHistory(dir, gameId, playerId);
|
|
213
|
+
const start = got.start ?? was?.start;
|
|
214
|
+
if (!start)
|
|
215
|
+
return false;
|
|
216
|
+
const next = { version: FOG_HISTORY_VERSION, gameId, playerId, start, turns: { ...(was?.turns ?? {}), ...got.turns } };
|
|
217
|
+
await mkdir(fogHistoryDir(dir), { recursive: true, mode: 0o700 });
|
|
218
|
+
const tmp = `${path}.${randomUUID()}.tmp`;
|
|
219
|
+
await writeFile(tmp, JSON.stringify(next), { mode: 0o600 });
|
|
220
|
+
await rename(tmp, path);
|
|
221
|
+
await prune(dir);
|
|
222
|
+
return true;
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
catch {
|
|
226
|
+
return false;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
/** Keep at most {@link MAX_FOG_HISTORIES} files, the least recently written dropped. */
|
|
230
|
+
async function prune(dir) {
|
|
231
|
+
const names = (await readdir(fogHistoryDir(dir)).catch(() => [])).filter((n) => /^\d+-\d+\.json$/.test(n));
|
|
232
|
+
if (names.length <= MAX_FOG_HISTORIES)
|
|
233
|
+
return;
|
|
234
|
+
const withTimes = await Promise.all(names.map(async (n) => ({ n, t: (await stat(join(fogHistoryDir(dir), n)).catch(() => undefined))?.mtimeMs ?? 0 })));
|
|
235
|
+
withTimes.sort((a, b) => a.t - b.t);
|
|
236
|
+
for (const { n } of withTimes.slice(0, names.length - MAX_FOG_HISTORIES))
|
|
237
|
+
await rm(join(fogHistoryDir(dir), n), { force: true });
|
|
238
|
+
}
|
|
239
|
+
/** The turns (1-based) up to `completed` a capture still lacks, at most {@link FOG_CAPTURE_TURNS}, ascending. */
|
|
240
|
+
export function missingTurns(h, completed) {
|
|
241
|
+
const out = [];
|
|
242
|
+
for (let n = 1; n <= completed && out.length < FOG_CAPTURE_TURNS; n++)
|
|
243
|
+
if (!h?.turns[String(n)])
|
|
244
|
+
out.push(n);
|
|
245
|
+
return out;
|
|
246
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
// #709: a game's raw GameFeed history, bounded. On a 2,770-territory map, 54 turns of history serialize to ~31 MB, past
|
|
2
|
+
// the 10 MiB a stdio MCP client reads in one message (it then closes the connection and every later call fails). The
|
|
3
|
+
// full and raw views of warapp_get_game therefore carry a window of whole turns: `distributionStanding`, then per turn
|
|
4
|
+
// n its `standing<n>` (the board before turn n) and `turn<n>` (its orders), oldest first, from `from` (default the first)
|
|
5
|
+
// to `to` (default the last), kept while the serialized window stays within `maxChars`. Pure.
|
|
6
|
+
/** The most characters of history one result carries, compact: the raw view indents it (about twice the size) and adds the map, so a result stays near half a client's 10 MiB message. */
|
|
7
|
+
export const HISTORY_MAX_CHARS = 2_500_000;
|
|
8
|
+
const KEY = /^(standing|turn)(\d+)$/;
|
|
9
|
+
/** The history's turn numbers (from its `standing<n>` / `turn<n>` keys), ascending. */
|
|
10
|
+
function turnsOf(history) {
|
|
11
|
+
const out = new Set();
|
|
12
|
+
for (const k of Object.keys(history)) {
|
|
13
|
+
const m = KEY.exec(k);
|
|
14
|
+
if (m)
|
|
15
|
+
out.add(Number(m[2]));
|
|
16
|
+
}
|
|
17
|
+
return [...out].sort((a, b) => a - b);
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* The window of `history` (a GameFeed history object) for turns `from`–`to`, within `maxChars`. Not an object, or no
|
|
21
|
+
* turn keys: returned as it is, with no window. Keys it does not know are kept only with the first window (from the
|
|
22
|
+
* first turn), so nothing is lost across pages.
|
|
23
|
+
*/
|
|
24
|
+
export function historyWindow(history, o = {}) {
|
|
25
|
+
if (!history || typeof history !== 'object' || Array.isArray(history))
|
|
26
|
+
return { history };
|
|
27
|
+
const h = history;
|
|
28
|
+
const turns = turnsOf(h);
|
|
29
|
+
if (!turns.length)
|
|
30
|
+
return { history };
|
|
31
|
+
const max = o.maxChars ?? HISTORY_MAX_CHARS;
|
|
32
|
+
const first = turns[0];
|
|
33
|
+
const last = turns[turns.length - 1];
|
|
34
|
+
const from = Math.max(o.from ?? first, first);
|
|
35
|
+
const to = Math.min(o.to ?? last, last);
|
|
36
|
+
const out = {};
|
|
37
|
+
let chars = 2;
|
|
38
|
+
const add = (k, v) => {
|
|
39
|
+
const size = JSON.stringify(k).length + JSON.stringify(v ?? null).length + 2;
|
|
40
|
+
if (chars + size > max)
|
|
41
|
+
return false;
|
|
42
|
+
out[k] = v;
|
|
43
|
+
chars += size;
|
|
44
|
+
return true;
|
|
45
|
+
};
|
|
46
|
+
const isBoard = (k) => k === 'distributionStanding' || k.startsWith('standing');
|
|
47
|
+
// A turn's orders, filtered to one player when asked.
|
|
48
|
+
const ordersOf = (v) => {
|
|
49
|
+
if (o.player === undefined || !v || typeof v !== 'object' || !Array.isArray(v.orders))
|
|
50
|
+
return v;
|
|
51
|
+
const t = v;
|
|
52
|
+
return { ...t, orders: t.orders.filter((x) => !!x && typeof x === 'object' && String(x.playerID) === o.player) };
|
|
53
|
+
};
|
|
54
|
+
if (from === first)
|
|
55
|
+
for (const [k, v] of Object.entries(h))
|
|
56
|
+
if (!KEY.test(k) && !(o.boards === false && isBoard(k)))
|
|
57
|
+
add(k, v);
|
|
58
|
+
let kept = null;
|
|
59
|
+
let next;
|
|
60
|
+
for (const n of turns) {
|
|
61
|
+
if (n < from || n > to)
|
|
62
|
+
continue;
|
|
63
|
+
const pair = [`standing${n}`, `turn${n}`]
|
|
64
|
+
.filter((k) => k in h && !(o.boards === false && isBoard(k)))
|
|
65
|
+
.map((k) => [k, k.startsWith('turn') ? ordersOf(h[k]) : h[k]]);
|
|
66
|
+
const size = pair.reduce((s, [k, v]) => s + JSON.stringify(k).length + JSON.stringify(v ?? null).length + 2, 0);
|
|
67
|
+
if (chars + size > max) {
|
|
68
|
+
next = n;
|
|
69
|
+
break;
|
|
70
|
+
}
|
|
71
|
+
for (const [k, v] of pair)
|
|
72
|
+
add(k, v);
|
|
73
|
+
kept = { first: kept?.first ?? n, last: n };
|
|
74
|
+
}
|
|
75
|
+
const window = {
|
|
76
|
+
turns: kept,
|
|
77
|
+
of: { first, last },
|
|
78
|
+
...(next !== undefined ? { next } : {}),
|
|
79
|
+
chars,
|
|
80
|
+
...(next !== undefined
|
|
81
|
+
? { note: `The history is too large for one result: turns ${kept ? `${kept.first}–${kept.last}` : 'none'} of ${first}–${last} are here; read on with history_from ${next}.` }
|
|
82
|
+
: {}),
|
|
83
|
+
};
|
|
84
|
+
return { history: out, window };
|
|
85
|
+
}
|
package/dist/protocol/methods.js
CHANGED
|
@@ -846,6 +846,14 @@ export function writeRetrieveChatParams(w, p) {
|
|
|
846
846
|
export function writeRetrievePrivateMessageHistoryParams(w, p) {
|
|
847
847
|
w.int32(p.gameId).string(beforeMarker(p.before)).int32(p.counterpart);
|
|
848
848
|
}
|
|
849
|
+
/**
|
|
850
|
+
* GetTurns(auth, …) — the client's history slider (#568). READ FROM THE CLIENT BUNDLE's writer: the int32 game id, an
|
|
851
|
+
* optional list of int32 turn indexes (0-based; the client asks 0..n−1, at most 1,000 at a time), then a bool (the client
|
|
852
|
+
* sends true). Reply: a result flag, then `GetTurnsReturn` (the starting standing(s), then each turn's `GameTurn`).
|
|
853
|
+
*/
|
|
854
|
+
export function writeGetTurnsParams(w, p) {
|
|
855
|
+
w.int32(p.gameId).bool(true).list(p.turns, (x, t) => x.int32(t)).bool(true);
|
|
856
|
+
}
|
|
849
857
|
/**
|
|
850
858
|
* RetrieveGameGroupMessageHistory(auth, …) — the history button of a game group's chat (#697). READ FROM THE CLIENT
|
|
851
859
|
* BUNDLE's writer, the same as RetrievePrivateMessageHistory's: the int32 game id, the lowest message id received in
|
|
@@ -28,8 +28,9 @@ const yieldToLoop = () => new Promise((resolve) => setImmediate(resolve));
|
|
|
28
28
|
/** Run the harness over `dir`. Never requests. */
|
|
29
29
|
export async function calibrationHarness(dir, opts = {}) {
|
|
30
30
|
const src = await calibrationSources(dir);
|
|
31
|
-
const counts = { histories: src.statuses, skipped: src.skipped, scored: 0, recordOnly: 0, benchmarked: 0, samples: 0 };
|
|
31
|
+
const counts = { histories: src.statuses, skipped: src.skipped, scored: 0, recordOnly: 0, benchmarked: 0, samples: 0, boards: {}, capturedTurns: 0, rebuiltScored: 0, rebuiltSamples: 0 };
|
|
32
32
|
const byFormat = {};
|
|
33
|
+
const rebuiltByFormat = {};
|
|
33
34
|
const benchByFormat = {};
|
|
34
35
|
const eraEntries = [];
|
|
35
36
|
const lossEntries = [];
|
|
@@ -39,6 +40,8 @@ export async function calibrationHarness(dir, opts = {}) {
|
|
|
39
40
|
const { history: h, settings, map, cached } = input;
|
|
40
41
|
if (input.source === 'record-only')
|
|
41
42
|
counts.recordOnly++;
|
|
43
|
+
counts.boards[input.boards] = (counts.boards[input.boards] ?? 0) + 1;
|
|
44
|
+
counts.capturedTurns += input.capturedTurns;
|
|
42
45
|
const me = h.me;
|
|
43
46
|
const graph = graphOf(applyBonusOverrides(map, settings));
|
|
44
47
|
const seated = h.players.filter((p) => holdsSeat(p.state));
|
|
@@ -60,11 +63,18 @@ export async function calibrationHarness(dir, opts = {}) {
|
|
|
60
63
|
players: asPlaying,
|
|
61
64
|
opponents,
|
|
62
65
|
});
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
+
if (input.boards === 'rebuilt') {
|
|
67
|
+
counts.rebuiltSamples += samples.length;
|
|
68
|
+
if (samples.length)
|
|
69
|
+
counts.rebuiltScored++;
|
|
70
|
+
}
|
|
71
|
+
else {
|
|
72
|
+
counts.samples += samples.length;
|
|
73
|
+
if (samples.length)
|
|
74
|
+
counts.scored++;
|
|
75
|
+
}
|
|
66
76
|
const agg = aggregateEstimates(samples);
|
|
67
|
-
const f = (byFormat[format] ??= {});
|
|
77
|
+
const f = ((input.boards === 'rebuilt' ? rebuiltByFormat : byFormat)[format] ??= {});
|
|
68
78
|
for (const [k, c] of Object.entries(agg))
|
|
69
79
|
f[k] = addCalibration(f[k] ?? {}, c);
|
|
70
80
|
const bench = openingBenchmark({
|
|
@@ -112,14 +122,19 @@ export async function calibrationHarness(dir, opts = {}) {
|
|
|
112
122
|
await yieldToLoop();
|
|
113
123
|
}
|
|
114
124
|
opts.signal?.throwIfAborted();
|
|
115
|
-
const
|
|
116
|
-
|
|
117
|
-
for (const [
|
|
118
|
-
for (const [
|
|
119
|
-
(
|
|
125
|
+
const summarize = (from) => {
|
|
126
|
+
const out = {};
|
|
127
|
+
for (const [format, ests] of Object.entries(from))
|
|
128
|
+
for (const [k, c] of Object.entries(ests))
|
|
129
|
+
for (const [band, stats] of Object.entries(c))
|
|
130
|
+
((out[format] ??= {})[k] ??= {})[band] = ratioSummary(stats);
|
|
131
|
+
return out;
|
|
132
|
+
};
|
|
133
|
+
const calibration = summarize(byFormat);
|
|
134
|
+
const calibrationRebuilt = summarize(rebuiltByFormat);
|
|
120
135
|
const benchmark = {};
|
|
121
136
|
for (const [format, list] of Object.entries(benchByFormat))
|
|
122
137
|
benchmark[format] = aggregateBenchmarks(list);
|
|
123
138
|
benchmark.all = aggregateBenchmarks(Object.values(benchByFormat).flat());
|
|
124
|
-
return { counts, calibration, benchmark, byEra: benchmarkByEra(eraEntries), earlyLosses: earlyLossesByEra(lossEntries) };
|
|
139
|
+
return { counts, calibration, calibrationRebuilt, benchmark, byEra: benchmarkByEra(eraEntries), earlyLosses: earlyLossesByEra(lossEntries) };
|
|
125
140
|
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
// #568 (owner decision 2026-12-01): keep my fogged view of every turn of a game while it is played (src/fog-history.ts),
|
|
2
|
+
// by one GetTurns request for the turns not kept yet. warapp_plan_turn starts it alongside the plan's own work and awaits
|
|
3
|
+
// it before answering (so the answer waits for this request at most), never failing the plan; a game not in play, no
|
|
4
|
+
// data dir, or any failure: nothing kept. Never throws.
|
|
5
|
+
import { readFogHistory, missingTurns, mergeFogHistory, readTurnsReturn } from '../fog-history.js';
|
|
6
|
+
import { Method, writeGetTurnsParams } from '../protocol/methods.js';
|
|
7
|
+
import { turnsCompleted } from './common.js';
|
|
8
|
+
const GET_TURNS_RETURN = 'warlight.shared.GetTurnsReturn';
|
|
9
|
+
/** The turns kept by this call (`0`: none needed or none read). */
|
|
10
|
+
export async function captureFogHistory(ctx, game, me) {
|
|
11
|
+
try {
|
|
12
|
+
if (!ctx.dataDir || game.state !== 'Playing')
|
|
13
|
+
return 0;
|
|
14
|
+
const completed = turnsCompleted(game) ?? 0;
|
|
15
|
+
if (completed < 1)
|
|
16
|
+
return 0;
|
|
17
|
+
const have = await readFogHistory(ctx.dataDir, game.id, me);
|
|
18
|
+
const missing = missingTurns(have, completed);
|
|
19
|
+
if (!missing.length)
|
|
20
|
+
return 0;
|
|
21
|
+
const env = await ctx.rpc.call('GetTurns', Method.GetTurns, (w) => writeGetTurnsParams(w, { gameId: game.id, turns: missing.map((n) => n - 1) }));
|
|
22
|
+
if (!env.body.bool())
|
|
23
|
+
return 0;
|
|
24
|
+
const got = readTurnsReturn((await ctx.bundle()).readClass(GET_TURNS_RETURN, env.body));
|
|
25
|
+
if (!got)
|
|
26
|
+
return 0;
|
|
27
|
+
const turns = Object.fromEntries(Object.entries(got.turns).filter(([n]) => Number(n) <= completed));
|
|
28
|
+
if (!Object.keys(turns).length && !got.start)
|
|
29
|
+
return 0;
|
|
30
|
+
return (await mergeFogHistory(ctx.dataDir, game.id, me, { ...(got.start ? { start: got.start } : {}), turns })) ? Object.keys(turns).length : 0;
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
return 0;
|
|
34
|
+
}
|
|
35
|
+
}
|
package/dist/tools/game.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
import { leavers } from '../normalize.js';
|
|
3
3
|
import { recordFinalResult } from '../outlook-log.js';
|
|
4
|
+
import { historyWindow } from '../history-window.js';
|
|
4
5
|
import { historyReport } from '../trend.js';
|
|
5
6
|
import { currentTurn, gameIdArg, mapSummary, readAnnotations, respond, turnsCompleted, untrustedDescription, viewArg } from './common.js';
|
|
6
7
|
import { lookupMeta } from './hints.js';
|
|
@@ -138,14 +139,38 @@ cards) {
|
|
|
138
139
|
.optional()
|
|
139
140
|
.describe('Also fetch past turns (GetHistory; war.app documents it for finished games). The result then says ' +
|
|
140
141
|
'whether the history read (`historyRead`: boards, first and last turn, layout) or why not ' +
|
|
141
|
-
'(`historyUnreadable`: reason and the reply\'s top-level key names); the
|
|
142
|
-
'view "
|
|
142
|
+
'(`historyUnreadable`: reason and the reply\'s top-level key names); the turns themselves only in ' +
|
|
143
|
+
'view "raw", for an analysis of your own, bounded (#709): whole turns, oldest first, while they fit in about 2.5 MB, with ' +
|
|
144
|
+
'`historyWindow` saying which turns came and, when more did not fit, `next` to pass as `history_from`; `history_player` ' +
|
|
145
|
+
'keeps one player\'s orders and `history_boards: false` leaves the boards out. Default false.'),
|
|
143
146
|
include_chat: z.boolean().optional().describe('Also fetch the game chat (GetChat). Default false.'),
|
|
147
|
+
history_from: z.coerce
|
|
148
|
+
.number()
|
|
149
|
+
.int()
|
|
150
|
+
.min(0)
|
|
151
|
+
.optional()
|
|
152
|
+
.describe('With include_history in view "raw": the first turn of history to include (default the first; #709).'),
|
|
153
|
+
history_to: z.coerce
|
|
154
|
+
.number()
|
|
155
|
+
.int()
|
|
156
|
+
.min(0)
|
|
157
|
+
.optional()
|
|
158
|
+
.describe('With include_history in view "raw": the last turn of history to include (default the last).'),
|
|
159
|
+
history_player: z.coerce
|
|
160
|
+
.number()
|
|
161
|
+
.int()
|
|
162
|
+
.positive()
|
|
163
|
+
.optional()
|
|
164
|
+
.describe('With include_history in view "raw": only this player\'s orders (GameFeed id); the boards stay whole.'),
|
|
165
|
+
history_boards: z
|
|
166
|
+
.boolean()
|
|
167
|
+
.optional()
|
|
168
|
+
.describe('With include_history in view "raw": false leaves out the per-turn boards, the orders alone (default true).'),
|
|
144
169
|
view: viewArg(VIEWS, 'compact (default) keeps the game state and turn, players with committed flags, a settings digest and a map ' +
|
|
145
170
|
'summary; "full" is every normalized field (all settings as sent, the board standing) with the map ' +
|
|
146
171
|
'summarized; "raw" is the whole normalized game including the full map.'),
|
|
147
172
|
}),
|
|
148
|
-
}, async ({ game_id, include_history, include_chat, view }) => {
|
|
173
|
+
}, async ({ game_id, include_history, include_chat, view, history_from, history_to, history_player, history_boards }) => {
|
|
149
174
|
const game = await client.getGame(game_id, {
|
|
150
175
|
settings: true,
|
|
151
176
|
...(include_history ? { history: true } : {}),
|
|
@@ -184,12 +209,30 @@ cards) {
|
|
|
184
209
|
// #302: with the history asked for, whether it read, and if not why (key names and counts only).
|
|
185
210
|
const report = include_history ? historyReport(game) : undefined;
|
|
186
211
|
const historyRead = report ? ('read' in report ? { historyRead: report.read } : { historyUnreadable: report.unreadable }) : {};
|
|
212
|
+
// #709: the raw turns bounded to a window a client can read in one message.
|
|
213
|
+
const bounded = () => {
|
|
214
|
+
if (game.history === undefined)
|
|
215
|
+
return { game };
|
|
216
|
+
const w = historyWindow(game.history, {
|
|
217
|
+
...(history_from !== undefined ? { from: history_from } : {}),
|
|
218
|
+
...(history_to !== undefined ? { to: history_to } : {}),
|
|
219
|
+
// The history names players by in-game id: the GameFeed id less two check digits each end.
|
|
220
|
+
...(history_player !== undefined ? { player: String(history_player).slice(2, -2) } : {}),
|
|
221
|
+
...(history_boards === false ? { boards: false } : {}),
|
|
222
|
+
});
|
|
223
|
+
return { game: { ...game, history: w.history }, ...(w.window ? { historyWindow: w.window } : {}) };
|
|
224
|
+
};
|
|
187
225
|
return respond(view, VIEWS, (rung) => {
|
|
188
226
|
if (rung === 'compact')
|
|
189
227
|
return { ...compact(game), ...folded, ...historyRead };
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
228
|
+
// The history is for the server to store and analyse (the end-of-game pass reads it whole); the model gets its
|
|
229
|
+
// summary (`historyRead`) unless it asks for the turns themselves with view "raw" (owner, 2026-12-01).
|
|
230
|
+
if (rung === 'full') {
|
|
231
|
+
const { history: _h, ...rest } = game;
|
|
232
|
+
return { game: { ...rest, map: game.map ? mapSummary(game.map) : undefined }, ...folded, ...historyRead };
|
|
233
|
+
}
|
|
234
|
+
const b = bounded();
|
|
235
|
+
return { game: b.game, ...(b.historyWindow ? { historyWindow: b.historyWindow } : {}) };
|
|
193
236
|
});
|
|
194
237
|
});
|
|
195
238
|
}
|
package/dist/tools/turn.js
CHANGED
|
@@ -100,6 +100,7 @@ import { commanderCheckOn, defaultFoggedCount, foggedAttackersArg, foggedCommand
|
|
|
100
100
|
import { foggedStack, likelyStackAt } from '../analysis/commander-fog.js';
|
|
101
101
|
import { VACATED_FOG_ARMIES } from '../analysis/plan/vacated.js';
|
|
102
102
|
import { nextIncomeLow } from '../analysis/income-range.js';
|
|
103
|
+
import { captureFogHistory } from './fog-capture.js';
|
|
103
104
|
import { incomeRules } from '../analysis/player.js';
|
|
104
105
|
import { recordIncomeLow } from '../decision-log.js';
|
|
105
106
|
import { HEADROOM_COMPACT, headroomView, headroomWarnings, keepTripwires, readTripwires, safeHeadroom, teamsOf, tripwireWarnings, untrustedDeploy } from './survival.js';
|
|
@@ -2678,6 +2679,9 @@ export function registerTurnTools(server, ctx, opts = {}) {
|
|
|
2678
2679
|
nextIncome: plan.expected.nextIncome,
|
|
2679
2680
|
})
|
|
2680
2681
|
: { view: {}, warnings: [] };
|
|
2682
|
+
// #568: my fogged view of every turn kept while the game is played (one GetTurns for the turns not kept yet),
|
|
2683
|
+
// started here so it overlaps the rest of the plan, and awaited before the answer (never failing it).
|
|
2684
|
+
let fogCapture;
|
|
2681
2685
|
// #412: the decision log — this turn's decision (a what-if plan is only an observation of the board,
|
|
2682
2686
|
// never the turn's decision), and the previous turn's outcome from this board and income.
|
|
2683
2687
|
if (ctx.dataDir && turn !== null) {
|
|
@@ -2703,6 +2707,8 @@ export function registerTurnTools(server, ctx, opts = {}) {
|
|
|
2703
2707
|
cards: { hand: handLog(myCards), advice: cardAdviceLog(advice.view) },
|
|
2704
2708
|
times: bootTimes(game),
|
|
2705
2709
|
});
|
|
2710
|
+
if (!whatIf)
|
|
2711
|
+
fogCapture = captureFogHistory(ctx, game, me.id);
|
|
2706
2712
|
}
|
|
2707
2713
|
// B4: the planner does not read what my chat messages promised (words change no estimate), so a
|
|
2708
2714
|
// plan that breaks a commitment still in force says so here; warapp_submit_turn warns again.
|
|
@@ -3167,6 +3173,7 @@ export function registerTurnTools(server, ctx, opts = {}) {
|
|
|
3167
3173
|
const scaleAllies = new Set(teammatesOf(game.players, me).map((p) => p.id));
|
|
3168
3174
|
const scope = opponentScope(graph, seen, me.id, [...new Set([...estimates.map((e) => e.playerId), ...game.players.filter((p) => (p.state ?? 'Playing') === 'Playing').map((p) => p.id)])].filter((p) => p !== me.id && !scaleAllies.has(p)));
|
|
3169
3175
|
const inScope = (p) => !scope.large || scope.near.includes(p);
|
|
3176
|
+
await fogCapture;
|
|
3170
3177
|
return respond(view, VIEWS, (rung) => ({
|
|
3171
3178
|
game: { id: game.id, name: game.name ?? null, turn: currentTurn(game) },
|
|
3172
3179
|
player: { id: me.id, name: me.name },
|
package/dist/version.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// Single source of truth for the server version. release-please bumps the
|
|
2
2
|
// literal on the marked line (registered in release-please-config.json
|
|
3
3
|
// extra-files); every other module imports VERSION from here.
|
|
4
|
-
export const VERSION = '0.
|
|
4
|
+
export const VERSION = '0.27.0'; // x-release-please-version
|