@evomap/evolver-cli 2.0.0-beta.2 → 2.0.0-beta.5
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/dist/assetHealth.d.ts +6 -0
- package/dist/assetHealth.js +105 -0
- package/dist/assetSidecarRecovery.d.ts +14 -0
- package/dist/assetSidecarRecovery.js +171 -0
- package/dist/assetTrust.d.ts +24 -0
- package/dist/assetTrust.js +218 -0
- package/dist/autoexec.d.ts +9 -2
- package/dist/autoexec.js +48 -8
- package/dist/cycleConsumer.d.ts +4 -2
- package/dist/cycleConsumer.js +194 -36
- package/dist/dashboard.d.ts +3 -1
- package/dist/dashboard.js +22 -4
- package/dist/dispatch.d.ts +9 -1
- package/dist/dispatch.js +9 -0
- package/dist/doctor.d.ts +2 -0
- package/dist/doctor.js +18 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.js +76 -8
- package/dist/lifecycle.d.ts +19 -1
- package/dist/lifecycle.js +220 -27
- package/dist/localMemoryGraph.d.ts +97 -0
- package/dist/localMemoryGraph.js +889 -0
- package/dist/migrate/v1Import.d.ts +7 -1
- package/dist/migrate/v1Import.js +132 -11
- package/dist/runtimeCapabilities.d.ts +18 -0
- package/dist/runtimeCapabilities.js +81 -0
- package/package.json +11 -7
|
@@ -0,0 +1,889 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { closeSync, constants, existsSync, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readSync, readdirSync, realpathSync, renameSync, statSync, unlinkSync, writeSync, } from 'node:fs';
|
|
3
|
+
import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
|
|
4
|
+
import { userInfo } from 'node:os';
|
|
5
|
+
import { gzipSync, gunzipSync } from 'node:zlib';
|
|
6
|
+
import { algo, events, util } from '@evomap/evolver-core';
|
|
7
|
+
const ACTIVE_FILE = 'memory_graph.v2.jsonl';
|
|
8
|
+
const COMPACT_FILE = 'memory_graph.compact.jsonl';
|
|
9
|
+
const LOCK_FILE = 'memory_graph.lock';
|
|
10
|
+
const RECOVERY_FILE = 'memory_graph.recovery.json';
|
|
11
|
+
const ARCHIVE_PATTERN = /^memory_graph\.v2\.(\d{13})\.jsonl\.gz$/;
|
|
12
|
+
const DEFAULT_MAX_COMPACT_BYTES = 2 * 1024 * 1024;
|
|
13
|
+
export function resolveLocalMemoryUserId(info = userInfo()) {
|
|
14
|
+
if (Number.isInteger(info.uid) && info.uid >= 0)
|
|
15
|
+
return String(info.uid);
|
|
16
|
+
return `account:${process.platform}:${info.username.trim().toLowerCase()}:${resolve(info.homedir)}`;
|
|
17
|
+
}
|
|
18
|
+
export function resolveLocalMemoryUserIdentity(graphDir, info = userInfo()) {
|
|
19
|
+
const userId = resolveLocalMemoryUserId(info);
|
|
20
|
+
if (info.uid !== -1)
|
|
21
|
+
return { userId, legacyUserIds: [] };
|
|
22
|
+
const fromHome = relative(resolve(info.homedir), resolve(graphDir));
|
|
23
|
+
const privateToAccount = fromHome === '' || (!fromHome.startsWith('..') && !isAbsolute(fromHome));
|
|
24
|
+
return { userId, legacyUserIds: privateToAccount ? ['-1'] : [] };
|
|
25
|
+
}
|
|
26
|
+
export class MemoryGraphImportStateRejectedError extends Error {
|
|
27
|
+
constructor() {
|
|
28
|
+
super('memory_graph_import_state_rejected');
|
|
29
|
+
this.name = 'MemoryGraphImportStateRejectedError';
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
export class MemoryGraphBusyError extends Error {
|
|
33
|
+
constructor() {
|
|
34
|
+
super('memory_graph_busy');
|
|
35
|
+
this.name = 'MemoryGraphBusyError';
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
export class LocalMemoryGraph {
|
|
39
|
+
dir;
|
|
40
|
+
userScope;
|
|
41
|
+
readableUserScopes;
|
|
42
|
+
now;
|
|
43
|
+
maxActiveBytes;
|
|
44
|
+
maxTailBytes;
|
|
45
|
+
maxLineBytes;
|
|
46
|
+
maxCompactBytes;
|
|
47
|
+
maxCompactEdges;
|
|
48
|
+
archiveRetention;
|
|
49
|
+
importedFingerprints = new Map();
|
|
50
|
+
constructor(options) {
|
|
51
|
+
this.dir = resolve(options.dir);
|
|
52
|
+
this.userScope = scopeHash(`user:${options.userId}`);
|
|
53
|
+
this.readableUserScopes = new Set([
|
|
54
|
+
this.userScope,
|
|
55
|
+
...(options.legacyUserIds ?? []).map((userId) => scopeHash(`user:${userId}`)),
|
|
56
|
+
]);
|
|
57
|
+
this.now = options.now ?? Date.now;
|
|
58
|
+
this.maxActiveBytes = positiveInt(options.maxActiveBytes, 4 * 1024 * 1024);
|
|
59
|
+
this.maxTailBytes = positiveInt(options.maxTailBytes, 512 * 1024);
|
|
60
|
+
this.maxLineBytes = positiveInt(options.maxLineBytes, 16 * 1024);
|
|
61
|
+
this.maxCompactBytes = positiveInt(options.maxCompactBytes, DEFAULT_MAX_COMPACT_BYTES);
|
|
62
|
+
this.maxCompactEdges = positiveInt(options.maxCompactEdges, 4096);
|
|
63
|
+
this.archiveRetention = positiveInt(options.archiveRetention, 3);
|
|
64
|
+
}
|
|
65
|
+
query(input) {
|
|
66
|
+
const diagnostics = emptyDiagnostics();
|
|
67
|
+
const workspaceScope = this.workspaceScope(input.workspace);
|
|
68
|
+
if (!workspaceScope)
|
|
69
|
+
return { genes: [], diagnostics: { ...diagnostics, recovery: 'degraded' } };
|
|
70
|
+
try {
|
|
71
|
+
return this.withGraphLock(() => {
|
|
72
|
+
const records = this.readQueryableRecords(diagnostics).filter((record) => {
|
|
73
|
+
if (record.provenance !== 'v2_local' && record.provenance !== 'v1_import') {
|
|
74
|
+
diagnostics.provenanceRejected += 1;
|
|
75
|
+
return false;
|
|
76
|
+
}
|
|
77
|
+
if (record.workspaceScope !== workspaceScope || !this.readableUserScopes.has(record.userScope)) {
|
|
78
|
+
diagnostics.scopeRejected += 1;
|
|
79
|
+
return false;
|
|
80
|
+
}
|
|
81
|
+
return true;
|
|
82
|
+
});
|
|
83
|
+
if (records.length === 0 && diagnostics.recovery === 'healthy')
|
|
84
|
+
diagnostics.recovery = 'empty';
|
|
85
|
+
return algo.deriveMemoryGraphAdvice(records, input.signals, this.now(), diagnostics);
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
catch (error) {
|
|
89
|
+
if (error instanceof MemoryGraphBusyError) {
|
|
90
|
+
return { genes: [], diagnostics: { ...diagnostics, recovery: 'degraded', busy: true } };
|
|
91
|
+
}
|
|
92
|
+
throw error;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
recordOutcome(input) {
|
|
96
|
+
const workspaceScope = this.workspaceScope(input.workspace);
|
|
97
|
+
if (!workspaceScope)
|
|
98
|
+
return;
|
|
99
|
+
const geneId = algo.safeMemoryGeneId(input.geneId);
|
|
100
|
+
if (!geneId)
|
|
101
|
+
return;
|
|
102
|
+
const signals = algo.normalizeMemorySignals(input.signals);
|
|
103
|
+
const record = {
|
|
104
|
+
version: 2,
|
|
105
|
+
kind: 'outcome',
|
|
106
|
+
provenance: 'v2_local',
|
|
107
|
+
workspaceScope,
|
|
108
|
+
userScope: this.userScope,
|
|
109
|
+
signalFingerprint: algo.memorySignalFingerprint(signals),
|
|
110
|
+
signals,
|
|
111
|
+
geneId,
|
|
112
|
+
status: input.status,
|
|
113
|
+
score: clampScore(input.score),
|
|
114
|
+
at: validIso(input.at) ?? new Date(this.now()).toISOString(),
|
|
115
|
+
};
|
|
116
|
+
let persisted = false;
|
|
117
|
+
try {
|
|
118
|
+
this.withGraphLock(() => { persisted = this.appendRecordUnlocked(record); });
|
|
119
|
+
}
|
|
120
|
+
catch (error) {
|
|
121
|
+
// The append is already durable, so surfacing only the cleanup failure would invite duplicate retries.
|
|
122
|
+
if (persisted && error instanceof util.LockReleaseError)
|
|
123
|
+
return;
|
|
124
|
+
throw error;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
importV1Outcome(workspace, raw, source = 'legacy-memory-graph') {
|
|
128
|
+
const workspaceScope = this.workspaceScope(workspace);
|
|
129
|
+
const sourceScope = scopeHash(`source:${source}`);
|
|
130
|
+
const parsed = parseV1Outcome(raw, workspaceScope, this.userScope, sourceScope);
|
|
131
|
+
if (!parsed)
|
|
132
|
+
return false;
|
|
133
|
+
return this.withGraphLock(() => {
|
|
134
|
+
const dedupeScope = `${workspaceScope}\u0000${this.userScope}\u0000${sourceScope}`;
|
|
135
|
+
const stateFingerprint = this.importStateFingerprint();
|
|
136
|
+
let cache = this.importedFingerprints.get(dedupeScope);
|
|
137
|
+
if (!cache || cache.stateFingerprint !== stateFingerprint) {
|
|
138
|
+
const values = new Set();
|
|
139
|
+
for (const record of this.readImportRecords()) {
|
|
140
|
+
if (record.workspaceScope !== workspaceScope || record.userScope !== this.userScope)
|
|
141
|
+
continue;
|
|
142
|
+
if (record.sourceScope && record.sourceScope !== sourceScope)
|
|
143
|
+
continue;
|
|
144
|
+
if (record.sourceFingerprint)
|
|
145
|
+
values.add(record.sourceFingerprint);
|
|
146
|
+
if (record.legacySourceFingerprint)
|
|
147
|
+
values.add(record.legacySourceFingerprint);
|
|
148
|
+
}
|
|
149
|
+
cache = { stateFingerprint, values };
|
|
150
|
+
this.importedFingerprints.set(dedupeScope, cache);
|
|
151
|
+
}
|
|
152
|
+
if ((parsed.sourceFingerprint && cache.values.has(parsed.sourceFingerprint))
|
|
153
|
+
|| (parsed.legacySourceFingerprint && cache.values.has(parsed.legacySourceFingerprint)))
|
|
154
|
+
return false;
|
|
155
|
+
if (!this.appendRecordUnlocked(parsed))
|
|
156
|
+
return false;
|
|
157
|
+
if (parsed.sourceFingerprint)
|
|
158
|
+
cache.values.add(parsed.sourceFingerprint);
|
|
159
|
+
if (parsed.legacySourceFingerprint)
|
|
160
|
+
cache.values.add(parsed.legacySourceFingerprint);
|
|
161
|
+
cache.stateFingerprint = this.importStateFingerprint();
|
|
162
|
+
return true;
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
maintain() {
|
|
166
|
+
return this.withGraphLock(() => this.maintainUnlocked());
|
|
167
|
+
}
|
|
168
|
+
maintainUnlocked() {
|
|
169
|
+
this.ensureSecureDir();
|
|
170
|
+
const health = this.inspectHealthUnlocked();
|
|
171
|
+
if (health.archives > 0 && this.compactRequiresRecovery()) {
|
|
172
|
+
const recovered = this.recoverFromArchivesUnlocked();
|
|
173
|
+
if (recovered.recovery === 'recovered')
|
|
174
|
+
return recovered;
|
|
175
|
+
}
|
|
176
|
+
const activePath = join(this.dir, ACTIVE_FILE);
|
|
177
|
+
if (!existsSync(activePath) || statSync(activePath).size < this.maxActiveBytes) {
|
|
178
|
+
return {
|
|
179
|
+
rotated: false,
|
|
180
|
+
compactedRecords: health.compactedRecords,
|
|
181
|
+
corruptLines: health.corruptLines,
|
|
182
|
+
oversizedLines: health.oversizedLines,
|
|
183
|
+
archives: health.archives,
|
|
184
|
+
recovery: health.recovery,
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
return this.rotateAndCompactUnlocked();
|
|
188
|
+
}
|
|
189
|
+
recoverFromArchives() {
|
|
190
|
+
return this.withGraphLock(() => this.recoverFromArchivesUnlocked());
|
|
191
|
+
}
|
|
192
|
+
recoverFromArchivesUnlocked() {
|
|
193
|
+
this.ensureSecureDir();
|
|
194
|
+
const diagnostics = emptyDiagnostics();
|
|
195
|
+
const compactRecords = this.readCompact(diagnostics);
|
|
196
|
+
const archiveRecords = [];
|
|
197
|
+
for (const file of this.archiveFiles().slice(-this.archiveRetention)) {
|
|
198
|
+
const path = join(this.dir, file);
|
|
199
|
+
if (!this.secureRegularFile(path))
|
|
200
|
+
continue;
|
|
201
|
+
try {
|
|
202
|
+
const compressed = this.readRawBounded(path, this.maxActiveBytes);
|
|
203
|
+
if (compressed === null) {
|
|
204
|
+
diagnostics.truncated = true;
|
|
205
|
+
continue;
|
|
206
|
+
}
|
|
207
|
+
const raw = gunzipSync(compressed, { maxOutputLength: this.maxActiveBytes + this.maxLineBytes });
|
|
208
|
+
archiveRecords.push(...this.parseBuffer(raw, diagnostics));
|
|
209
|
+
}
|
|
210
|
+
catch {
|
|
211
|
+
diagnostics.corruptLines += 1;
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
const compacted = mergeRecoveryRecords(compactRecords, archiveRecords, this.maxCompactEdges);
|
|
215
|
+
const compactedRecords = compacted.length > 0 ? this.writeCompact(compacted) : 0;
|
|
216
|
+
if (compactedRecords > 0)
|
|
217
|
+
this.writeRecoveryMarker();
|
|
218
|
+
return {
|
|
219
|
+
rotated: false,
|
|
220
|
+
compactedRecords,
|
|
221
|
+
corruptLines: diagnostics.corruptLines,
|
|
222
|
+
oversizedLines: diagnostics.oversizedLines,
|
|
223
|
+
archives: this.archiveFiles().length,
|
|
224
|
+
recovery: compactedRecords > 0 ? 'recovered' : 'degraded',
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
inspectHealth() {
|
|
228
|
+
if (!existsSync(this.dir))
|
|
229
|
+
return emptyHealth();
|
|
230
|
+
try {
|
|
231
|
+
return this.withGraphLock(() => this.inspectHealthUnlocked());
|
|
232
|
+
}
|
|
233
|
+
catch (error) {
|
|
234
|
+
if (error instanceof MemoryGraphBusyError) {
|
|
235
|
+
return { ...emptyHealth(), recovery: 'degraded', busy: true };
|
|
236
|
+
}
|
|
237
|
+
throw error;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
inspectHealthUnlocked() {
|
|
241
|
+
if (!existsSync(this.dir))
|
|
242
|
+
return emptyHealth();
|
|
243
|
+
const dirStat = lstatSync(this.dir);
|
|
244
|
+
if (!dirStat.isDirectory() || dirStat.isSymbolicLink())
|
|
245
|
+
throw new Error('memory_graph_dir_rejected');
|
|
246
|
+
const compactDiagnostics = emptyDiagnostics();
|
|
247
|
+
const activeDiagnostics = emptyDiagnostics();
|
|
248
|
+
const compactPath = join(this.dir, COMPACT_FILE);
|
|
249
|
+
const activePath = join(this.dir, ACTIVE_FILE);
|
|
250
|
+
const compactedRecords = this.readCompact(compactDiagnostics).length;
|
|
251
|
+
const activeRecords = this.readWholeBounded(activePath, activeDiagnostics, this.maxActiveBytes).length;
|
|
252
|
+
const archives = this.archiveFiles().length;
|
|
253
|
+
const oversizedFiles = Number(fileExceeds(compactPath, this.maxCompactBytes)) + Number(fileExceeds(activePath, this.maxActiveBytes));
|
|
254
|
+
const rejectedFiles = Number(existsSync(compactPath) && !this.secureRegularFile(compactPath))
|
|
255
|
+
+ Number(existsSync(activePath) && !this.secureRegularFile(activePath));
|
|
256
|
+
const corruptLines = compactDiagnostics.corruptLines + activeDiagnostics.corruptLines + rejectedFiles;
|
|
257
|
+
const oversizedLines = compactDiagnostics.oversizedLines + activeDiagnostics.oversizedLines;
|
|
258
|
+
const compactMissingWithArchives = archives > 0 && (!existsSync(compactPath) || statSync(compactPath).size === 0);
|
|
259
|
+
const degraded = corruptLines > 0 || oversizedLines > 0 || oversizedFiles > 0 || compactMissingWithArchives;
|
|
260
|
+
const records = compactedRecords + activeRecords;
|
|
261
|
+
return {
|
|
262
|
+
recovery: degraded ? 'degraded' : records === 0 ? 'empty' : this.hasRecoveryMarker() ? 'recovered' : 'healthy',
|
|
263
|
+
compactedRecords,
|
|
264
|
+
activeRecords,
|
|
265
|
+
corruptLines,
|
|
266
|
+
oversizedLines,
|
|
267
|
+
oversizedFiles,
|
|
268
|
+
archives,
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
withGraphLock(operation) {
|
|
272
|
+
this.ensureSecureDir();
|
|
273
|
+
const lockPath = join(this.dir, LOCK_FILE);
|
|
274
|
+
try {
|
|
275
|
+
util.acquireLock(lockPath);
|
|
276
|
+
}
|
|
277
|
+
catch (error) {
|
|
278
|
+
if (error instanceof util.LockTimeoutError)
|
|
279
|
+
throw new MemoryGraphBusyError();
|
|
280
|
+
throw error;
|
|
281
|
+
}
|
|
282
|
+
let value;
|
|
283
|
+
let operationError;
|
|
284
|
+
let operationFailed = false;
|
|
285
|
+
try {
|
|
286
|
+
this.ensureSecureDir();
|
|
287
|
+
value = operation();
|
|
288
|
+
}
|
|
289
|
+
catch (error) {
|
|
290
|
+
operationFailed = true;
|
|
291
|
+
operationError = error;
|
|
292
|
+
}
|
|
293
|
+
let releaseError;
|
|
294
|
+
try {
|
|
295
|
+
const released = util.releaseLock(lockPath);
|
|
296
|
+
const reliable = released.released
|
|
297
|
+
&& (released.reason === 'released' || released.reason === 'released_with_cleanup_error');
|
|
298
|
+
if (!reliable)
|
|
299
|
+
releaseError = new util.LockReleaseError(released.reason);
|
|
300
|
+
}
|
|
301
|
+
catch (error) {
|
|
302
|
+
releaseError = error;
|
|
303
|
+
}
|
|
304
|
+
if (operationFailed)
|
|
305
|
+
throw operationError;
|
|
306
|
+
if (releaseError !== undefined)
|
|
307
|
+
throw releaseError;
|
|
308
|
+
return value;
|
|
309
|
+
}
|
|
310
|
+
importStateFingerprint() {
|
|
311
|
+
return [COMPACT_FILE, ACTIVE_FILE].map((file) => {
|
|
312
|
+
const path = join(this.dir, file);
|
|
313
|
+
if (!existsSync(path))
|
|
314
|
+
return `${file}:missing`;
|
|
315
|
+
const stat = lstatSync(path, { bigint: true });
|
|
316
|
+
return `${file}:${stat.dev}:${stat.ino}:${stat.mode}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}`;
|
|
317
|
+
}).join('|');
|
|
318
|
+
}
|
|
319
|
+
appendRecordUnlocked(record) {
|
|
320
|
+
this.ensureSecureDir();
|
|
321
|
+
const line = `${JSON.stringify(record)}\n`;
|
|
322
|
+
if (Buffer.byteLength(line) > this.maxLineBytes)
|
|
323
|
+
return false;
|
|
324
|
+
const activePath = join(this.dir, ACTIVE_FILE);
|
|
325
|
+
if (existsSync(activePath) && statSync(activePath).size + Buffer.byteLength(line) > this.maxActiveBytes) {
|
|
326
|
+
const maintenance = this.rotateAndCompactUnlocked();
|
|
327
|
+
if (!maintenance.rotated)
|
|
328
|
+
return false;
|
|
329
|
+
}
|
|
330
|
+
const fd = openNoFollow(activePath, constants.O_WRONLY | constants.O_CREAT | constants.O_APPEND, 0o600);
|
|
331
|
+
try {
|
|
332
|
+
const stat = fstatSync(fd);
|
|
333
|
+
if (!stat.isFile())
|
|
334
|
+
return false;
|
|
335
|
+
writeSync(fd, line, undefined, 'utf8');
|
|
336
|
+
fsyncSync(fd);
|
|
337
|
+
return true;
|
|
338
|
+
}
|
|
339
|
+
finally {
|
|
340
|
+
closeSync(fd);
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
rotateAndCompactUnlocked() {
|
|
344
|
+
const diagnostics = emptyDiagnostics();
|
|
345
|
+
const activePath = join(this.dir, ACTIVE_FILE);
|
|
346
|
+
const records = [...this.readCompact(diagnostics), ...this.readWholeBounded(activePath, diagnostics, this.maxActiveBytes)];
|
|
347
|
+
const compacted = compactRecords(records, this.maxCompactEdges);
|
|
348
|
+
const compactedRecords = this.writeCompact(compacted);
|
|
349
|
+
if (compacted.length > 0 && compactedRecords === 0) {
|
|
350
|
+
return {
|
|
351
|
+
rotated: false,
|
|
352
|
+
compactedRecords: 0,
|
|
353
|
+
corruptLines: diagnostics.corruptLines,
|
|
354
|
+
oversizedLines: diagnostics.oversizedLines,
|
|
355
|
+
archives: this.archiveFiles().length,
|
|
356
|
+
recovery: 'degraded',
|
|
357
|
+
};
|
|
358
|
+
}
|
|
359
|
+
if (compacted.length === 0 || compactedRecords > 0)
|
|
360
|
+
this.clearRecoveryMarker();
|
|
361
|
+
let rotated = false;
|
|
362
|
+
if (existsSync(activePath) && this.secureRegularFile(activePath)) {
|
|
363
|
+
const raw = this.readRawTail(activePath, this.maxActiveBytes);
|
|
364
|
+
if (statSync(activePath).size > raw.length)
|
|
365
|
+
diagnostics.truncated = true;
|
|
366
|
+
const archivePath = this.nextArchivePath();
|
|
367
|
+
this.writeAtomic(archivePath, gzipSync(raw));
|
|
368
|
+
this.writeAtomic(activePath, Buffer.alloc(0));
|
|
369
|
+
rotated = true;
|
|
370
|
+
}
|
|
371
|
+
this.pruneArchives();
|
|
372
|
+
return {
|
|
373
|
+
rotated,
|
|
374
|
+
compactedRecords,
|
|
375
|
+
corruptLines: diagnostics.corruptLines,
|
|
376
|
+
oversizedLines: diagnostics.oversizedLines,
|
|
377
|
+
archives: this.archiveFiles().length,
|
|
378
|
+
recovery: diagnostics.corruptLines > 0 || diagnostics.oversizedLines > 0 || diagnostics.truncated
|
|
379
|
+
? 'degraded'
|
|
380
|
+
: compactedRecords > 0 ? 'healthy' : 'empty',
|
|
381
|
+
};
|
|
382
|
+
}
|
|
383
|
+
compactRequiresRecovery() {
|
|
384
|
+
const path = join(this.dir, COMPACT_FILE);
|
|
385
|
+
if (!existsSync(path) || !this.secureRegularFile(path) || statSync(path).size === 0)
|
|
386
|
+
return true;
|
|
387
|
+
const diagnostics = emptyDiagnostics();
|
|
388
|
+
this.readCompact(diagnostics);
|
|
389
|
+
return diagnostics.corruptLines > 0 || diagnostics.oversizedLines > 0 || diagnostics.truncated;
|
|
390
|
+
}
|
|
391
|
+
readQueryableRecords(diagnostics) {
|
|
392
|
+
this.ensureSecureDir();
|
|
393
|
+
const compactPath = join(this.dir, COMPACT_FILE);
|
|
394
|
+
const compactDiagnostics = emptyDiagnostics();
|
|
395
|
+
let records = this.readCompact(compactDiagnostics);
|
|
396
|
+
const archives = this.archiveFiles().length;
|
|
397
|
+
const compactExists = existsSync(compactPath);
|
|
398
|
+
const compactSecure = compactExists && this.secureRegularFile(compactPath);
|
|
399
|
+
const compactNeedsRecovery = archives > 0 && (!compactExists
|
|
400
|
+
|| !compactSecure
|
|
401
|
+
|| (compactSecure && statSync(compactPath).size === 0)
|
|
402
|
+
|| compactDiagnostics.corruptLines > 0
|
|
403
|
+
|| compactDiagnostics.oversizedLines > 0
|
|
404
|
+
|| compactDiagnostics.truncated);
|
|
405
|
+
mergeDiagnostics(diagnostics, compactDiagnostics);
|
|
406
|
+
if (compactNeedsRecovery) {
|
|
407
|
+
try {
|
|
408
|
+
const recovery = this.recoverFromArchivesUnlocked();
|
|
409
|
+
if (recovery.recovery === 'recovered') {
|
|
410
|
+
const recoveredDiagnostics = emptyDiagnostics();
|
|
411
|
+
records = this.readCompact(recoveredDiagnostics);
|
|
412
|
+
mergeDiagnostics(diagnostics, recoveredDiagnostics);
|
|
413
|
+
diagnostics.recovery = 'recovered';
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
catch {
|
|
417
|
+
diagnostics.recovery = 'degraded';
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
records.push(...this.readWholeBounded(join(this.dir, ACTIVE_FILE), diagnostics, this.maxActiveBytes));
|
|
421
|
+
if (diagnostics.recovery !== 'recovered' && (diagnostics.corruptLines > 0 || diagnostics.oversizedLines > 0 || diagnostics.truncated))
|
|
422
|
+
diagnostics.recovery = 'degraded';
|
|
423
|
+
return records;
|
|
424
|
+
}
|
|
425
|
+
readImportRecords() {
|
|
426
|
+
this.ensureSecureDir();
|
|
427
|
+
const diagnostics = emptyDiagnostics();
|
|
428
|
+
const activePath = join(this.dir, ACTIVE_FILE);
|
|
429
|
+
if (existsSync(activePath)) {
|
|
430
|
+
if (!this.secureRegularFile(activePath) || statSync(activePath).size > this.maxActiveBytes) {
|
|
431
|
+
throw new MemoryGraphImportStateRejectedError();
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
return [...this.readCompact(diagnostics), ...this.readWholeBounded(activePath, diagnostics, this.maxActiveBytes)];
|
|
435
|
+
}
|
|
436
|
+
readCompact(diagnostics) {
|
|
437
|
+
const path = join(this.dir, COMPACT_FILE);
|
|
438
|
+
if (!existsSync(path) || !this.secureRegularFile(path))
|
|
439
|
+
return [];
|
|
440
|
+
if (statSync(path).size > this.maxCompactBytes) {
|
|
441
|
+
diagnostics.truncated = true;
|
|
442
|
+
diagnostics.oversizedLines += 1;
|
|
443
|
+
return [];
|
|
444
|
+
}
|
|
445
|
+
return this.readWholeBounded(path, diagnostics, this.maxCompactBytes);
|
|
446
|
+
}
|
|
447
|
+
readWholeBounded(path, diagnostics, maxBytes) {
|
|
448
|
+
if (!existsSync(path) || !this.secureRegularFile(path))
|
|
449
|
+
return [];
|
|
450
|
+
const fd = openNoFollow(path, constants.O_RDONLY, 0o600);
|
|
451
|
+
try {
|
|
452
|
+
const stat = fstatSync(fd);
|
|
453
|
+
if (!stat.isFile())
|
|
454
|
+
return [];
|
|
455
|
+
if (stat.size > maxBytes) {
|
|
456
|
+
diagnostics.truncated = true;
|
|
457
|
+
return this.readTailFromFd(fd, stat.size, diagnostics, maxBytes);
|
|
458
|
+
}
|
|
459
|
+
const raw = readFdBytes(fd, stat.size, 0);
|
|
460
|
+
diagnostics.bytesRead += raw.length;
|
|
461
|
+
return this.parseBuffer(raw, diagnostics);
|
|
462
|
+
}
|
|
463
|
+
finally {
|
|
464
|
+
closeSync(fd);
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
readTail(path, diagnostics, maxBytes = this.maxTailBytes) {
|
|
468
|
+
if (!existsSync(path) || !this.secureRegularFile(path))
|
|
469
|
+
return [];
|
|
470
|
+
const fd = openNoFollow(path, constants.O_RDONLY, 0o600);
|
|
471
|
+
try {
|
|
472
|
+
const size = fstatSync(fd).size;
|
|
473
|
+
return this.readTailFromFd(fd, size, diagnostics, maxBytes);
|
|
474
|
+
}
|
|
475
|
+
finally {
|
|
476
|
+
closeSync(fd);
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
readTailFromFd(fd, size, diagnostics, maxBytes) {
|
|
480
|
+
const bytes = Math.min(size, maxBytes);
|
|
481
|
+
const buffer = readFdBytes(fd, bytes, size - bytes);
|
|
482
|
+
diagnostics.bytesRead += buffer.length;
|
|
483
|
+
diagnostics.truncated ||= size > buffer.length;
|
|
484
|
+
if (size <= buffer.length)
|
|
485
|
+
return this.parseBuffer(buffer, diagnostics);
|
|
486
|
+
const newline = buffer.indexOf(0x0a);
|
|
487
|
+
return this.parseBuffer(newline >= 0 ? buffer.subarray(newline + 1) : Buffer.alloc(0), diagnostics);
|
|
488
|
+
}
|
|
489
|
+
readRawTail(path, maxBytes) {
|
|
490
|
+
const fd = openNoFollow(path, constants.O_RDONLY, 0o600);
|
|
491
|
+
try {
|
|
492
|
+
const size = fstatSync(fd).size;
|
|
493
|
+
const bytes = Math.min(size, maxBytes);
|
|
494
|
+
const buffer = readFdBytes(fd, bytes, size - bytes);
|
|
495
|
+
if (size <= bytes)
|
|
496
|
+
return buffer;
|
|
497
|
+
const newline = buffer.indexOf(0x0a);
|
|
498
|
+
return newline >= 0 ? buffer.subarray(newline + 1) : Buffer.alloc(0);
|
|
499
|
+
}
|
|
500
|
+
finally {
|
|
501
|
+
closeSync(fd);
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
parseBuffer(buffer, diagnostics) {
|
|
505
|
+
const out = [];
|
|
506
|
+
for (const line of buffer.toString('utf8').split('\n')) {
|
|
507
|
+
if (!line.trim())
|
|
508
|
+
continue;
|
|
509
|
+
if (Buffer.byteLength(line) > this.maxLineBytes) {
|
|
510
|
+
diagnostics.oversizedLines += 1;
|
|
511
|
+
continue;
|
|
512
|
+
}
|
|
513
|
+
try {
|
|
514
|
+
const raw = JSON.parse(line);
|
|
515
|
+
if (isObject(raw) && raw['version'] === 2 && raw['kind'] === 'outcome' && raw['provenance'] !== 'v2_local' && raw['provenance'] !== 'v1_import') {
|
|
516
|
+
diagnostics.provenanceRejected += 1;
|
|
517
|
+
continue;
|
|
518
|
+
}
|
|
519
|
+
const parsed = parseV2Record(raw);
|
|
520
|
+
if (parsed) {
|
|
521
|
+
out.push(parsed);
|
|
522
|
+
diagnostics.recordsRead += 1;
|
|
523
|
+
}
|
|
524
|
+
else {
|
|
525
|
+
diagnostics.corruptLines += 1;
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
catch {
|
|
529
|
+
diagnostics.corruptLines += 1;
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
return out;
|
|
533
|
+
}
|
|
534
|
+
writeCompact(records) {
|
|
535
|
+
const fitted = fitCompactRecords(records, this.maxCompactBytes);
|
|
536
|
+
if (records.length > 0 && fitted.records.length === 0)
|
|
537
|
+
return 0;
|
|
538
|
+
this.writeAtomic(join(this.dir, COMPACT_FILE), fitted.payload);
|
|
539
|
+
return fitted.records.length;
|
|
540
|
+
}
|
|
541
|
+
writeAtomic(path, payload) {
|
|
542
|
+
this.ensureSecureDir();
|
|
543
|
+
if (existsSync(path) && !this.secureRegularFile(path))
|
|
544
|
+
throw new Error('memory_graph_path_rejected');
|
|
545
|
+
const temp = join(dirname(path), `.${basename(path)}.${this.now()}.tmp`);
|
|
546
|
+
const fd = openNoFollow(temp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, 0o600);
|
|
547
|
+
try {
|
|
548
|
+
writeSync(fd, payload);
|
|
549
|
+
fsyncSync(fd);
|
|
550
|
+
}
|
|
551
|
+
finally {
|
|
552
|
+
closeSync(fd);
|
|
553
|
+
}
|
|
554
|
+
renameSync(temp, path);
|
|
555
|
+
}
|
|
556
|
+
ensureSecureDir() {
|
|
557
|
+
if (!existsSync(this.dir))
|
|
558
|
+
mkdirSync(this.dir, { recursive: true, mode: 0o700 });
|
|
559
|
+
const stat = lstatSync(this.dir);
|
|
560
|
+
if (!stat.isDirectory() || stat.isSymbolicLink())
|
|
561
|
+
throw new Error('memory_graph_dir_rejected');
|
|
562
|
+
}
|
|
563
|
+
secureRegularFile(path) {
|
|
564
|
+
const stat = lstatSync(path);
|
|
565
|
+
return stat.isFile() && !stat.isSymbolicLink();
|
|
566
|
+
}
|
|
567
|
+
workspaceScope(workspace) {
|
|
568
|
+
try {
|
|
569
|
+
const absolute = resolve(workspace);
|
|
570
|
+
const linkStat = lstatSync(absolute);
|
|
571
|
+
if (!linkStat.isDirectory() || linkStat.isSymbolicLink())
|
|
572
|
+
return null;
|
|
573
|
+
const canonical = realpathSync(absolute);
|
|
574
|
+
return scopeHash(`workspace:${canonical}`);
|
|
575
|
+
}
|
|
576
|
+
catch {
|
|
577
|
+
return null;
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
archiveFiles() {
|
|
581
|
+
if (!existsSync(this.dir))
|
|
582
|
+
return [];
|
|
583
|
+
return readdirSync(this.dir).filter((file) => ARCHIVE_PATTERN.test(file)).sort();
|
|
584
|
+
}
|
|
585
|
+
nextArchivePath() {
|
|
586
|
+
const latest = this.archiveFiles().at(-1);
|
|
587
|
+
const latestTimestamp = latest ? Number(ARCHIVE_PATTERN.exec(latest)?.[1] ?? 0) : 0;
|
|
588
|
+
const timestamp = Math.max(Math.floor(this.now()), latestTimestamp + 1);
|
|
589
|
+
return join(this.dir, `memory_graph.v2.${timestamp}.jsonl.gz`);
|
|
590
|
+
}
|
|
591
|
+
pruneArchives() {
|
|
592
|
+
const files = this.archiveFiles();
|
|
593
|
+
for (const file of files.slice(0, Math.max(0, files.length - this.archiveRetention)))
|
|
594
|
+
unlinkSync(join(this.dir, file));
|
|
595
|
+
}
|
|
596
|
+
writeRecoveryMarker() {
|
|
597
|
+
this.writeAtomic(join(this.dir, RECOVERY_FILE), Buffer.from(`${JSON.stringify({ version: 1, recoveredAt: new Date(this.now()).toISOString() })}\n`, 'utf8'));
|
|
598
|
+
}
|
|
599
|
+
hasRecoveryMarker() {
|
|
600
|
+
const path = join(this.dir, RECOVERY_FILE);
|
|
601
|
+
if (!existsSync(path) || !this.secureRegularFile(path))
|
|
602
|
+
return false;
|
|
603
|
+
try {
|
|
604
|
+
const bytes = this.readRawBounded(path, this.maxLineBytes);
|
|
605
|
+
if (bytes === null)
|
|
606
|
+
return false;
|
|
607
|
+
const raw = JSON.parse(bytes.toString('utf8'));
|
|
608
|
+
return isObject(raw) && raw['version'] === 1 && typeof raw['recoveredAt'] === 'string' && validIso(raw['recoveredAt']) !== null;
|
|
609
|
+
}
|
|
610
|
+
catch {
|
|
611
|
+
return false;
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
clearRecoveryMarker() {
|
|
615
|
+
const path = join(this.dir, RECOVERY_FILE);
|
|
616
|
+
if (existsSync(path) && this.secureRegularFile(path))
|
|
617
|
+
unlinkSync(path);
|
|
618
|
+
}
|
|
619
|
+
readRawBounded(path, maxBytes) {
|
|
620
|
+
if (!existsSync(path) || !this.secureRegularFile(path))
|
|
621
|
+
return null;
|
|
622
|
+
const fd = openNoFollow(path, constants.O_RDONLY, 0o600);
|
|
623
|
+
try {
|
|
624
|
+
const stat = fstatSync(fd);
|
|
625
|
+
if (!stat.isFile() || stat.size > maxBytes)
|
|
626
|
+
return null;
|
|
627
|
+
return readFdBytes(fd, stat.size, 0);
|
|
628
|
+
}
|
|
629
|
+
finally {
|
|
630
|
+
closeSync(fd);
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
const MEMORY_GRAPH_REASON_PATTERN = /scoped memory-graph outcome ([+-]\d+\.\d{3}) \(boost=([+-]?\d+\.\d{2})\)/;
|
|
635
|
+
export function sanitizeMemoryGraphSelectionReason(value) {
|
|
636
|
+
if (typeof value !== 'string')
|
|
637
|
+
return undefined;
|
|
638
|
+
const match = MEMORY_GRAPH_REASON_PATTERN.exec(value);
|
|
639
|
+
if (!match?.[1] || !match[2])
|
|
640
|
+
return undefined;
|
|
641
|
+
const outcome = Number(match[1]);
|
|
642
|
+
const boost = Number(match[2]);
|
|
643
|
+
if (!Number.isFinite(outcome) || !Number.isFinite(boost) || Math.abs(outcome) > 1 || Math.abs(boost) > 1)
|
|
644
|
+
return undefined;
|
|
645
|
+
return `scoped memory-graph outcome ${match[1]} (boost=${match[2]})`;
|
|
646
|
+
}
|
|
647
|
+
export function formatMemoryGraphOperatorStatus(status) {
|
|
648
|
+
const state = status.recovery === 'healthy' || status.recovery === 'degraded'
|
|
649
|
+
|| status.recovery === 'recovered' || status.recovery === 'empty'
|
|
650
|
+
? status.recovery
|
|
651
|
+
: 'degraded';
|
|
652
|
+
const reason = sanitizeMemoryGraphSelectionReason(status.selectionReason);
|
|
653
|
+
return [
|
|
654
|
+
`state=${state}`,
|
|
655
|
+
...(status.busy === true ? ['busy=1'] : []),
|
|
656
|
+
`corrupt=${boundedOperatorCount(status.corruptLines)}`,
|
|
657
|
+
`oversized_lines=${boundedOperatorCount(status.oversizedLines)}`,
|
|
658
|
+
`oversized_files=${boundedOperatorCount(status.oversizedFiles)}`,
|
|
659
|
+
`archives=${boundedOperatorCount(status.archives)}`,
|
|
660
|
+
...(reason ? [`selection=${reason}`] : []),
|
|
661
|
+
].join(' ');
|
|
662
|
+
}
|
|
663
|
+
export function loadMemoryGraphOperatorStatus(env = process.env) {
|
|
664
|
+
const home = events.evomapHome(env);
|
|
665
|
+
const graphDir = join(home, 'evolution');
|
|
666
|
+
let health;
|
|
667
|
+
try {
|
|
668
|
+
health = new LocalMemoryGraph({
|
|
669
|
+
dir: graphDir,
|
|
670
|
+
...resolveLocalMemoryUserIdentity(graphDir),
|
|
671
|
+
}).inspectHealth();
|
|
672
|
+
}
|
|
673
|
+
catch {
|
|
674
|
+
health = { ...emptyHealth(), recovery: 'degraded', corruptLines: 1 };
|
|
675
|
+
}
|
|
676
|
+
let selectionReason;
|
|
677
|
+
try {
|
|
678
|
+
const rootEvents = events.readEvents(join(home, 'evolution', 'root_events.jsonl'));
|
|
679
|
+
for (let index = rootEvents.length - 1; index >= 0; index -= 1) {
|
|
680
|
+
const event = rootEvents[index];
|
|
681
|
+
if (event?.type !== 'decision.gene_selected')
|
|
682
|
+
continue;
|
|
683
|
+
selectionReason = sanitizeMemoryGraphSelectionReason(event.payload?.['selectedReason']);
|
|
684
|
+
if (selectionReason)
|
|
685
|
+
break;
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
catch {
|
|
689
|
+
// Health remains available even when the optional event rationale cannot be read.
|
|
690
|
+
}
|
|
691
|
+
return { ...health, ...(selectionReason ? { selectionReason } : {}) };
|
|
692
|
+
}
|
|
693
|
+
function parseV2Record(value) {
|
|
694
|
+
if (!isObject(value) || value['version'] !== 2 || value['kind'] !== 'outcome')
|
|
695
|
+
return null;
|
|
696
|
+
const provenance = value['provenance'];
|
|
697
|
+
if (provenance !== 'v2_local' && provenance !== 'v1_import')
|
|
698
|
+
return null;
|
|
699
|
+
const workspaceScope = safeToken(value['workspaceScope'], 128);
|
|
700
|
+
const userScope = safeToken(value['userScope'], 128);
|
|
701
|
+
const signalFingerprint = safeToken(value['signalFingerprint'], 4096);
|
|
702
|
+
const geneId = typeof value['geneId'] === 'string' ? algo.safeMemoryGeneId(value['geneId']) : '';
|
|
703
|
+
const status = value['status'];
|
|
704
|
+
const at = typeof value['at'] === 'string' ? validIso(value['at']) : null;
|
|
705
|
+
if (!workspaceScope || !userScope || !signalFingerprint || !geneId || (status !== 'success' && status !== 'failed') || !at)
|
|
706
|
+
return null;
|
|
707
|
+
return {
|
|
708
|
+
version: 2,
|
|
709
|
+
kind: 'outcome',
|
|
710
|
+
provenance,
|
|
711
|
+
workspaceScope,
|
|
712
|
+
userScope,
|
|
713
|
+
signalFingerprint,
|
|
714
|
+
signals: algo.normalizeMemorySignals(Array.isArray(value['signals']) ? value['signals'].filter((item) => typeof item === 'string') : []),
|
|
715
|
+
geneId,
|
|
716
|
+
status,
|
|
717
|
+
score: clampScore(Number(value['score'])),
|
|
718
|
+
at,
|
|
719
|
+
...(safeToken(value['sourceFingerprint'], 128) ? { sourceFingerprint: safeToken(value['sourceFingerprint'], 128) } : {}),
|
|
720
|
+
...(safeToken(value['sourceScope'], 128) ? { sourceScope: safeToken(value['sourceScope'], 128) } : {}),
|
|
721
|
+
...(safeToken(value['legacySourceFingerprint'], 128) ? { legacySourceFingerprint: safeToken(value['legacySourceFingerprint'], 128) } : {}),
|
|
722
|
+
...(positiveCount(value['successCount']) !== undefined ? { successCount: positiveCount(value['successCount']) } : {}),
|
|
723
|
+
...(positiveCount(value['failCount']) !== undefined ? { failCount: positiveCount(value['failCount']) } : {}),
|
|
724
|
+
};
|
|
725
|
+
}
|
|
726
|
+
function parseV1Outcome(value, workspaceScope, userScope, sourceScope) {
|
|
727
|
+
if (!workspaceScope || !isObject(value) || value['type'] !== 'MemoryGraphEvent' || value['kind'] !== 'outcome')
|
|
728
|
+
return null;
|
|
729
|
+
const gene = isObject(value['gene']) ? value['gene'] : null;
|
|
730
|
+
const signal = isObject(value['signal']) ? value['signal'] : null;
|
|
731
|
+
const outcome = isObject(value['outcome']) ? value['outcome'] : null;
|
|
732
|
+
const geneId = typeof gene?.['id'] === 'string' ? algo.safeMemoryGeneId(gene['id']) : '';
|
|
733
|
+
const status = outcome?.['status'];
|
|
734
|
+
const at = typeof value['ts'] === 'string' ? validIso(value['ts']) : null;
|
|
735
|
+
if (!geneId || (status !== 'success' && status !== 'failed') || !at)
|
|
736
|
+
return null;
|
|
737
|
+
const signals = algo.normalizeMemorySignals(Array.isArray(signal?.['signals']) ? signal['signals'].filter((item) => typeof item === 'string') : []);
|
|
738
|
+
const score = clampScore(Number(outcome?.['score']));
|
|
739
|
+
const legacySourceFingerprint = scopeHash(JSON.stringify({
|
|
740
|
+
id: safeToken(value['id'], 240) ?? '',
|
|
741
|
+
at,
|
|
742
|
+
geneId,
|
|
743
|
+
status,
|
|
744
|
+
score,
|
|
745
|
+
signals,
|
|
746
|
+
}));
|
|
747
|
+
const sourceFingerprint = scopeHash(JSON.stringify({
|
|
748
|
+
workspaceScope,
|
|
749
|
+
userScope,
|
|
750
|
+
sourceScope,
|
|
751
|
+
legacySourceFingerprint,
|
|
752
|
+
}));
|
|
753
|
+
return {
|
|
754
|
+
version: 2,
|
|
755
|
+
kind: 'outcome',
|
|
756
|
+
provenance: 'v1_import',
|
|
757
|
+
workspaceScope,
|
|
758
|
+
userScope,
|
|
759
|
+
sourceScope,
|
|
760
|
+
signalFingerprint: algo.memorySignalFingerprint(signals),
|
|
761
|
+
signals,
|
|
762
|
+
geneId,
|
|
763
|
+
status,
|
|
764
|
+
score,
|
|
765
|
+
at,
|
|
766
|
+
sourceFingerprint,
|
|
767
|
+
legacySourceFingerprint,
|
|
768
|
+
};
|
|
769
|
+
}
|
|
770
|
+
function compactRecords(records, maxEdges) {
|
|
771
|
+
const byEdge = new Map();
|
|
772
|
+
for (const record of records) {
|
|
773
|
+
const key = compactRecordKey(record);
|
|
774
|
+
const current = byEdge.get(key);
|
|
775
|
+
const successCount = (record.successCount ?? (record.status === 'success' ? 1 : 0)) + (current?.successCount ?? (current?.status === 'success' ? 1 : 0));
|
|
776
|
+
const failCount = (record.failCount ?? (record.status === 'failed' ? 1 : 0)) + (current?.failCount ?? (current?.status === 'failed' ? 1 : 0));
|
|
777
|
+
const newest = !current || Date.parse(record.at) >= Date.parse(current.at) ? record : current;
|
|
778
|
+
byEdge.set(key, { ...newest, successCount, failCount });
|
|
779
|
+
}
|
|
780
|
+
return [...byEdge.values()]
|
|
781
|
+
.sort((left, right) => Date.parse(right.at) - Date.parse(left.at) || left.geneId.localeCompare(right.geneId))
|
|
782
|
+
.slice(0, maxEdges);
|
|
783
|
+
}
|
|
784
|
+
function compactRecordKey(record) {
|
|
785
|
+
return record.provenance === 'v1_import' && record.sourceFingerprint
|
|
786
|
+
? `import\u0000${record.workspaceScope}\u0000${record.userScope}\u0000${record.sourceScope ?? 'legacy-unscoped'}\u0000${record.sourceFingerprint}`
|
|
787
|
+
: `${record.workspaceScope}\u0000${record.userScope}\u0000${record.signalFingerprint}\u0000${record.geneId}`;
|
|
788
|
+
}
|
|
789
|
+
function mergeRecoveryRecords(compact, archives, maxEdges) {
|
|
790
|
+
const preserved = compactRecords(compact, compact.length);
|
|
791
|
+
const preservedKeys = new Set(preserved.map(compactRecordKey));
|
|
792
|
+
const recovered = compactRecords(archives, archives.length)
|
|
793
|
+
.filter((record) => !preservedKeys.has(compactRecordKey(record)));
|
|
794
|
+
return compactRecords([...preserved, ...recovered], maxEdges);
|
|
795
|
+
}
|
|
796
|
+
function fitCompactRecords(records, maxBytes) {
|
|
797
|
+
const kept = [];
|
|
798
|
+
const lines = [];
|
|
799
|
+
let bytes = 0;
|
|
800
|
+
for (const record of records) {
|
|
801
|
+
const line = Buffer.from(`${JSON.stringify(record)}\n`, 'utf8');
|
|
802
|
+
if (bytes + line.length > maxBytes)
|
|
803
|
+
break;
|
|
804
|
+
kept.push(record);
|
|
805
|
+
lines.push(line);
|
|
806
|
+
bytes += line.length;
|
|
807
|
+
}
|
|
808
|
+
return { records: kept, payload: Buffer.concat(lines, bytes) };
|
|
809
|
+
}
|
|
810
|
+
function emptyDiagnostics() {
|
|
811
|
+
return { bytesRead: 0, recordsRead: 0, corruptLines: 0, oversizedLines: 0, scopeRejected: 0, provenanceRejected: 0, truncated: false, recovery: 'healthy' };
|
|
812
|
+
}
|
|
813
|
+
function mergeDiagnostics(target, source) {
|
|
814
|
+
target.bytesRead += source.bytesRead;
|
|
815
|
+
target.recordsRead += source.recordsRead;
|
|
816
|
+
target.corruptLines += source.corruptLines;
|
|
817
|
+
target.oversizedLines += source.oversizedLines;
|
|
818
|
+
target.scopeRejected += source.scopeRejected;
|
|
819
|
+
target.provenanceRejected += source.provenanceRejected;
|
|
820
|
+
target.truncated ||= source.truncated;
|
|
821
|
+
if (source.busy === true)
|
|
822
|
+
target.busy = true;
|
|
823
|
+
if (target.recovery !== 'recovered' && source.recovery !== 'healthy')
|
|
824
|
+
target.recovery = source.recovery;
|
|
825
|
+
}
|
|
826
|
+
function emptyHealth() {
|
|
827
|
+
return {
|
|
828
|
+
recovery: 'empty',
|
|
829
|
+
compactedRecords: 0,
|
|
830
|
+
activeRecords: 0,
|
|
831
|
+
corruptLines: 0,
|
|
832
|
+
oversizedLines: 0,
|
|
833
|
+
oversizedFiles: 0,
|
|
834
|
+
archives: 0,
|
|
835
|
+
};
|
|
836
|
+
}
|
|
837
|
+
function fileExceeds(path, maxBytes) {
|
|
838
|
+
try {
|
|
839
|
+
const stat = lstatSync(path);
|
|
840
|
+
return stat.isFile() && !stat.isSymbolicLink() && stat.size > maxBytes;
|
|
841
|
+
}
|
|
842
|
+
catch {
|
|
843
|
+
return false;
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
function openNoFollow(path, flags, mode) {
|
|
847
|
+
return openSync(path, flags | constants.O_NOFOLLOW, mode);
|
|
848
|
+
}
|
|
849
|
+
function readFdBytes(fd, length, position) {
|
|
850
|
+
const buffer = Buffer.alloc(length);
|
|
851
|
+
let offset = 0;
|
|
852
|
+
while (offset < length) {
|
|
853
|
+
const read = readSync(fd, buffer, offset, length - offset, position + offset);
|
|
854
|
+
if (read === 0)
|
|
855
|
+
break;
|
|
856
|
+
offset += read;
|
|
857
|
+
}
|
|
858
|
+
return offset === length ? buffer : buffer.subarray(0, offset);
|
|
859
|
+
}
|
|
860
|
+
function scopeHash(value) {
|
|
861
|
+
return `sha256:${createHash('sha256').update(value).digest('hex')}`;
|
|
862
|
+
}
|
|
863
|
+
function safeToken(value, maxChars) {
|
|
864
|
+
if (typeof value !== 'string')
|
|
865
|
+
return null;
|
|
866
|
+
const trimmed = value.trim();
|
|
867
|
+
return trimmed.length > 0 && trimmed.length <= maxChars ? trimmed : null;
|
|
868
|
+
}
|
|
869
|
+
function boundedOperatorCount(value) {
|
|
870
|
+
const count = Number(value);
|
|
871
|
+
return Number.isFinite(count) && count > 0 ? Math.min(1_000_000, Math.floor(count)) : 0;
|
|
872
|
+
}
|
|
873
|
+
function positiveCount(value) {
|
|
874
|
+
const count = Number(value);
|
|
875
|
+
return Number.isFinite(count) && count > 0 ? Math.min(1_000_000, Math.floor(count)) : undefined;
|
|
876
|
+
}
|
|
877
|
+
function positiveInt(value, fallback) {
|
|
878
|
+
return Number.isFinite(value) && Number(value) > 0 ? Math.floor(Number(value)) : fallback;
|
|
879
|
+
}
|
|
880
|
+
function clampScore(value) {
|
|
881
|
+
return Number.isFinite(value) ? Math.max(0, Math.min(1, value)) : 0;
|
|
882
|
+
}
|
|
883
|
+
function validIso(value) {
|
|
884
|
+
const parsed = Date.parse(value);
|
|
885
|
+
return Number.isFinite(parsed) ? new Date(parsed).toISOString() : null;
|
|
886
|
+
}
|
|
887
|
+
function isObject(value) {
|
|
888
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
889
|
+
}
|