poi-plugin-brainoff 1.0.0 → 1.0.1
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/LICENSE +662 -662
- package/package.json +6 -2
- package/plugin/index.js +1 -1
- package/src/computeWorker.js +81 -81
- package/src/data/empiricalComps.js +773 -773
- package/src/engine/constants.js +490 -490
- package/src/engine/rng.js +169 -169
- package/src/optimizer/fleetConstraints.js +733 -733
|
@@ -1,773 +1,773 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
|
-
// Wave 20: live, incremental empirical enemy-composition data computed directly from the local poi battle-detail logs.
|
|
4
|
-
//
|
|
5
|
-
// Replaces the manual `node scripts/build_comp_weights.js` rebuild step:
|
|
6
|
-
// * every <ts>.json.gz log is reduced once to an "observation" {ts, map, cell, ships, hq, form} (or a skip verdict);
|
|
7
|
-
// * per-file results are persisted in a user cache file keyed by file name + mtimeMs + size (versioned, atomic write),
|
|
8
|
-
// so a refresh only gunzips new / changed files;
|
|
9
|
-
// * observations are aggregated in memory into the same table shape as data/empirical_comp_weights.json
|
|
10
|
-
// ({ maps: { mapId: { node: { total, hqMin, hqMax, byHq: { hq: { shipsCsv: n } } } } }, hqRange, nBattles, ... })
|
|
11
|
-
// which src/engine/sortie.js applyEmpiricalCompWeights consumes;
|
|
12
|
-
// * a cut-off time (asOf, ms) keeps results reproducible: only observations with ts <= asOf are aggregated;
|
|
13
|
-
// * without a readable poi directory (or with source = 'seed') the bundled seed table data/empirical_comp_weights.json is used.
|
|
14
|
-
//
|
|
15
|
-
// Node-letter resolution (POI_NODE_LETTER + exact-composition match + 7-2 phase split) lives here so src/ never requires
|
|
16
|
-
// scripts/; scripts/build_comp_weights.js is now a thin export wrapper around this module.
|
|
17
|
-
|
|
18
|
-
const fs = require('fs');
|
|
19
|
-
const os = require('os');
|
|
20
|
-
const path = require('path');
|
|
21
|
-
const zlib = require('zlib');
|
|
22
|
-
const crypto = require('crypto');
|
|
23
|
-
const { MAPS, POI_CELLS } = require('./maps');
|
|
24
|
-
|
|
25
|
-
// Bump when extractObservation() semantics change: every cached per-file verdict is discarded.
|
|
26
|
-
// 2 (Phase D, E11): night-start (battle_midnight/sp_midnight) and radar-ambush (ld_shooting) packets are observations too.
|
|
27
|
-
const CACHE_VERSION = 2;
|
|
28
|
-
const SEED_PATH = path.join(__dirname, '../../data/empirical_comp_weights.json');
|
|
29
|
-
const LOG_FILE_RE = /^\d+\.json\.gz$/;
|
|
30
|
-
// A log that fails to parse and was modified within this window is treated as "still being written" (retried next refresh,
|
|
31
|
-
// never cached). Older unreadable files are cached as 'bad' (keyed by mtime + size, so a rewrite is re-parsed).
|
|
32
|
-
const PENDING_GRACE_MS = 10 * 60 * 1000;
|
|
33
|
-
|
|
34
|
-
// Verified Phase 2 poi edge/node ID -> map letter mapping (matching exact comp pools in MAPS)
|
|
35
|
-
const POI_NODE_LETTER = {
|
|
36
|
-
'1-1': { 1: 'A', 2: 'B', 3: 'C' },
|
|
37
|
-
'1-2': { 1: 'A', 3: 'C', 5: 'E' },
|
|
38
|
-
'1-3': { 3: 'C', 5: 'E', 6: 'F', 10: 'J', 11: 'E', 12: 'F', 13: 'J' },
|
|
39
|
-
'1-4': { 2: 'B', 4: 'D', 8: 'H', 10: 'J', 12: 'L', 17: 'L' },
|
|
40
|
-
'1-5': { 1: 'A', 4: 'D', 6: 'F', 9: 'I', 12: 'J' },
|
|
41
|
-
'1-6': { 3: 'E', 12: 'F', 13: 'B' },
|
|
42
|
-
'2-1': { 3: 'C', 4: 'D', 8: 'H', 9: 'D' },
|
|
43
|
-
'2-2': { 2: 'B', 5: 'E', 7: 'G', 11: 'K', 14: 'K' },
|
|
44
|
-
'2-3': { 1: 'A', 5: 'E', 10: 'J', 11: 'K', 14: 'N', 16: 'F', 17: 'F', 19: 'K', 20: 'N' },
|
|
45
|
-
'2-4': { 2: 'B', 5: 'E', 6: 'F', 9: 'I', 13: 'M', 16: 'P', 18: 'L', 19: 'L', 21: 'P' },
|
|
46
|
-
'2-5': { 3: 'C', 5: 'E', 15: 'O' },
|
|
47
|
-
'3-1': { 3: 'C', 6: 'F', 9: 'G' },
|
|
48
|
-
'3-2': { 3: 'C', 12: 'L' },
|
|
49
|
-
'3-3': { 1: 'A', 7: 'G', 13: 'M' },
|
|
50
|
-
'3-4': { 1: 'A', 3: 'C', 7: 'G' },
|
|
51
|
-
};
|
|
52
|
-
// Phase D: cell -> letter tables of the map modules (src/data/maps_phaseD/*.js poiCells; empty until poi logs exist). The
|
|
53
|
-
// unique-composition fallback below is ambiguous on 4-5 E/G and 5-2 C/L (identical pools), so those need real cell ids.
|
|
54
|
-
for (const [base, cells] of Object.entries(POI_CELLS || {})) {
|
|
55
|
-
if (!POI_NODE_LETTER[base]) POI_NODE_LETTER[base] = { ...cells };
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
// Phase D (E8): poi logs a multi-gauge map under its base id (7-2, 7-3); the simulator models each gauge as its own map id
|
|
59
|
-
// (7-2-1 / 7-2-2 ...). Derived from MAPS[*].baseMapId (was the literal '7-2' -> ['7-2-1', '7-2-2']).
|
|
60
|
-
const PHASED_MAPS = {};
|
|
61
|
-
for (const [id, m] of Object.entries(MAPS)) {
|
|
62
|
-
if (m && m.baseMapId && m.baseMapId !== id) (PHASED_MAPS[m.baseMapId] || (PHASED_MAPS[m.baseMapId] = [])).push(id);
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
function resolveNodeLetter(mapId, nid, eIdsCsv) {
|
|
66
|
-
const m = MAPS[mapId];
|
|
67
|
-
// (Phase D: a gauge-split map id falls back to the cell table of its poi base map id)
|
|
68
|
-
const mapped = POI_NODE_LETTER[mapId]?.[nid] || (m && m.baseMapId && m.baseMapId !== mapId ? POI_NODE_LETTER[m.baseMapId]?.[nid] : undefined);
|
|
69
|
-
if (!m) return null;
|
|
70
|
-
if (mapped && m.nodes[mapped]?.comps?.some((c) => c.ships.join(',') === eIdsCsv)) return mapped;
|
|
71
|
-
// Fallback: unique node match by ship composition
|
|
72
|
-
const matches = Object.entries(m.nodes)
|
|
73
|
-
.filter(([, nd]) => nd.comps && nd.comps.some((c) => c.ships.join(',') === eIdsCsv))
|
|
74
|
-
.map(([nl]) => nl);
|
|
75
|
-
return matches.length === 1 ? matches[0] : (mapped || null);
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
// poi logs 7-2 as map [7, 2, node] for BOTH gauge phases; the simulator models them as 7-2-1 (G boss) / 7-2-2 (M boss).
|
|
79
|
-
// Resolve against every phase whose node pool contains this exact enemy composition (shared nodes count for both).
|
|
80
|
-
function resolveMapPhases(mapId, nid, eIdsCsv) {
|
|
81
|
-
const phaseIds = PHASED_MAPS[mapId] ? PHASED_MAPS[mapId].filter((k) => MAPS[k]) : (MAPS[mapId] ? [mapId] : []);
|
|
82
|
-
const out = [];
|
|
83
|
-
for (const pid of phaseIds) {
|
|
84
|
-
const letter = resolveNodeLetter(pid, nid, eIdsCsv);
|
|
85
|
-
if (!letter) continue;
|
|
86
|
-
// Multi-phase maps: require an exact composition match so a 7-2-1-only boss comp never leaks into 7-2-2 (and vice versa)
|
|
87
|
-
if (phaseIds.length > 1 && !MAPS[pid].nodes[letter]?.comps?.some((c) => c.ships.join(',') === eIdsCsv)) continue;
|
|
88
|
-
out.push({ mapId: pid, nodeLetter: letter });
|
|
89
|
-
}
|
|
90
|
-
return out;
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
// Reduce one parsed poi battle-detail log to an observation. Pure function of the log content (cached per file), so it
|
|
94
|
-
// deliberately does NOT consult MAPS: node letters are resolved at aggregation time (MAPS data updates need no re-parse).
|
|
95
|
-
// Same filters as the pre-Wave-20 builder: 演習 (empty map), non-abyssal enemies (ids < 1500), combined / escort fleets,
|
|
96
|
-
// logs without a day-battle packet or HQ level; plus (Wave 20) 教程战 = tutorial logs with an empty main fleet.
|
|
97
|
-
function extractObservation(d, ts) {
|
|
98
|
-
if (!d || typeof d !== 'object') return { kind: 'skip', reason: 'invalid' };
|
|
99
|
-
if (!Array.isArray(d.map) || d.map.length < 3) return { kind: 'skip', reason: 'practice/non-sortie' };
|
|
100
|
-
const mapId = `${d.map[0]}-${d.map[1]}`;
|
|
101
|
-
// Phase D (E11): the first battle packet of the node -- day battle, aerial battle, long-distance air raid, radar ambush
|
|
102
|
-
// (ld_shooting) or night-start node (battle_midnight/sp_midnight; never the night continuation battle_midnight/battle).
|
|
103
|
-
const day = (d.packet || []).find((p) => p && /api_req_(sortie\/(battle|airbattle|ld_airbattle|ld_shooting)|battle_midnight\/sp_midnight)$/.test(String(p.poi_path || '')));
|
|
104
|
-
if (!day || !Array.isArray(day.api_ship_ke)) return { kind: 'skip', reason: 'no-day-battle' };
|
|
105
|
-
if (day.api_ship_ke.some((id) => id > 0 && id < 1500)) return { kind: 'skip', reason: 'non-abyssal (tutorial)' };
|
|
106
|
-
if (d.fleet && (d.fleet.type !== 0 || (d.fleet.escort && d.fleet.escort.length))) return { kind: 'skip', reason: 'combined/escort' };
|
|
107
|
-
// Wave 20: 教程战 (tutorial sortie logged with an empty main fleet, scripted enemy) is not a natural comp draw
|
|
108
|
-
if (d.fleet && Array.isArray(d.fleet.main) && d.fleet.main.length === 0) return { kind: 'skip', reason: 'tutorial (empty fleet)' };
|
|
109
|
-
const ships = day.api_ship_ke.filter((x) => x > 0).join(',');
|
|
110
|
-
const hq = d.admiral?.lv || d.admiral?.api_level || (d.packet || []).find((p) => p && p.api_member_lv)?.api_member_lv;
|
|
111
|
-
if (!hq || !ships) return { kind: 'skip', reason: 'no-hq/no-enemy' };
|
|
112
|
-
const form = Array.isArray(day.api_formation) && day.api_formation.length > 1 ? Number(day.api_formation[1]) : null;
|
|
113
|
-
return { kind: 'obs', obs: { ts, map: mapId, cell: d.map[2], ships, hq: Number(hq), form } };
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
function resolvePoiBattleDir() {
|
|
117
|
-
if (process.env.POI_BATTLE_DIR) return process.env.POI_BATTLE_DIR;
|
|
118
|
-
if (process.env.POI_DATA_DIR) return path.join(process.env.POI_DATA_DIR, 'battle-detail');
|
|
119
|
-
if (process.platform === 'win32') {
|
|
120
|
-
const appData = process.env.APPDATA || (process.env.USERPROFILE ? path.join(process.env.USERPROFILE, 'AppData', 'Roaming') : null);
|
|
121
|
-
return appData ? path.join(appData, 'poi', 'battle-detail') : null;
|
|
122
|
-
}
|
|
123
|
-
if (process.platform === 'darwin') {
|
|
124
|
-
return path.join(os.homedir(), 'Library', 'Application Support', 'poi', 'battle-detail');
|
|
125
|
-
}
|
|
126
|
-
return path.join(process.env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config'), 'poi', 'battle-detail');
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
function resolveCacheDir() {
|
|
130
|
-
if (process.env.KC_CACHE_DIR) return process.env.KC_CACHE_DIR;
|
|
131
|
-
if (process.platform === 'win32') {
|
|
132
|
-
const local = process.env.LOCALAPPDATA || (process.env.USERPROFILE ? path.join(process.env.USERPROFILE, 'AppData', 'Local') : os.tmpdir());
|
|
133
|
-
return path.join(local, 'brainoff');
|
|
134
|
-
}
|
|
135
|
-
return path.join(process.env.XDG_CACHE_HOME || path.join(os.homedir(), '.cache'), 'brainoff');
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
function cacheFileFor(dir, cacheDir = resolveCacheDir()) {
|
|
139
|
-
const h = crypto.createHash('sha1').update(path.resolve(dir).toLowerCase()).digest('hex').slice(0, 12);
|
|
140
|
-
return path.join(cacheDir, `comp_obs_${h}.json`);
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
function writeFileAtomic(file, text) {
|
|
144
|
-
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
145
|
-
const tmp = `${file}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2, 8)}.tmp`;
|
|
146
|
-
fs.writeFileSync(tmp, text, 'utf8');
|
|
147
|
-
try {
|
|
148
|
-
fs.renameSync(tmp, file);
|
|
149
|
-
} catch (err) {
|
|
150
|
-
try { fs.unlinkSync(tmp); } catch (_) { /* ignore */ }
|
|
151
|
-
throw err;
|
|
152
|
-
}
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
// ------------------------------------------------------------------------------------------------ observation store
|
|
156
|
-
// In-process state per log directory: { files: Map(name -> entry), cacheLoaded, sig, observations, version, lastCheckMs }
|
|
157
|
-
// entry = { m: mtimeMs, s: size, k: 'o' | 's' | 'b', o?: obs, r?: reason } ('b' = unreadable & older than the grace window)
|
|
158
|
-
// retryBad: names of 'b' entries loaded from the disk cache; each is re-parsed once per process (audit19 P3-5), so a file that
|
|
159
|
-
// was unreadable only transiently (or repaired in place with the same mtime + size) is not excluded forever.
|
|
160
|
-
const stores = new Map();
|
|
161
|
-
let storeVersionSeq = 0;
|
|
162
|
-
const stats0 = () => ({ files: 0, reused: 0, parsed: 0, pending: 0, bad: 0, skipped: 0, observations: 0, cacheWritten: false, elapsedMs: 0 });
|
|
163
|
-
|
|
164
|
-
function getStore(dir) {
|
|
165
|
-
const key = path.resolve(dir);
|
|
166
|
-
let st = stores.get(key);
|
|
167
|
-
if (!st) {
|
|
168
|
-
st = { dir: key, files: new Map(), retryBad: new Set(), cacheLoaded: false, sig: null, observations: [], version: 0, pendingCount: 0, lastCheckMs: 0, lastStats: null };
|
|
169
|
-
stores.set(key, st);
|
|
170
|
-
}
|
|
171
|
-
return st;
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
function loadDiskCache(st, cacheDir) {
|
|
175
|
-
if (st.cacheLoaded) return;
|
|
176
|
-
st.cacheLoaded = true;
|
|
177
|
-
const file = cacheFileFor(st.dir, cacheDir);
|
|
178
|
-
let raw;
|
|
179
|
-
try { raw = JSON.parse(fs.readFileSync(file, 'utf8')); } catch (_) { return; }
|
|
180
|
-
if (!raw || raw.version !== CACHE_VERSION || !raw.files || typeof raw.files !== 'object') return; // version bump: drop all
|
|
181
|
-
// The cache file name is a hash of the lower-cased directory: also require the stored directory to match (audit19 P3-5)
|
|
182
|
-
if (typeof raw.dir !== 'string' || path.resolve(raw.dir).toLowerCase() !== st.dir.toLowerCase()) return;
|
|
183
|
-
for (const [name, e] of Object.entries(raw.files)) {
|
|
184
|
-
if (e && typeof e === 'object' && (e.k === 'o' || e.k === 's' || e.k === 'b')) {
|
|
185
|
-
st.files.set(name, e);
|
|
186
|
-
if (e.k === 'b') st.retryBad.add(name);
|
|
187
|
-
}
|
|
188
|
-
}
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
// prev entry still valid for the file's current stat? ('b' entries from the disk cache are re-tried once per process)
|
|
192
|
-
function canReuse(st, name, prev, fst) {
|
|
193
|
-
if (!prev || prev.m !== fst.mtimeMs || prev.s !== fst.size) return false;
|
|
194
|
-
return !(prev.k === 'b' && st.retryBad.has(name));
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
// Store a fresh verdict; returns true when the entry actually changed (a repeated 'b' verdict for the same file is a no-op)
|
|
198
|
-
function storeVerdict(st, name, prev, fst, v) {
|
|
199
|
-
st.retryBad.delete(name);
|
|
200
|
-
if (prev && prev.k === 'b' && v.k === 'b' && prev.m === fst.mtimeMs && prev.s === fst.size) return false;
|
|
201
|
-
st.files.set(name, { m: fst.mtimeMs, s: fst.size, ...v });
|
|
202
|
-
return true;
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
function saveDiskCache(st, cacheDir) {
|
|
206
|
-
const files = {};
|
|
207
|
-
for (const [name, e] of [...st.files.entries()].sort((a, b) => (a[0] < b[0] ? -1 : 1))) files[name] = e;
|
|
208
|
-
const payload = { version: CACHE_VERSION, dir: st.dir, updatedAt: new Date().toISOString(), files };
|
|
209
|
-
writeFileAtomic(cacheFileFor(st.dir, cacheDir), JSON.stringify(payload));
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
function verdictFromBuffer(buf, ts, mtimeMs, now) {
|
|
213
|
-
let d = null;
|
|
214
|
-
try { d = JSON.parse(zlib.gunzipSync(buf)); } catch (_) { d = null; }
|
|
215
|
-
if (!d) return (now - mtimeMs) < PENDING_GRACE_MS ? null : { k: 'b', r: 'corrupt gzip/json' }; // null = pending, retry later
|
|
216
|
-
const v = extractObservation(d, ts);
|
|
217
|
-
return v.kind === 'obs' ? { k: 'o', o: v.obs } : { k: 's', r: v.reason };
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
function dirSignature(dir) {
|
|
221
|
-
const dst = fs.statSync(dir);
|
|
222
|
-
const names = fs.readdirSync(dir).filter((f) => LOG_FILE_RE.test(f));
|
|
223
|
-
return { sig: `${dst.mtimeMs}|${names.length}`, names };
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
function finalizeStore(st, names, changed, stats, cacheDir, t0) {
|
|
227
|
-
// Drop entries of deleted files
|
|
228
|
-
const live = new Set(names);
|
|
229
|
-
for (const name of [...st.files.keys()]) {
|
|
230
|
-
if (!live.has(name)) { st.files.delete(name); changed = true; }
|
|
231
|
-
}
|
|
232
|
-
if (changed || !st.version) {
|
|
233
|
-
const obs = [];
|
|
234
|
-
for (const name of names) {
|
|
235
|
-
const e = st.files.get(name);
|
|
236
|
-
if (e && e.k === 'o' && e.o) obs.push(e.o);
|
|
237
|
-
}
|
|
238
|
-
obs.sort((a, b) => a.ts - b.ts || (a.cell - b.cell));
|
|
239
|
-
st.observations = obs;
|
|
240
|
-
st.version = ++storeVersionSeq;
|
|
241
|
-
if (changed) {
|
|
242
|
-
try { saveDiskCache(st, cacheDir); stats.cacheWritten = true; } catch (_) { /* read-only cache dir: in-memory only */ }
|
|
243
|
-
}
|
|
244
|
-
}
|
|
245
|
-
stats.observations = st.observations.length;
|
|
246
|
-
stats.elapsedMs = Date.now() - t0;
|
|
247
|
-
st.lastStats = stats;
|
|
248
|
-
return stats;
|
|
249
|
-
}
|
|
250
|
-
|
|
251
|
-
// Synchronous incremental refresh (CLI / library / worker fallback). Returns stats; throws if the directory is unreadable.
|
|
252
|
-
function refreshStoreSync(dir, { cacheDir = resolveCacheDir() } = {}) {
|
|
253
|
-
const t0 = Date.now();
|
|
254
|
-
const st = getStore(dir);
|
|
255
|
-
loadDiskCache(st, cacheDir);
|
|
256
|
-
const { sig, names } = dirSignature(dir);
|
|
257
|
-
const stats = stats0();
|
|
258
|
-
stats.files = names.length;
|
|
259
|
-
let changed = false;
|
|
260
|
-
let pending = 0;
|
|
261
|
-
const now = Date.now();
|
|
262
|
-
for (const name of names) {
|
|
263
|
-
const full = path.join(dir, name);
|
|
264
|
-
let fst;
|
|
265
|
-
try { fst = fs.statSync(full); } catch (_) { pending++; continue; }
|
|
266
|
-
const prev = st.files.get(name);
|
|
267
|
-
if (canReuse(st, name, prev, fst)) {
|
|
268
|
-
stats.reused++;
|
|
269
|
-
if (prev.k === 'b') stats.bad++; else if (prev.k === 's') stats.skipped++;
|
|
270
|
-
continue;
|
|
271
|
-
}
|
|
272
|
-
let buf;
|
|
273
|
-
try { buf = fs.readFileSync(full); } catch (_) { pending++; continue; }
|
|
274
|
-
stats.parsed++;
|
|
275
|
-
const v = verdictFromBuffer(buf, Number(name.slice(0, -8)), fst.mtimeMs, now);
|
|
276
|
-
if (!v) {
|
|
277
|
-
pending++;
|
|
278
|
-
if (prev) { st.files.delete(name); changed = true; }
|
|
279
|
-
continue;
|
|
280
|
-
}
|
|
281
|
-
if (v.k === 'b') stats.bad++; else if (v.k === 's') stats.skipped++;
|
|
282
|
-
if (storeVerdict(st, name, prev, fst, v)) changed = true;
|
|
283
|
-
}
|
|
284
|
-
stats.pending = pending;
|
|
285
|
-
st.pendingCount = pending;
|
|
286
|
-
st.sig = pending ? null : sig; // pending files force a re-check on the next refresh
|
|
287
|
-
st.lastCheckMs = Date.now();
|
|
288
|
-
return finalizeStore(st, names, changed, stats, cacheDir, t0);
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
// Asynchronous variant for the HTTP server main thread (gunzip off the event loop thread pool; no long sync stall).
|
|
292
|
-
async function refreshStoreAsync(dir, { cacheDir = resolveCacheDir() } = {}) {
|
|
293
|
-
const t0 = Date.now();
|
|
294
|
-
const st = getStore(dir);
|
|
295
|
-
loadDiskCache(st, cacheDir);
|
|
296
|
-
const fsp = fs.promises;
|
|
297
|
-
const dst = await fsp.stat(dir);
|
|
298
|
-
const names = (await fsp.readdir(dir)).filter((f) => LOG_FILE_RE.test(f));
|
|
299
|
-
const sig = `${dst.mtimeMs}|${names.length}`;
|
|
300
|
-
const stats = stats0();
|
|
301
|
-
stats.files = names.length;
|
|
302
|
-
let changed = false;
|
|
303
|
-
let pending = 0;
|
|
304
|
-
const now = Date.now();
|
|
305
|
-
const gunzip = (buf) => new Promise((resolve) => zlib.gunzip(buf, (err, out) => resolve(err ? null : out)));
|
|
306
|
-
for (const name of names) {
|
|
307
|
-
const full = path.join(dir, name);
|
|
308
|
-
let fst;
|
|
309
|
-
try { fst = await fsp.stat(full); } catch (_) { pending++; continue; }
|
|
310
|
-
const prev = st.files.get(name);
|
|
311
|
-
if (canReuse(st, name, prev, fst)) {
|
|
312
|
-
stats.reused++;
|
|
313
|
-
if (prev.k === 'b') stats.bad++; else if (prev.k === 's') stats.skipped++;
|
|
314
|
-
continue;
|
|
315
|
-
}
|
|
316
|
-
let buf;
|
|
317
|
-
try { buf = await fsp.readFile(full); } catch (_) { pending++; continue; }
|
|
318
|
-
stats.parsed++;
|
|
319
|
-
const ts = Number(name.slice(0, -8));
|
|
320
|
-
const out = await gunzip(buf);
|
|
321
|
-
let v;
|
|
322
|
-
if (!out) {
|
|
323
|
-
v = (now - fst.mtimeMs) < PENDING_GRACE_MS ? null : { k: 'b', r: 'corrupt gzip/json' };
|
|
324
|
-
} else {
|
|
325
|
-
let d = null;
|
|
326
|
-
try { d = JSON.parse(out); } catch (_) { d = null; }
|
|
327
|
-
if (!d) v = (now - fst.mtimeMs) < PENDING_GRACE_MS ? null : { k: 'b', r: 'corrupt gzip/json' };
|
|
328
|
-
else { const x = extractObservation(d, ts); v = x.kind === 'obs' ? { k: 'o', o: x.obs } : { k: 's', r: x.reason }; }
|
|
329
|
-
}
|
|
330
|
-
if (!v) {
|
|
331
|
-
pending++;
|
|
332
|
-
if (prev) { st.files.delete(name); changed = true; }
|
|
333
|
-
continue;
|
|
334
|
-
}
|
|
335
|
-
if (v.k === 'b') stats.bad++; else if (v.k === 's') stats.skipped++;
|
|
336
|
-
if (storeVerdict(st, name, prev, fst, v)) changed = true;
|
|
337
|
-
}
|
|
338
|
-
stats.pending = pending;
|
|
339
|
-
st.pendingCount = pending;
|
|
340
|
-
st.sig = pending ? null : sig;
|
|
341
|
-
st.lastCheckMs = Date.now();
|
|
342
|
-
return finalizeStore(st, names, changed, stats, cacheDir, t0);
|
|
343
|
-
}
|
|
344
|
-
|
|
345
|
-
// ------------------------------------------------------------------------------------------------ aggregation
|
|
346
|
-
function stableHash(obsList) {
|
|
347
|
-
const h = crypto.createHash('sha1');
|
|
348
|
-
for (const o of obsList) h.update(`${o.ts}|${o.map}|${o.cell}|${o.ships}|${o.hq}\n`);
|
|
349
|
-
return h.digest('hex').slice(0, 12);
|
|
350
|
-
}
|
|
351
|
-
|
|
352
|
-
// Aggregate observations (ts <= asOf when asOf != null) into the table shape consumed by applyEmpiricalCompWeights.
|
|
353
|
-
// scannedMaxTs = newest log file (any kind, excluding files still being written) with ts <= asOf.
|
|
354
|
-
function aggregateObservations(observations, { asOf = null, scannedTs = null, source = 'live' } = {}) {
|
|
355
|
-
const maps = {};
|
|
356
|
-
let nBattles = 0;
|
|
357
|
-
let minHq = Infinity;
|
|
358
|
-
let maxHq = 0;
|
|
359
|
-
let minTs = Infinity;
|
|
360
|
-
let maxTs = 0;
|
|
361
|
-
const counted = [];
|
|
362
|
-
for (const o of observations) {
|
|
363
|
-
if (asOf != null && o.ts > asOf) continue;
|
|
364
|
-
const targets = resolveMapPhases(o.map, o.cell, o.ships);
|
|
365
|
-
if (!targets.length) continue;
|
|
366
|
-
nBattles++;
|
|
367
|
-
counted.push(o);
|
|
368
|
-
if (o.ts > 0) { if (o.ts < minTs) minTs = o.ts; if (o.ts > maxTs) maxTs = o.ts; }
|
|
369
|
-
if (o.hq < minHq) minHq = o.hq;
|
|
370
|
-
if (o.hq > maxHq) maxHq = o.hq;
|
|
371
|
-
for (const { mapId, nodeLetter } of targets) {
|
|
372
|
-
if (!maps[mapId]) maps[mapId] = {};
|
|
373
|
-
if (!maps[mapId][nodeLetter]) maps[mapId][nodeLetter] = { total: 0, hqMin: o.hq, hqMax: o.hq, byHq: {} };
|
|
374
|
-
const rec = maps[mapId][nodeLetter];
|
|
375
|
-
rec.total++;
|
|
376
|
-
if (o.hq < rec.hqMin) rec.hqMin = o.hq;
|
|
377
|
-
if (o.hq > rec.hqMax) rec.hqMax = o.hq;
|
|
378
|
-
const hk = String(o.hq);
|
|
379
|
-
if (!rec.byHq[hk]) rec.byHq[hk] = {};
|
|
380
|
-
rec.byHq[hk][o.ships] = (rec.byHq[hk][o.ships] || 0) + 1;
|
|
381
|
-
}
|
|
382
|
-
}
|
|
383
|
-
let scannedMaxTs = 0;
|
|
384
|
-
if (Array.isArray(scannedTs)) {
|
|
385
|
-
for (const ts of scannedTs) if ((asOf == null || ts <= asOf) && ts > scannedMaxTs) scannedMaxTs = ts;
|
|
386
|
-
} else {
|
|
387
|
-
scannedMaxTs = maxTs;
|
|
388
|
-
}
|
|
389
|
-
const iso = (ts) => new Date(ts).toISOString();
|
|
390
|
-
const tbl = {
|
|
391
|
-
source: 'local poi battle-detail, not wiki',
|
|
392
|
-
generatedAt: new Date().toISOString().slice(0, 10),
|
|
393
|
-
nBattles,
|
|
394
|
-
hqRange: nBattles > 0 ? [minHq, maxHq] : [0, 0],
|
|
395
|
-
dateRange: nBattles > 0 && Number.isFinite(minTs) ? [iso(minTs).slice(0, 10), iso(maxTs).slice(0, 10)] : null,
|
|
396
|
-
scannedMaxDate: scannedMaxTs > 0 ? iso(scannedMaxTs).slice(0, 10) : null,
|
|
397
|
-
scannedMaxTs: scannedMaxTs > 0 ? scannedMaxTs : null,
|
|
398
|
-
// Legacy hard-window model parameters (model 'window'; see src/engine/sortie.js applyEmpiricalCompWeights)
|
|
399
|
-
alpha: 0.5,
|
|
400
|
-
hqWindow: [-10, 5],
|
|
401
|
-
minSamples: 10,
|
|
402
|
-
maps,
|
|
403
|
-
};
|
|
404
|
-
tbl.fingerprint = {
|
|
405
|
-
source,
|
|
406
|
-
nBattles,
|
|
407
|
-
asOf: asOf != null ? asOf : null,
|
|
408
|
-
asOfIso: asOf != null ? iso(asOf) : null,
|
|
409
|
-
scannedMaxTs: tbl.scannedMaxTs,
|
|
410
|
-
hash: stableHash(counted),
|
|
411
|
-
};
|
|
412
|
-
return tbl;
|
|
413
|
-
}
|
|
414
|
-
|
|
415
|
-
// ------------------------------------------------------------------------------------------------ seed table
|
|
416
|
-
let seedCache;
|
|
417
|
-
function loadSeedTable(filePath = SEED_PATH) {
|
|
418
|
-
if (filePath === SEED_PATH && seedCache !== undefined) return seedCache;
|
|
419
|
-
let tbl = null;
|
|
420
|
-
if (fs.existsSync(filePath)) {
|
|
421
|
-
try {
|
|
422
|
-
tbl = JSON.parse(fs.readFileSync(filePath, 'utf8'));
|
|
423
|
-
} catch (err) {
|
|
424
|
-
console.warn(`[empiricalComps] Failed to parse seed comp table (${filePath}), falling back to wiki equal weights: ${err.message}`);
|
|
425
|
-
tbl = null;
|
|
426
|
-
}
|
|
427
|
-
}
|
|
428
|
-
if (tbl) {
|
|
429
|
-
const obs = Array.isArray(tbl.observations) ? tbl.observations : null;
|
|
430
|
-
const counted = obs ? obs.filter((o) => resolveMapPhases(o.map, o.cell, o.ships).length) : [];
|
|
431
|
-
// audit19 P3-6: the seed is itself a table cut at its export cut-off -> report that as asOf (not "实时(无截止)"), so the
|
|
432
|
-
// fingerprint matches a live run with compAsOf = seed asOf (same hash, same asOf).
|
|
433
|
-
const seedAsOf = Number.isFinite(Number(tbl.asOf)) && Number(tbl.asOf) > 0 ? Number(tbl.asOf)
|
|
434
|
-
: (Number.isFinite(Number(tbl.scannedMaxTs)) && Number(tbl.scannedMaxTs) > 0 ? Number(tbl.scannedMaxTs) : null);
|
|
435
|
-
tbl.fingerprint = {
|
|
436
|
-
source: 'seed',
|
|
437
|
-
nBattles: tbl.nBattles || 0,
|
|
438
|
-
asOf: seedAsOf,
|
|
439
|
-
asOfIso: seedAsOf != null ? new Date(seedAsOf).toISOString() : null,
|
|
440
|
-
seedAsOf,
|
|
441
|
-
scannedMaxTs: tbl.scannedMaxTs || null,
|
|
442
|
-
hash: obs ? stableHash(counted) : crypto.createHash('sha1').update(JSON.stringify(tbl.maps || {})).digest('hex').slice(0, 12),
|
|
443
|
-
};
|
|
444
|
-
}
|
|
445
|
-
if (filePath === SEED_PATH) seedCache = tbl;
|
|
446
|
-
return tbl;
|
|
447
|
-
}
|
|
448
|
-
|
|
449
|
-
// ------------------------------------------------------------------------------------------------ resolution API
|
|
450
|
-
// Cut-off time parsing (CLI --comp-asof / HTTP compAsOf / KC_COMP_ASOF). Accepted:
|
|
451
|
-
// * millisecond epoch timestamps (number or digit string) >= 1e11 (1973-03-03); smaller values are rejected (audit19 P3-3:
|
|
452
|
-
// "20261120" or a seconds timestamp would otherwise silently become a 1970 cut-off and exclude every battle);
|
|
453
|
-
// * ISO dates / date-times. Date-only = end of that UTC day (inclusive). A date-time WITHOUT zone is read as UTC (not local
|
|
454
|
-
// time) so the same string reproduces the same table on every machine; an explicit zone (Z / +09:00 / +0900) is honoured.
|
|
455
|
-
// Calendar / clock fields are range-checked (2026-02-30, 24:00, +25:00 are rejected instead of rolled over by Date.parse).
|
|
456
|
-
const ASOF_MIN_MS = 1e11;
|
|
457
|
-
const ASOF_MAX_MS = 8.64e15;
|
|
458
|
-
const ASOF_HINT = '需为毫秒时间戳(≥1e11,如 1795934234683)或 ISO 日期/时间,如 2026-11-20、2026-11-20T12:00:00(无时区按 UTC)、2026-11-20T21:00:00+09:00';
|
|
459
|
-
function parseAsOf(raw) {
|
|
460
|
-
if (raw === undefined || raw === null || raw === '') return { ok: true, value: null };
|
|
461
|
-
const checkMs = (v, shown) => {
|
|
462
|
-
if (!Number.isFinite(v) || !Number.isInteger(v) || v <= 0 || v >= ASOF_MAX_MS) return { ok: false, error: `无效 compAsOf 时间戳: ${shown}(${ASOF_HINT})` };
|
|
463
|
-
if (v < ASOF_MIN_MS) return { ok: false, error: `无效 compAsOf 时间戳: ${shown}(数值过小,不像毫秒时间戳;${ASOF_HINT})` };
|
|
464
|
-
return { ok: true, value: v };
|
|
465
|
-
};
|
|
466
|
-
if (typeof raw === 'number') return checkMs(raw, raw);
|
|
467
|
-
if (typeof raw !== 'string') return { ok: false, error: `compAsOf 必须为 ISO 时间字符串或毫秒时间戳(${ASOF_HINT})` };
|
|
468
|
-
const s = raw.trim();
|
|
469
|
-
if (/^\d+$/.test(s)) return checkMs(Number(s), raw);
|
|
470
|
-
// ISO 8601 date or date-time only (rejects free-form strings Date.parse would accept)
|
|
471
|
-
const m = /^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2})(\.\d{1,3})?)?(Z|([+-])(\d{2}):?(\d{2}))?)?$/i.exec(s);
|
|
472
|
-
if (!m) return { ok: false, error: `无效 compAsOf 时间: "${raw}"(${ASOF_HINT})` };
|
|
473
|
-
const [, Y, Mo, D, h, mi, sec, frac, zone, sign, zh, zm] = m;
|
|
474
|
-
const y = Number(Y), mo = Number(Mo), d = Number(D);
|
|
475
|
-
// Round-trip check: Date.UTC rolls 2026-02-30 over to 03-02, so compare the fields back (years < 1973 fail checkMs anyway)
|
|
476
|
-
const probe = new Date(Date.UTC(y, mo - 1, d));
|
|
477
|
-
if (mo < 1 || mo > 12 || d < 1 || probe.getUTCFullYear() !== y || probe.getUTCMonth() !== mo - 1 || probe.getUTCDate() !== d) {
|
|
478
|
-
return { ok: false, error: `无效 compAsOf 日期: "${raw}"(${Y}-${Mo}-${D} 不是有效日期)` };
|
|
479
|
-
}
|
|
480
|
-
let v;
|
|
481
|
-
if (h === undefined) {
|
|
482
|
-
v = Date.UTC(y, mo - 1, d, 23, 59, 59, 999); // date-only -> end of that UTC day (inclusive cut-off)
|
|
483
|
-
} else {
|
|
484
|
-
const H = Number(h), Mi = Number(mi), Sc = sec !== undefined ? Number(sec) : 0;
|
|
485
|
-
if (H > 23 || Mi > 59 || Sc > 59) return { ok: false, error: `无效 compAsOf 时间: "${raw}"(时/分/秒超出范围)` };
|
|
486
|
-
const ms = frac ? Math.round(Number(frac) * 1000) : 0;
|
|
487
|
-
let off = 0;
|
|
488
|
-
if (zone && zone.toUpperCase() !== 'Z') {
|
|
489
|
-
const ZH = Number(zh), ZM = Number(zm);
|
|
490
|
-
if (ZH > 14 || ZM > 59) return { ok: false, error: `无效 compAsOf 时区偏移: "${raw}"` };
|
|
491
|
-
off = (sign === '-' ? -1 : 1) * (ZH * 60 + ZM) * 60000;
|
|
492
|
-
}
|
|
493
|
-
v = Date.UTC(y, mo - 1, d, H, Mi, Sc, ms) - off; // no zone -> UTC (off = 0)
|
|
494
|
-
}
|
|
495
|
-
return checkMs(v, `"${raw}"`);
|
|
496
|
-
}
|
|
497
|
-
|
|
498
|
-
function parseSource(raw) {
|
|
499
|
-
if (raw === undefined || raw === null || raw === '') return { ok: true, value: 'auto' };
|
|
500
|
-
const s = String(raw).trim().toLowerCase();
|
|
501
|
-
if (s === 'auto' || s === 'live' || s === 'seed') return { ok: true, value: s };
|
|
502
|
-
return { ok: false, error: `无效 compSource: "${raw}"(可选: auto, live, seed)` };
|
|
503
|
-
}
|
|
504
|
-
|
|
505
|
-
// Process-default cut-off / source from KC_COMP_ASOF / KC_COMP_SOURCE. An invalid value is ignored with ONE warning per
|
|
506
|
-
// distinct value (audit19 P3-6: getCompTable() runs per request / run, the warning used to repeat every time).
|
|
507
|
-
const warnedEnv = new Set();
|
|
508
|
-
function warnEnvOnce(name, raw, error) {
|
|
509
|
-
const k = `${name}=${raw}`;
|
|
510
|
-
if (warnedEnv.has(k)) return;
|
|
511
|
-
warnedEnv.add(k);
|
|
512
|
-
console.warn(`[empiricalComps] 忽略无效环境变量 ${name}: ${error}`);
|
|
513
|
-
}
|
|
514
|
-
function envDefaults() {
|
|
515
|
-
const a = parseAsOf(process.env.KC_COMP_ASOF);
|
|
516
|
-
const s = parseSource(process.env.KC_COMP_SOURCE);
|
|
517
|
-
if (!a.ok) warnEnvOnce('KC_COMP_ASOF', process.env.KC_COMP_ASOF, a.error);
|
|
518
|
-
if (!s.ok) warnEnvOnce('KC_COMP_SOURCE', process.env.KC_COMP_SOURCE, s.error);
|
|
519
|
-
return { asOf: a.ok ? a.value : null, source: s.ok ? s.value : 'auto' };
|
|
520
|
-
}
|
|
521
|
-
|
|
522
|
-
const tableMemo = new Map(); // `${source}|${asOf}|${storeVersion}` -> table
|
|
523
|
-
let installedTable = null; // set by computeWorker (table resolved by the server main thread) or setActiveCompTable()
|
|
524
|
-
|
|
525
|
-
function liveAvailable(dir) {
|
|
526
|
-
try { return !!dir && fs.existsSync(dir) && fs.statSync(dir).isDirectory(); } catch (_) { return false; }
|
|
527
|
-
}
|
|
528
|
-
|
|
529
|
-
// Why the live directory is not usable (for the "使用内置种子表" notice): distinguishes "no APPDATA/USERPROFILE", "does not
|
|
530
|
-
// exist" (ENOENT) and "exists but access denied" (EPERM / EACCES — e.g. an agent terminal or sandbox that can read the
|
|
531
|
-
// claude-bridge snapshot but not the battle-detail folder). Pure diagnosis, never throws.
|
|
532
|
-
function poiDirStatus(dir) {
|
|
533
|
-
if (!dir) return { dir: null, code: 'NO_APPDATA' };
|
|
534
|
-
try {
|
|
535
|
-
const st = fs.statSync(dir);
|
|
536
|
-
if (!st.isDirectory()) return { dir, code: 'NOT_A_DIR' };
|
|
537
|
-
fs.readdirSync(dir);
|
|
538
|
-
return { dir, code: 'OK' };
|
|
539
|
-
} catch (err) {
|
|
540
|
-
return { dir, code: (err && err.code) || 'ERROR' };
|
|
541
|
-
}
|
|
542
|
-
}
|
|
543
|
-
|
|
544
|
-
function seedWithNotice(asOf, reason, detail) {
|
|
545
|
-
const seed = loadSeedTable();
|
|
546
|
-
if (!seed) return null;
|
|
547
|
-
if (asOf == null) {
|
|
548
|
-
if (reason) seed.fingerprint.reason = reason;
|
|
549
|
-
if (detail) seed.fingerprint.reasonDetail = detail; else delete seed.fingerprint.reasonDetail;
|
|
550
|
-
return seed;
|
|
551
|
-
}
|
|
552
|
-
// Seed carries per-battle observations (Wave 20 export) -> the cut-off still applies
|
|
553
|
-
const key = `seed|${asOf}`;
|
|
554
|
-
if (tableMemo.has(key)) return tableMemo.get(key);
|
|
555
|
-
let tbl;
|
|
556
|
-
if (Array.isArray(seed.observations)) {
|
|
557
|
-
tbl = aggregateObservations(seed.observations, { asOf, source: 'seed' });
|
|
558
|
-
tbl.scannedMaxTs = tbl.scannedMaxTs != null ? Math.min(tbl.scannedMaxTs, seed.scannedMaxTs || Infinity) : null;
|
|
559
|
-
tbl.fingerprint.seedAsOf = seed.fingerprint.seedAsOf;
|
|
560
|
-
} else {
|
|
561
|
-
tbl = seed;
|
|
562
|
-
}
|
|
563
|
-
if (reason) tbl.fingerprint.reason = reason;
|
|
564
|
-
if (detail) tbl.fingerprint.reasonDetail = detail; else delete tbl.fingerprint.reasonDetail;
|
|
565
|
-
tableMemo.set(key, tbl);
|
|
566
|
-
return tbl;
|
|
567
|
-
}
|
|
568
|
-
|
|
569
|
-
// Resolve the empirical comp table for { asOf, source, refresh }.
|
|
570
|
-
// source 'auto' (default): live poi logs when the directory is readable and holds at least one sortie observation,
|
|
571
|
-
// otherwise the bundled seed table; 'live': live only (seed if unavailable, with reason);
|
|
572
|
-
// 'seed': always the seed table.
|
|
573
|
-
// refresh: true -> incremental re-scan of the log directory first (CLI start, server throttled checks).
|
|
574
|
-
// Without refresh the in-process observation store is reused (lazily loaded once per process).
|
|
575
|
-
function getCompTable(opts = {}) {
|
|
576
|
-
const env = envDefaults();
|
|
577
|
-
const explicitAsOf = opts.asOf !== undefined && opts.asOf !== null;
|
|
578
|
-
const explicitSource = opts.source !== undefined && opts.source !== null && opts.source !== 'auto';
|
|
579
|
-
if (installedTable && !explicitAsOf && !explicitSource && !opts.refresh) return installedTable;
|
|
580
|
-
const asOf = explicitAsOf ? opts.asOf : env.asOf;
|
|
581
|
-
const source = explicitSource ? opts.source : env.source;
|
|
582
|
-
if (source === 'seed') return seedWithNotice(asOf, 'forced');
|
|
583
|
-
const dir = opts.dir || resolvePoiBattleDir();
|
|
584
|
-
if (!liveAvailable(dir)) return seedWithNotice(asOf, 'no-poi-dir', poiDirStatus(dir));
|
|
585
|
-
const st = getStore(dir);
|
|
586
|
-
try {
|
|
587
|
-
if (opts.refresh || !st.version) refreshStoreSync(dir, { cacheDir: opts.cacheDir });
|
|
588
|
-
} catch (err) {
|
|
589
|
-
if (!st.version) return seedWithNotice(asOf, 'poi-dir-unreadable', { dir, code: (err && err.code) || 'ERROR' });
|
|
590
|
-
}
|
|
591
|
-
if (!st.observations.length) return seedWithNotice(asOf, 'no-sortie-logs');
|
|
592
|
-
return liveTableFromStore(st, asOf);
|
|
593
|
-
}
|
|
594
|
-
|
|
595
|
-
function liveTableFromStore(st, asOf) {
|
|
596
|
-
const key = `live|${st.dir}|${asOf}|${st.version}`;
|
|
597
|
-
if (tableMemo.has(key)) return tableMemo.get(key);
|
|
598
|
-
if (tableMemo.size > 64) tableMemo.clear();
|
|
599
|
-
const scannedTs = [];
|
|
600
|
-
for (const [name, e] of st.files) if (e) scannedTs.push(Number(name.slice(0, -8)));
|
|
601
|
-
const tbl = aggregateObservations(st.observations, { asOf, scannedTs, source: 'live' });
|
|
602
|
-
tbl.fingerprint.pendingFiles = st.pendingCount || 0;
|
|
603
|
-
tableMemo.set(key, tbl);
|
|
604
|
-
return tbl;
|
|
605
|
-
}
|
|
606
|
-
|
|
607
|
-
// Server helper: throttled async refresh. Resolves once the store is current (concurrent callers share one refresh).
|
|
608
|
-
const inflight = new Map();
|
|
609
|
-
async function refreshLiveThrottled({ minIntervalMs = 30000, dir = resolvePoiBattleDir(), cacheDir } = {}) {
|
|
610
|
-
if (!liveAvailable(dir)) return { refreshed: false, available: false };
|
|
611
|
-
const st = getStore(dir);
|
|
612
|
-
const key = st.dir;
|
|
613
|
-
if (inflight.has(key)) return inflight.get(key);
|
|
614
|
-
const now = Date.now();
|
|
615
|
-
if (st.version && now - st.lastCheckMs < minIntervalMs) return { refreshed: false, available: true, throttled: true };
|
|
616
|
-
const p = (async () => {
|
|
617
|
-
try {
|
|
618
|
-
if (st.version && st.sig) {
|
|
619
|
-
// Cheap signature check (directory mtime + file count) before stat-ing every file
|
|
620
|
-
let sig = null;
|
|
621
|
-
try {
|
|
622
|
-
const dst = await fs.promises.stat(dir);
|
|
623
|
-
const n = (await fs.promises.readdir(dir)).filter((f) => LOG_FILE_RE.test(f)).length;
|
|
624
|
-
sig = `${dst.mtimeMs}|${n}`;
|
|
625
|
-
} catch (_) { sig = null; }
|
|
626
|
-
if (sig && sig === st.sig) { st.lastCheckMs = Date.now(); return { refreshed: false, available: true, unchanged: true }; }
|
|
627
|
-
}
|
|
628
|
-
const stats = await refreshStoreAsync(dir, { cacheDir });
|
|
629
|
-
return { refreshed: true, available: true, stats };
|
|
630
|
-
} catch (err) {
|
|
631
|
-
return { refreshed: false, available: !!st.version, error: err.message };
|
|
632
|
-
} finally {
|
|
633
|
-
inflight.delete(key);
|
|
634
|
-
}
|
|
635
|
-
})();
|
|
636
|
-
inflight.set(key, p);
|
|
637
|
-
return p;
|
|
638
|
-
}
|
|
639
|
-
|
|
640
|
-
function setActiveCompTable(tbl) { installedTable = tbl || null; }
|
|
641
|
-
function getInstalledCompTable() { return installedTable; }
|
|
642
|
-
|
|
643
|
-
function getStoreStats(dir = resolvePoiBattleDir()) {
|
|
644
|
-
if (!dir) return null;
|
|
645
|
-
const st = stores.get(path.resolve(dir));
|
|
646
|
-
return st ? { ...st.lastStats, version: st.version, observations: st.observations.length } : null;
|
|
647
|
-
}
|
|
648
|
-
|
|
649
|
-
function clearEmpiricalCompState() {
|
|
650
|
-
stores.clear();
|
|
651
|
-
tableMemo.clear();
|
|
652
|
-
inflight.clear();
|
|
653
|
-
installedTable = null;
|
|
654
|
-
seedCache = undefined;
|
|
655
|
-
}
|
|
656
|
-
|
|
657
|
-
// Test switch (audit19 P3-8): KC_COMP_NO_LIVE_COUNT=1 disables the "N newer live battles not included" count entirely, so test
|
|
658
|
-
// suites running on the seed (KC_COMP_SOURCE=seed) never even read-only scan the user's real poi log directory.
|
|
659
|
-
function liveCountDisabled() { return process.env.KC_COMP_NO_LIVE_COUNT === '1'; }
|
|
660
|
-
|
|
661
|
-
// Count live sortie observations newer than a timestamp (used for the seed / asOf notices). Returns null when there is no
|
|
662
|
-
// readable poi directory (or counting is disabled).
|
|
663
|
-
// sync: true (CLI / library, one-shot): a cold store is refreshed synchronously first (incremental, disk-cached);
|
|
664
|
-
// sync: false (HTTP server main thread, audit19 P3-4): never blocks the event loop and never duplicates the async warm-up
|
|
665
|
-
// scan: while the store is not loaded yet the result is { pending: true } ("统计中"); the server keeps the store
|
|
666
|
-
// current with refreshLiveThrottled() and describeCompData() is memoized per store version, so the count follows.
|
|
667
|
-
function countLiveNewerThan(ts, dir = resolvePoiBattleDir(), { sync = true } = {}) {
|
|
668
|
-
if (liveCountDisabled()) return null;
|
|
669
|
-
if (!dir) return null;
|
|
670
|
-
const known = stores.get(path.resolve(dir));
|
|
671
|
-
if (!sync && !(known && known.version)) return liveAvailable(dir) ? { pending: true, newer: null, latestTs: null } : null;
|
|
672
|
-
if (!liveAvailable(dir)) return null;
|
|
673
|
-
const st = getStore(dir);
|
|
674
|
-
if (!st.version) { try { refreshStoreSync(dir); } catch (_) { return null; } }
|
|
675
|
-
let n = 0;
|
|
676
|
-
let latest = 0;
|
|
677
|
-
for (const o of st.observations) {
|
|
678
|
-
if (o.ts > ts && resolveMapPhases(o.map, o.cell, o.ships).length) { n++; if (o.ts > latest) latest = o.ts; }
|
|
679
|
-
}
|
|
680
|
-
return { newer: n, latestTs: latest || null };
|
|
681
|
-
}
|
|
682
|
-
|
|
683
|
-
// Live-store state stamp for describeCompData's memo: the "另有 N 场未纳入" count must follow store refreshes (audit19 P3-4).
|
|
684
|
-
function liveCountStamp() {
|
|
685
|
-
if (liveCountDisabled()) return 'off';
|
|
686
|
-
const dir = resolvePoiBattleDir();
|
|
687
|
-
const st = dir ? stores.get(path.resolve(dir)) : null;
|
|
688
|
-
return `${dir || ''}#${st ? st.version : 0}`;
|
|
689
|
-
}
|
|
690
|
-
|
|
691
|
-
// Human-readable data-source notice: only for the seed table or an explicit cut-off (live mode is never "stale").
|
|
692
|
-
// checkLive: also count live poi sortie battles newer than the seed / cut-off. Used by the CLI fingerprint line and the HTTP
|
|
693
|
-
// server (status / sim / optimize). NOTE: this still READS the real poi directory even when the table itself is the seed
|
|
694
|
-
// (KC_COMP_SOURCE=seed / --comp-source seed): a read-only, disk-cached incremental scan for the count; it never affects the
|
|
695
|
-
// table or the results. Set KC_COMP_NO_LIVE_COUNT=1 to skip it completely (the test suites do). runMonteCarlo always calls
|
|
696
|
-
// with checkLive: false. sync: false (server) = never scan on the calling thread (see countLiveNewerThan).
|
|
697
|
-
// Memoized per table object + reason + live-store version.
|
|
698
|
-
const describeMemo = new WeakMap();
|
|
699
|
-
function describeCompData(tbl, { checkLive = true, sync = true } = {}) {
|
|
700
|
-
const fp = tbl && tbl.fingerprint;
|
|
701
|
-
if (!fp) return { notice: null, fingerprint: null };
|
|
702
|
-
const memoKey = `${checkLive ? (sync ? 'live-sync' : 'live-async') : 'plain'}|${fp.reason || ''}`; // seed reason can change
|
|
703
|
-
const stampOf = () => (checkLive ? liveCountStamp() : '');
|
|
704
|
-
const memo = describeMemo.get(tbl);
|
|
705
|
-
const hit = memo && memo[memoKey];
|
|
706
|
-
if (hit && hit.stamp === stampOf()) return hit.out;
|
|
707
|
-
const day = (ts) => (ts ? new Date(ts).toISOString().slice(0, 16).replace('T', ' ') + ' UTC' : '-');
|
|
708
|
-
let notice = null;
|
|
709
|
-
if (fp.source === 'seed') {
|
|
710
|
-
const rd = fp.reasonDetail || null;
|
|
711
|
-
const denied = rd && (rd.code === 'EPERM' || rd.code === 'EACCES');
|
|
712
|
-
const why = fp.reason === 'forced' ? '(已指定 --comp-source seed / KC_COMP_SOURCE=seed)'
|
|
713
|
-
: fp.reason === 'no-sortie-logs' ? '(poi 战斗记录目录中没有可用的出击记录)'
|
|
714
|
-
: rd && rd.code === 'NO_APPDATA' ? '(未找到本地 poi 战斗记录目录:环境变量 APPDATA / USERPROFILE 均未设置,可用 POI_BATTLE_DIR 指定)'
|
|
715
|
-
: rd && rd.dir ? `(${denied ? '无权访问' : fp.reason === 'poi-dir-unreadable' ? '读取失败' : '找不到'}本地 poi 战斗记录目录 ${rd.dir}:${rd.code}`
|
|
716
|
-
+ `${denied ? ';若在受限终端 / 沙箱中运行,请放行该目录或用 POI_BATTLE_DIR 指定可读路径' : ''})`
|
|
717
|
-
: '(未找到可读的本地 poi 战斗记录目录)';
|
|
718
|
-
notice = `使用内置种子表${why}:${fp.nBattles} 场出击,截至 ${day(tbl.scannedMaxTs)}`;
|
|
719
|
-
if (fp.asOf != null && fp.asOf !== fp.seedAsOf) notice += `,并按截止时间 ${day(fp.asOf)} 过滤`;
|
|
720
|
-
if (checkLive && fp.reason === 'forced') {
|
|
721
|
-
const nw = countLiveNewerThan(Math.max(tbl.scannedMaxTs || 0, fp.asOf || 0), undefined, { sync });
|
|
722
|
-
if (nw && nw.pending) notice += ';本地 poi 新记录统计中';
|
|
723
|
-
else if (nw && nw.newer > 0) notice += `;本地 poi 记录在其后另有 ${nw.newer} 场出击未纳入`;
|
|
724
|
-
}
|
|
725
|
-
notice += '。';
|
|
726
|
-
} else if (fp.asOf != null) {
|
|
727
|
-
const nw = checkLive ? countLiveNewerThan(fp.asOf, undefined, { sync }) : null;
|
|
728
|
-
const extra = nw && nw.pending ? '(其后新增场数统计中)' : (nw && nw.newer > 0 ? `,其后 ${nw.newer} 场出击未纳入` : '');
|
|
729
|
-
notice = `经验编成按截止时间 ${day(fp.asOf)} 复现:纳入 ${fp.nBattles} 场出击${extra}。`;
|
|
730
|
-
}
|
|
731
|
-
const out = { notice, fingerprint: fp };
|
|
732
|
-
describeMemo.set(tbl, { ...(memo || {}), [memoKey]: { stamp: stampOf(), out } }); // latest store version only
|
|
733
|
-
return out;
|
|
734
|
-
}
|
|
735
|
-
|
|
736
|
-
function formatFingerprint(fp) {
|
|
737
|
-
if (!fp) return '-';
|
|
738
|
-
const t = (ts) => (ts ? new Date(ts).toISOString().slice(0, 19).replace('T', ' ') + 'Z' : '-');
|
|
739
|
-
const seedCut = fp.source === 'seed' && fp.asOf != null && fp.asOf === fp.seedAsOf ? '(种子表截止)' : '';
|
|
740
|
-
return `source=${fp.source} | ${fp.nBattles}场 | asOf=${fp.asOf != null ? t(fp.asOf) + seedCut : '实时(无截止)'} | 数据截至=${t(fp.scannedMaxTs)} | hash=${fp.hash || '-'}${fp.model ? ` | 模型=${fp.model}` : ''}`;
|
|
741
|
-
}
|
|
742
|
-
|
|
743
|
-
module.exports = {
|
|
744
|
-
CACHE_VERSION,
|
|
745
|
-
SEED_PATH,
|
|
746
|
-
POI_NODE_LETTER,
|
|
747
|
-
PHASED_MAPS,
|
|
748
|
-
PENDING_GRACE_MS,
|
|
749
|
-
resolveNodeLetter,
|
|
750
|
-
resolveMapPhases,
|
|
751
|
-
extractObservation,
|
|
752
|
-
resolvePoiBattleDir,
|
|
753
|
-
resolveCacheDir,
|
|
754
|
-
cacheFileFor,
|
|
755
|
-
refreshStoreSync,
|
|
756
|
-
refreshStoreAsync,
|
|
757
|
-
refreshLiveThrottled,
|
|
758
|
-
aggregateObservations,
|
|
759
|
-
stableHash,
|
|
760
|
-
loadSeedTable,
|
|
761
|
-
parseAsOf,
|
|
762
|
-
parseSource,
|
|
763
|
-
getCompTable,
|
|
764
|
-
setActiveCompTable,
|
|
765
|
-
getInstalledCompTable,
|
|
766
|
-
getStoreStats,
|
|
767
|
-
describeCompData,
|
|
768
|
-
formatFingerprint,
|
|
769
|
-
countLiveNewerThan,
|
|
770
|
-
envDefaults,
|
|
771
|
-
clearEmpiricalCompState,
|
|
772
|
-
writeFileAtomic,
|
|
773
|
-
};
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Wave 20: live, incremental empirical enemy-composition data computed directly from the local poi battle-detail logs.
|
|
4
|
+
//
|
|
5
|
+
// Replaces the manual `node scripts/build_comp_weights.js` rebuild step:
|
|
6
|
+
// * every <ts>.json.gz log is reduced once to an "observation" {ts, map, cell, ships, hq, form} (or a skip verdict);
|
|
7
|
+
// * per-file results are persisted in a user cache file keyed by file name + mtimeMs + size (versioned, atomic write),
|
|
8
|
+
// so a refresh only gunzips new / changed files;
|
|
9
|
+
// * observations are aggregated in memory into the same table shape as data/empirical_comp_weights.json
|
|
10
|
+
// ({ maps: { mapId: { node: { total, hqMin, hqMax, byHq: { hq: { shipsCsv: n } } } } }, hqRange, nBattles, ... })
|
|
11
|
+
// which src/engine/sortie.js applyEmpiricalCompWeights consumes;
|
|
12
|
+
// * a cut-off time (asOf, ms) keeps results reproducible: only observations with ts <= asOf are aggregated;
|
|
13
|
+
// * without a readable poi directory (or with source = 'seed') the bundled seed table data/empirical_comp_weights.json is used.
|
|
14
|
+
//
|
|
15
|
+
// Node-letter resolution (POI_NODE_LETTER + exact-composition match + 7-2 phase split) lives here so src/ never requires
|
|
16
|
+
// scripts/; scripts/build_comp_weights.js is now a thin export wrapper around this module.
|
|
17
|
+
|
|
18
|
+
const fs = require('fs');
|
|
19
|
+
const os = require('os');
|
|
20
|
+
const path = require('path');
|
|
21
|
+
const zlib = require('zlib');
|
|
22
|
+
const crypto = require('crypto');
|
|
23
|
+
const { MAPS, POI_CELLS } = require('./maps');
|
|
24
|
+
|
|
25
|
+
// Bump when extractObservation() semantics change: every cached per-file verdict is discarded.
|
|
26
|
+
// 2 (Phase D, E11): night-start (battle_midnight/sp_midnight) and radar-ambush (ld_shooting) packets are observations too.
|
|
27
|
+
const CACHE_VERSION = 2;
|
|
28
|
+
const SEED_PATH = path.join(__dirname, '../../data/empirical_comp_weights.json');
|
|
29
|
+
const LOG_FILE_RE = /^\d+\.json\.gz$/;
|
|
30
|
+
// A log that fails to parse and was modified within this window is treated as "still being written" (retried next refresh,
|
|
31
|
+
// never cached). Older unreadable files are cached as 'bad' (keyed by mtime + size, so a rewrite is re-parsed).
|
|
32
|
+
const PENDING_GRACE_MS = 10 * 60 * 1000;
|
|
33
|
+
|
|
34
|
+
// Verified Phase 2 poi edge/node ID -> map letter mapping (matching exact comp pools in MAPS)
|
|
35
|
+
const POI_NODE_LETTER = {
|
|
36
|
+
'1-1': { 1: 'A', 2: 'B', 3: 'C' },
|
|
37
|
+
'1-2': { 1: 'A', 3: 'C', 5: 'E' },
|
|
38
|
+
'1-3': { 3: 'C', 5: 'E', 6: 'F', 10: 'J', 11: 'E', 12: 'F', 13: 'J' },
|
|
39
|
+
'1-4': { 2: 'B', 4: 'D', 8: 'H', 10: 'J', 12: 'L', 17: 'L' },
|
|
40
|
+
'1-5': { 1: 'A', 4: 'D', 6: 'F', 9: 'I', 12: 'J' },
|
|
41
|
+
'1-6': { 3: 'E', 12: 'F', 13: 'B' },
|
|
42
|
+
'2-1': { 3: 'C', 4: 'D', 8: 'H', 9: 'D' },
|
|
43
|
+
'2-2': { 2: 'B', 5: 'E', 7: 'G', 11: 'K', 14: 'K' },
|
|
44
|
+
'2-3': { 1: 'A', 5: 'E', 10: 'J', 11: 'K', 14: 'N', 16: 'F', 17: 'F', 19: 'K', 20: 'N' },
|
|
45
|
+
'2-4': { 2: 'B', 5: 'E', 6: 'F', 9: 'I', 13: 'M', 16: 'P', 18: 'L', 19: 'L', 21: 'P' },
|
|
46
|
+
'2-5': { 3: 'C', 5: 'E', 15: 'O' },
|
|
47
|
+
'3-1': { 3: 'C', 6: 'F', 9: 'G' },
|
|
48
|
+
'3-2': { 3: 'C', 12: 'L' },
|
|
49
|
+
'3-3': { 1: 'A', 7: 'G', 13: 'M' },
|
|
50
|
+
'3-4': { 1: 'A', 3: 'C', 7: 'G' },
|
|
51
|
+
};
|
|
52
|
+
// Phase D: cell -> letter tables of the map modules (src/data/maps_phaseD/*.js poiCells; empty until poi logs exist). The
|
|
53
|
+
// unique-composition fallback below is ambiguous on 4-5 E/G and 5-2 C/L (identical pools), so those need real cell ids.
|
|
54
|
+
for (const [base, cells] of Object.entries(POI_CELLS || {})) {
|
|
55
|
+
if (!POI_NODE_LETTER[base]) POI_NODE_LETTER[base] = { ...cells };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// Phase D (E8): poi logs a multi-gauge map under its base id (7-2, 7-3); the simulator models each gauge as its own map id
|
|
59
|
+
// (7-2-1 / 7-2-2 ...). Derived from MAPS[*].baseMapId (was the literal '7-2' -> ['7-2-1', '7-2-2']).
|
|
60
|
+
const PHASED_MAPS = {};
|
|
61
|
+
for (const [id, m] of Object.entries(MAPS)) {
|
|
62
|
+
if (m && m.baseMapId && m.baseMapId !== id) (PHASED_MAPS[m.baseMapId] || (PHASED_MAPS[m.baseMapId] = [])).push(id);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function resolveNodeLetter(mapId, nid, eIdsCsv) {
|
|
66
|
+
const m = MAPS[mapId];
|
|
67
|
+
// (Phase D: a gauge-split map id falls back to the cell table of its poi base map id)
|
|
68
|
+
const mapped = POI_NODE_LETTER[mapId]?.[nid] || (m && m.baseMapId && m.baseMapId !== mapId ? POI_NODE_LETTER[m.baseMapId]?.[nid] : undefined);
|
|
69
|
+
if (!m) return null;
|
|
70
|
+
if (mapped && m.nodes[mapped]?.comps?.some((c) => c.ships.join(',') === eIdsCsv)) return mapped;
|
|
71
|
+
// Fallback: unique node match by ship composition
|
|
72
|
+
const matches = Object.entries(m.nodes)
|
|
73
|
+
.filter(([, nd]) => nd.comps && nd.comps.some((c) => c.ships.join(',') === eIdsCsv))
|
|
74
|
+
.map(([nl]) => nl);
|
|
75
|
+
return matches.length === 1 ? matches[0] : (mapped || null);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// poi logs 7-2 as map [7, 2, node] for BOTH gauge phases; the simulator models them as 7-2-1 (G boss) / 7-2-2 (M boss).
|
|
79
|
+
// Resolve against every phase whose node pool contains this exact enemy composition (shared nodes count for both).
|
|
80
|
+
function resolveMapPhases(mapId, nid, eIdsCsv) {
|
|
81
|
+
const phaseIds = PHASED_MAPS[mapId] ? PHASED_MAPS[mapId].filter((k) => MAPS[k]) : (MAPS[mapId] ? [mapId] : []);
|
|
82
|
+
const out = [];
|
|
83
|
+
for (const pid of phaseIds) {
|
|
84
|
+
const letter = resolveNodeLetter(pid, nid, eIdsCsv);
|
|
85
|
+
if (!letter) continue;
|
|
86
|
+
// Multi-phase maps: require an exact composition match so a 7-2-1-only boss comp never leaks into 7-2-2 (and vice versa)
|
|
87
|
+
if (phaseIds.length > 1 && !MAPS[pid].nodes[letter]?.comps?.some((c) => c.ships.join(',') === eIdsCsv)) continue;
|
|
88
|
+
out.push({ mapId: pid, nodeLetter: letter });
|
|
89
|
+
}
|
|
90
|
+
return out;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// Reduce one parsed poi battle-detail log to an observation. Pure function of the log content (cached per file), so it
|
|
94
|
+
// deliberately does NOT consult MAPS: node letters are resolved at aggregation time (MAPS data updates need no re-parse).
|
|
95
|
+
// Same filters as the pre-Wave-20 builder: 演習 (empty map), non-abyssal enemies (ids < 1500), combined / escort fleets,
|
|
96
|
+
// logs without a day-battle packet or HQ level; plus (Wave 20) 教程战 = tutorial logs with an empty main fleet.
|
|
97
|
+
function extractObservation(d, ts) {
|
|
98
|
+
if (!d || typeof d !== 'object') return { kind: 'skip', reason: 'invalid' };
|
|
99
|
+
if (!Array.isArray(d.map) || d.map.length < 3) return { kind: 'skip', reason: 'practice/non-sortie' };
|
|
100
|
+
const mapId = `${d.map[0]}-${d.map[1]}`;
|
|
101
|
+
// Phase D (E11): the first battle packet of the node -- day battle, aerial battle, long-distance air raid, radar ambush
|
|
102
|
+
// (ld_shooting) or night-start node (battle_midnight/sp_midnight; never the night continuation battle_midnight/battle).
|
|
103
|
+
const day = (d.packet || []).find((p) => p && /api_req_(sortie\/(battle|airbattle|ld_airbattle|ld_shooting)|battle_midnight\/sp_midnight)$/.test(String(p.poi_path || '')));
|
|
104
|
+
if (!day || !Array.isArray(day.api_ship_ke)) return { kind: 'skip', reason: 'no-day-battle' };
|
|
105
|
+
if (day.api_ship_ke.some((id) => id > 0 && id < 1500)) return { kind: 'skip', reason: 'non-abyssal (tutorial)' };
|
|
106
|
+
if (d.fleet && (d.fleet.type !== 0 || (d.fleet.escort && d.fleet.escort.length))) return { kind: 'skip', reason: 'combined/escort' };
|
|
107
|
+
// Wave 20: 教程战 (tutorial sortie logged with an empty main fleet, scripted enemy) is not a natural comp draw
|
|
108
|
+
if (d.fleet && Array.isArray(d.fleet.main) && d.fleet.main.length === 0) return { kind: 'skip', reason: 'tutorial (empty fleet)' };
|
|
109
|
+
const ships = day.api_ship_ke.filter((x) => x > 0).join(',');
|
|
110
|
+
const hq = d.admiral?.lv || d.admiral?.api_level || (d.packet || []).find((p) => p && p.api_member_lv)?.api_member_lv;
|
|
111
|
+
if (!hq || !ships) return { kind: 'skip', reason: 'no-hq/no-enemy' };
|
|
112
|
+
const form = Array.isArray(day.api_formation) && day.api_formation.length > 1 ? Number(day.api_formation[1]) : null;
|
|
113
|
+
return { kind: 'obs', obs: { ts, map: mapId, cell: d.map[2], ships, hq: Number(hq), form } };
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function resolvePoiBattleDir() {
|
|
117
|
+
if (process.env.POI_BATTLE_DIR) return process.env.POI_BATTLE_DIR;
|
|
118
|
+
if (process.env.POI_DATA_DIR) return path.join(process.env.POI_DATA_DIR, 'battle-detail');
|
|
119
|
+
if (process.platform === 'win32') {
|
|
120
|
+
const appData = process.env.APPDATA || (process.env.USERPROFILE ? path.join(process.env.USERPROFILE, 'AppData', 'Roaming') : null);
|
|
121
|
+
return appData ? path.join(appData, 'poi', 'battle-detail') : null;
|
|
122
|
+
}
|
|
123
|
+
if (process.platform === 'darwin') {
|
|
124
|
+
return path.join(os.homedir(), 'Library', 'Application Support', 'poi', 'battle-detail');
|
|
125
|
+
}
|
|
126
|
+
return path.join(process.env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config'), 'poi', 'battle-detail');
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function resolveCacheDir() {
|
|
130
|
+
if (process.env.KC_CACHE_DIR) return process.env.KC_CACHE_DIR;
|
|
131
|
+
if (process.platform === 'win32') {
|
|
132
|
+
const local = process.env.LOCALAPPDATA || (process.env.USERPROFILE ? path.join(process.env.USERPROFILE, 'AppData', 'Local') : os.tmpdir());
|
|
133
|
+
return path.join(local, 'brainoff');
|
|
134
|
+
}
|
|
135
|
+
return path.join(process.env.XDG_CACHE_HOME || path.join(os.homedir(), '.cache'), 'brainoff');
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function cacheFileFor(dir, cacheDir = resolveCacheDir()) {
|
|
139
|
+
const h = crypto.createHash('sha1').update(path.resolve(dir).toLowerCase()).digest('hex').slice(0, 12);
|
|
140
|
+
return path.join(cacheDir, `comp_obs_${h}.json`);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function writeFileAtomic(file, text) {
|
|
144
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
145
|
+
const tmp = `${file}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2, 8)}.tmp`;
|
|
146
|
+
fs.writeFileSync(tmp, text, 'utf8');
|
|
147
|
+
try {
|
|
148
|
+
fs.renameSync(tmp, file);
|
|
149
|
+
} catch (err) {
|
|
150
|
+
try { fs.unlinkSync(tmp); } catch (_) { /* ignore */ }
|
|
151
|
+
throw err;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// ------------------------------------------------------------------------------------------------ observation store
|
|
156
|
+
// In-process state per log directory: { files: Map(name -> entry), cacheLoaded, sig, observations, version, lastCheckMs }
|
|
157
|
+
// entry = { m: mtimeMs, s: size, k: 'o' | 's' | 'b', o?: obs, r?: reason } ('b' = unreadable & older than the grace window)
|
|
158
|
+
// retryBad: names of 'b' entries loaded from the disk cache; each is re-parsed once per process (audit19 P3-5), so a file that
|
|
159
|
+
// was unreadable only transiently (or repaired in place with the same mtime + size) is not excluded forever.
|
|
160
|
+
const stores = new Map();
|
|
161
|
+
let storeVersionSeq = 0;
|
|
162
|
+
const stats0 = () => ({ files: 0, reused: 0, parsed: 0, pending: 0, bad: 0, skipped: 0, observations: 0, cacheWritten: false, elapsedMs: 0 });
|
|
163
|
+
|
|
164
|
+
function getStore(dir) {
|
|
165
|
+
const key = path.resolve(dir);
|
|
166
|
+
let st = stores.get(key);
|
|
167
|
+
if (!st) {
|
|
168
|
+
st = { dir: key, files: new Map(), retryBad: new Set(), cacheLoaded: false, sig: null, observations: [], version: 0, pendingCount: 0, lastCheckMs: 0, lastStats: null };
|
|
169
|
+
stores.set(key, st);
|
|
170
|
+
}
|
|
171
|
+
return st;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function loadDiskCache(st, cacheDir) {
|
|
175
|
+
if (st.cacheLoaded) return;
|
|
176
|
+
st.cacheLoaded = true;
|
|
177
|
+
const file = cacheFileFor(st.dir, cacheDir);
|
|
178
|
+
let raw;
|
|
179
|
+
try { raw = JSON.parse(fs.readFileSync(file, 'utf8')); } catch (_) { return; }
|
|
180
|
+
if (!raw || raw.version !== CACHE_VERSION || !raw.files || typeof raw.files !== 'object') return; // version bump: drop all
|
|
181
|
+
// The cache file name is a hash of the lower-cased directory: also require the stored directory to match (audit19 P3-5)
|
|
182
|
+
if (typeof raw.dir !== 'string' || path.resolve(raw.dir).toLowerCase() !== st.dir.toLowerCase()) return;
|
|
183
|
+
for (const [name, e] of Object.entries(raw.files)) {
|
|
184
|
+
if (e && typeof e === 'object' && (e.k === 'o' || e.k === 's' || e.k === 'b')) {
|
|
185
|
+
st.files.set(name, e);
|
|
186
|
+
if (e.k === 'b') st.retryBad.add(name);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// prev entry still valid for the file's current stat? ('b' entries from the disk cache are re-tried once per process)
|
|
192
|
+
function canReuse(st, name, prev, fst) {
|
|
193
|
+
if (!prev || prev.m !== fst.mtimeMs || prev.s !== fst.size) return false;
|
|
194
|
+
return !(prev.k === 'b' && st.retryBad.has(name));
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// Store a fresh verdict; returns true when the entry actually changed (a repeated 'b' verdict for the same file is a no-op)
|
|
198
|
+
function storeVerdict(st, name, prev, fst, v) {
|
|
199
|
+
st.retryBad.delete(name);
|
|
200
|
+
if (prev && prev.k === 'b' && v.k === 'b' && prev.m === fst.mtimeMs && prev.s === fst.size) return false;
|
|
201
|
+
st.files.set(name, { m: fst.mtimeMs, s: fst.size, ...v });
|
|
202
|
+
return true;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function saveDiskCache(st, cacheDir) {
|
|
206
|
+
const files = {};
|
|
207
|
+
for (const [name, e] of [...st.files.entries()].sort((a, b) => (a[0] < b[0] ? -1 : 1))) files[name] = e;
|
|
208
|
+
const payload = { version: CACHE_VERSION, dir: st.dir, updatedAt: new Date().toISOString(), files };
|
|
209
|
+
writeFileAtomic(cacheFileFor(st.dir, cacheDir), JSON.stringify(payload));
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function verdictFromBuffer(buf, ts, mtimeMs, now) {
|
|
213
|
+
let d = null;
|
|
214
|
+
try { d = JSON.parse(zlib.gunzipSync(buf)); } catch (_) { d = null; }
|
|
215
|
+
if (!d) return (now - mtimeMs) < PENDING_GRACE_MS ? null : { k: 'b', r: 'corrupt gzip/json' }; // null = pending, retry later
|
|
216
|
+
const v = extractObservation(d, ts);
|
|
217
|
+
return v.kind === 'obs' ? { k: 'o', o: v.obs } : { k: 's', r: v.reason };
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function dirSignature(dir) {
|
|
221
|
+
const dst = fs.statSync(dir);
|
|
222
|
+
const names = fs.readdirSync(dir).filter((f) => LOG_FILE_RE.test(f));
|
|
223
|
+
return { sig: `${dst.mtimeMs}|${names.length}`, names };
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function finalizeStore(st, names, changed, stats, cacheDir, t0) {
|
|
227
|
+
// Drop entries of deleted files
|
|
228
|
+
const live = new Set(names);
|
|
229
|
+
for (const name of [...st.files.keys()]) {
|
|
230
|
+
if (!live.has(name)) { st.files.delete(name); changed = true; }
|
|
231
|
+
}
|
|
232
|
+
if (changed || !st.version) {
|
|
233
|
+
const obs = [];
|
|
234
|
+
for (const name of names) {
|
|
235
|
+
const e = st.files.get(name);
|
|
236
|
+
if (e && e.k === 'o' && e.o) obs.push(e.o);
|
|
237
|
+
}
|
|
238
|
+
obs.sort((a, b) => a.ts - b.ts || (a.cell - b.cell));
|
|
239
|
+
st.observations = obs;
|
|
240
|
+
st.version = ++storeVersionSeq;
|
|
241
|
+
if (changed) {
|
|
242
|
+
try { saveDiskCache(st, cacheDir); stats.cacheWritten = true; } catch (_) { /* read-only cache dir: in-memory only */ }
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
stats.observations = st.observations.length;
|
|
246
|
+
stats.elapsedMs = Date.now() - t0;
|
|
247
|
+
st.lastStats = stats;
|
|
248
|
+
return stats;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// Synchronous incremental refresh (CLI / library / worker fallback). Returns stats; throws if the directory is unreadable.
|
|
252
|
+
function refreshStoreSync(dir, { cacheDir = resolveCacheDir() } = {}) {
|
|
253
|
+
const t0 = Date.now();
|
|
254
|
+
const st = getStore(dir);
|
|
255
|
+
loadDiskCache(st, cacheDir);
|
|
256
|
+
const { sig, names } = dirSignature(dir);
|
|
257
|
+
const stats = stats0();
|
|
258
|
+
stats.files = names.length;
|
|
259
|
+
let changed = false;
|
|
260
|
+
let pending = 0;
|
|
261
|
+
const now = Date.now();
|
|
262
|
+
for (const name of names) {
|
|
263
|
+
const full = path.join(dir, name);
|
|
264
|
+
let fst;
|
|
265
|
+
try { fst = fs.statSync(full); } catch (_) { pending++; continue; }
|
|
266
|
+
const prev = st.files.get(name);
|
|
267
|
+
if (canReuse(st, name, prev, fst)) {
|
|
268
|
+
stats.reused++;
|
|
269
|
+
if (prev.k === 'b') stats.bad++; else if (prev.k === 's') stats.skipped++;
|
|
270
|
+
continue;
|
|
271
|
+
}
|
|
272
|
+
let buf;
|
|
273
|
+
try { buf = fs.readFileSync(full); } catch (_) { pending++; continue; }
|
|
274
|
+
stats.parsed++;
|
|
275
|
+
const v = verdictFromBuffer(buf, Number(name.slice(0, -8)), fst.mtimeMs, now);
|
|
276
|
+
if (!v) {
|
|
277
|
+
pending++;
|
|
278
|
+
if (prev) { st.files.delete(name); changed = true; }
|
|
279
|
+
continue;
|
|
280
|
+
}
|
|
281
|
+
if (v.k === 'b') stats.bad++; else if (v.k === 's') stats.skipped++;
|
|
282
|
+
if (storeVerdict(st, name, prev, fst, v)) changed = true;
|
|
283
|
+
}
|
|
284
|
+
stats.pending = pending;
|
|
285
|
+
st.pendingCount = pending;
|
|
286
|
+
st.sig = pending ? null : sig; // pending files force a re-check on the next refresh
|
|
287
|
+
st.lastCheckMs = Date.now();
|
|
288
|
+
return finalizeStore(st, names, changed, stats, cacheDir, t0);
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
// Asynchronous variant for the HTTP server main thread (gunzip off the event loop thread pool; no long sync stall).
|
|
292
|
+
async function refreshStoreAsync(dir, { cacheDir = resolveCacheDir() } = {}) {
|
|
293
|
+
const t0 = Date.now();
|
|
294
|
+
const st = getStore(dir);
|
|
295
|
+
loadDiskCache(st, cacheDir);
|
|
296
|
+
const fsp = fs.promises;
|
|
297
|
+
const dst = await fsp.stat(dir);
|
|
298
|
+
const names = (await fsp.readdir(dir)).filter((f) => LOG_FILE_RE.test(f));
|
|
299
|
+
const sig = `${dst.mtimeMs}|${names.length}`;
|
|
300
|
+
const stats = stats0();
|
|
301
|
+
stats.files = names.length;
|
|
302
|
+
let changed = false;
|
|
303
|
+
let pending = 0;
|
|
304
|
+
const now = Date.now();
|
|
305
|
+
const gunzip = (buf) => new Promise((resolve) => zlib.gunzip(buf, (err, out) => resolve(err ? null : out)));
|
|
306
|
+
for (const name of names) {
|
|
307
|
+
const full = path.join(dir, name);
|
|
308
|
+
let fst;
|
|
309
|
+
try { fst = await fsp.stat(full); } catch (_) { pending++; continue; }
|
|
310
|
+
const prev = st.files.get(name);
|
|
311
|
+
if (canReuse(st, name, prev, fst)) {
|
|
312
|
+
stats.reused++;
|
|
313
|
+
if (prev.k === 'b') stats.bad++; else if (prev.k === 's') stats.skipped++;
|
|
314
|
+
continue;
|
|
315
|
+
}
|
|
316
|
+
let buf;
|
|
317
|
+
try { buf = await fsp.readFile(full); } catch (_) { pending++; continue; }
|
|
318
|
+
stats.parsed++;
|
|
319
|
+
const ts = Number(name.slice(0, -8));
|
|
320
|
+
const out = await gunzip(buf);
|
|
321
|
+
let v;
|
|
322
|
+
if (!out) {
|
|
323
|
+
v = (now - fst.mtimeMs) < PENDING_GRACE_MS ? null : { k: 'b', r: 'corrupt gzip/json' };
|
|
324
|
+
} else {
|
|
325
|
+
let d = null;
|
|
326
|
+
try { d = JSON.parse(out); } catch (_) { d = null; }
|
|
327
|
+
if (!d) v = (now - fst.mtimeMs) < PENDING_GRACE_MS ? null : { k: 'b', r: 'corrupt gzip/json' };
|
|
328
|
+
else { const x = extractObservation(d, ts); v = x.kind === 'obs' ? { k: 'o', o: x.obs } : { k: 's', r: x.reason }; }
|
|
329
|
+
}
|
|
330
|
+
if (!v) {
|
|
331
|
+
pending++;
|
|
332
|
+
if (prev) { st.files.delete(name); changed = true; }
|
|
333
|
+
continue;
|
|
334
|
+
}
|
|
335
|
+
if (v.k === 'b') stats.bad++; else if (v.k === 's') stats.skipped++;
|
|
336
|
+
if (storeVerdict(st, name, prev, fst, v)) changed = true;
|
|
337
|
+
}
|
|
338
|
+
stats.pending = pending;
|
|
339
|
+
st.pendingCount = pending;
|
|
340
|
+
st.sig = pending ? null : sig;
|
|
341
|
+
st.lastCheckMs = Date.now();
|
|
342
|
+
return finalizeStore(st, names, changed, stats, cacheDir, t0);
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
// ------------------------------------------------------------------------------------------------ aggregation
|
|
346
|
+
function stableHash(obsList) {
|
|
347
|
+
const h = crypto.createHash('sha1');
|
|
348
|
+
for (const o of obsList) h.update(`${o.ts}|${o.map}|${o.cell}|${o.ships}|${o.hq}\n`);
|
|
349
|
+
return h.digest('hex').slice(0, 12);
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
// Aggregate observations (ts <= asOf when asOf != null) into the table shape consumed by applyEmpiricalCompWeights.
|
|
353
|
+
// scannedMaxTs = newest log file (any kind, excluding files still being written) with ts <= asOf.
|
|
354
|
+
function aggregateObservations(observations, { asOf = null, scannedTs = null, source = 'live' } = {}) {
|
|
355
|
+
const maps = {};
|
|
356
|
+
let nBattles = 0;
|
|
357
|
+
let minHq = Infinity;
|
|
358
|
+
let maxHq = 0;
|
|
359
|
+
let minTs = Infinity;
|
|
360
|
+
let maxTs = 0;
|
|
361
|
+
const counted = [];
|
|
362
|
+
for (const o of observations) {
|
|
363
|
+
if (asOf != null && o.ts > asOf) continue;
|
|
364
|
+
const targets = resolveMapPhases(o.map, o.cell, o.ships);
|
|
365
|
+
if (!targets.length) continue;
|
|
366
|
+
nBattles++;
|
|
367
|
+
counted.push(o);
|
|
368
|
+
if (o.ts > 0) { if (o.ts < minTs) minTs = o.ts; if (o.ts > maxTs) maxTs = o.ts; }
|
|
369
|
+
if (o.hq < minHq) minHq = o.hq;
|
|
370
|
+
if (o.hq > maxHq) maxHq = o.hq;
|
|
371
|
+
for (const { mapId, nodeLetter } of targets) {
|
|
372
|
+
if (!maps[mapId]) maps[mapId] = {};
|
|
373
|
+
if (!maps[mapId][nodeLetter]) maps[mapId][nodeLetter] = { total: 0, hqMin: o.hq, hqMax: o.hq, byHq: {} };
|
|
374
|
+
const rec = maps[mapId][nodeLetter];
|
|
375
|
+
rec.total++;
|
|
376
|
+
if (o.hq < rec.hqMin) rec.hqMin = o.hq;
|
|
377
|
+
if (o.hq > rec.hqMax) rec.hqMax = o.hq;
|
|
378
|
+
const hk = String(o.hq);
|
|
379
|
+
if (!rec.byHq[hk]) rec.byHq[hk] = {};
|
|
380
|
+
rec.byHq[hk][o.ships] = (rec.byHq[hk][o.ships] || 0) + 1;
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
let scannedMaxTs = 0;
|
|
384
|
+
if (Array.isArray(scannedTs)) {
|
|
385
|
+
for (const ts of scannedTs) if ((asOf == null || ts <= asOf) && ts > scannedMaxTs) scannedMaxTs = ts;
|
|
386
|
+
} else {
|
|
387
|
+
scannedMaxTs = maxTs;
|
|
388
|
+
}
|
|
389
|
+
const iso = (ts) => new Date(ts).toISOString();
|
|
390
|
+
const tbl = {
|
|
391
|
+
source: 'local poi battle-detail, not wiki',
|
|
392
|
+
generatedAt: new Date().toISOString().slice(0, 10),
|
|
393
|
+
nBattles,
|
|
394
|
+
hqRange: nBattles > 0 ? [minHq, maxHq] : [0, 0],
|
|
395
|
+
dateRange: nBattles > 0 && Number.isFinite(minTs) ? [iso(minTs).slice(0, 10), iso(maxTs).slice(0, 10)] : null,
|
|
396
|
+
scannedMaxDate: scannedMaxTs > 0 ? iso(scannedMaxTs).slice(0, 10) : null,
|
|
397
|
+
scannedMaxTs: scannedMaxTs > 0 ? scannedMaxTs : null,
|
|
398
|
+
// Legacy hard-window model parameters (model 'window'; see src/engine/sortie.js applyEmpiricalCompWeights)
|
|
399
|
+
alpha: 0.5,
|
|
400
|
+
hqWindow: [-10, 5],
|
|
401
|
+
minSamples: 10,
|
|
402
|
+
maps,
|
|
403
|
+
};
|
|
404
|
+
tbl.fingerprint = {
|
|
405
|
+
source,
|
|
406
|
+
nBattles,
|
|
407
|
+
asOf: asOf != null ? asOf : null,
|
|
408
|
+
asOfIso: asOf != null ? iso(asOf) : null,
|
|
409
|
+
scannedMaxTs: tbl.scannedMaxTs,
|
|
410
|
+
hash: stableHash(counted),
|
|
411
|
+
};
|
|
412
|
+
return tbl;
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
// ------------------------------------------------------------------------------------------------ seed table
|
|
416
|
+
let seedCache;
|
|
417
|
+
function loadSeedTable(filePath = SEED_PATH) {
|
|
418
|
+
if (filePath === SEED_PATH && seedCache !== undefined) return seedCache;
|
|
419
|
+
let tbl = null;
|
|
420
|
+
if (fs.existsSync(filePath)) {
|
|
421
|
+
try {
|
|
422
|
+
tbl = JSON.parse(fs.readFileSync(filePath, 'utf8'));
|
|
423
|
+
} catch (err) {
|
|
424
|
+
console.warn(`[empiricalComps] Failed to parse seed comp table (${filePath}), falling back to wiki equal weights: ${err.message}`);
|
|
425
|
+
tbl = null;
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
if (tbl) {
|
|
429
|
+
const obs = Array.isArray(tbl.observations) ? tbl.observations : null;
|
|
430
|
+
const counted = obs ? obs.filter((o) => resolveMapPhases(o.map, o.cell, o.ships).length) : [];
|
|
431
|
+
// audit19 P3-6: the seed is itself a table cut at its export cut-off -> report that as asOf (not "实时(无截止)"), so the
|
|
432
|
+
// fingerprint matches a live run with compAsOf = seed asOf (same hash, same asOf).
|
|
433
|
+
const seedAsOf = Number.isFinite(Number(tbl.asOf)) && Number(tbl.asOf) > 0 ? Number(tbl.asOf)
|
|
434
|
+
: (Number.isFinite(Number(tbl.scannedMaxTs)) && Number(tbl.scannedMaxTs) > 0 ? Number(tbl.scannedMaxTs) : null);
|
|
435
|
+
tbl.fingerprint = {
|
|
436
|
+
source: 'seed',
|
|
437
|
+
nBattles: tbl.nBattles || 0,
|
|
438
|
+
asOf: seedAsOf,
|
|
439
|
+
asOfIso: seedAsOf != null ? new Date(seedAsOf).toISOString() : null,
|
|
440
|
+
seedAsOf,
|
|
441
|
+
scannedMaxTs: tbl.scannedMaxTs || null,
|
|
442
|
+
hash: obs ? stableHash(counted) : crypto.createHash('sha1').update(JSON.stringify(tbl.maps || {})).digest('hex').slice(0, 12),
|
|
443
|
+
};
|
|
444
|
+
}
|
|
445
|
+
if (filePath === SEED_PATH) seedCache = tbl;
|
|
446
|
+
return tbl;
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
// ------------------------------------------------------------------------------------------------ resolution API
|
|
450
|
+
// Cut-off time parsing (CLI --comp-asof / HTTP compAsOf / KC_COMP_ASOF). Accepted:
|
|
451
|
+
// * millisecond epoch timestamps (number or digit string) >= 1e11 (1973-03-03); smaller values are rejected (audit19 P3-3:
|
|
452
|
+
// "20261120" or a seconds timestamp would otherwise silently become a 1970 cut-off and exclude every battle);
|
|
453
|
+
// * ISO dates / date-times. Date-only = end of that UTC day (inclusive). A date-time WITHOUT zone is read as UTC (not local
|
|
454
|
+
// time) so the same string reproduces the same table on every machine; an explicit zone (Z / +09:00 / +0900) is honoured.
|
|
455
|
+
// Calendar / clock fields are range-checked (2026-02-30, 24:00, +25:00 are rejected instead of rolled over by Date.parse).
|
|
456
|
+
const ASOF_MIN_MS = 1e11;
|
|
457
|
+
const ASOF_MAX_MS = 8.64e15;
|
|
458
|
+
const ASOF_HINT = '需为毫秒时间戳(≥1e11,如 1795934234683)或 ISO 日期/时间,如 2026-11-20、2026-11-20T12:00:00(无时区按 UTC)、2026-11-20T21:00:00+09:00';
|
|
459
|
+
function parseAsOf(raw) {
|
|
460
|
+
if (raw === undefined || raw === null || raw === '') return { ok: true, value: null };
|
|
461
|
+
const checkMs = (v, shown) => {
|
|
462
|
+
if (!Number.isFinite(v) || !Number.isInteger(v) || v <= 0 || v >= ASOF_MAX_MS) return { ok: false, error: `无效 compAsOf 时间戳: ${shown}(${ASOF_HINT})` };
|
|
463
|
+
if (v < ASOF_MIN_MS) return { ok: false, error: `无效 compAsOf 时间戳: ${shown}(数值过小,不像毫秒时间戳;${ASOF_HINT})` };
|
|
464
|
+
return { ok: true, value: v };
|
|
465
|
+
};
|
|
466
|
+
if (typeof raw === 'number') return checkMs(raw, raw);
|
|
467
|
+
if (typeof raw !== 'string') return { ok: false, error: `compAsOf 必须为 ISO 时间字符串或毫秒时间戳(${ASOF_HINT})` };
|
|
468
|
+
const s = raw.trim();
|
|
469
|
+
if (/^\d+$/.test(s)) return checkMs(Number(s), raw);
|
|
470
|
+
// ISO 8601 date or date-time only (rejects free-form strings Date.parse would accept)
|
|
471
|
+
const m = /^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2})(\.\d{1,3})?)?(Z|([+-])(\d{2}):?(\d{2}))?)?$/i.exec(s);
|
|
472
|
+
if (!m) return { ok: false, error: `无效 compAsOf 时间: "${raw}"(${ASOF_HINT})` };
|
|
473
|
+
const [, Y, Mo, D, h, mi, sec, frac, zone, sign, zh, zm] = m;
|
|
474
|
+
const y = Number(Y), mo = Number(Mo), d = Number(D);
|
|
475
|
+
// Round-trip check: Date.UTC rolls 2026-02-30 over to 03-02, so compare the fields back (years < 1973 fail checkMs anyway)
|
|
476
|
+
const probe = new Date(Date.UTC(y, mo - 1, d));
|
|
477
|
+
if (mo < 1 || mo > 12 || d < 1 || probe.getUTCFullYear() !== y || probe.getUTCMonth() !== mo - 1 || probe.getUTCDate() !== d) {
|
|
478
|
+
return { ok: false, error: `无效 compAsOf 日期: "${raw}"(${Y}-${Mo}-${D} 不是有效日期)` };
|
|
479
|
+
}
|
|
480
|
+
let v;
|
|
481
|
+
if (h === undefined) {
|
|
482
|
+
v = Date.UTC(y, mo - 1, d, 23, 59, 59, 999); // date-only -> end of that UTC day (inclusive cut-off)
|
|
483
|
+
} else {
|
|
484
|
+
const H = Number(h), Mi = Number(mi), Sc = sec !== undefined ? Number(sec) : 0;
|
|
485
|
+
if (H > 23 || Mi > 59 || Sc > 59) return { ok: false, error: `无效 compAsOf 时间: "${raw}"(时/分/秒超出范围)` };
|
|
486
|
+
const ms = frac ? Math.round(Number(frac) * 1000) : 0;
|
|
487
|
+
let off = 0;
|
|
488
|
+
if (zone && zone.toUpperCase() !== 'Z') {
|
|
489
|
+
const ZH = Number(zh), ZM = Number(zm);
|
|
490
|
+
if (ZH > 14 || ZM > 59) return { ok: false, error: `无效 compAsOf 时区偏移: "${raw}"` };
|
|
491
|
+
off = (sign === '-' ? -1 : 1) * (ZH * 60 + ZM) * 60000;
|
|
492
|
+
}
|
|
493
|
+
v = Date.UTC(y, mo - 1, d, H, Mi, Sc, ms) - off; // no zone -> UTC (off = 0)
|
|
494
|
+
}
|
|
495
|
+
return checkMs(v, `"${raw}"`);
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
function parseSource(raw) {
|
|
499
|
+
if (raw === undefined || raw === null || raw === '') return { ok: true, value: 'auto' };
|
|
500
|
+
const s = String(raw).trim().toLowerCase();
|
|
501
|
+
if (s === 'auto' || s === 'live' || s === 'seed') return { ok: true, value: s };
|
|
502
|
+
return { ok: false, error: `无效 compSource: "${raw}"(可选: auto, live, seed)` };
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
// Process-default cut-off / source from KC_COMP_ASOF / KC_COMP_SOURCE. An invalid value is ignored with ONE warning per
|
|
506
|
+
// distinct value (audit19 P3-6: getCompTable() runs per request / run, the warning used to repeat every time).
|
|
507
|
+
const warnedEnv = new Set();
|
|
508
|
+
function warnEnvOnce(name, raw, error) {
|
|
509
|
+
const k = `${name}=${raw}`;
|
|
510
|
+
if (warnedEnv.has(k)) return;
|
|
511
|
+
warnedEnv.add(k);
|
|
512
|
+
console.warn(`[empiricalComps] 忽略无效环境变量 ${name}: ${error}`);
|
|
513
|
+
}
|
|
514
|
+
function envDefaults() {
|
|
515
|
+
const a = parseAsOf(process.env.KC_COMP_ASOF);
|
|
516
|
+
const s = parseSource(process.env.KC_COMP_SOURCE);
|
|
517
|
+
if (!a.ok) warnEnvOnce('KC_COMP_ASOF', process.env.KC_COMP_ASOF, a.error);
|
|
518
|
+
if (!s.ok) warnEnvOnce('KC_COMP_SOURCE', process.env.KC_COMP_SOURCE, s.error);
|
|
519
|
+
return { asOf: a.ok ? a.value : null, source: s.ok ? s.value : 'auto' };
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
const tableMemo = new Map(); // `${source}|${asOf}|${storeVersion}` -> table
|
|
523
|
+
let installedTable = null; // set by computeWorker (table resolved by the server main thread) or setActiveCompTable()
|
|
524
|
+
|
|
525
|
+
function liveAvailable(dir) {
|
|
526
|
+
try { return !!dir && fs.existsSync(dir) && fs.statSync(dir).isDirectory(); } catch (_) { return false; }
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
// Why the live directory is not usable (for the "使用内置种子表" notice): distinguishes "no APPDATA/USERPROFILE", "does not
|
|
530
|
+
// exist" (ENOENT) and "exists but access denied" (EPERM / EACCES — e.g. an agent terminal or sandbox that can read the
|
|
531
|
+
// claude-bridge snapshot but not the battle-detail folder). Pure diagnosis, never throws.
|
|
532
|
+
function poiDirStatus(dir) {
|
|
533
|
+
if (!dir) return { dir: null, code: 'NO_APPDATA' };
|
|
534
|
+
try {
|
|
535
|
+
const st = fs.statSync(dir);
|
|
536
|
+
if (!st.isDirectory()) return { dir, code: 'NOT_A_DIR' };
|
|
537
|
+
fs.readdirSync(dir);
|
|
538
|
+
return { dir, code: 'OK' };
|
|
539
|
+
} catch (err) {
|
|
540
|
+
return { dir, code: (err && err.code) || 'ERROR' };
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
function seedWithNotice(asOf, reason, detail) {
|
|
545
|
+
const seed = loadSeedTable();
|
|
546
|
+
if (!seed) return null;
|
|
547
|
+
if (asOf == null) {
|
|
548
|
+
if (reason) seed.fingerprint.reason = reason;
|
|
549
|
+
if (detail) seed.fingerprint.reasonDetail = detail; else delete seed.fingerprint.reasonDetail;
|
|
550
|
+
return seed;
|
|
551
|
+
}
|
|
552
|
+
// Seed carries per-battle observations (Wave 20 export) -> the cut-off still applies
|
|
553
|
+
const key = `seed|${asOf}`;
|
|
554
|
+
if (tableMemo.has(key)) return tableMemo.get(key);
|
|
555
|
+
let tbl;
|
|
556
|
+
if (Array.isArray(seed.observations)) {
|
|
557
|
+
tbl = aggregateObservations(seed.observations, { asOf, source: 'seed' });
|
|
558
|
+
tbl.scannedMaxTs = tbl.scannedMaxTs != null ? Math.min(tbl.scannedMaxTs, seed.scannedMaxTs || Infinity) : null;
|
|
559
|
+
tbl.fingerprint.seedAsOf = seed.fingerprint.seedAsOf;
|
|
560
|
+
} else {
|
|
561
|
+
tbl = seed;
|
|
562
|
+
}
|
|
563
|
+
if (reason) tbl.fingerprint.reason = reason;
|
|
564
|
+
if (detail) tbl.fingerprint.reasonDetail = detail; else delete tbl.fingerprint.reasonDetail;
|
|
565
|
+
tableMemo.set(key, tbl);
|
|
566
|
+
return tbl;
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
// Resolve the empirical comp table for { asOf, source, refresh }.
|
|
570
|
+
// source 'auto' (default): live poi logs when the directory is readable and holds at least one sortie observation,
|
|
571
|
+
// otherwise the bundled seed table; 'live': live only (seed if unavailable, with reason);
|
|
572
|
+
// 'seed': always the seed table.
|
|
573
|
+
// refresh: true -> incremental re-scan of the log directory first (CLI start, server throttled checks).
|
|
574
|
+
// Without refresh the in-process observation store is reused (lazily loaded once per process).
|
|
575
|
+
function getCompTable(opts = {}) {
|
|
576
|
+
const env = envDefaults();
|
|
577
|
+
const explicitAsOf = opts.asOf !== undefined && opts.asOf !== null;
|
|
578
|
+
const explicitSource = opts.source !== undefined && opts.source !== null && opts.source !== 'auto';
|
|
579
|
+
if (installedTable && !explicitAsOf && !explicitSource && !opts.refresh) return installedTable;
|
|
580
|
+
const asOf = explicitAsOf ? opts.asOf : env.asOf;
|
|
581
|
+
const source = explicitSource ? opts.source : env.source;
|
|
582
|
+
if (source === 'seed') return seedWithNotice(asOf, 'forced');
|
|
583
|
+
const dir = opts.dir || resolvePoiBattleDir();
|
|
584
|
+
if (!liveAvailable(dir)) return seedWithNotice(asOf, 'no-poi-dir', poiDirStatus(dir));
|
|
585
|
+
const st = getStore(dir);
|
|
586
|
+
try {
|
|
587
|
+
if (opts.refresh || !st.version) refreshStoreSync(dir, { cacheDir: opts.cacheDir });
|
|
588
|
+
} catch (err) {
|
|
589
|
+
if (!st.version) return seedWithNotice(asOf, 'poi-dir-unreadable', { dir, code: (err && err.code) || 'ERROR' });
|
|
590
|
+
}
|
|
591
|
+
if (!st.observations.length) return seedWithNotice(asOf, 'no-sortie-logs');
|
|
592
|
+
return liveTableFromStore(st, asOf);
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
function liveTableFromStore(st, asOf) {
|
|
596
|
+
const key = `live|${st.dir}|${asOf}|${st.version}`;
|
|
597
|
+
if (tableMemo.has(key)) return tableMemo.get(key);
|
|
598
|
+
if (tableMemo.size > 64) tableMemo.clear();
|
|
599
|
+
const scannedTs = [];
|
|
600
|
+
for (const [name, e] of st.files) if (e) scannedTs.push(Number(name.slice(0, -8)));
|
|
601
|
+
const tbl = aggregateObservations(st.observations, { asOf, scannedTs, source: 'live' });
|
|
602
|
+
tbl.fingerprint.pendingFiles = st.pendingCount || 0;
|
|
603
|
+
tableMemo.set(key, tbl);
|
|
604
|
+
return tbl;
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
// Server helper: throttled async refresh. Resolves once the store is current (concurrent callers share one refresh).
|
|
608
|
+
const inflight = new Map();
|
|
609
|
+
async function refreshLiveThrottled({ minIntervalMs = 30000, dir = resolvePoiBattleDir(), cacheDir } = {}) {
|
|
610
|
+
if (!liveAvailable(dir)) return { refreshed: false, available: false };
|
|
611
|
+
const st = getStore(dir);
|
|
612
|
+
const key = st.dir;
|
|
613
|
+
if (inflight.has(key)) return inflight.get(key);
|
|
614
|
+
const now = Date.now();
|
|
615
|
+
if (st.version && now - st.lastCheckMs < minIntervalMs) return { refreshed: false, available: true, throttled: true };
|
|
616
|
+
const p = (async () => {
|
|
617
|
+
try {
|
|
618
|
+
if (st.version && st.sig) {
|
|
619
|
+
// Cheap signature check (directory mtime + file count) before stat-ing every file
|
|
620
|
+
let sig = null;
|
|
621
|
+
try {
|
|
622
|
+
const dst = await fs.promises.stat(dir);
|
|
623
|
+
const n = (await fs.promises.readdir(dir)).filter((f) => LOG_FILE_RE.test(f)).length;
|
|
624
|
+
sig = `${dst.mtimeMs}|${n}`;
|
|
625
|
+
} catch (_) { sig = null; }
|
|
626
|
+
if (sig && sig === st.sig) { st.lastCheckMs = Date.now(); return { refreshed: false, available: true, unchanged: true }; }
|
|
627
|
+
}
|
|
628
|
+
const stats = await refreshStoreAsync(dir, { cacheDir });
|
|
629
|
+
return { refreshed: true, available: true, stats };
|
|
630
|
+
} catch (err) {
|
|
631
|
+
return { refreshed: false, available: !!st.version, error: err.message };
|
|
632
|
+
} finally {
|
|
633
|
+
inflight.delete(key);
|
|
634
|
+
}
|
|
635
|
+
})();
|
|
636
|
+
inflight.set(key, p);
|
|
637
|
+
return p;
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
function setActiveCompTable(tbl) { installedTable = tbl || null; }
|
|
641
|
+
function getInstalledCompTable() { return installedTable; }
|
|
642
|
+
|
|
643
|
+
function getStoreStats(dir = resolvePoiBattleDir()) {
|
|
644
|
+
if (!dir) return null;
|
|
645
|
+
const st = stores.get(path.resolve(dir));
|
|
646
|
+
return st ? { ...st.lastStats, version: st.version, observations: st.observations.length } : null;
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
function clearEmpiricalCompState() {
|
|
650
|
+
stores.clear();
|
|
651
|
+
tableMemo.clear();
|
|
652
|
+
inflight.clear();
|
|
653
|
+
installedTable = null;
|
|
654
|
+
seedCache = undefined;
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
// Test switch (audit19 P3-8): KC_COMP_NO_LIVE_COUNT=1 disables the "N newer live battles not included" count entirely, so test
|
|
658
|
+
// suites running on the seed (KC_COMP_SOURCE=seed) never even read-only scan the user's real poi log directory.
|
|
659
|
+
function liveCountDisabled() { return process.env.KC_COMP_NO_LIVE_COUNT === '1'; }
|
|
660
|
+
|
|
661
|
+
// Count live sortie observations newer than a timestamp (used for the seed / asOf notices). Returns null when there is no
|
|
662
|
+
// readable poi directory (or counting is disabled).
|
|
663
|
+
// sync: true (CLI / library, one-shot): a cold store is refreshed synchronously first (incremental, disk-cached);
|
|
664
|
+
// sync: false (HTTP server main thread, audit19 P3-4): never blocks the event loop and never duplicates the async warm-up
|
|
665
|
+
// scan: while the store is not loaded yet the result is { pending: true } ("统计中"); the server keeps the store
|
|
666
|
+
// current with refreshLiveThrottled() and describeCompData() is memoized per store version, so the count follows.
|
|
667
|
+
function countLiveNewerThan(ts, dir = resolvePoiBattleDir(), { sync = true } = {}) {
|
|
668
|
+
if (liveCountDisabled()) return null;
|
|
669
|
+
if (!dir) return null;
|
|
670
|
+
const known = stores.get(path.resolve(dir));
|
|
671
|
+
if (!sync && !(known && known.version)) return liveAvailable(dir) ? { pending: true, newer: null, latestTs: null } : null;
|
|
672
|
+
if (!liveAvailable(dir)) return null;
|
|
673
|
+
const st = getStore(dir);
|
|
674
|
+
if (!st.version) { try { refreshStoreSync(dir); } catch (_) { return null; } }
|
|
675
|
+
let n = 0;
|
|
676
|
+
let latest = 0;
|
|
677
|
+
for (const o of st.observations) {
|
|
678
|
+
if (o.ts > ts && resolveMapPhases(o.map, o.cell, o.ships).length) { n++; if (o.ts > latest) latest = o.ts; }
|
|
679
|
+
}
|
|
680
|
+
return { newer: n, latestTs: latest || null };
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
// Live-store state stamp for describeCompData's memo: the "另有 N 场未纳入" count must follow store refreshes (audit19 P3-4).
|
|
684
|
+
function liveCountStamp() {
|
|
685
|
+
if (liveCountDisabled()) return 'off';
|
|
686
|
+
const dir = resolvePoiBattleDir();
|
|
687
|
+
const st = dir ? stores.get(path.resolve(dir)) : null;
|
|
688
|
+
return `${dir || ''}#${st ? st.version : 0}`;
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
// Human-readable data-source notice: only for the seed table or an explicit cut-off (live mode is never "stale").
|
|
692
|
+
// checkLive: also count live poi sortie battles newer than the seed / cut-off. Used by the CLI fingerprint line and the HTTP
|
|
693
|
+
// server (status / sim / optimize). NOTE: this still READS the real poi directory even when the table itself is the seed
|
|
694
|
+
// (KC_COMP_SOURCE=seed / --comp-source seed): a read-only, disk-cached incremental scan for the count; it never affects the
|
|
695
|
+
// table or the results. Set KC_COMP_NO_LIVE_COUNT=1 to skip it completely (the test suites do). runMonteCarlo always calls
|
|
696
|
+
// with checkLive: false. sync: false (server) = never scan on the calling thread (see countLiveNewerThan).
|
|
697
|
+
// Memoized per table object + reason + live-store version.
|
|
698
|
+
const describeMemo = new WeakMap();
|
|
699
|
+
function describeCompData(tbl, { checkLive = true, sync = true } = {}) {
|
|
700
|
+
const fp = tbl && tbl.fingerprint;
|
|
701
|
+
if (!fp) return { notice: null, fingerprint: null };
|
|
702
|
+
const memoKey = `${checkLive ? (sync ? 'live-sync' : 'live-async') : 'plain'}|${fp.reason || ''}`; // seed reason can change
|
|
703
|
+
const stampOf = () => (checkLive ? liveCountStamp() : '');
|
|
704
|
+
const memo = describeMemo.get(tbl);
|
|
705
|
+
const hit = memo && memo[memoKey];
|
|
706
|
+
if (hit && hit.stamp === stampOf()) return hit.out;
|
|
707
|
+
const day = (ts) => (ts ? new Date(ts).toISOString().slice(0, 16).replace('T', ' ') + ' UTC' : '-');
|
|
708
|
+
let notice = null;
|
|
709
|
+
if (fp.source === 'seed') {
|
|
710
|
+
const rd = fp.reasonDetail || null;
|
|
711
|
+
const denied = rd && (rd.code === 'EPERM' || rd.code === 'EACCES');
|
|
712
|
+
const why = fp.reason === 'forced' ? '(已指定 --comp-source seed / KC_COMP_SOURCE=seed)'
|
|
713
|
+
: fp.reason === 'no-sortie-logs' ? '(poi 战斗记录目录中没有可用的出击记录)'
|
|
714
|
+
: rd && rd.code === 'NO_APPDATA' ? '(未找到本地 poi 战斗记录目录:环境变量 APPDATA / USERPROFILE 均未设置,可用 POI_BATTLE_DIR 指定)'
|
|
715
|
+
: rd && rd.dir ? `(${denied ? '无权访问' : fp.reason === 'poi-dir-unreadable' ? '读取失败' : '找不到'}本地 poi 战斗记录目录 ${rd.dir}:${rd.code}`
|
|
716
|
+
+ `${denied ? ';若在受限终端 / 沙箱中运行,请放行该目录或用 POI_BATTLE_DIR 指定可读路径' : ''})`
|
|
717
|
+
: '(未找到可读的本地 poi 战斗记录目录)';
|
|
718
|
+
notice = `使用内置种子表${why}:${fp.nBattles} 场出击,截至 ${day(tbl.scannedMaxTs)}`;
|
|
719
|
+
if (fp.asOf != null && fp.asOf !== fp.seedAsOf) notice += `,并按截止时间 ${day(fp.asOf)} 过滤`;
|
|
720
|
+
if (checkLive && fp.reason === 'forced') {
|
|
721
|
+
const nw = countLiveNewerThan(Math.max(tbl.scannedMaxTs || 0, fp.asOf || 0), undefined, { sync });
|
|
722
|
+
if (nw && nw.pending) notice += ';本地 poi 新记录统计中';
|
|
723
|
+
else if (nw && nw.newer > 0) notice += `;本地 poi 记录在其后另有 ${nw.newer} 场出击未纳入`;
|
|
724
|
+
}
|
|
725
|
+
notice += '。';
|
|
726
|
+
} else if (fp.asOf != null) {
|
|
727
|
+
const nw = checkLive ? countLiveNewerThan(fp.asOf, undefined, { sync }) : null;
|
|
728
|
+
const extra = nw && nw.pending ? '(其后新增场数统计中)' : (nw && nw.newer > 0 ? `,其后 ${nw.newer} 场出击未纳入` : '');
|
|
729
|
+
notice = `经验编成按截止时间 ${day(fp.asOf)} 复现:纳入 ${fp.nBattles} 场出击${extra}。`;
|
|
730
|
+
}
|
|
731
|
+
const out = { notice, fingerprint: fp };
|
|
732
|
+
describeMemo.set(tbl, { ...(memo || {}), [memoKey]: { stamp: stampOf(), out } }); // latest store version only
|
|
733
|
+
return out;
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
function formatFingerprint(fp) {
|
|
737
|
+
if (!fp) return '-';
|
|
738
|
+
const t = (ts) => (ts ? new Date(ts).toISOString().slice(0, 19).replace('T', ' ') + 'Z' : '-');
|
|
739
|
+
const seedCut = fp.source === 'seed' && fp.asOf != null && fp.asOf === fp.seedAsOf ? '(种子表截止)' : '';
|
|
740
|
+
return `source=${fp.source} | ${fp.nBattles}场 | asOf=${fp.asOf != null ? t(fp.asOf) + seedCut : '实时(无截止)'} | 数据截至=${t(fp.scannedMaxTs)} | hash=${fp.hash || '-'}${fp.model ? ` | 模型=${fp.model}` : ''}`;
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
module.exports = {
|
|
744
|
+
CACHE_VERSION,
|
|
745
|
+
SEED_PATH,
|
|
746
|
+
POI_NODE_LETTER,
|
|
747
|
+
PHASED_MAPS,
|
|
748
|
+
PENDING_GRACE_MS,
|
|
749
|
+
resolveNodeLetter,
|
|
750
|
+
resolveMapPhases,
|
|
751
|
+
extractObservation,
|
|
752
|
+
resolvePoiBattleDir,
|
|
753
|
+
resolveCacheDir,
|
|
754
|
+
cacheFileFor,
|
|
755
|
+
refreshStoreSync,
|
|
756
|
+
refreshStoreAsync,
|
|
757
|
+
refreshLiveThrottled,
|
|
758
|
+
aggregateObservations,
|
|
759
|
+
stableHash,
|
|
760
|
+
loadSeedTable,
|
|
761
|
+
parseAsOf,
|
|
762
|
+
parseSource,
|
|
763
|
+
getCompTable,
|
|
764
|
+
setActiveCompTable,
|
|
765
|
+
getInstalledCompTable,
|
|
766
|
+
getStoreStats,
|
|
767
|
+
describeCompData,
|
|
768
|
+
formatFingerprint,
|
|
769
|
+
countLiveNewerThan,
|
|
770
|
+
envDefaults,
|
|
771
|
+
clearEmpiricalCompState,
|
|
772
|
+
writeFileAtomic,
|
|
773
|
+
};
|