@chrischall/warapp-mcp 0.25.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/cards-in-effect.js +1 -1
- package/dist/analysis/fog-view.js +35 -0
- package/dist/analysis/income-range.js +26 -0
- package/dist/analysis/pacts.js +53 -11
- package/dist/analysis/turn-order.js +145 -0
- package/dist/bundle.js +1160 -513
- package/dist/calibration-source.js +39 -4
- package/dist/decision-log.js +20 -1
- package/dist/fog-history.js +246 -0
- package/dist/history-window.js +85 -0
- package/dist/protocol/methods.js +17 -0
- package/dist/tools/calibration-harness.js +26 -11
- package/dist/tools/chat.js +63 -9
- package/dist/tools/diplomacy.js +8 -3
- package/dist/tools/fog-capture.js +35 -0
- package/dist/tools/game.js +62 -7
- package/dist/tools/relations.js +2 -0
- package/dist/tools/turn-order.js +53 -0
- package/dist/tools/turn.js +59 -3
- package/dist/turn-orders.js +27 -3
- 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())
|
package/dist/decision-log.js
CHANGED
|
@@ -712,13 +712,32 @@ export async function recordCheck(dir, gameId, playerId, turn, summary, opts = {
|
|
|
712
712
|
return false;
|
|
713
713
|
}
|
|
714
714
|
}
|
|
715
|
+
/**
|
|
716
|
+
* #698: keep the low end of the plan's next income on that turn's entry (`incomeLow`; the plan's `nextIncome` is the
|
|
717
|
+
* best case), to be scored against the next turn's income. Only on an entry with a decision. Never throws.
|
|
718
|
+
*/
|
|
719
|
+
export async function recordIncomeLow(dir, gameId, playerId, turn, low, opts = {}) {
|
|
720
|
+
try {
|
|
721
|
+
return await updateDecisionLog(dir, gameId, playerId, (log) => {
|
|
722
|
+
const was = log.turns[String(turn)];
|
|
723
|
+
// A plan logged after the orders went is not logged (recordDecision keeps the sent turn's): neither is its low end.
|
|
724
|
+
if (!was?.decision || was.sent)
|
|
725
|
+
return log;
|
|
726
|
+
const incomeLow = { low: low.low, falls: [...low.falls], belowEstimate: [...low.belowEstimate] };
|
|
727
|
+
return { ...log, turns: { ...log.turns, [String(turn)]: { ...was, incomeLow } } };
|
|
728
|
+
}, opts);
|
|
729
|
+
}
|
|
730
|
+
catch {
|
|
731
|
+
return false;
|
|
732
|
+
}
|
|
733
|
+
}
|
|
715
734
|
/**
|
|
716
735
|
* #570: keep the resolved turn's visible orders on that turn's entry (an entry is started when none exists).
|
|
717
736
|
* Read again, the newest read wins. `true` when written. Never throws.
|
|
718
737
|
*/
|
|
719
738
|
export async function recordSeenTurn(dir, gameId, playerId, seen, opts = {}) {
|
|
720
739
|
try {
|
|
721
|
-
const kept = { orders: seen.orders, ...(seen.omitted ? { omitted: seen.omitted } : {}) };
|
|
740
|
+
const kept = { orders: seen.orders, ...(seen.omitted ? { omitted: seen.omitted } : {}), ...(seen.moveOrder ? { moveOrder: seen.moveOrder } : {}) };
|
|
722
741
|
return await updateDecisionLog(dir, gameId, playerId, (log) => {
|
|
723
742
|
const was = log.turns[String(seen.turn)] ?? {};
|
|
724
743
|
return { ...log, turns: { ...log.turns, [String(seen.turn)]: { ...was, seen: kept } } };
|
|
@@ -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
|
@@ -21,6 +21,7 @@ export const Method = {
|
|
|
21
21
|
RegisterChatView: 44,
|
|
22
22
|
RetrieveChat: 45,
|
|
23
23
|
RetrievePrivateMessageHistory: 46,
|
|
24
|
+
RetrieveGameGroupMessageHistory: 47,
|
|
24
25
|
GetGameSettings: 49,
|
|
25
26
|
GetMyGames: 51,
|
|
26
27
|
AcceptGame: 61,
|
|
@@ -845,6 +846,22 @@ export function writeRetrieveChatParams(w, p) {
|
|
|
845
846
|
export function writeRetrievePrivateMessageHistoryParams(w, p) {
|
|
846
847
|
w.int32(p.gameId).string(beforeMarker(p.before)).int32(p.counterpart);
|
|
847
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
|
+
}
|
|
857
|
+
/**
|
|
858
|
+
* RetrieveGameGroupMessageHistory(auth, …) — the history button of a game group's chat (#697). READ FROM THE CLIENT
|
|
859
|
+
* BUNDLE's writer, the same as RetrievePrivateMessageHistory's: the int32 game id, the lowest message id received in
|
|
860
|
+
* the group (string; 9999E14 when none), the group's int32 id. Reply as RetrieveChat's.
|
|
861
|
+
*/
|
|
862
|
+
export function writeRetrieveGameGroupMessageHistoryParams(w, p) {
|
|
863
|
+
w.int32(p.gameId).string(beforeMarker(p.before)).int32(p.group);
|
|
864
|
+
}
|
|
848
865
|
/**
|
|
849
866
|
* SendChat(auth, …) per docs/WEB-PROTOCOL.md (read from the client's
|
|
850
867
|
* serializer; the owner verifies it live): game id, text, channel, optional
|
|
@@ -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
|
}
|