@chrischall/warapp-mcp 0.6.0 → 0.8.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/README.md +100 -7
- package/dist/analysis/accept-surrender.js +20 -2
- package/dist/analysis/calibrate.js +1 -0
- package/dist/analysis/card-support.js +187 -20
- package/dist/analysis/card-threats.js +68 -3
- package/dist/analysis/chat-advice.js +182 -0
- package/dist/analysis/chat-blocks.js +106 -0
- package/dist/analysis/chat-intent.js +559 -0
- package/dist/analysis/chat-read.js +159 -0
- package/dist/analysis/coalition.js +55 -0
- package/dist/analysis/decision-replay.js +279 -0
- package/dist/analysis/decision-truth.js +146 -0
- package/dist/analysis/finished-game.js +62 -3
- package/dist/analysis/game-lessons.js +12 -6
- package/dist/analysis/local-deploy.js +14 -0
- package/dist/analysis/opponent-profile.js +46 -3
- package/dist/analysis/opponents.js +246 -19
- package/dist/analysis/outlook.js +323 -17
- package/dist/analysis/picks.js +270 -37
- package/dist/analysis/plan/after-leftover.js +28 -3
- package/dist/analysis/plan/captures.js +80 -16
- package/dist/analysis/plan/completed.js +8 -1
- package/dist/analysis/plan/conceded-out.js +16 -11
- package/dist/analysis/plan/deploy-estimates.js +513 -0
- package/dist/analysis/plan/doomed-out.js +135 -0
- package/dist/analysis/plan/estimates.js +73 -7
- package/dist/analysis/plan/free-capture.js +34 -0
- package/dist/analysis/plan/guard-off.js +2 -1
- package/dist/analysis/plan/holds.js +85 -313
- package/dist/analysis/plan/horizon.js +42 -0
- package/dist/analysis/plan/leftover.js +188 -10
- package/dist/analysis/plan/observe.js +896 -0
- package/dist/analysis/plan/orders.js +35 -1
- package/dist/analysis/plan/relations.js +115 -2
- package/dist/analysis/plan/report.js +10 -4
- package/dist/analysis/plan/shared.js +7 -1189
- package/dist/analysis/plan/stand-still.js +7 -5
- package/dist/analysis/plan/state.js +12 -0
- package/dist/analysis/plan/stockpile.js +104 -0
- package/dist/analysis/plan/strike-stack.js +467 -0
- package/dist/analysis/plan/strike.js +8 -441
- package/dist/analysis/plan/targets.js +374 -72
- package/dist/analysis/plan/threats.js +120 -9
- package/dist/analysis/plan/transfers.js +35 -1
- package/dist/analysis/plan/two-move.js +70 -0
- package/dist/analysis/plan/vacated.js +124 -2
- package/dist/analysis/plan/withdraw.js +316 -0
- package/dist/analysis/planner.js +356 -53
- package/dist/analysis/player.js +4 -0
- package/dist/analysis/relations.js +8 -2
- package/dist/analysis/since-last.js +18 -5
- package/dist/analysis/stress.js +1 -1
- package/dist/board.js +36 -2
- package/dist/build-id.js +106 -0
- package/dist/bundle.js +15863 -10242
- package/dist/chat-automation.js +22 -0
- package/dist/client.js +14 -0
- package/dist/decision-log.js +1093 -0
- package/dist/finished-store.js +5 -1
- package/dist/lessons-store.js +322 -21
- package/dist/my-games.js +2 -0
- package/dist/open-games.js +122 -18
- package/dist/outlook-log.js +42 -1
- package/dist/protocol/methods.js +4 -2
- package/dist/review-export.js +198 -0
- package/dist/state-bundle.js +62 -3
- package/dist/state-cli.js +5 -3
- package/dist/strategy/notes.js +56 -0
- package/dist/tools/accept-surrender.js +23 -9
- package/dist/tools/award.js +5 -1
- package/dist/tools/card-advice.js +102 -33
- package/dist/tools/card-support-advice.js +53 -8
- package/dist/tools/chat-advice.js +330 -0
- package/dist/tools/chat-inbox.js +15 -4
- package/dist/tools/chat.js +41 -11
- package/dist/tools/check-plan.js +16 -3
- package/dist/tools/commander-check.js +2 -1
- package/dist/tools/decision-capture.js +461 -0
- package/dist/tools/end-of-game.js +146 -18
- package/dist/tools/game-kind.js +92 -0
- package/dist/tools/how-lost.js +7 -2
- package/dist/tools/index.js +3 -0
- package/dist/tools/join-game.js +51 -9
- package/dist/tools/live-context.js +6 -0
- package/dist/tools/live.js +43 -6
- package/dist/tools/map-curves.js +73 -0
- package/dist/tools/notifications.js +4 -3
- package/dist/tools/open-games.js +2 -2
- package/dist/tools/opponents.js +2 -0
- package/dist/tools/past-games.js +74 -8
- package/dist/tools/picks.js +169 -57
- package/dist/tools/profile-hook.js +62 -3
- package/dist/tools/profile-opponents.js +2 -0
- package/dist/tools/push.js +2 -2
- package/dist/tools/relations.js +2 -0
- package/dist/tools/scout.js +16 -2
- package/dist/tools/state.js +6 -1
- package/dist/tools/strategy.js +3 -3
- package/dist/tools/stress-opponents.js +2 -0
- package/dist/tools/surrender-pending.js +10 -1
- package/dist/tools/surrender.js +18 -3
- package/dist/tools/turn.js +353 -19
- package/dist/tools/where.js +3 -1
- package/dist/version.js +1 -1
- package/manifest.json +23 -2
- package/mint.yaml +23 -0
- package/package.json +1 -1
- package/server.json +20 -2
- package/skills/warapp-mcp/SKILL.md +42 -8
|
@@ -0,0 +1,1093 @@
|
|
|
1
|
+
// The decision log (#412): per game, an entry for every turn the account plays. A turn this server
|
|
2
|
+
// planned is a full entry: what was seen (the fogged board), what the planner read and decided and why,
|
|
3
|
+
// what was actually sent (and any override), and what happened next. Any other turn the server sees (a
|
|
4
|
+
// board read live or filled from history) gets at least an observation entry (`kind: 'observed'`: the
|
|
5
|
+
// board, plus what was sent when known), which a later plan of that turn upgrades and which never
|
|
6
|
+
// overwrites a planned entry. It is the data strategy changes and scenarios are replayed against offline
|
|
7
|
+
// (src/analysis/decision-replay.ts, scripts/replay-decisions.mjs).
|
|
8
|
+
//
|
|
9
|
+
// `<dataDir>/decisions/<gameId>.json`: `{ version: 1, gameId, playerId, status, turns }`, one account's
|
|
10
|
+
// view per game. Name-free: player ids and the map's own territory and bonus names only; every player
|
|
11
|
+
// name the caller passes is scrubbed from every string (and a `name` field holding one is dropped).
|
|
12
|
+
// Boards are delta-encoded against the previous logged turn's board (the territories whose owner,
|
|
13
|
+
// armies, fog or units changed), with a full board at the first logged turn and every
|
|
14
|
+
// FULL_BOARD_EVERY turns after the last full one, so any turn rebuilds (`boardAt`). The planner's
|
|
15
|
+
// input is kept without what the map store and the board give back (the graph, the board) and without
|
|
16
|
+
// what `planTurn` sets itself; Maps and Sets are tagged so `decodeInput` restores them.
|
|
17
|
+
//
|
|
18
|
+
// 0600 in a 0700 folder, written atomically under the in-process path lock; best effort (never throws
|
|
19
|
+
// into a tool); a file that exists but does not parse, or carries another `version` (or none: a newer
|
|
20
|
+
// build's, say, sharing the data dir), is never overwritten, listed or pruned. The header (`version`,
|
|
21
|
+
// `gameId`, `playerId`, `status`) is always written before `turns`, so listing reads only the head of each
|
|
22
|
+
// file (`HEAD_BYTES`), never a whole log. At most MAX_DECISION_GAMES games and MAX_DECISION_BYTES in all
|
|
23
|
+
// (`pruneDecisionLogs`: the oldest finished games first, never one still running; a log is parsed whole
|
|
24
|
+
// only just before it is deleted; `pruneDecisionLogs` runs after a write at most once per
|
|
25
|
+
// DECISION_PRUNE_INTERVAL_MS per data dir). `WARAPP_DECISION_LOG=off` writes nothing; `full` keeps every
|
|
26
|
+
// turn whole (no compaction).
|
|
27
|
+
//
|
|
28
|
+
// Once a game is finished (the end-of-game pass, src/tools/end-of-game.ts) every turn of the game gets its
|
|
29
|
+
// `truth` from the full history and every logged turn its `accuracy` (`recordTruth`; pure part
|
|
30
|
+
// src/analysis/decision-truth.ts), then the log is compacted (`compactDecisionLog`): no-gaps rule (b) —
|
|
31
|
+
// every turn keeps its board, decision, sent orders, override, `next`, `truth` and `accuracy`; only the
|
|
32
|
+
// replay `input` of an uninteresting turn is dropped.
|
|
33
|
+
//
|
|
34
|
+
// #437 (v2, additive: the `version` stays 1 and an entry written before these reads as it is): each turn
|
|
35
|
+
// also carries the build beside `planner.version` (`build`: the git commit of a checkout, else a hash of the
|
|
36
|
+
// bundle), its wall-clock `times` (`plannedAt`, `sentAt`, the turn's start and boot deadlines when the game
|
|
37
|
+
// read gives them — this log may hold wall-clock times), the plan's `firstMover`, the `cards` (my hand by
|
|
38
|
+
// type, the advice offered by kind, target ids and a reason code, and what was played), and the `checks`
|
|
39
|
+
// (the submit's commander check, weakest headroom rows, below-plan rows and chat warnings; and the latest
|
|
40
|
+
// warapp_check_plan summary). All small, all kept through compaction.
|
|
41
|
+
//
|
|
42
|
+
// #437 task 2 (additive too): per game, `events` (`{ turn, kind, player?, detail?, at }`, at most
|
|
43
|
+
// MAX_GAME_EVENTS, the newest kept and `eventsDropped` counting the rest): a seat's state change diffed against
|
|
44
|
+
// the last states seen (`seats`, by GameFeed id: booted, surrender-accepted, eliminated, ended-by-vote,
|
|
45
|
+
// turned-ai, any other non-playing state as `seat-state` with its word), a pending surrender seen, my acceptance
|
|
46
|
+
// of one and my own surrender (with my income, the strongest opponent's income and the outlook state the outlook
|
|
47
|
+
// log held then) — never twice for the same change; `join` (the lobby's settings key and readable flags and the
|
|
48
|
+
// joining policy's checks by code); and `opponents` (per GameFeed id the turn first seen, an AI seat, and the
|
|
49
|
+
// level and ranked record when warapp_scout_player read them). A log may hold only these (a lobby joined): the
|
|
50
|
+
// end-of-game passes finish and compact it like any other.
|
|
51
|
+
//
|
|
52
|
+
// #437 task 3 (additive too): per game, `picks` — the pick advisor's summary (`advice`: ids, the top scores,
|
|
53
|
+
// warning codes, the award orders judged and the worst outcome, coverage and any alternative; a re-plan
|
|
54
|
+
// replaces it, `advices` counting the plans), the list warapp_submit_picks sent and war.app read back
|
|
55
|
+
// (`submitted`, the latest send wins, `submits` counting them) and the award read on turn 1 (`award`, written
|
|
56
|
+
// once). All ids and numbers, kept through compaction.
|
|
57
|
+
import { open, readdir, readFile, stat, unlink } from 'node:fs/promises';
|
|
58
|
+
import { join } from 'node:path';
|
|
59
|
+
import { estimateOff } from './analysis/decision-truth.js';
|
|
60
|
+
import { writeJsonAtomic } from './map-store.js';
|
|
61
|
+
import { withPathLock } from './path-lock.js';
|
|
62
|
+
import { serverBuild } from './build-id.js';
|
|
63
|
+
import { VERSION } from './version.js';
|
|
64
|
+
export const DECISION_LOG_VERSION = 1;
|
|
65
|
+
/** Games whose decision logs are kept at most. */
|
|
66
|
+
export const MAX_DECISION_GAMES = 1000;
|
|
67
|
+
/** Bytes of decision logs kept at most, all games together. */
|
|
68
|
+
export const MAX_DECISION_BYTES = 500 * 1024 * 1024;
|
|
69
|
+
/** A full board at least this many turns after the last full one (and at the first logged turn). */
|
|
70
|
+
export const FULL_BOARD_EVERY = 10;
|
|
71
|
+
/** The post-write prune runs at most once per this interval per data dir. */
|
|
72
|
+
export const DECISION_PRUNE_INTERVAL_MS = 10 * 60_000;
|
|
73
|
+
const isRec = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
74
|
+
const isInt = (v) => typeof v === 'number' && Number.isSafeInteger(v);
|
|
75
|
+
export const decisionsDir = (dir) => join(dir, 'decisions');
|
|
76
|
+
export const decisionLogPath = (dir, gameId) => join(decisionsDir(dir), `${gameId}.json`);
|
|
77
|
+
const DECISION_FILE = /^(\d{1,12})\.json$/;
|
|
78
|
+
/** Bytes read from the head of a log to list it: the header comes first, so this always covers it. */
|
|
79
|
+
const HEAD_BYTES = 512;
|
|
80
|
+
export function decisionLogMode(env = process.env) {
|
|
81
|
+
const v = env.WARAPP_DECISION_LOG?.trim().toLowerCase();
|
|
82
|
+
return v === 'off' ? 'off' : v === 'full' ? 'full' : 'on';
|
|
83
|
+
}
|
|
84
|
+
/** The keys of `PlanInput` that are not kept in {@link LoggedInput}. */
|
|
85
|
+
const INPUT_DROPPED = new Set(['graph', 'board', 'vacated', 'bonusPush', 'previousBoard']);
|
|
86
|
+
/** Chat messages kept per turn at most. */
|
|
87
|
+
export const MAX_LOGGED_CHAT = 50;
|
|
88
|
+
/** Game events kept at most per log (the newest). */
|
|
89
|
+
export const MAX_GAME_EVENTS = 500;
|
|
90
|
+
const iso = (ms) => new Date(ms ?? Date.now()).toISOString();
|
|
91
|
+
// ---------------------------------------------------------------------------------------------
|
|
92
|
+
// Encoding
|
|
93
|
+
/** Maps and Sets tagged, undefined and functions dropped: JSON-safe and reversible. */
|
|
94
|
+
export function encodeValue(v) {
|
|
95
|
+
if (v instanceof Map)
|
|
96
|
+
return { $map: [...v].map(([k, x]) => [encodeValue(k), encodeValue(x)]) };
|
|
97
|
+
if (v instanceof Set)
|
|
98
|
+
return { $set: [...v].map(encodeValue) };
|
|
99
|
+
if (Array.isArray(v))
|
|
100
|
+
return v.map((x) => (x === undefined ? null : encodeValue(x)));
|
|
101
|
+
if (isRec(v)) {
|
|
102
|
+
const out = {};
|
|
103
|
+
for (const [k, x] of Object.entries(v)) {
|
|
104
|
+
if (x === undefined || typeof x === 'function')
|
|
105
|
+
continue;
|
|
106
|
+
out[k] = encodeValue(x);
|
|
107
|
+
}
|
|
108
|
+
return out;
|
|
109
|
+
}
|
|
110
|
+
return typeof v === 'number' && !Number.isFinite(v) ? null : v;
|
|
111
|
+
}
|
|
112
|
+
/** The reverse of {@link encodeValue}. */
|
|
113
|
+
export function decodeValue(v) {
|
|
114
|
+
if (Array.isArray(v))
|
|
115
|
+
return v.map(decodeValue);
|
|
116
|
+
if (isRec(v)) {
|
|
117
|
+
const keys = Object.keys(v);
|
|
118
|
+
if (keys.length === 1 && Array.isArray(v.$map)) {
|
|
119
|
+
return new Map(v.$map.filter(Array.isArray).map((p) => [decodeValue(p[0]), decodeValue(p[1])]));
|
|
120
|
+
}
|
|
121
|
+
if (keys.length === 1 && Array.isArray(v.$set))
|
|
122
|
+
return new Set(v.$set.map(decodeValue));
|
|
123
|
+
const out = {};
|
|
124
|
+
for (const [k, x] of Object.entries(v))
|
|
125
|
+
out[k] = decodeValue(x);
|
|
126
|
+
return out;
|
|
127
|
+
}
|
|
128
|
+
return v;
|
|
129
|
+
}
|
|
130
|
+
const plainBoard = (b) => ({ source: b.source, verified: b.verified, territories: b.territories });
|
|
131
|
+
/** The territories of `now` that differ from `base` (or are not on it), and the ids `base` has that `now` lacks. */
|
|
132
|
+
function diff(base, now) {
|
|
133
|
+
const was = new Map(base.territories.map((x) => [x.territoryId, JSON.stringify(x)]));
|
|
134
|
+
const changed = now.territories.filter((x) => was.get(x.territoryId) !== JSON.stringify(x));
|
|
135
|
+
const ids = new Set(now.territories.map((x) => x.territoryId));
|
|
136
|
+
const removed = base.territories.map((x) => x.territoryId).filter((id) => !ids.has(id));
|
|
137
|
+
return { changed, ...(removed.length ? { removed } : {}) };
|
|
138
|
+
}
|
|
139
|
+
/** `base` with `d` applied, territories in `base`'s order then new ones by id. */
|
|
140
|
+
function patch(base, d) {
|
|
141
|
+
const changed = new Map(d.changed.map((x) => [x.territoryId, x]));
|
|
142
|
+
const removed = new Set(d.removed ?? []);
|
|
143
|
+
const kept = base.territories.filter((x) => !removed.has(x.territoryId)).map((x) => changed.get(x.territoryId) ?? x);
|
|
144
|
+
const known = new Set(base.territories.map((x) => x.territoryId));
|
|
145
|
+
const added = d.changed.filter((x) => !known.has(x.territoryId));
|
|
146
|
+
return { source: d.source, verified: d.verified, territories: [...kept, ...added] };
|
|
147
|
+
}
|
|
148
|
+
const turnKeys = (turns) => Object.keys(turns)
|
|
149
|
+
.filter((k) => /^\d+$/.test(k))
|
|
150
|
+
.map(Number)
|
|
151
|
+
.sort((a, b) => a - b);
|
|
152
|
+
/** The board seen on `turn`, rebuilt; `undefined` when the turn keeps none or its chain is broken. */
|
|
153
|
+
export function boardAt(log, turn, depth = 0) {
|
|
154
|
+
const b = log.turns[String(turn)]?.board;
|
|
155
|
+
if (!b || depth > 10_000)
|
|
156
|
+
return undefined;
|
|
157
|
+
if (b.kind === 'full')
|
|
158
|
+
return { source: b.source, verified: b.verified, territories: b.territories };
|
|
159
|
+
if (b.base >= turn)
|
|
160
|
+
return undefined;
|
|
161
|
+
const base = boardAt(log, b.base, depth + 1);
|
|
162
|
+
return base ? patch(base, b) : undefined;
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Re-encode every kept board of `turns` from `boards` (turn → whole board): full at the first and at
|
|
166
|
+
* least every {@link FULL_BOARD_EVERY} turns, else a delta on the previous turn that keeps a board.
|
|
167
|
+
* Turns not in `boards` keep no board. Mutates `turns`.
|
|
168
|
+
*/
|
|
169
|
+
export function encodeBoards(turns, boards) {
|
|
170
|
+
let prev;
|
|
171
|
+
let lastFull = Number.NEGATIVE_INFINITY;
|
|
172
|
+
for (const turn of turnKeys(turns)) {
|
|
173
|
+
const entry = turns[String(turn)];
|
|
174
|
+
const board = boards.get(turn);
|
|
175
|
+
if (!board) {
|
|
176
|
+
delete entry.board;
|
|
177
|
+
continue;
|
|
178
|
+
}
|
|
179
|
+
if (!prev || turn - lastFull >= FULL_BOARD_EVERY) {
|
|
180
|
+
entry.board = { kind: 'full', source: board.source, verified: board.verified, territories: board.territories };
|
|
181
|
+
lastFull = turn;
|
|
182
|
+
}
|
|
183
|
+
else {
|
|
184
|
+
entry.board = { kind: 'delta', base: prev.turn, source: board.source, verified: board.verified, ...diff(prev.board, board) };
|
|
185
|
+
}
|
|
186
|
+
prev = { turn, board };
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
/** Every kept board of `log`, whole, by turn. */
|
|
190
|
+
export function decodeBoards(log) {
|
|
191
|
+
const out = new Map();
|
|
192
|
+
for (const turn of turnKeys(log.turns)) {
|
|
193
|
+
const b = boardAt(log, turn);
|
|
194
|
+
if (b)
|
|
195
|
+
out.set(turn, b);
|
|
196
|
+
}
|
|
197
|
+
return out;
|
|
198
|
+
}
|
|
199
|
+
/** The input as kept (see {@link LoggedInput}). */
|
|
200
|
+
export function encodeInput(input) {
|
|
201
|
+
const out = {};
|
|
202
|
+
for (const [k, v] of Object.entries(input)) {
|
|
203
|
+
if (INPUT_DROPPED.has(k) || v === undefined)
|
|
204
|
+
continue;
|
|
205
|
+
out[k] = encodeValue(v);
|
|
206
|
+
}
|
|
207
|
+
if (input.board.teammateOrders)
|
|
208
|
+
out.teammateOrders = encodeValue(input.board.teammateOrders);
|
|
209
|
+
if (input.previousBoard) {
|
|
210
|
+
const prev = plainBoard(input.previousBoard);
|
|
211
|
+
out.previousBoard = { source: prev.source, verified: prev.verified, ...diff(plainBoard(input.board), prev) };
|
|
212
|
+
}
|
|
213
|
+
return out;
|
|
214
|
+
}
|
|
215
|
+
/** The planner's input rebuilt from a kept one, this turn's board and the map's graph. */
|
|
216
|
+
export function decodeInput(logged, board, graph) {
|
|
217
|
+
const { previousBoard, teammateOrders, plannedBoard, ...rest } = logged;
|
|
218
|
+
const out = decodeValue(rest);
|
|
219
|
+
const planned = isRec(plannedBoard) && Array.isArray(plannedBoard.changed) ? patch(board, plannedBoard) : board;
|
|
220
|
+
return {
|
|
221
|
+
...out,
|
|
222
|
+
graph,
|
|
223
|
+
board: Array.isArray(teammateOrders) ? { ...planned, teammateOrders: decodeValue(teammateOrders) } : planned,
|
|
224
|
+
...(isRec(previousBoard) && Array.isArray(previousBoard.changed) ? { previousBoard: patch(board, previousBoard) } : {}),
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
/** The estimates as logged: ids, figures and flags only. */
|
|
228
|
+
export function loggedEstimates(estimates) {
|
|
229
|
+
return [...estimates]
|
|
230
|
+
.sort((a, b) => a.playerId - b.playerId)
|
|
231
|
+
.map((e) => ({ player: e.playerId, estimate: e.estimate, source: e.source, coverage: e.coverage?.share ?? null, thin: !!e.thinEvidence }));
|
|
232
|
+
}
|
|
233
|
+
/** My income as `input` gives it, card armies out; `undefined` when it holds none. */
|
|
234
|
+
function earnedIncome(input) {
|
|
235
|
+
const { income, cardArmies } = (input ?? {});
|
|
236
|
+
if (typeof income !== 'number')
|
|
237
|
+
return undefined;
|
|
238
|
+
return income - (typeof cardArmies === 'number' ? cardArmies : 0);
|
|
239
|
+
}
|
|
240
|
+
function decisionOf(plan, outlook, outlookLean, estimates, income) {
|
|
241
|
+
return encodeValue({
|
|
242
|
+
goal: plan.goal,
|
|
243
|
+
profile: plan.profile,
|
|
244
|
+
deploys: plan.deploys,
|
|
245
|
+
moves: plan.moves,
|
|
246
|
+
expected: plan.expected,
|
|
247
|
+
conceded: plan.conceded,
|
|
248
|
+
offence: plan.offence,
|
|
249
|
+
enemyDeploy: plan.enemyDeploy,
|
|
250
|
+
cardAdvice: plan.cardAdvice,
|
|
251
|
+
rationale: plan.rationale,
|
|
252
|
+
warnings: plan.warnings,
|
|
253
|
+
outlook: outlook ?? null,
|
|
254
|
+
...(outlookLean ? { outlookLean } : {}),
|
|
255
|
+
...(estimates ? { estimates: loggedEstimates(estimates) } : {}),
|
|
256
|
+
...(income !== undefined ? { income } : {}),
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
260
|
+
/**
|
|
261
|
+
* `v` with every player name in `players` replaced by `Player <id>` in every string, and every `name`
|
|
262
|
+
* field holding one dropped. A name is matched only standing alone (no letter, digit or `_` either side), so
|
|
263
|
+
* a short name never rewrites part of a territory or bonus name. Names shorter than two characters are left.
|
|
264
|
+
*/
|
|
265
|
+
export function scrubNames(v, players) {
|
|
266
|
+
const named = (players ?? [])
|
|
267
|
+
.filter((p) => typeof p.name === 'string' && p.name.trim().length >= 2)
|
|
268
|
+
.map((p) => ({ id: p.id, name: p.name.trim() }))
|
|
269
|
+
.sort((a, b) => b.name.length - a.name.length);
|
|
270
|
+
if (!named.length)
|
|
271
|
+
return v;
|
|
272
|
+
const byName = new Set(named.map((p) => p.name.toLowerCase()));
|
|
273
|
+
const res = named.map((p) => ({ re: new RegExp(`(?<![\\p{L}\\p{N}_])(?:Player )?${escapeRe(p.name)}(?![\\p{L}\\p{N}_])`, 'giu'), to: `Player ${p.id}` }));
|
|
274
|
+
const walk = (x) => {
|
|
275
|
+
if (typeof x === 'string')
|
|
276
|
+
return res.reduce((s, r) => s.replace(r.re, r.to), x);
|
|
277
|
+
if (Array.isArray(x))
|
|
278
|
+
return x.map(walk);
|
|
279
|
+
if (isRec(x)) {
|
|
280
|
+
const out = {};
|
|
281
|
+
for (const [k, y] of Object.entries(x)) {
|
|
282
|
+
if (k === 'name' && typeof y === 'string' && byName.has(y.trim().toLowerCase()))
|
|
283
|
+
continue;
|
|
284
|
+
out[k] = walk(y);
|
|
285
|
+
}
|
|
286
|
+
return out;
|
|
287
|
+
}
|
|
288
|
+
return x;
|
|
289
|
+
};
|
|
290
|
+
return walk(v);
|
|
291
|
+
}
|
|
292
|
+
function logOf(c, gameId) {
|
|
293
|
+
if (!isRec(c) || c.version !== DECISION_LOG_VERSION || c.gameId !== gameId || !isInt(c.playerId) || !isRec(c.turns))
|
|
294
|
+
return undefined;
|
|
295
|
+
const status = c.status === 'finished' || c.status === 'compacted' ? c.status : 'active';
|
|
296
|
+
return {
|
|
297
|
+
version: DECISION_LOG_VERSION,
|
|
298
|
+
gameId,
|
|
299
|
+
playerId: c.playerId,
|
|
300
|
+
status,
|
|
301
|
+
turns: c.turns,
|
|
302
|
+
...(isRec(c.accuracySummary) ? { accuracySummary: c.accuracySummary } : {}),
|
|
303
|
+
...(Array.isArray(c.truthMissing) ? { truthMissing: c.truthMissing.filter(isInt) } : {}),
|
|
304
|
+
...(Array.isArray(c.events) ? { events: c.events.filter(isRec) } : {}),
|
|
305
|
+
...(isInt(c.eventsDropped) ? { eventsDropped: c.eventsDropped } : {}),
|
|
306
|
+
...(isRec(c.seats) ? { seats: c.seats } : {}),
|
|
307
|
+
...(isRec(c.join) ? { join: c.join } : {}),
|
|
308
|
+
...(isRec(c.opponents) ? { opponents: c.opponents } : {}),
|
|
309
|
+
...(isRec(c.picks) ? { picks: c.picks } : {}),
|
|
310
|
+
};
|
|
311
|
+
}
|
|
312
|
+
/** Whether a log holds anything: a turn, or per-game context (#437). */
|
|
313
|
+
export const hasContent = (log) => Object.keys(log.turns).length > 0 || !!log.events?.length || !!log.join || !!log.seats || !!log.opponents || !!log.picks;
|
|
314
|
+
async function readRaw(dir, gameId) {
|
|
315
|
+
let text;
|
|
316
|
+
try {
|
|
317
|
+
text = await readFile(decisionLogPath(dir, gameId), 'utf8');
|
|
318
|
+
}
|
|
319
|
+
catch (e) {
|
|
320
|
+
return e?.code === 'ENOENT' ? { kind: 'absent' } : { kind: 'unreadable' };
|
|
321
|
+
}
|
|
322
|
+
try {
|
|
323
|
+
const log = logOf(JSON.parse(text), gameId);
|
|
324
|
+
return log ? { kind: 'log', log } : { kind: 'unreadable' };
|
|
325
|
+
}
|
|
326
|
+
catch {
|
|
327
|
+
return { kind: 'unreadable' };
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
/** The log of `gameId` (only `playerId`'s when given); `undefined` when absent, unusable or another's. Never throws. */
|
|
331
|
+
export async function readDecisionLog(dir, gameId, playerId) {
|
|
332
|
+
const r = await readRaw(dir, gameId);
|
|
333
|
+
if (r.kind !== 'log' || (playerId !== undefined && r.log.playerId !== playerId))
|
|
334
|
+
return undefined;
|
|
335
|
+
return r.log;
|
|
336
|
+
}
|
|
337
|
+
/**
|
|
338
|
+
* Read, change and write `gameId`'s log as `playerId` under the path lock. `mutate` gets the log (a new
|
|
339
|
+
* empty one when none exists) and returns the log to write, or `undefined` to write nothing. `true` when
|
|
340
|
+
* written. Never writes over a file that does not parse or another account's log. Never throws.
|
|
341
|
+
*/
|
|
342
|
+
export async function updateDecisionLog(dir, gameId, playerId, mutate, opts = {}) {
|
|
343
|
+
if ((opts.mode ?? decisionLogMode()) === 'off')
|
|
344
|
+
return false;
|
|
345
|
+
const path = decisionLogPath(dir, gameId);
|
|
346
|
+
try {
|
|
347
|
+
const written = await withPathLock(path, async () => {
|
|
348
|
+
const r = await readRaw(dir, gameId);
|
|
349
|
+
if (r.kind === 'unreadable')
|
|
350
|
+
return false;
|
|
351
|
+
if (r.kind === 'log' && r.log.playerId !== playerId)
|
|
352
|
+
return false;
|
|
353
|
+
const current = r.kind === 'log' ? r.log : { version: DECISION_LOG_VERSION, gameId, playerId, status: 'active', turns: {} };
|
|
354
|
+
const next = mutate(current);
|
|
355
|
+
if (!next)
|
|
356
|
+
return false;
|
|
357
|
+
// The header first: listing reads only the head of the file.
|
|
358
|
+
const { version: _v, gameId: _g, playerId: _p, status, turns, ...rest } = next;
|
|
359
|
+
await writeJsonAtomic(path, decisionsDir(dir), { version: DECISION_LOG_VERSION, gameId, playerId, status, turns, ...rest });
|
|
360
|
+
return true;
|
|
361
|
+
});
|
|
362
|
+
// Outside the lock: the prune takes each log's own lock.
|
|
363
|
+
if (written)
|
|
364
|
+
await prunedAfterWrite(dir, opts.caps);
|
|
365
|
+
return written;
|
|
366
|
+
}
|
|
367
|
+
catch {
|
|
368
|
+
return false;
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
/** When each data dir's post-write prune last ran (this process). */
|
|
372
|
+
const lastPrune = new Map();
|
|
373
|
+
/** {@link pruneDecisionLogs} at most once per {@link DECISION_PRUNE_INTERVAL_MS} per data dir. Never throws. */
|
|
374
|
+
async function prunedAfterWrite(dir, caps) {
|
|
375
|
+
const now = Date.now();
|
|
376
|
+
const last = lastPrune.get(dir);
|
|
377
|
+
if (last !== undefined && now - last < DECISION_PRUNE_INTERVAL_MS)
|
|
378
|
+
return;
|
|
379
|
+
lastPrune.set(dir, now);
|
|
380
|
+
if (lastPrune.size > 100)
|
|
381
|
+
lastPrune.delete(lastPrune.keys().next().value);
|
|
382
|
+
await pruneDecisionLogs(dir, caps).catch(() => undefined);
|
|
383
|
+
}
|
|
384
|
+
/**
|
|
385
|
+
* Log the turn planned, replacing any entry for that turn — unless its orders were already sent: then
|
|
386
|
+
* the entry stays as it is (decision, sent orders, override, board), since a plan made after the
|
|
387
|
+
* orders went out did not choose them, and nothing re-sends them (no-gaps rule). Name-free: every name
|
|
388
|
+
* in `rec.players` is scrubbed. `true` when written (`false` for a turn already sent). Never throws.
|
|
389
|
+
*/
|
|
390
|
+
export async function recordDecision(dir, gameId, playerId, rec, opts = {}) {
|
|
391
|
+
try {
|
|
392
|
+
const board = plainBoard(rec.board);
|
|
393
|
+
const teammateOrders = rec.input.board.teammateOrders ?? rec.board.teammateOrders;
|
|
394
|
+
const input = encodeInput({ ...rec.input, board: teammateOrders ? { ...board, teammateOrders } : board });
|
|
395
|
+
if (rec.plannedBoard) {
|
|
396
|
+
const d = diff(board, plainBoard(rec.plannedBoard));
|
|
397
|
+
if (d.changed.length || d.removed)
|
|
398
|
+
input.plannedBoard = { source: rec.plannedBoard.source, verified: rec.plannedBoard.verified, ...d };
|
|
399
|
+
}
|
|
400
|
+
const build = serverBuild();
|
|
401
|
+
const entry = scrubNames({
|
|
402
|
+
kind: 'planned',
|
|
403
|
+
input,
|
|
404
|
+
planner: { version: VERSION, ...(build ? { build } : {}) },
|
|
405
|
+
decision: decisionOf(rec.plan, rec.outlookState, rec.outlookLean, rec.estimates, earnedIncome(rec.input)),
|
|
406
|
+
times: encodeValue({ plannedAt: iso(rec.now), ...rec.times }),
|
|
407
|
+
...(rec.firstMover !== undefined ? { firstMover: rec.firstMover ? { ...rec.firstMover } : null } : {}),
|
|
408
|
+
...(rec.cards ? { cards: encodeValue(rec.cards) } : {}),
|
|
409
|
+
}, rec.players);
|
|
410
|
+
return await updateDecisionLog(dir, gameId, playerId, (log) => {
|
|
411
|
+
const was = log.turns[String(rec.turn)];
|
|
412
|
+
if (was?.sent)
|
|
413
|
+
return undefined;
|
|
414
|
+
const boards = decodeBoards(log);
|
|
415
|
+
boards.set(rec.turn, board);
|
|
416
|
+
// #415: the chat read on the turn outlives a re-plan of it; #437: a warapp_check_plan run before this plan keeps its summary.
|
|
417
|
+
const turns = {
|
|
418
|
+
...log.turns,
|
|
419
|
+
[String(rec.turn)]: { ...entry, ...(was?.chat ? { chat: was.chat } : {}), ...(was?.checks ? { checks: was.checks } : {}) },
|
|
420
|
+
};
|
|
421
|
+
encodeBoards(turns, boards);
|
|
422
|
+
return { ...log, turns };
|
|
423
|
+
}, opts);
|
|
424
|
+
}
|
|
425
|
+
catch {
|
|
426
|
+
return false;
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
/**
|
|
430
|
+
* Log the boards of turns seen but not planned (no-gaps rule (a)), in one write: an observation entry
|
|
431
|
+
* each, keeping any sent orders and override already logged for the turn. Never overwrites a planned
|
|
432
|
+
* entry, and a board filled from history never replaces a board already logged (a live one is the
|
|
433
|
+
* better view); a later {@link recordDecision} of the turn upgrades it. `true` when written (`false`
|
|
434
|
+
* when nothing was new). Never throws.
|
|
435
|
+
*/
|
|
436
|
+
export async function recordObservations(dir, gameId, playerId, seen, opts = {}) {
|
|
437
|
+
try {
|
|
438
|
+
const items = seen.map((o) => ({ turn: o.turn, board: plainBoard(o.board), source: o.source }));
|
|
439
|
+
if (!items.length)
|
|
440
|
+
return false;
|
|
441
|
+
return await updateDecisionLog(dir, gameId, playerId, (log) => {
|
|
442
|
+
const turns = { ...log.turns };
|
|
443
|
+
const boards = decodeBoards(log);
|
|
444
|
+
let changed = false;
|
|
445
|
+
for (const o of items) {
|
|
446
|
+
const was = turns[String(o.turn)];
|
|
447
|
+
if (was?.kind === 'planned' || was?.decision)
|
|
448
|
+
continue;
|
|
449
|
+
if (o.source === 'history' && was?.board)
|
|
450
|
+
continue;
|
|
451
|
+
boards.set(o.turn, o.board);
|
|
452
|
+
turns[String(o.turn)] = { ...was, kind: 'observed', source: o.source };
|
|
453
|
+
changed = true;
|
|
454
|
+
}
|
|
455
|
+
if (!changed)
|
|
456
|
+
return undefined;
|
|
457
|
+
encodeBoards(turns, boards);
|
|
458
|
+
return { ...log, turns };
|
|
459
|
+
}, opts);
|
|
460
|
+
}
|
|
461
|
+
catch {
|
|
462
|
+
return false;
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
/** {@link recordObservations} of one board. */
|
|
466
|
+
export async function recordObservation(dir, gameId, playerId, turn, board, source, opts = {}) {
|
|
467
|
+
return recordObservations(dir, gameId, playerId, [{ turn, board, source }], opts);
|
|
468
|
+
}
|
|
469
|
+
/**
|
|
470
|
+
* Log the orders actually sent on `turn`, with `override` when they differ from the decision (or came
|
|
471
|
+
* from outside the planner). Starts an entry when the turn has none. Name-free: every name in
|
|
472
|
+
* `opts.players` is scrubbed from the override's reason. `true` when written. Never throws.
|
|
473
|
+
*/
|
|
474
|
+
export async function recordSent(dir, gameId, playerId, turn, sent, override, opts = {}) {
|
|
475
|
+
const kept = encodeValue(sent);
|
|
476
|
+
const ov = override
|
|
477
|
+
? { by: override.by, ...(override.reason !== undefined ? { reason: scrubNames(String(override.reason), opts.players) } : {}) }
|
|
478
|
+
: undefined;
|
|
479
|
+
return updateDecisionLog(dir, gameId, playerId, (log) => {
|
|
480
|
+
const { override: _old, ...was } = log.turns[String(turn)] ?? {};
|
|
481
|
+
const times = { ...was.times, sentAt: iso(undefined) };
|
|
482
|
+
return { ...log, turns: { ...log.turns, [String(turn)]: { ...was, sent: kept, times, ...(ov ? { override: ov } : {}) } } };
|
|
483
|
+
}, opts);
|
|
484
|
+
}
|
|
485
|
+
const CHAT_CHANNELS_LOGGED = new Set(['public', 'team', 'private', 'unknown']);
|
|
486
|
+
const CONFIDENCES = new Set(['high', 'medium', 'low']);
|
|
487
|
+
/** A chat entry as kept: only its known fields, each checked (no text, no name). */
|
|
488
|
+
function keptChat(m) {
|
|
489
|
+
if (!isRec(m))
|
|
490
|
+
return undefined;
|
|
491
|
+
const channel = CHAT_CHANNELS_LOGGED.has(m.channel) ? m.channel : 'unknown';
|
|
492
|
+
return {
|
|
493
|
+
...(typeof m.id === 'string' && m.id.length <= 40 ? { id: m.id } : {}),
|
|
494
|
+
...(typeof m.time === 'string' && m.time.length <= 40 ? { time: m.time } : {}),
|
|
495
|
+
...(isInt(m.turn) ? { turn: m.turn } : {}),
|
|
496
|
+
from: isInt(m.from) ? m.from : null,
|
|
497
|
+
channel,
|
|
498
|
+
toMe: m.toMe === true,
|
|
499
|
+
intents: Array.isArray(m.intents) ? m.intents.filter((i) => typeof i === 'string' && /^[a-z-]{1,30}$/.test(i)) : [],
|
|
500
|
+
confidence: CONFIDENCES.has(m.confidence) ? m.confidence : 'low',
|
|
501
|
+
...(typeof m.stance === 'string' && /^[a-z]{1,20}$/.test(m.stance) ? { stance: m.stance } : {}),
|
|
502
|
+
...(typeof m.blocks === 'boolean' ? { blocks: m.blocks } : {}),
|
|
503
|
+
};
|
|
504
|
+
}
|
|
505
|
+
const chatKey = (m) => `${m.id ?? ''}|${m.time ?? ''}|${m.from ?? ''}|${m.channel}|${m.turn ?? ''}`;
|
|
506
|
+
/**
|
|
507
|
+
* Add the chat read on `turn` to its entry (#415): merged with what is there by message (a later reading of the
|
|
508
|
+
* same message replaces it), at most {@link MAX_LOGGED_CHAT} (the newest). Nothing when the turn has no entry or
|
|
509
|
+
* nothing is given. Ids and labels only. `true` when written. Never throws.
|
|
510
|
+
*/
|
|
511
|
+
export async function recordChat(dir, gameId, playerId, turn, chat, opts = {}) {
|
|
512
|
+
try {
|
|
513
|
+
const kept = chat.map(keptChat).filter((m) => m !== undefined);
|
|
514
|
+
if (!kept.length)
|
|
515
|
+
return false;
|
|
516
|
+
return await updateDecisionLog(dir, gameId, playerId, (log) => {
|
|
517
|
+
const e = log.turns[String(turn)];
|
|
518
|
+
if (!e)
|
|
519
|
+
return undefined;
|
|
520
|
+
const merged = new Map((e.chat ?? []).map((m) => [chatKey(m), m]));
|
|
521
|
+
for (const m of kept) {
|
|
522
|
+
// A later reading replaces the message's fields, keeping those it does not give; a block flag alone (the
|
|
523
|
+
// submit's, #415 task 4b) only sets `blocks` on the plan's reading of the message.
|
|
524
|
+
const was = merged.get(chatKey(m));
|
|
525
|
+
merged.delete(chatKey(m));
|
|
526
|
+
merged.set(chatKey(m), was ? (opts.blockFlagOnly ? { ...was, blocks: m.blocks } : { ...was, ...m }) : m);
|
|
527
|
+
}
|
|
528
|
+
return { ...log, turns: { ...log.turns, [String(turn)]: { ...e, chat: [...merged.values()].slice(-MAX_LOGGED_CHAT) } } };
|
|
529
|
+
}, opts);
|
|
530
|
+
}
|
|
531
|
+
catch {
|
|
532
|
+
return false;
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
/** Fill what happened after `turn`; nothing when the turn has no entry. `true` when written. Never throws. */
|
|
536
|
+
export async function recordOutcome(dir, gameId, playerId, turn, next, opts = {}) {
|
|
537
|
+
const kept = encodeValue(next);
|
|
538
|
+
return updateDecisionLog(dir, gameId, playerId, (log) => {
|
|
539
|
+
const e = log.turns[String(turn)];
|
|
540
|
+
return e ? { ...log, turns: { ...log.turns, [String(turn)]: { ...e, next: kept } } } : undefined;
|
|
541
|
+
}, opts);
|
|
542
|
+
}
|
|
543
|
+
/**
|
|
544
|
+
* Fill what happened after `turn` with `make(entry, board)` (the turn's own entry and its rebuilt board),
|
|
545
|
+
* under one lock: nothing when the turn has no entry, already has its outcome, or `make` gives none.
|
|
546
|
+
* `true` when written. Never throws.
|
|
547
|
+
*/
|
|
548
|
+
export async function fillOutcome(dir, gameId, playerId, turn, make, opts = {}) {
|
|
549
|
+
return updateDecisionLog(dir, gameId, playerId, (log) => {
|
|
550
|
+
const e = log.turns[String(turn)];
|
|
551
|
+
if (!e || e.next)
|
|
552
|
+
return undefined;
|
|
553
|
+
const next = make(e, boardAt(log, turn));
|
|
554
|
+
return next ? { ...log, turns: { ...log.turns, [String(turn)]: { ...e, next: encodeValue(next) } } } : undefined;
|
|
555
|
+
}, opts);
|
|
556
|
+
}
|
|
557
|
+
const mine = (b, me) => new Set(b.territories.flatMap((x) => (x.owner.kind === 'player' && x.owner.playerId === me ? [x.territoryId] : [])));
|
|
558
|
+
const byNum = (a, b) => a - b;
|
|
559
|
+
/**
|
|
560
|
+
* What happened after a turn, from its board (`before`) and the following turn's (`after`): the income
|
|
561
|
+
* then (`null`: unread), the territories gained and lost, which of the plan's `captures` I held, the
|
|
562
|
+
* bonuses (id → every member territory) I held in full, and whether I had no territory left.
|
|
563
|
+
*/
|
|
564
|
+
export function decisionOutcome(a) {
|
|
565
|
+
const now = mine(a.after, a.me);
|
|
566
|
+
const was = a.before ? mine(a.before, a.me) : undefined;
|
|
567
|
+
return {
|
|
568
|
+
income: a.income,
|
|
569
|
+
gained: was ? [...now].filter((id) => !was.has(id)).sort(byNum) : [],
|
|
570
|
+
lost: was ? [...was].filter((id) => !now.has(id)).sort(byNum) : [],
|
|
571
|
+
capturesMade: a.captures.filter((id) => now.has(id)),
|
|
572
|
+
capturesMissed: a.captures.filter((id) => !now.has(id)),
|
|
573
|
+
capturesMissedTo: a.captures.flatMap((id) => {
|
|
574
|
+
const o = now.has(id) ? undefined : a.after.territories.find((x) => x.territoryId === id)?.owner;
|
|
575
|
+
return o?.kind === 'player' ? [{ territoryId: id, owner: o.playerId }] : [];
|
|
576
|
+
}),
|
|
577
|
+
bonusesHeld: [...a.bonuses]
|
|
578
|
+
.filter(([, ts]) => ts.length > 0 && ts.every((id) => now.has(id)))
|
|
579
|
+
.map(([id]) => id)
|
|
580
|
+
.sort(byNum),
|
|
581
|
+
eliminated: now.size === 0,
|
|
582
|
+
};
|
|
583
|
+
}
|
|
584
|
+
/**
|
|
585
|
+
* Whether the orders sent differ from a decision's: the deploys compared per territory (merged, in any
|
|
586
|
+
* order), the moves one by one in the order sent, the commander flag included (a planned commander move
|
|
587
|
+
* sent without it, or the reverse, differs); a percentage or mode move always differs. Card plays are
|
|
588
|
+
* not compared (the planner plays none).
|
|
589
|
+
*/
|
|
590
|
+
export function ordersDiffer(decision, sent) {
|
|
591
|
+
const sum = (ds) => {
|
|
592
|
+
const m = new Map();
|
|
593
|
+
for (const d of ds)
|
|
594
|
+
m.set(d.territoryId, (m.get(d.territoryId) ?? 0) + d.armies);
|
|
595
|
+
return JSON.stringify([...m].filter(([, n]) => n !== 0).sort(([x], [y]) => x - y));
|
|
596
|
+
};
|
|
597
|
+
if (sum(decision.deploys) !== sum(sent.deploys))
|
|
598
|
+
return true;
|
|
599
|
+
if (decision.moves.length !== sent.moves.length)
|
|
600
|
+
return true;
|
|
601
|
+
return sent.moves.some((m, i) => {
|
|
602
|
+
const d = decision.moves[i];
|
|
603
|
+
return m.exact === false || m.from !== d.from || m.to !== d.to || m.armies !== d.armies || !!m.commander !== !!d.commander;
|
|
604
|
+
});
|
|
605
|
+
}
|
|
606
|
+
/** #437: the cards a turn's sent orders played (by name) and how many they discarded. */
|
|
607
|
+
const playedOf = (sent) => ({
|
|
608
|
+
played: (sent.cards ?? []).map((c) => c.card),
|
|
609
|
+
discarded: (sent.discards ?? []).length,
|
|
610
|
+
});
|
|
611
|
+
/**
|
|
612
|
+
* Log the orders sent on `turn` (one lock: read, compare, write). Against a logged decision an override
|
|
613
|
+
* is kept only when the orders differ (`by` the agent unless said); with no decision logged, only when
|
|
614
|
+
* the caller says who chose them or why (`by` hand unless said): orders from outside the planner. An
|
|
615
|
+
* entry (an observation's board, say) keeps everything else; a turn with none gets one. `true` when
|
|
616
|
+
* written. Never throws.
|
|
617
|
+
*/
|
|
618
|
+
export async function recordSubmission(dir, gameId, playerId, turn, sub, opts = {}) {
|
|
619
|
+
try {
|
|
620
|
+
const kept = encodeValue(sub.sent);
|
|
621
|
+
const reason = sub.reason !== undefined ? scrubNames(String(sub.reason), sub.players) : undefined;
|
|
622
|
+
return await updateDecisionLog(dir, gameId, playerId, (log) => {
|
|
623
|
+
const { override: _old, ...was } = log.turns[String(turn)] ?? {};
|
|
624
|
+
const decided = was.decision;
|
|
625
|
+
const by = decided ? (ordersDiffer(decided, sub.orders) ? (sub.by ?? 'agent') : undefined) : sub.by !== undefined || reason !== undefined ? (sub.by ?? 'hand') : undefined;
|
|
626
|
+
const override = by ? { by, ...(reason !== undefined ? { reason } : {}) } : undefined;
|
|
627
|
+
const times = { ...was.times, sentAt: iso(sub.now) };
|
|
628
|
+
const cards = { ...was.cards, ...playedOf(kept) };
|
|
629
|
+
const checks = sub.checks ? { ...was.checks, submit: encodeValue(sub.checks) } : was.checks;
|
|
630
|
+
return {
|
|
631
|
+
...log,
|
|
632
|
+
turns: { ...log.turns, [String(turn)]: { ...was, sent: kept, times, cards, ...(checks ? { checks } : {}), ...(override ? { override } : {}) } },
|
|
633
|
+
};
|
|
634
|
+
}, opts);
|
|
635
|
+
}
|
|
636
|
+
catch {
|
|
637
|
+
return false;
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
/**
|
|
641
|
+
* #437: log warapp_check_plan's summary for `turn` (the latest run wins), starting an entry when the turn
|
|
642
|
+
* has none; everything else on the entry is kept. `true` when written. Never throws.
|
|
643
|
+
*/
|
|
644
|
+
export async function recordCheck(dir, gameId, playerId, turn, summary, opts = {}) {
|
|
645
|
+
try {
|
|
646
|
+
const kept = encodeValue(summary);
|
|
647
|
+
return await updateDecisionLog(dir, gameId, playerId, (log) => {
|
|
648
|
+
const was = log.turns[String(turn)] ?? {};
|
|
649
|
+
return { ...log, turns: { ...log.turns, [String(turn)]: { ...was, checks: { ...was.checks, checkPlan: kept } } } };
|
|
650
|
+
}, opts);
|
|
651
|
+
}
|
|
652
|
+
catch {
|
|
653
|
+
return false;
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
// ---------------------------------------------------------------------------------------------
|
|
657
|
+
// #437 task 2: per-game events and context
|
|
658
|
+
/** States in which a seat's change is no event (still in, or not yet in). */
|
|
659
|
+
const QUIET_STATES = new Set(['Playing', 'Invited']);
|
|
660
|
+
const SEAT_KINDS = {
|
|
661
|
+
Booted: 'booted',
|
|
662
|
+
SurrenderAccepted: 'surrender-accepted',
|
|
663
|
+
Eliminated: 'eliminated',
|
|
664
|
+
EndedByVote: 'ended-by-vote',
|
|
665
|
+
};
|
|
666
|
+
/** A state word as kept: a plain word, else `other` (never free text). */
|
|
667
|
+
const stateWord = (s) => (s === undefined ? null : /^[A-Za-z]{1,40}$/.test(s) ? s : 'other');
|
|
668
|
+
/**
|
|
669
|
+
* The seat events between the states last seen (`was`; none: first sight, when a seat already out is an
|
|
670
|
+
* event too) and `players` now, and the states to keep (seats no longer listed kept as they were). Pure.
|
|
671
|
+
*/
|
|
672
|
+
export function seatEvents(was, players, turn, now = Date.now()) {
|
|
673
|
+
const at = iso(now);
|
|
674
|
+
const events = [];
|
|
675
|
+
const seats = { ...was };
|
|
676
|
+
for (const p of players) {
|
|
677
|
+
const next = { state: stateWord(p.state), ai: !!p.humanTurnedIntoAI };
|
|
678
|
+
const prev = was?.[String(p.id)];
|
|
679
|
+
if (next.state !== null && next.state !== prev?.state && !QUIET_STATES.has(next.state)) {
|
|
680
|
+
const kind = SEAT_KINDS[next.state];
|
|
681
|
+
events.push(kind ? { turn, kind, player: p.id, at } : { turn, kind: 'seat-state', player: p.id, detail: next.state, at });
|
|
682
|
+
}
|
|
683
|
+
if (next.ai && !prev?.ai)
|
|
684
|
+
events.push({ turn, kind: 'turned-ai', player: p.id, at });
|
|
685
|
+
seats[String(p.id)] = next;
|
|
686
|
+
}
|
|
687
|
+
return { events, seats };
|
|
688
|
+
}
|
|
689
|
+
/** `log` with `events` appended, the newest {@link MAX_GAME_EVENTS} kept. */
|
|
690
|
+
function withEvents(log, events) {
|
|
691
|
+
if (!events.length)
|
|
692
|
+
return log;
|
|
693
|
+
const all = [...(log.events ?? []), ...events];
|
|
694
|
+
const drop = Math.max(0, all.length - MAX_GAME_EVENTS);
|
|
695
|
+
return {
|
|
696
|
+
...log,
|
|
697
|
+
events: all.slice(drop),
|
|
698
|
+
...(drop || log.eventsDropped ? { eventsDropped: (log.eventsDropped ?? 0) + drop } : {}),
|
|
699
|
+
};
|
|
700
|
+
}
|
|
701
|
+
/**
|
|
702
|
+
* Log the seat events since the states last seen, keep the states, and add every other seat not seen
|
|
703
|
+
* before to `opponents` (the turn, and `ai` for an AI seat). Writes only on a change. `true` when written.
|
|
704
|
+
* Never throws.
|
|
705
|
+
*/
|
|
706
|
+
export async function recordSeats(dir, gameId, playerId, rec, opts = {}) {
|
|
707
|
+
try {
|
|
708
|
+
return await updateDecisionLog(dir, gameId, playerId, (log) => {
|
|
709
|
+
if (!rec.create && !hasContent(log))
|
|
710
|
+
return undefined;
|
|
711
|
+
const { events, seats } = seatEvents(log.seats, rec.players, rec.turn, rec.now);
|
|
712
|
+
const opponents = { ...log.opponents };
|
|
713
|
+
let met = false;
|
|
714
|
+
for (const p of rec.players) {
|
|
715
|
+
if (p.id === playerId || opponents[String(p.id)])
|
|
716
|
+
continue;
|
|
717
|
+
opponents[String(p.id)] = { firstSeen: rec.turn, ...(p.isAI ? { ai: true } : {}) };
|
|
718
|
+
met = true;
|
|
719
|
+
}
|
|
720
|
+
const same = !!log.seats && JSON.stringify(seats) === JSON.stringify(log.seats);
|
|
721
|
+
if (same && !events.length && !met && hasContent(log))
|
|
722
|
+
return undefined;
|
|
723
|
+
return withEvents({ ...log, seats, ...(Object.keys(opponents).length ? { opponents } : {}) }, events);
|
|
724
|
+
}, opts);
|
|
725
|
+
}
|
|
726
|
+
catch {
|
|
727
|
+
return false;
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
/** What makes two events the same change: a kind and player, and my surrender's status. */
|
|
731
|
+
const eventKey = (e) => `${e.kind}:${e.player ?? ''}:${e.kind === 'my-surrender' && typeof e.detail === 'object' ? e.detail.status : ''}`;
|
|
732
|
+
/**
|
|
733
|
+
* Log one event (a pending surrender seen, my acceptance, my own surrender), never twice for the same
|
|
734
|
+
* change ({@link eventKey}). Starts a log only with `create`. `true` when written. Never throws.
|
|
735
|
+
*/
|
|
736
|
+
export async function recordGameEvent(dir, gameId, playerId, ev, o = {}, opts = {}) {
|
|
737
|
+
try {
|
|
738
|
+
const { now, ...rest } = ev;
|
|
739
|
+
const event = encodeValue({ ...rest, at: iso(now) });
|
|
740
|
+
const key = eventKey(event);
|
|
741
|
+
return await updateDecisionLog(dir, gameId, playerId, (log) => {
|
|
742
|
+
if (!o.create && !hasContent(log))
|
|
743
|
+
return undefined;
|
|
744
|
+
if ((log.events ?? []).some((e) => eventKey(e) === key))
|
|
745
|
+
return undefined;
|
|
746
|
+
return withEvents(log, [event]);
|
|
747
|
+
}, opts);
|
|
748
|
+
}
|
|
749
|
+
catch {
|
|
750
|
+
return false;
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
/** Keep the lobby joined (the latest join wins), starting a log when the game has none. `true` when written. Never throws. */
|
|
754
|
+
export async function recordJoin(dir, gameId, playerId, join, opts = {}) {
|
|
755
|
+
try {
|
|
756
|
+
const kept = encodeValue(join);
|
|
757
|
+
return await updateDecisionLog(dir, gameId, playerId, (log) => ({ ...log, join: kept }), opts);
|
|
758
|
+
}
|
|
759
|
+
catch {
|
|
760
|
+
return false;
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
/**
|
|
764
|
+
* Keep what a tool read of opponent `player` (the latest read wins) in a log that exists; a seat not seen
|
|
765
|
+
* before is first seen on the read's turn. `true` when written. Never throws.
|
|
766
|
+
*/
|
|
767
|
+
export async function recordOpponentRead(dir, gameId, playerId, player, read, opts = {}) {
|
|
768
|
+
if (player === playerId)
|
|
769
|
+
return false;
|
|
770
|
+
try {
|
|
771
|
+
return await updateDecisionLog(dir, gameId, playerId, (log) => {
|
|
772
|
+
if (!hasContent(log))
|
|
773
|
+
return undefined;
|
|
774
|
+
const was = log.opponents?.[String(player)];
|
|
775
|
+
const next = encodeValue({
|
|
776
|
+
...was,
|
|
777
|
+
firstSeen: was?.firstSeen ?? read.turn,
|
|
778
|
+
level: read.level,
|
|
779
|
+
ranked: read.ranked,
|
|
780
|
+
...(read.bootRatePct !== undefined ? { bootRatePct: read.bootRatePct } : {}),
|
|
781
|
+
readTurn: read.turn,
|
|
782
|
+
});
|
|
783
|
+
return { ...log, opponents: { ...log.opponents, [String(player)]: next } };
|
|
784
|
+
}, opts);
|
|
785
|
+
}
|
|
786
|
+
catch {
|
|
787
|
+
return false;
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
// ---------------------------------------------------------------------------------------------
|
|
791
|
+
// #437 task 3: the picks phase
|
|
792
|
+
/** Keep the pick advisor's summary (a re-plan replaces it), starting a log when the game has none. `true` when written. Never throws. */
|
|
793
|
+
export async function recordPicksAdvice(dir, gameId, playerId, advice, opts = {}) {
|
|
794
|
+
try {
|
|
795
|
+
const kept = encodeValue(advice);
|
|
796
|
+
return await updateDecisionLog(dir, gameId, playerId, (log) => ({ ...log, picks: { ...log.picks, advice: kept, advices: (log.picks?.advices ?? 0) + 1 } }), opts);
|
|
797
|
+
}
|
|
798
|
+
catch {
|
|
799
|
+
return false;
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
/** Keep the list warapp_submit_picks sent and read back (the latest send wins), starting a log when none. `true` when written. Never throws. */
|
|
803
|
+
export async function recordPicksSent(dir, gameId, playerId, sent, opts = {}) {
|
|
804
|
+
try {
|
|
805
|
+
const { now, ...rest } = sent;
|
|
806
|
+
const kept = encodeValue({ at: iso(now), ...rest });
|
|
807
|
+
return await updateDecisionLog(dir, gameId, playerId, (log) => ({ ...log, picks: { ...log.picks, submitted: kept, submits: (log.picks?.submits ?? 0) + 1 } }), opts);
|
|
808
|
+
}
|
|
809
|
+
catch {
|
|
810
|
+
return false;
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
/** Keep the award read on turn 1, once (never over one kept), starting a log when none. `true` when written. Never throws. */
|
|
814
|
+
export async function recordPicksAward(dir, gameId, playerId, award, opts = {}) {
|
|
815
|
+
try {
|
|
816
|
+
const { now, ...rest } = award;
|
|
817
|
+
const kept = encodeValue({ at: iso(now), ...rest });
|
|
818
|
+
return await updateDecisionLog(dir, gameId, playerId, (log) => (log.picks?.award ? undefined : { ...log, picks: { ...log.picks, award: kept } }), opts);
|
|
819
|
+
}
|
|
820
|
+
catch {
|
|
821
|
+
return false;
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
// ---------------------------------------------------------------------------------------------
|
|
825
|
+
// The end of a game: truth, accuracy and compaction
|
|
826
|
+
/**
|
|
827
|
+
* #454: a decision's finer outlook reading — its lean beside an even state, else its state (a decision #453 logged
|
|
828
|
+
* with the lean as the state reads alike). `null` with none.
|
|
829
|
+
*/
|
|
830
|
+
export function decisionReading(d) {
|
|
831
|
+
return d?.outlookLean ?? d?.outlook ?? null;
|
|
832
|
+
}
|
|
833
|
+
/** What each turn of `log` offers the truth's scoring: its board, logged outlook, estimates and income. */
|
|
834
|
+
export function loggedTurns(log) {
|
|
835
|
+
const out = new Map();
|
|
836
|
+
for (const turn of turnKeys(log.turns)) {
|
|
837
|
+
const e = log.turns[String(turn)];
|
|
838
|
+
if (!e.board && !e.decision)
|
|
839
|
+
continue;
|
|
840
|
+
const board = boardAt(log, turn);
|
|
841
|
+
// The decision's income first: compaction never drops it (an entry written before it was kept
|
|
842
|
+
// there falls back to the input; compaction copies it into the decision before dropping that).
|
|
843
|
+
const income = e.decision?.income ?? earnedIncome(e.input) ?? log.turns[String(turn - 1)]?.next?.income ?? null;
|
|
844
|
+
out.set(turn, {
|
|
845
|
+
...(board ? { board } : {}),
|
|
846
|
+
outlook: decisionReading(e.decision),
|
|
847
|
+
estimates: e.decision?.estimates ?? [],
|
|
848
|
+
myIncome: typeof income === 'number' ? income : null,
|
|
849
|
+
});
|
|
850
|
+
}
|
|
851
|
+
return out;
|
|
852
|
+
}
|
|
853
|
+
/**
|
|
854
|
+
* Write the end-of-game truth (no-gaps rule (c)): `make` gets what each logged turn offers and returns
|
|
855
|
+
* the truth (src/analysis/decision-truth.ts); every turn it covers gets its `truth` (a turn with no
|
|
856
|
+
* entry, a truth-only entry), every logged turn its `accuracy`, the log its `accuracySummary` and
|
|
857
|
+
* `truthMissing`, and status `finished` (a compacted log stays compacted). Starts no log: a game with
|
|
858
|
+
* none, or with truth only, gets nothing. Running it again replaces what it wrote. `true` when written.
|
|
859
|
+
* Never throws.
|
|
860
|
+
*/
|
|
861
|
+
export async function recordTruth(dir, gameId, playerId, make, opts = {}) {
|
|
862
|
+
return updateDecisionLog(dir, gameId, playerId, (log) => {
|
|
863
|
+
// No turn logged (no log, or truth only): nothing to score, and a truth-only file per finished game
|
|
864
|
+
// would crowd real logs out of the prune's budget. Gaps inside a log still get truth-only entries.
|
|
865
|
+
if (!Object.values(log.turns).some((e) => Object.keys(e).some((k) => k !== 'truth' && k !== 'accuracy')))
|
|
866
|
+
return undefined;
|
|
867
|
+
const r = make(loggedTurns(log));
|
|
868
|
+
if (!r)
|
|
869
|
+
return undefined;
|
|
870
|
+
const turns = {};
|
|
871
|
+
for (const [k, e] of Object.entries(log.turns)) {
|
|
872
|
+
const { truth: _t, accuracy: _a, ...rest } = e;
|
|
873
|
+
if (Object.keys(rest).length)
|
|
874
|
+
turns[k] = rest;
|
|
875
|
+
}
|
|
876
|
+
for (const [turn, truth] of r.truth)
|
|
877
|
+
turns[String(turn)] = { ...turns[String(turn)], truth: encodeValue(truth) };
|
|
878
|
+
for (const [turn, accuracy] of r.accuracy)
|
|
879
|
+
if (turns[String(turn)])
|
|
880
|
+
turns[String(turn)].accuracy = encodeValue(accuracy);
|
|
881
|
+
return {
|
|
882
|
+
...log,
|
|
883
|
+
status: log.status === 'compacted' ? 'compacted' : 'finished',
|
|
884
|
+
turns,
|
|
885
|
+
accuracySummary: encodeValue(r.summary),
|
|
886
|
+
truthMissing: [...r.missing],
|
|
887
|
+
};
|
|
888
|
+
}, opts);
|
|
889
|
+
}
|
|
890
|
+
/** Turns kept whole before a loss or an elimination, and from the start of the game. */
|
|
891
|
+
export const KEEP_BEFORE_LOSS = 5;
|
|
892
|
+
export const KEEP_FIRST = 3;
|
|
893
|
+
/** Next income this far below the plan's expectation (a share of it) keeps the turn whole. */
|
|
894
|
+
export const INCOME_SHORTFALL = 0.2;
|
|
895
|
+
/**
|
|
896
|
+
* The turns whose replay input compaction keeps (#412 task 3): any override; a turn whose outlook state
|
|
897
|
+
* changed from the previous decided turn's; the {@link KEEP_BEFORE_LOSS} decided turns up to an
|
|
898
|
+
* elimination (and, with `lost`, the last ones of the game); the first {@link KEEP_FIRST} decided turns;
|
|
899
|
+
* a turn whose next income fell short of the expected by {@link INCOME_SHORTFALL} or more; a turn whose
|
|
900
|
+
* accuracy shows an estimate off by more than 1.5× or under 0.5×. Reads nothing compaction drops, so it
|
|
901
|
+
* gives the same answer before and after. Pure.
|
|
902
|
+
*/
|
|
903
|
+
export function interestingTurns(log, opts = {}) {
|
|
904
|
+
const decided = turnKeys(log.turns).filter((t) => log.turns[String(t)].decision);
|
|
905
|
+
const out = new Set(decided.slice(0, KEEP_FIRST));
|
|
906
|
+
const lastBefore = (i) => decided.slice(Math.max(0, i - KEEP_BEFORE_LOSS + 1), i + 1).forEach((t) => out.add(t));
|
|
907
|
+
if (opts.lost && decided.length)
|
|
908
|
+
lastBefore(decided.length - 1);
|
|
909
|
+
let prevOutlook;
|
|
910
|
+
decided.forEach((turn, i) => {
|
|
911
|
+
const e = log.turns[String(turn)];
|
|
912
|
+
const outlook = decisionReading(e.decision);
|
|
913
|
+
if (i > 0 && outlook !== prevOutlook)
|
|
914
|
+
out.add(turn);
|
|
915
|
+
prevOutlook = outlook;
|
|
916
|
+
if (e.override)
|
|
917
|
+
out.add(turn);
|
|
918
|
+
if (e.next?.eliminated)
|
|
919
|
+
lastBefore(i);
|
|
920
|
+
const expected = e.decision.expected?.nextIncome;
|
|
921
|
+
if (typeof expected === 'number' && expected > 0 && typeof e.next?.income === 'number' && e.next.income <= expected * (1 - INCOME_SHORTFALL))
|
|
922
|
+
out.add(turn);
|
|
923
|
+
if (estimateOff(e.accuracy))
|
|
924
|
+
out.add(turn);
|
|
925
|
+
});
|
|
926
|
+
// An entry that is not decided (sent orders only, say) keeps its override's turn too.
|
|
927
|
+
for (const t of turnKeys(log.turns))
|
|
928
|
+
if (log.turns[String(t)].override)
|
|
929
|
+
out.add(t);
|
|
930
|
+
return out;
|
|
931
|
+
}
|
|
932
|
+
/**
|
|
933
|
+
* `log` compacted: every uninteresting turn's `input` dropped, everything else kept; status `compacted`.
|
|
934
|
+
* A decision written without its `income` gets it from the input first, so the truth reads the same
|
|
935
|
+
* income after compaction as before. Pure.
|
|
936
|
+
*/
|
|
937
|
+
export function compactLog(log, opts = {}) {
|
|
938
|
+
const keep = interestingTurns(log, opts);
|
|
939
|
+
const turns = {};
|
|
940
|
+
for (const [k, e] of Object.entries(log.turns)) {
|
|
941
|
+
if (e.input && !keep.has(Number(k))) {
|
|
942
|
+
const { input, ...rest } = e;
|
|
943
|
+
const income = earnedIncome(input);
|
|
944
|
+
turns[k] = rest.decision && rest.decision.income === undefined && income !== undefined ? { ...rest, decision: { ...rest.decision, income } } : rest;
|
|
945
|
+
}
|
|
946
|
+
else
|
|
947
|
+
turns[k] = e;
|
|
948
|
+
}
|
|
949
|
+
return { ...log, status: 'compacted', turns };
|
|
950
|
+
}
|
|
951
|
+
/**
|
|
952
|
+
* Compact a finished game's log (no-gaps rule (b): only uninteresting turns' replay `input` goes). Under
|
|
953
|
+
* `WARAPP_DECISION_LOG=full` nothing is dropped and the log is marked `finished`. Nothing for a game with
|
|
954
|
+
* no log. Idempotent. `true` when written. Never throws.
|
|
955
|
+
*/
|
|
956
|
+
export async function compactDecisionLog(dir, gameId, playerId, opts = {}) {
|
|
957
|
+
const mode = opts.mode ?? decisionLogMode();
|
|
958
|
+
return updateDecisionLog(dir, gameId, playerId, (log) => {
|
|
959
|
+
if (!hasContent(log))
|
|
960
|
+
return undefined;
|
|
961
|
+
if (mode === 'full')
|
|
962
|
+
return log.status === 'active' ? { ...log, status: 'finished' } : undefined;
|
|
963
|
+
const done = compactLog(log, opts.lost ? { lost: true } : {});
|
|
964
|
+
const dropped = Object.keys(log.turns).some((k) => log.turns[k].input && !done.turns[k].input);
|
|
965
|
+
return dropped || log.status !== 'compacted' ? done : undefined;
|
|
966
|
+
}, { ...opts, mode });
|
|
967
|
+
}
|
|
968
|
+
/**
|
|
969
|
+
* Mark the logs of games known to be over `finished`, dropping nothing (each stays whole for a later
|
|
970
|
+
* truth and compaction, which accept a `finished` log): a game whose end-of-game pass captured no
|
|
971
|
+
* history (`read-failed`, `history-unreadable`) or did not run (`WARAPP_PLAYER_PROFILE=off`) would
|
|
972
|
+
* otherwise keep its log `active`, which the prune never deletes. `playerId` restricts it to that
|
|
973
|
+
* account's logs; without it the log's own owner serves (the account may be unknown, but the game is
|
|
974
|
+
* over whoever played it). A missing, unreadable, empty or already finished/compacted log is left as
|
|
975
|
+
* it is; only the head of each file is read unless it needs a write. Returns the game ids written.
|
|
976
|
+
* Never throws.
|
|
977
|
+
*/
|
|
978
|
+
export async function finishDecisionLogs(dir, gameIds, playerId, opts = {}) {
|
|
979
|
+
if ((opts.mode ?? decisionLogMode()) === 'off')
|
|
980
|
+
return [];
|
|
981
|
+
const done = [];
|
|
982
|
+
for (const gameId of new Set(gameIds)) {
|
|
983
|
+
try {
|
|
984
|
+
const head = await headOf(decisionLogPath(dir, gameId), gameId);
|
|
985
|
+
if (head?.status !== 'active' || (playerId !== undefined && head.playerId !== playerId))
|
|
986
|
+
continue;
|
|
987
|
+
const written = await updateDecisionLog(dir, gameId, head.playerId, (log) => (log.status === 'active' && hasContent(log) ? { ...log, status: 'finished' } : undefined), opts);
|
|
988
|
+
if (written)
|
|
989
|
+
done.push(gameId);
|
|
990
|
+
}
|
|
991
|
+
catch {
|
|
992
|
+
// Missing or unreadable: nothing to close.
|
|
993
|
+
}
|
|
994
|
+
}
|
|
995
|
+
return done;
|
|
996
|
+
}
|
|
997
|
+
/**
|
|
998
|
+
* The header of a log read from its first {@link HEAD_BYTES} bytes (it is written before `turns`): the
|
|
999
|
+
* text up to `"turns":` closed with an empty `turns`. `undefined` when the head holds no header.
|
|
1000
|
+
*/
|
|
1001
|
+
async function headOf(path, gameId) {
|
|
1002
|
+
const fh = await open(path, 'r');
|
|
1003
|
+
let head;
|
|
1004
|
+
try {
|
|
1005
|
+
const buf = Buffer.alloc(HEAD_BYTES);
|
|
1006
|
+
const { bytesRead } = await fh.read(buf, 0, HEAD_BYTES, 0);
|
|
1007
|
+
head = buf.subarray(0, bytesRead).toString('utf8');
|
|
1008
|
+
}
|
|
1009
|
+
finally {
|
|
1010
|
+
await fh.close();
|
|
1011
|
+
}
|
|
1012
|
+
const at = head.indexOf('"turns":');
|
|
1013
|
+
if (at < 0)
|
|
1014
|
+
return undefined;
|
|
1015
|
+
return logOf(JSON.parse(`${head.slice(0, at)}"turns":{}}`), gameId);
|
|
1016
|
+
}
|
|
1017
|
+
/**
|
|
1018
|
+
* The account a decision log at `path` belongs to, read from its head only ({@link HEAD_BYTES}: the
|
|
1019
|
+
* header is written before `turns`), so a caller sorting logs by account never reads one whole.
|
|
1020
|
+
* `undefined` when the head holds no header for `gameId`. Never throws.
|
|
1021
|
+
*/
|
|
1022
|
+
export async function decisionLogOwner(path, gameId) {
|
|
1023
|
+
try {
|
|
1024
|
+
return (await headOf(path, gameId))?.playerId;
|
|
1025
|
+
}
|
|
1026
|
+
catch {
|
|
1027
|
+
return undefined;
|
|
1028
|
+
}
|
|
1029
|
+
}
|
|
1030
|
+
/** Every decision log whose header reads (from the head of the file only), by game id. Never throws. */
|
|
1031
|
+
export async function listDecisionLogs(dir) {
|
|
1032
|
+
let names;
|
|
1033
|
+
try {
|
|
1034
|
+
names = await readdir(decisionsDir(dir));
|
|
1035
|
+
}
|
|
1036
|
+
catch {
|
|
1037
|
+
return [];
|
|
1038
|
+
}
|
|
1039
|
+
const out = [];
|
|
1040
|
+
for (const name of names) {
|
|
1041
|
+
const m = DECISION_FILE.exec(name);
|
|
1042
|
+
if (!m)
|
|
1043
|
+
continue;
|
|
1044
|
+
const gameId = Number(m[1]);
|
|
1045
|
+
try {
|
|
1046
|
+
const path = decisionLogPath(dir, gameId);
|
|
1047
|
+
const [s, log] = await Promise.all([stat(path), headOf(path, gameId)]);
|
|
1048
|
+
if (log)
|
|
1049
|
+
out.push({ gameId, playerId: log.playerId, status: log.status, bytes: s.size, mtimeMs: s.mtimeMs });
|
|
1050
|
+
}
|
|
1051
|
+
catch {
|
|
1052
|
+
// Unreadable: neither listed nor pruned.
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
return out.sort((a, b) => a.gameId - b.gameId);
|
|
1056
|
+
}
|
|
1057
|
+
/**
|
|
1058
|
+
* Delete the least recently written finished (or compacted) logs while more than `maxGames` logs or
|
|
1059
|
+
* more than `maxBytes` in all are kept; a game still running is never deleted, and a file that does not
|
|
1060
|
+
* parse is neither counted nor deleted. Returns the game ids deleted, oldest first. Never throws.
|
|
1061
|
+
*/
|
|
1062
|
+
export async function pruneDecisionLogs(dir, caps = {}) {
|
|
1063
|
+
const maxGames = caps.maxGames ?? MAX_DECISION_GAMES;
|
|
1064
|
+
const maxBytes = caps.maxBytes ?? MAX_DECISION_BYTES;
|
|
1065
|
+
const all = await listDecisionLogs(dir);
|
|
1066
|
+
let count = all.length;
|
|
1067
|
+
let bytes = all.reduce((s, l) => s + l.bytes, 0);
|
|
1068
|
+
const done = all.filter((l) => l.status !== 'active').sort((a, b) => a.mtimeMs - b.mtimeMs || a.gameId - b.gameId);
|
|
1069
|
+
const removed = [];
|
|
1070
|
+
for (const l of done) {
|
|
1071
|
+
if (count <= maxGames && bytes <= maxBytes)
|
|
1072
|
+
break;
|
|
1073
|
+
try {
|
|
1074
|
+
// Parsed whole only now, just before it goes: a file that does not parse is never deleted.
|
|
1075
|
+
const gone = await withPathLock(decisionLogPath(dir, l.gameId), async () => {
|
|
1076
|
+
const r = await readRaw(dir, l.gameId);
|
|
1077
|
+
if (r.kind !== 'log' || r.log.status === 'active')
|
|
1078
|
+
return false;
|
|
1079
|
+
await unlink(decisionLogPath(dir, l.gameId));
|
|
1080
|
+
return true;
|
|
1081
|
+
});
|
|
1082
|
+
if (!gone)
|
|
1083
|
+
continue;
|
|
1084
|
+
removed.push(l.gameId);
|
|
1085
|
+
count -= 1;
|
|
1086
|
+
bytes -= l.bytes;
|
|
1087
|
+
}
|
|
1088
|
+
catch {
|
|
1089
|
+
// Gone already, or not removable: leave it.
|
|
1090
|
+
}
|
|
1091
|
+
}
|
|
1092
|
+
return removed;
|
|
1093
|
+
}
|