@evomap/evolver-cli 2.0.0-beta.2 → 2.0.0-beta.22
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/antiGeneBenchmark.js +2 -0
- package/dist/antiGeneRollout.js +9 -3
- package/dist/assetHealth.d.ts +6 -0
- package/dist/assetHealth.js +107 -0
- package/dist/assetRepair.d.ts +24 -0
- package/dist/assetRepair.js +172 -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 +231 -0
- package/dist/atp.d.ts +10 -5
- package/dist/atp.js +119 -26
- package/dist/atpAutoBuyer.d.ts +120 -0
- package/dist/atpAutoBuyer.js +814 -0
- package/dist/atpAutoDeliver.js +2 -2
- package/dist/autoDistillAntiGene.js +7 -5
- package/dist/autoDistillLlm.d.ts +26 -0
- package/dist/autoDistillLlm.js +119 -22
- package/dist/autoDistillTranscript.js +3 -2
- package/dist/autoexec.d.ts +111 -24
- package/dist/autoexec.js +887 -120
- package/dist/autoexecConfig.d.ts +10 -0
- package/dist/autoexecConfig.js +69 -0
- package/dist/cli.js +13 -0
- package/dist/cliContracts.d.ts +33 -2
- package/dist/cliContracts.js +818 -78
- package/dist/commandCatalog.d.ts +72 -0
- package/dist/commandCatalog.js +120 -0
- package/dist/commands.d.ts +1 -0
- package/dist/commands.js +1 -0
- package/dist/curriculumCapabilityGaps.d.ts +6 -0
- package/dist/curriculumCapabilityGaps.js +24 -0
- package/dist/cycleConsumer.d.ts +17 -2
- package/dist/cycleConsumer.js +374 -50
- package/dist/dashboard.d.ts +13 -1
- package/dist/dashboard.js +235 -18
- package/dist/dispatch.d.ts +9 -2
- package/dist/dispatch.js +29 -6
- package/dist/distillAdmission.d.ts +13 -0
- package/dist/distillAdmission.js +35 -0
- package/dist/distillObserver.js +27 -12
- package/dist/distillPrimitives.d.ts +11 -8
- package/dist/distillPrimitives.js +116 -22
- package/dist/doctor.d.ts +13 -0
- package/dist/doctor.js +177 -10
- package/dist/identityHome.d.ts +9 -0
- package/dist/identityHome.js +47 -0
- package/dist/index.d.ts +73 -40
- package/dist/index.js +745 -207
- package/dist/issueReport.d.ts +7 -0
- package/dist/issueReport.js +291 -0
- package/dist/learningTrace.d.ts +15 -0
- package/dist/learningTrace.js +73 -0
- package/dist/lifecycle.d.ts +199 -2
- package/dist/lifecycle.js +4999 -152
- package/dist/lifecycleBootstrapTransaction.d.ts +235 -0
- package/dist/lifecycleBootstrapTransaction.js +2182 -0
- package/dist/localMemoryGraph.d.ts +184 -0
- package/dist/localMemoryGraph.js +2689 -0
- package/dist/login.d.ts +1 -1
- package/dist/login.js +3 -3
- package/dist/materialPackage.js +3 -6
- package/dist/materialSnapshot.d.ts +35 -1
- package/dist/materialSnapshot.js +265 -18
- package/dist/memoryGraphOps.d.ts +8 -0
- package/dist/memoryGraphOps.js +140 -0
- package/dist/migrate/assetFormatMap.d.ts +61 -0
- package/dist/migrate/assetFormatMap.js +53 -0
- package/dist/migrate/envTranslate.d.ts +26 -0
- package/dist/migrate/envTranslate.js +147 -0
- package/dist/migrate/fieldMap.d.ts +7 -5
- package/dist/migrate/fieldMap.js +20 -14
- package/dist/migrate/oauthImport.d.ts +66 -0
- package/dist/migrate/oauthImport.js +667 -0
- package/dist/migrate/v1Import.d.ts +98 -1
- package/dist/migrate/v1Import.js +1532 -71
- package/dist/modelCompatibility.d.ts +10 -0
- package/dist/modelCompatibility.js +296 -0
- package/dist/promptRecallHook.d.ts +24 -0
- package/dist/promptRecallHook.js +425 -0
- package/dist/recallVerifyReport.d.ts +37 -0
- package/dist/recallVerifyReport.js +244 -0
- package/dist/recipe.d.ts +14 -2
- package/dist/recipe.js +543 -65
- package/dist/repairedAssetStore.d.ts +2 -0
- package/dist/repairedAssetStore.js +12 -0
- package/dist/requiredSandboxValidation.d.ts +5 -0
- package/dist/requiredSandboxValidation.js +4 -0
- package/dist/reuse.d.ts +18 -4
- package/dist/reuse.js +375 -107
- package/dist/reviewFilter.d.ts +3 -1
- package/dist/reviewFilter.js +3 -1
- package/dist/runtimeCapabilities.d.ts +18 -0
- package/dist/runtimeCapabilities.js +81 -0
- package/dist/runtimeSessionSource.d.ts +8 -2
- package/dist/runtimeSessionSource.js +63 -11
- package/dist/selectionPolicyConfig.d.ts +8 -0
- package/dist/selectionPolicyConfig.js +18 -0
- package/dist/semanticIdfConfig.d.ts +2 -0
- package/dist/semanticIdfConfig.js +4 -0
- package/dist/sessionIngest.d.ts +43 -0
- package/dist/sessionIngest.js +180 -0
- package/dist/setupHooks.d.ts +5 -0
- package/dist/setupHooks.js +330 -14
- package/dist/skill2gep.d.ts +13 -9
- package/dist/skill2gep.js +99 -36
- package/dist/skillDistill.d.ts +8 -4
- package/dist/skillDistill.js +39 -9
- package/dist/solo/mode.js +1 -0
- package/dist/sync.d.ts +13 -1
- package/dist/sync.js +1947 -265
- package/dist/thesis.d.ts +1 -1
- package/dist/thesis.js +20 -3
- package/dist/trajectoryExport.js +21 -3
- package/dist/v1Compat.d.ts +1 -0
- package/dist/v1Compat.js +9 -0
- package/dist/valueDigest.js +8 -1
- package/dist/windowsLegacyTaskCleanup.d.ts +228 -0
- package/dist/windowsLegacyTaskCleanup.js +1475 -0
- package/dist/workflow.d.ts +39 -0
- package/dist/workflow.js +386 -0
- package/dist/workflowRuntime.d.ts +66 -0
- package/dist/workflowRuntime.js +638 -0
- package/package.json +14 -7
|
@@ -0,0 +1,2689 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { closeSync, constants, existsSync, fstatSync, ftruncateSync, fsyncSync, lstatSync, mkdirSync, openSync, readSync, readdirSync, realpathSync, renameSync, rmdirSync, 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 EPOCH_FILE = 'memory_graph.epoch.json';
|
|
12
|
+
const ROTATION_JOURNAL_FILE = 'memory_graph.rotation.json';
|
|
13
|
+
const ARCHIVE_PATTERN = /^memory_graph\.v2\.(\d{13})\.jsonl\.gz$/;
|
|
14
|
+
const ROTATION_GENERATION_PATTERN = /^\d{13}$/;
|
|
15
|
+
const ROTATION_TRANSACTION_PATTERN = /^txn_[a-f0-9]{64}$/;
|
|
16
|
+
const ROTATION_STAGE_PATTERN = /^memory_graph\.rotation\.(\d{13})\.(compact|archive|active)\.stage$/;
|
|
17
|
+
const ROTATION_TEMP_PATTERN = /^\.(?:memory_graph\.rotation\.json|memory_graph\.rotation\.(\d{13})\.(compact|archive|active)\.stage)\.(\d{13})\.tmp$/;
|
|
18
|
+
const RESET_BACKUP_PATTERN = /^memory_graph\.reset\.(\d{13,})$/;
|
|
19
|
+
const RESET_PENDING_PATTERN = /^memory_graph\.reset\.pending\.(\d{13,})$/;
|
|
20
|
+
const LEGACY_EPOCH_ID = 'legacy';
|
|
21
|
+
const DEFAULT_MAX_COMPACT_BYTES = 2 * 1024 * 1024;
|
|
22
|
+
const MAX_ROTATION_JOURNAL_BYTES = 64 * 1024;
|
|
23
|
+
export function resolveLocalMemoryUserId(info = userInfo()) {
|
|
24
|
+
if (Number.isInteger(info.uid) && info.uid >= 0)
|
|
25
|
+
return String(info.uid);
|
|
26
|
+
return `account:${process.platform}:${info.username.trim().toLowerCase()}:${resolve(info.homedir)}`;
|
|
27
|
+
}
|
|
28
|
+
export function resolveLocalMemoryUserIdentity(graphDir, info = userInfo()) {
|
|
29
|
+
const userId = resolveLocalMemoryUserId(info);
|
|
30
|
+
if (info.uid !== -1)
|
|
31
|
+
return { userId, legacyUserIds: [] };
|
|
32
|
+
const fromHome = relative(resolve(info.homedir), resolve(graphDir));
|
|
33
|
+
const privateToAccount = fromHome === '' || (!fromHome.startsWith('..') && !isAbsolute(fromHome));
|
|
34
|
+
return { userId, legacyUserIds: privateToAccount ? ['-1'] : [] };
|
|
35
|
+
}
|
|
36
|
+
export class MemoryGraphImportStateRejectedError extends Error {
|
|
37
|
+
constructor() {
|
|
38
|
+
super('memory_graph_import_state_rejected');
|
|
39
|
+
this.name = 'MemoryGraphImportStateRejectedError';
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
const memoryGraphV1OutcomePlans = new WeakMap();
|
|
43
|
+
export class MemoryGraphBusyError extends Error {
|
|
44
|
+
constructor() {
|
|
45
|
+
super('memory_graph_busy');
|
|
46
|
+
this.name = 'MemoryGraphBusyError';
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
export class LocalMemoryGraph {
|
|
50
|
+
dir;
|
|
51
|
+
userScope;
|
|
52
|
+
readableUserScopes;
|
|
53
|
+
now;
|
|
54
|
+
maxActiveBytes;
|
|
55
|
+
maxTailBytes;
|
|
56
|
+
maxLineBytes;
|
|
57
|
+
maxCompactBytes;
|
|
58
|
+
maxCompactEdges;
|
|
59
|
+
archiveRetention;
|
|
60
|
+
onRotationPhase;
|
|
61
|
+
importedFingerprints = new Map();
|
|
62
|
+
rotationCleanupFailed = false;
|
|
63
|
+
constructor(options) {
|
|
64
|
+
this.dir = resolve(options.dir);
|
|
65
|
+
this.userScope = scopeHash(`user:${options.userId}`);
|
|
66
|
+
this.readableUserScopes = new Set([
|
|
67
|
+
this.userScope,
|
|
68
|
+
...(options.legacyUserIds ?? []).map((userId) => scopeHash(`user:${userId}`)),
|
|
69
|
+
]);
|
|
70
|
+
this.now = options.now ?? Date.now;
|
|
71
|
+
this.maxActiveBytes = positiveInt(options.maxActiveBytes, 4 * 1024 * 1024);
|
|
72
|
+
this.maxTailBytes = positiveInt(options.maxTailBytes, 512 * 1024);
|
|
73
|
+
this.maxLineBytes = positiveInt(options.maxLineBytes, 16 * 1024);
|
|
74
|
+
this.maxCompactBytes = positiveInt(options.maxCompactBytes, DEFAULT_MAX_COMPACT_BYTES);
|
|
75
|
+
this.maxCompactEdges = positiveInt(options.maxCompactEdges, 4096);
|
|
76
|
+
this.archiveRetention = positiveInt(options.archiveRetention, 3);
|
|
77
|
+
this.onRotationPhase = options.onRotationPhase;
|
|
78
|
+
}
|
|
79
|
+
query(input) {
|
|
80
|
+
const diagnostics = emptyDiagnostics();
|
|
81
|
+
const workspaceScope = this.workspaceScope(input.workspace);
|
|
82
|
+
if (!workspaceScope)
|
|
83
|
+
return { genes: [], diagnostics: { ...diagnostics, recovery: 'degraded' } };
|
|
84
|
+
try {
|
|
85
|
+
return this.withGraphLock(() => {
|
|
86
|
+
const records = this.readQueryableRecords(diagnostics).filter((record) => {
|
|
87
|
+
if (record.provenance !== 'v2_local' && record.provenance !== 'v1_import') {
|
|
88
|
+
diagnostics.provenanceRejected += 1;
|
|
89
|
+
return false;
|
|
90
|
+
}
|
|
91
|
+
if (record.workspaceScope !== workspaceScope || !this.readableUserScopes.has(record.userScope)) {
|
|
92
|
+
diagnostics.scopeRejected += 1;
|
|
93
|
+
return false;
|
|
94
|
+
}
|
|
95
|
+
return true;
|
|
96
|
+
});
|
|
97
|
+
if (this.rotationCleanupFailed)
|
|
98
|
+
diagnostics.recovery = 'degraded';
|
|
99
|
+
if (records.length === 0 && diagnostics.recovery === 'healthy')
|
|
100
|
+
diagnostics.recovery = 'empty';
|
|
101
|
+
return algo.deriveMemoryGraphAdvice(records, input.signals, this.now(), diagnostics);
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
catch (error) {
|
|
105
|
+
if (error instanceof MemoryGraphBusyError) {
|
|
106
|
+
return { genes: [], diagnostics: { ...diagnostics, recovery: 'degraded', busy: true } };
|
|
107
|
+
}
|
|
108
|
+
throw error;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
recordOutcome(input) {
|
|
112
|
+
const workspaceScope = this.workspaceScope(input.workspace);
|
|
113
|
+
if (!workspaceScope)
|
|
114
|
+
return;
|
|
115
|
+
const geneId = algo.safeMemoryGeneId(input.geneId);
|
|
116
|
+
if (!geneId)
|
|
117
|
+
return;
|
|
118
|
+
const signals = algo.normalizeMemorySignals(input.signals);
|
|
119
|
+
const record = {
|
|
120
|
+
version: 2,
|
|
121
|
+
kind: 'outcome',
|
|
122
|
+
provenance: 'v2_local',
|
|
123
|
+
workspaceScope,
|
|
124
|
+
userScope: this.userScope,
|
|
125
|
+
signalFingerprint: algo.memorySignalFingerprint(signals),
|
|
126
|
+
signals,
|
|
127
|
+
geneId,
|
|
128
|
+
status: input.status,
|
|
129
|
+
score: clampScore(input.score),
|
|
130
|
+
at: validIso(input.at) ?? new Date(this.now()).toISOString(),
|
|
131
|
+
};
|
|
132
|
+
let persisted = false;
|
|
133
|
+
try {
|
|
134
|
+
this.withGraphLock(() => { persisted = this.appendRecordUnlocked(record); });
|
|
135
|
+
}
|
|
136
|
+
catch (error) {
|
|
137
|
+
// The append is already durable, so surfacing only the cleanup failure would invite duplicate retries.
|
|
138
|
+
if (persisted && error instanceof util.LockReleaseError)
|
|
139
|
+
return;
|
|
140
|
+
throw error;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
importV1Outcome(workspace, raw, source = 'legacy-memory-graph') {
|
|
144
|
+
const workspaceScope = this.workspaceScope(workspace);
|
|
145
|
+
if (!workspaceScope)
|
|
146
|
+
return false;
|
|
147
|
+
const sourceScope = scopeHash(`source:${source}`);
|
|
148
|
+
const parsed = parseV1Outcome(raw, workspaceScope, this.userScope, sourceScope);
|
|
149
|
+
if (!parsed)
|
|
150
|
+
return false;
|
|
151
|
+
return this.withGraphLock(() => {
|
|
152
|
+
const dedupeScope = `${workspaceScope}\u0000${this.userScope}\u0000${sourceScope}`;
|
|
153
|
+
const cache = this.importFingerprintCache(dedupeScope, workspaceScope, sourceScope);
|
|
154
|
+
if (hasImportFingerprint(cache.values, parsed))
|
|
155
|
+
return false;
|
|
156
|
+
if (!this.appendRecordUnlocked(parsed))
|
|
157
|
+
return false;
|
|
158
|
+
addImportFingerprints(cache.values, parsed);
|
|
159
|
+
cache.stateFingerprint = this.importStateFingerprint();
|
|
160
|
+
return true;
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
/** Builds a stable import forecast without creating or locking the target graph. */
|
|
164
|
+
planV1Outcomes(workspace, raws, source = 'legacy-memory-graph') {
|
|
165
|
+
const total = raws.length;
|
|
166
|
+
const sourceScope = scopeHash(`source:${source}`);
|
|
167
|
+
const workspacePath = workspace ? resolve(workspace) : null;
|
|
168
|
+
const workspaceScope = workspacePath ? this.workspaceScope(workspacePath) : null;
|
|
169
|
+
if (!workspacePath || !workspaceScope) {
|
|
170
|
+
return sealV1OutcomePlan({ total, importable: 0, duplicates: 0, rejected: 0, deferred: total }, {
|
|
171
|
+
graphDir: this.dir,
|
|
172
|
+
userScope: this.userScope,
|
|
173
|
+
workspacePath: null,
|
|
174
|
+
workspaceScope: null,
|
|
175
|
+
sourceScope,
|
|
176
|
+
records: Object.freeze([]),
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
const target = this.readStableImportState();
|
|
180
|
+
const fingerprints = collectImportFingerprints(target.records, workspaceScope, this.userScope, sourceScope);
|
|
181
|
+
const records = [];
|
|
182
|
+
let importable = 0;
|
|
183
|
+
let duplicates = 0;
|
|
184
|
+
let rejected = 0;
|
|
185
|
+
for (const raw of raws) {
|
|
186
|
+
const parsed = parseV1Outcome(raw, workspaceScope, this.userScope, sourceScope);
|
|
187
|
+
if (!parsed) {
|
|
188
|
+
rejected += 1;
|
|
189
|
+
continue;
|
|
190
|
+
}
|
|
191
|
+
const normalized = { ...parsed, signals: [...parsed.signals] };
|
|
192
|
+
Object.freeze(normalized.signals);
|
|
193
|
+
Object.freeze(normalized);
|
|
194
|
+
if (hasImportFingerprint(fingerprints, parsed)) {
|
|
195
|
+
duplicates += 1;
|
|
196
|
+
records.push(normalized);
|
|
197
|
+
continue;
|
|
198
|
+
}
|
|
199
|
+
if (!this.importRecordFits(parsed, target.epochId)) {
|
|
200
|
+
rejected += 1;
|
|
201
|
+
continue;
|
|
202
|
+
}
|
|
203
|
+
records.push(normalized);
|
|
204
|
+
addImportFingerprints(fingerprints, normalized);
|
|
205
|
+
importable += 1;
|
|
206
|
+
}
|
|
207
|
+
Object.freeze(records);
|
|
208
|
+
return sealV1OutcomePlan({
|
|
209
|
+
total,
|
|
210
|
+
importable,
|
|
211
|
+
duplicates,
|
|
212
|
+
rejected,
|
|
213
|
+
deferred: 0,
|
|
214
|
+
}, {
|
|
215
|
+
graphDir: this.dir,
|
|
216
|
+
userScope: this.userScope,
|
|
217
|
+
workspacePath,
|
|
218
|
+
workspaceScope,
|
|
219
|
+
sourceScope,
|
|
220
|
+
records,
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
/** Applies only the normalized records sealed by planV1Outcomes. */
|
|
224
|
+
applyV1OutcomePlan(plan) {
|
|
225
|
+
const data = memoryGraphV1OutcomePlans.get(plan);
|
|
226
|
+
if (!data || data.graphDir !== this.dir || data.userScope !== this.userScope) {
|
|
227
|
+
throw new Error('memory_graph_import_plan_rejected');
|
|
228
|
+
}
|
|
229
|
+
if (data.records.length === 0)
|
|
230
|
+
return 0;
|
|
231
|
+
const workspacePath = data.workspacePath;
|
|
232
|
+
const workspaceScope = data.workspaceScope;
|
|
233
|
+
if (!workspacePath || !workspaceScope
|
|
234
|
+
|| this.workspaceScope(workspacePath) !== workspaceScope) {
|
|
235
|
+
throw new Error('memory_graph_import_plan_rejected');
|
|
236
|
+
}
|
|
237
|
+
let committedImported;
|
|
238
|
+
try {
|
|
239
|
+
return this.withGraphLock(() => {
|
|
240
|
+
const dedupeScope = `${workspaceScope}\u0000${this.userScope}\u0000${data.sourceScope}`;
|
|
241
|
+
const cache = this.importFingerprintCache(dedupeScope, workspaceScope, data.sourceScope);
|
|
242
|
+
let imported = 0;
|
|
243
|
+
for (const record of data.records) {
|
|
244
|
+
if (hasImportFingerprint(cache.values, record))
|
|
245
|
+
continue;
|
|
246
|
+
if (!this.appendRecordUnlocked(record))
|
|
247
|
+
continue;
|
|
248
|
+
addImportFingerprints(cache.values, record);
|
|
249
|
+
imported += 1;
|
|
250
|
+
}
|
|
251
|
+
cache.stateFingerprint = this.importStateFingerprint();
|
|
252
|
+
committedImported = imported;
|
|
253
|
+
return imported;
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
catch (error) {
|
|
257
|
+
// The completed appends are durable, so a cleanup-only failure must not invite replay.
|
|
258
|
+
if (committedImported !== undefined && committedImported > 0
|
|
259
|
+
&& error instanceof util.LockReleaseError)
|
|
260
|
+
return committedImported;
|
|
261
|
+
throw error;
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
maintain() {
|
|
265
|
+
return this.withGraphLock(() => this.withRotationCleanupStatus(this.maintainUnlocked()));
|
|
266
|
+
}
|
|
267
|
+
maintainUnlocked() {
|
|
268
|
+
this.ensureSecureDir();
|
|
269
|
+
const state = this.managedGraphStateFiles();
|
|
270
|
+
const epoch = this.readEpochState();
|
|
271
|
+
const health = this.inspectHealthUnlocked();
|
|
272
|
+
const recoveryDegraded = this.recoveryMarkerState(epoch) === 'degraded';
|
|
273
|
+
if ((health.archives > 0 || recoveryDegraded) && this.compactRequiresRecovery(epoch)) {
|
|
274
|
+
const recovered = this.recoverFromArchivesUnlocked(epoch);
|
|
275
|
+
if (recovered.recovery === 'recovered' || recovered.recovery === 'degraded'
|
|
276
|
+
|| (recovered.recovery === 'empty' && health.activeRecords === 0))
|
|
277
|
+
return recovered;
|
|
278
|
+
}
|
|
279
|
+
const activeState = state.find((file) => file.name === ACTIVE_FILE);
|
|
280
|
+
const activeBaseline = epoch.baseline?.active;
|
|
281
|
+
const activeBaselineTruncated = Boolean(activeState && activeBaseline
|
|
282
|
+
&& serializedIdentityMatches(activeBaseline.snapshot, activeState.identity)
|
|
283
|
+
&& activeState.identity.size < BigInt(activeBaseline.offset));
|
|
284
|
+
const active = activeBaselineTruncated
|
|
285
|
+
? null
|
|
286
|
+
: this.activePayloadForEpoch(epoch, this.maxActiveBytes);
|
|
287
|
+
if (active === null || !active.exists || active.logicalSize < this.maxActiveBytes) {
|
|
288
|
+
return {
|
|
289
|
+
rotated: false,
|
|
290
|
+
compactedRecords: health.compactedRecords,
|
|
291
|
+
corruptLines: health.corruptLines,
|
|
292
|
+
oversizedLines: health.oversizedLines,
|
|
293
|
+
archives: health.archives,
|
|
294
|
+
recovery: health.recovery,
|
|
295
|
+
};
|
|
296
|
+
}
|
|
297
|
+
return this.rotateAndCompactUnlocked(epoch);
|
|
298
|
+
}
|
|
299
|
+
recoverFromArchives() {
|
|
300
|
+
return this.withGraphLock(() => this.withRotationCleanupStatus(this.recoverFromArchivesUnlocked()));
|
|
301
|
+
}
|
|
302
|
+
/** Enforce archive retention without changing active or compact state. */
|
|
303
|
+
prune() {
|
|
304
|
+
return this.withGraphLock(() => {
|
|
305
|
+
this.ensureSecureDir();
|
|
306
|
+
this.managedGraphStateFiles();
|
|
307
|
+
this.readEpochState();
|
|
308
|
+
this.pruneArchives();
|
|
309
|
+
const health = this.inspectHealthUnlocked();
|
|
310
|
+
return this.withRotationCleanupStatus({
|
|
311
|
+
rotated: false,
|
|
312
|
+
compactedRecords: health.compactedRecords,
|
|
313
|
+
corruptLines: health.corruptLines,
|
|
314
|
+
oversizedLines: health.oversizedLines,
|
|
315
|
+
archives: health.archives,
|
|
316
|
+
recovery: health.recovery,
|
|
317
|
+
});
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
/**
|
|
321
|
+
* Copy every managed graph file into a non-active backup, then atomically
|
|
322
|
+
* advance the local storage epoch.
|
|
323
|
+
* The CLI requires explicit opt-in (`--yes`) before calling this method.
|
|
324
|
+
*/
|
|
325
|
+
resetGraph() {
|
|
326
|
+
let committed;
|
|
327
|
+
try {
|
|
328
|
+
return this.withGraphLock(() => {
|
|
329
|
+
this.ensureSecureDir();
|
|
330
|
+
this.managedGraphStateFiles();
|
|
331
|
+
this.readEpochState();
|
|
332
|
+
this.ensureEpochStateFile();
|
|
333
|
+
const state = this.managedGraphStateFiles();
|
|
334
|
+
const backup = this.createResetBackupDirectory();
|
|
335
|
+
const copied = [];
|
|
336
|
+
try {
|
|
337
|
+
for (const file of state) {
|
|
338
|
+
const payload = this.readResetSource(file);
|
|
339
|
+
const destination = join(backup.pendingDir, file.name);
|
|
340
|
+
this.writeAtomic(destination, payload);
|
|
341
|
+
const copiedIdentity = lstatSync(destination, { bigint: true });
|
|
342
|
+
const copiedPayload = this.readRawBounded(destination, payload.length);
|
|
343
|
+
if (!copiedIdentity.isFile() || copiedIdentity.isSymbolicLink()
|
|
344
|
+
|| copiedPayload === null || !copiedPayload.equals(payload)) {
|
|
345
|
+
throw new Error('memory_graph_reset_backup_failed');
|
|
346
|
+
}
|
|
347
|
+
copied.push({ name: file.name, path: destination, identity: copiedIdentity });
|
|
348
|
+
}
|
|
349
|
+
this.assertManagedStateUnchanged(state);
|
|
350
|
+
this.publishResetBackup(backup);
|
|
351
|
+
this.assertManagedStateUnchanged(state);
|
|
352
|
+
}
|
|
353
|
+
catch {
|
|
354
|
+
this.cleanupResetPendingDirectory(backup, copied);
|
|
355
|
+
throw new Error('memory_graph_reset_backup_failed');
|
|
356
|
+
}
|
|
357
|
+
const epochState = {
|
|
358
|
+
version: 1,
|
|
359
|
+
epochId: backup.backupId,
|
|
360
|
+
activatedAt: new Date(this.now()).toISOString(),
|
|
361
|
+
baseline: this.epochBaselineFromState(state),
|
|
362
|
+
};
|
|
363
|
+
const report = {
|
|
364
|
+
rotated: false,
|
|
365
|
+
compactedRecords: 0,
|
|
366
|
+
corruptLines: 0,
|
|
367
|
+
oversizedLines: 0,
|
|
368
|
+
archives: state.filter((file) => ARCHIVE_PATTERN.test(file.name)).length,
|
|
369
|
+
recovery: 'empty',
|
|
370
|
+
backupId: backup.backupId,
|
|
371
|
+
backupFiles: copied.length,
|
|
372
|
+
epochId: backup.backupId,
|
|
373
|
+
};
|
|
374
|
+
if (this.rotationCleanupFailed)
|
|
375
|
+
report.recovery = 'degraded';
|
|
376
|
+
try {
|
|
377
|
+
this.writeEpochState(epochState);
|
|
378
|
+
}
|
|
379
|
+
catch {
|
|
380
|
+
// The completed backup is intentionally retained. Until this atomic
|
|
381
|
+
// publish succeeds, readers continue using the previous epoch.
|
|
382
|
+
throw new Error('memory_graph_reset_failed');
|
|
383
|
+
}
|
|
384
|
+
committed = report;
|
|
385
|
+
this.importedFingerprints.clear();
|
|
386
|
+
return committed;
|
|
387
|
+
});
|
|
388
|
+
}
|
|
389
|
+
catch (error) {
|
|
390
|
+
if (committed) {
|
|
391
|
+
const reason = error instanceof util.LockReleaseError
|
|
392
|
+
? error.reason
|
|
393
|
+
: 'release_failed';
|
|
394
|
+
return { ...committed, lockReleaseWarning: reason };
|
|
395
|
+
}
|
|
396
|
+
throw error;
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
managedGraphStateFiles() {
|
|
400
|
+
const names = [
|
|
401
|
+
...this.archiveFiles(),
|
|
402
|
+
RECOVERY_FILE,
|
|
403
|
+
EPOCH_FILE,
|
|
404
|
+
ACTIVE_FILE,
|
|
405
|
+
COMPACT_FILE,
|
|
406
|
+
];
|
|
407
|
+
const state = [];
|
|
408
|
+
for (const name of names) {
|
|
409
|
+
const path = join(this.dir, name);
|
|
410
|
+
let identity;
|
|
411
|
+
try {
|
|
412
|
+
identity = lstatSync(path, { bigint: true });
|
|
413
|
+
}
|
|
414
|
+
catch (error) {
|
|
415
|
+
if (isObject(error) && error['code'] === 'ENOENT')
|
|
416
|
+
continue;
|
|
417
|
+
throw new Error('memory_graph_path_rejected');
|
|
418
|
+
}
|
|
419
|
+
if (!identity.isFile() || identity.isSymbolicLink())
|
|
420
|
+
throw new Error('memory_graph_path_rejected');
|
|
421
|
+
state.push({ name, path, identity });
|
|
422
|
+
}
|
|
423
|
+
return state;
|
|
424
|
+
}
|
|
425
|
+
createResetBackupDirectory() {
|
|
426
|
+
const latest = readdirSync(this.dir)
|
|
427
|
+
.map((name) => BigInt(RESET_BACKUP_PATTERN.exec(name)?.[1]
|
|
428
|
+
?? RESET_PENDING_PATTERN.exec(name)?.[1]
|
|
429
|
+
?? 0))
|
|
430
|
+
.reduce((max, value) => value > max ? value : max, 0n);
|
|
431
|
+
const now = BigInt(Math.max(0, Math.floor(this.now())));
|
|
432
|
+
const timestamp = now > latest ? now : latest + 1n;
|
|
433
|
+
const backupId = timestamp.toString().padStart(13, '0');
|
|
434
|
+
const backupDir = join(this.dir, `memory_graph.reset.${backupId}`);
|
|
435
|
+
const pendingDir = join(this.dir, `memory_graph.reset.pending.${backupId}`);
|
|
436
|
+
let created = false;
|
|
437
|
+
try {
|
|
438
|
+
assertPathMissing(backupDir, 'memory_graph_reset_backup_failed');
|
|
439
|
+
assertPathMissing(pendingDir, 'memory_graph_reset_backup_failed');
|
|
440
|
+
mkdirSync(pendingDir, { mode: 0o700 });
|
|
441
|
+
created = true;
|
|
442
|
+
const pendingIdentity = lstatSync(pendingDir, { bigint: true });
|
|
443
|
+
if (!pendingIdentity.isDirectory() || pendingIdentity.isSymbolicLink()) {
|
|
444
|
+
throw new Error('memory_graph_reset_backup_failed');
|
|
445
|
+
}
|
|
446
|
+
return { backupId, backupDir, pendingDir, pendingIdentity };
|
|
447
|
+
}
|
|
448
|
+
catch {
|
|
449
|
+
if (created) {
|
|
450
|
+
try {
|
|
451
|
+
rmdirSync(pendingDir);
|
|
452
|
+
}
|
|
453
|
+
catch {
|
|
454
|
+
// Leave an unexpected directory untouched for operator inspection.
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
throw new Error('memory_graph_reset_backup_failed');
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
publishResetBackup(backup) {
|
|
461
|
+
const identity = lstatSync(backup.pendingDir, { bigint: true });
|
|
462
|
+
if (!identity.isDirectory() || identity.isSymbolicLink()
|
|
463
|
+
|| !sameGraphFileIdentity(backup.pendingIdentity, identity)) {
|
|
464
|
+
throw new Error('memory_graph_reset_backup_failed');
|
|
465
|
+
}
|
|
466
|
+
assertPathMissing(backup.backupDir, 'memory_graph_reset_backup_failed');
|
|
467
|
+
renameSync(backup.pendingDir, backup.backupDir);
|
|
468
|
+
const published = lstatSync(backup.backupDir, { bigint: true });
|
|
469
|
+
if (!published.isDirectory() || published.isSymbolicLink()
|
|
470
|
+
|| !sameGraphFileIdentity(backup.pendingIdentity, published)) {
|
|
471
|
+
throw new Error('memory_graph_reset_backup_failed');
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
cleanupResetPendingDirectory(backup, copied) {
|
|
475
|
+
for (const file of [...copied].reverse()) {
|
|
476
|
+
try {
|
|
477
|
+
const current = lstatSync(file.path, { bigint: true });
|
|
478
|
+
if (current.isFile() && !current.isSymbolicLink()
|
|
479
|
+
&& sameGraphFileIdentity(file.identity, current))
|
|
480
|
+
unlinkSync(file.path);
|
|
481
|
+
}
|
|
482
|
+
catch {
|
|
483
|
+
// Live graph state was never changed; leave uncertain backup artifacts untouched.
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
try {
|
|
487
|
+
const current = lstatSync(backup.pendingDir, { bigint: true });
|
|
488
|
+
if (current.isDirectory() && !current.isSymbolicLink()
|
|
489
|
+
&& sameGraphFileIdentity(backup.pendingIdentity, current)
|
|
490
|
+
&& readdirSync(backup.pendingDir).length === 0)
|
|
491
|
+
rmdirSync(backup.pendingDir);
|
|
492
|
+
}
|
|
493
|
+
catch {
|
|
494
|
+
// A completed rename or an uncertain replacement must remain untouched.
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
readResetSource(file) {
|
|
498
|
+
const limit = file.name === ACTIVE_FILE
|
|
499
|
+
? this.maxActiveBytes + this.maxLineBytes
|
|
500
|
+
: file.name === COMPACT_FILE
|
|
501
|
+
? this.maxCompactBytes + this.maxLineBytes
|
|
502
|
+
: file.name === RECOVERY_FILE || file.name === EPOCH_FILE
|
|
503
|
+
? this.maxLineBytes
|
|
504
|
+
: this.maxActiveBytes + this.maxLineBytes;
|
|
505
|
+
if (file.identity.size > BigInt(limit))
|
|
506
|
+
throw new Error('memory_graph_reset_backup_failed');
|
|
507
|
+
const fd = openNoFollow(file.path, constants.O_RDONLY, 0o600);
|
|
508
|
+
try {
|
|
509
|
+
const before = fstatSync(fd, { bigint: true });
|
|
510
|
+
if (!before.isFile() || before.isSymbolicLink()
|
|
511
|
+
|| !sameGraphFileSnapshot(file.identity, before)
|
|
512
|
+
|| before.size > BigInt(limit))
|
|
513
|
+
throw new Error('memory_graph_reset_backup_failed');
|
|
514
|
+
const payload = readFdBytes(fd, Number(before.size), 0);
|
|
515
|
+
const after = fstatSync(fd, { bigint: true });
|
|
516
|
+
if (payload.length !== Number(before.size)
|
|
517
|
+
|| !sameGraphFileSnapshot(before, after))
|
|
518
|
+
throw new Error('memory_graph_reset_backup_failed');
|
|
519
|
+
return payload;
|
|
520
|
+
}
|
|
521
|
+
finally {
|
|
522
|
+
closeSync(fd);
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
assertManagedStateUnchanged(expected) {
|
|
526
|
+
const current = this.managedGraphStateFiles();
|
|
527
|
+
if (current.length !== expected.length)
|
|
528
|
+
throw new Error('memory_graph_reset_backup_failed');
|
|
529
|
+
for (let index = 0; index < expected.length; index += 1) {
|
|
530
|
+
const before = expected[index];
|
|
531
|
+
const after = current[index];
|
|
532
|
+
if (!before || !after || before.name !== after.name
|
|
533
|
+
|| !sameGraphFileSnapshot(before.identity, after.identity)) {
|
|
534
|
+
throw new Error('memory_graph_reset_backup_failed');
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
ensureEpochStateFile() {
|
|
539
|
+
const path = join(this.dir, EPOCH_FILE);
|
|
540
|
+
try {
|
|
541
|
+
lstatSync(path);
|
|
542
|
+
this.readEpochState();
|
|
543
|
+
return;
|
|
544
|
+
}
|
|
545
|
+
catch (error) {
|
|
546
|
+
if (!isObject(error) || error['code'] !== 'ENOENT') {
|
|
547
|
+
if (error instanceof Error && error.message === 'memory_graph_epoch_rejected')
|
|
548
|
+
throw error;
|
|
549
|
+
throw new Error('memory_graph_epoch_rejected');
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
if (this.hasResetBackup())
|
|
553
|
+
throw new Error('memory_graph_epoch_rejected');
|
|
554
|
+
this.writeEpochState({
|
|
555
|
+
version: 1,
|
|
556
|
+
epochId: LEGACY_EPOCH_ID,
|
|
557
|
+
activatedAt: new Date(this.now()).toISOString(),
|
|
558
|
+
});
|
|
559
|
+
}
|
|
560
|
+
currentEpochId() {
|
|
561
|
+
return this.readEpochState().epochId;
|
|
562
|
+
}
|
|
563
|
+
epochBaselineFromState(state) {
|
|
564
|
+
const active = state.find((file) => file.name === ACTIVE_FILE);
|
|
565
|
+
const compact = state.find((file) => file.name === COMPACT_FILE);
|
|
566
|
+
const recovery = state.find((file) => file.name === RECOVERY_FILE);
|
|
567
|
+
const archives = state
|
|
568
|
+
.filter((file) => ARCHIVE_PATTERN.test(file.name))
|
|
569
|
+
.slice(-this.archiveRetention)
|
|
570
|
+
.map((file) => ({ name: file.name, snapshot: serializeGraphFileSnapshot(file.identity) }));
|
|
571
|
+
if (active && active.identity.size > BigInt(Number.MAX_SAFE_INTEGER)) {
|
|
572
|
+
throw new Error('memory_graph_epoch_rejected');
|
|
573
|
+
}
|
|
574
|
+
return {
|
|
575
|
+
active: active
|
|
576
|
+
? { snapshot: serializeGraphFileSnapshot(active.identity), offset: Number(active.identity.size) }
|
|
577
|
+
: null,
|
|
578
|
+
compact: compact ? serializeGraphFileSnapshot(compact.identity) : null,
|
|
579
|
+
recovery: recovery ? serializeGraphFileSnapshot(recovery.identity) : null,
|
|
580
|
+
archives,
|
|
581
|
+
};
|
|
582
|
+
}
|
|
583
|
+
readEpochState() {
|
|
584
|
+
const path = join(this.dir, EPOCH_FILE);
|
|
585
|
+
let identity;
|
|
586
|
+
try {
|
|
587
|
+
identity = lstatSync(path, { bigint: true });
|
|
588
|
+
}
|
|
589
|
+
catch (error) {
|
|
590
|
+
if (isObject(error) && error['code'] === 'ENOENT') {
|
|
591
|
+
if (this.hasResetBackup())
|
|
592
|
+
throw new Error('memory_graph_epoch_rejected');
|
|
593
|
+
return { version: 1, epochId: LEGACY_EPOCH_ID, activatedAt: new Date(0).toISOString() };
|
|
594
|
+
}
|
|
595
|
+
throw new Error('memory_graph_epoch_rejected');
|
|
596
|
+
}
|
|
597
|
+
if (!identity.isFile() || identity.isSymbolicLink()
|
|
598
|
+
|| identity.size > BigInt(this.maxLineBytes))
|
|
599
|
+
throw new Error('memory_graph_epoch_rejected');
|
|
600
|
+
let fd;
|
|
601
|
+
try {
|
|
602
|
+
fd = openNoFollow(path, constants.O_RDONLY, 0o600);
|
|
603
|
+
}
|
|
604
|
+
catch {
|
|
605
|
+
throw new Error('memory_graph_epoch_rejected');
|
|
606
|
+
}
|
|
607
|
+
try {
|
|
608
|
+
const before = fstatSync(fd, { bigint: true });
|
|
609
|
+
if (!before.isFile() || before.isSymbolicLink()
|
|
610
|
+
|| !sameGraphFileSnapshot(identity, before))
|
|
611
|
+
throw new Error('memory_graph_epoch_rejected');
|
|
612
|
+
const payload = readFdBytes(fd, Number(before.size), 0);
|
|
613
|
+
const after = fstatSync(fd, { bigint: true });
|
|
614
|
+
if (payload.length !== Number(before.size)
|
|
615
|
+
|| !sameGraphFileSnapshot(before, after))
|
|
616
|
+
throw new Error('memory_graph_epoch_rejected');
|
|
617
|
+
const raw = JSON.parse(payload.toString('utf8'));
|
|
618
|
+
if (!isObject(raw) || raw['version'] !== 1)
|
|
619
|
+
throw new Error('memory_graph_epoch_rejected');
|
|
620
|
+
const epochId = safeEpochId(raw['epochId']);
|
|
621
|
+
const activatedAt = typeof raw['activatedAt'] === 'string' ? validIso(raw['activatedAt']) : null;
|
|
622
|
+
if (!epochId || !activatedAt)
|
|
623
|
+
throw new Error('memory_graph_epoch_rejected');
|
|
624
|
+
const hasBaseline = Object.prototype.hasOwnProperty.call(raw, 'baseline');
|
|
625
|
+
const baseline = hasBaseline ? parseEpochBaseline(raw['baseline']) : null;
|
|
626
|
+
if (hasBaseline && !baseline)
|
|
627
|
+
throw new Error('memory_graph_epoch_rejected');
|
|
628
|
+
if (epochId !== LEGACY_EPOCH_ID) {
|
|
629
|
+
if (!/^\d{13,}$/.test(epochId))
|
|
630
|
+
throw new Error('memory_graph_epoch_rejected');
|
|
631
|
+
let backup;
|
|
632
|
+
try {
|
|
633
|
+
backup = lstatSync(join(this.dir, `memory_graph.reset.${epochId}`));
|
|
634
|
+
}
|
|
635
|
+
catch {
|
|
636
|
+
throw new Error('memory_graph_epoch_rejected');
|
|
637
|
+
}
|
|
638
|
+
if (!backup.isDirectory() || backup.isSymbolicLink()) {
|
|
639
|
+
throw new Error('memory_graph_epoch_rejected');
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
return {
|
|
643
|
+
version: 1,
|
|
644
|
+
epochId,
|
|
645
|
+
activatedAt,
|
|
646
|
+
...(baseline ? { baseline } : {}),
|
|
647
|
+
};
|
|
648
|
+
}
|
|
649
|
+
catch {
|
|
650
|
+
throw new Error('memory_graph_epoch_rejected');
|
|
651
|
+
}
|
|
652
|
+
finally {
|
|
653
|
+
closeSync(fd);
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
writeEpochState(state) {
|
|
657
|
+
const payload = Buffer.from(JSON.stringify(state) + '\n', 'utf8');
|
|
658
|
+
if (payload.length > this.maxLineBytes)
|
|
659
|
+
throw new Error('memory_graph_epoch_rejected');
|
|
660
|
+
this.writeAtomic(join(this.dir, EPOCH_FILE), payload);
|
|
661
|
+
}
|
|
662
|
+
hasResetBackup() {
|
|
663
|
+
return readdirSync(this.dir).some((name) => RESET_BACKUP_PATTERN.test(name));
|
|
664
|
+
}
|
|
665
|
+
compactMatchesEpochBaseline(epoch) {
|
|
666
|
+
const baseline = epoch.baseline?.compact;
|
|
667
|
+
if (!baseline)
|
|
668
|
+
return false;
|
|
669
|
+
try {
|
|
670
|
+
const current = lstatSync(join(this.dir, COMPACT_FILE), { bigint: true });
|
|
671
|
+
return current.isFile() && !current.isSymbolicLink()
|
|
672
|
+
&& serializedSnapshotMatches(baseline, current);
|
|
673
|
+
}
|
|
674
|
+
catch {
|
|
675
|
+
return false;
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
readCompactForEpoch(epoch, diagnostics) {
|
|
679
|
+
return this.compactMatchesEpochBaseline(epoch) ? [] : this.readCompact(diagnostics);
|
|
680
|
+
}
|
|
681
|
+
activeLogicalWindow(epoch, identity) {
|
|
682
|
+
const active = epoch.baseline?.active;
|
|
683
|
+
if (!active || !serializedIdentityMatches(active.snapshot, identity)) {
|
|
684
|
+
return {
|
|
685
|
+
offset: 0,
|
|
686
|
+
size: identity.size > BigInt(Number.MAX_SAFE_INTEGER) ? 0 : Number(identity.size),
|
|
687
|
+
invalid: identity.size > BigInt(Number.MAX_SAFE_INTEGER),
|
|
688
|
+
};
|
|
689
|
+
}
|
|
690
|
+
const offset = active.offset;
|
|
691
|
+
if (identity.size < BigInt(offset) || identity.size > BigInt(Number.MAX_SAFE_INTEGER)) {
|
|
692
|
+
return { offset, size: 0, invalid: true };
|
|
693
|
+
}
|
|
694
|
+
return { offset, size: Number(identity.size) - offset, invalid: false };
|
|
695
|
+
}
|
|
696
|
+
activePayloadForEpoch(epoch, maxBytes) {
|
|
697
|
+
const path = join(this.dir, ACTIVE_FILE);
|
|
698
|
+
let identity;
|
|
699
|
+
try {
|
|
700
|
+
identity = lstatSync(path, { bigint: true });
|
|
701
|
+
}
|
|
702
|
+
catch (error) {
|
|
703
|
+
if (isObject(error) && error['code'] === 'ENOENT') {
|
|
704
|
+
return { payload: Buffer.alloc(0), logicalSize: 0, exists: false };
|
|
705
|
+
}
|
|
706
|
+
throw new Error('memory_graph_rotation_backup_failed');
|
|
707
|
+
}
|
|
708
|
+
if (!identity.isFile() || identity.isSymbolicLink()) {
|
|
709
|
+
throw new Error('memory_graph_path_rejected');
|
|
710
|
+
}
|
|
711
|
+
const window = this.activeLogicalWindow(epoch, identity);
|
|
712
|
+
if (window.invalid || window.size > maxBytes) {
|
|
713
|
+
throw new Error('memory_graph_rotation_backup_failed');
|
|
714
|
+
}
|
|
715
|
+
const fd = openNoFollow(path, constants.O_RDONLY, 0o600);
|
|
716
|
+
try {
|
|
717
|
+
const before = fstatSync(fd, { bigint: true });
|
|
718
|
+
if (!before.isFile() || before.isSymbolicLink()
|
|
719
|
+
|| !sameGraphFileSnapshot(identity, before)) {
|
|
720
|
+
throw new Error('memory_graph_rotation_backup_failed');
|
|
721
|
+
}
|
|
722
|
+
const payload = readFdBytes(fd, window.size, window.offset);
|
|
723
|
+
const after = fstatSync(fd, { bigint: true });
|
|
724
|
+
if (payload.length !== window.size || !sameGraphFileSnapshot(before, after)) {
|
|
725
|
+
throw new Error('memory_graph_rotation_backup_failed');
|
|
726
|
+
}
|
|
727
|
+
return { payload, logicalSize: window.size, exists: true };
|
|
728
|
+
}
|
|
729
|
+
finally {
|
|
730
|
+
closeSync(fd);
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
readActiveForEpoch(epoch, diagnostics, maxBytes) {
|
|
734
|
+
const path = join(this.dir, ACTIVE_FILE);
|
|
735
|
+
if (!existsSync(path) || !this.secureRegularFile(path))
|
|
736
|
+
return [];
|
|
737
|
+
const fd = openNoFollow(path, constants.O_RDONLY, 0o600);
|
|
738
|
+
try {
|
|
739
|
+
const identity = fstatSync(fd, { bigint: true });
|
|
740
|
+
if (!identity.isFile() || identity.isSymbolicLink())
|
|
741
|
+
return [];
|
|
742
|
+
const window = this.activeLogicalWindow(epoch, identity);
|
|
743
|
+
if (window.invalid) {
|
|
744
|
+
diagnostics.truncated = true;
|
|
745
|
+
return [];
|
|
746
|
+
}
|
|
747
|
+
const bytes = Math.min(window.size, maxBytes);
|
|
748
|
+
const position = window.offset + window.size - bytes;
|
|
749
|
+
const buffer = readFdBytes(fd, bytes, position);
|
|
750
|
+
diagnostics.bytesRead += buffer.length;
|
|
751
|
+
diagnostics.truncated ||= window.size > buffer.length;
|
|
752
|
+
if (window.size <= buffer.length)
|
|
753
|
+
return this.parseBuffer(buffer, diagnostics);
|
|
754
|
+
const newline = buffer.indexOf(0x0a);
|
|
755
|
+
return this.parseBuffer(newline >= 0 ? buffer.subarray(newline + 1) : Buffer.alloc(0), diagnostics);
|
|
756
|
+
}
|
|
757
|
+
finally {
|
|
758
|
+
closeSync(fd);
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
currentArchiveFiles(epoch) {
|
|
762
|
+
const baseline = new Map((epoch.baseline?.archives ?? [])
|
|
763
|
+
.map((entry) => [entry.name, entry.snapshot]));
|
|
764
|
+
return this.archiveFiles().slice(-this.archiveRetention).filter((file) => {
|
|
765
|
+
const expected = baseline.get(file);
|
|
766
|
+
if (!expected)
|
|
767
|
+
return true;
|
|
768
|
+
try {
|
|
769
|
+
const current = lstatSync(join(this.dir, file), { bigint: true });
|
|
770
|
+
return !current.isFile() || current.isSymbolicLink()
|
|
771
|
+
|| !serializedSnapshotMatches(expected, current);
|
|
772
|
+
}
|
|
773
|
+
catch {
|
|
774
|
+
return true;
|
|
775
|
+
}
|
|
776
|
+
});
|
|
777
|
+
}
|
|
778
|
+
recoverFromArchivesUnlocked(epochState) {
|
|
779
|
+
this.ensureSecureDir();
|
|
780
|
+
this.managedGraphStateFiles();
|
|
781
|
+
const epoch = epochState ?? this.readEpochState();
|
|
782
|
+
const currentEpoch = epoch.epochId;
|
|
783
|
+
const diagnostics = emptyDiagnostics();
|
|
784
|
+
const compactRecords = this.readCompactForEpoch(epoch, diagnostics)
|
|
785
|
+
.filter((record) => recordEpochId(record) === currentEpoch);
|
|
786
|
+
const archiveRecords = [];
|
|
787
|
+
const maxArchiveBytes = gzipRotationByteBound(this.maxActiveBytes);
|
|
788
|
+
const maxArchiveOutputBytes = safeRotationByteSum(this.maxActiveBytes, this.maxLineBytes);
|
|
789
|
+
for (const file of this.currentArchiveFiles(epoch)) {
|
|
790
|
+
const path = join(this.dir, file);
|
|
791
|
+
if (maxArchiveBytes === null || maxArchiveOutputBytes === null) {
|
|
792
|
+
diagnostics.truncated = true;
|
|
793
|
+
continue;
|
|
794
|
+
}
|
|
795
|
+
if (!this.secureRegularFile(path)) {
|
|
796
|
+
diagnostics.corruptLines += 1;
|
|
797
|
+
continue;
|
|
798
|
+
}
|
|
799
|
+
try {
|
|
800
|
+
const compressed = this.readRawBounded(path, maxArchiveBytes);
|
|
801
|
+
if (compressed === null) {
|
|
802
|
+
diagnostics.truncated = true;
|
|
803
|
+
continue;
|
|
804
|
+
}
|
|
805
|
+
const raw = gunzipSync(compressed, { maxOutputLength: maxArchiveOutputBytes });
|
|
806
|
+
archiveRecords.push(...this.parseBuffer(raw, diagnostics)
|
|
807
|
+
.filter((record) => recordEpochId(record) === currentEpoch));
|
|
808
|
+
}
|
|
809
|
+
catch {
|
|
810
|
+
diagnostics.corruptLines += 1;
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
const compacted = mergeRecoveryRecords(compactRecords, archiveRecords, this.maxCompactEdges);
|
|
814
|
+
const incomplete = this.recoveryMarkerState(epoch) === 'degraded'
|
|
815
|
+
|| diagnostics.corruptLines > 0
|
|
816
|
+
|| diagnostics.oversizedLines > 0
|
|
817
|
+
|| diagnostics.truncated;
|
|
818
|
+
// Persist the conservative state before publishing a partial compact so a
|
|
819
|
+
// marker-write failure cannot leave an apparently healthy partial recovery.
|
|
820
|
+
if (incomplete)
|
|
821
|
+
this.writeRecoveryMarker(currentEpoch, 'degraded');
|
|
822
|
+
const compactedRecords = compacted.length > 0 ? this.writeCompact(compacted).records : 0;
|
|
823
|
+
const recovery = incomplete
|
|
824
|
+
|| (compacted.length > 0 && compactedRecords === 0)
|
|
825
|
+
? 'degraded'
|
|
826
|
+
: compactedRecords > 0 ? 'recovered' : 'empty';
|
|
827
|
+
if (!incomplete)
|
|
828
|
+
this.writeRecoveryMarker(currentEpoch, recovery);
|
|
829
|
+
return {
|
|
830
|
+
rotated: false,
|
|
831
|
+
compactedRecords,
|
|
832
|
+
corruptLines: diagnostics.corruptLines,
|
|
833
|
+
oversizedLines: diagnostics.oversizedLines,
|
|
834
|
+
archives: this.archiveFiles().length,
|
|
835
|
+
recovery,
|
|
836
|
+
};
|
|
837
|
+
}
|
|
838
|
+
inspectHealth() {
|
|
839
|
+
try {
|
|
840
|
+
const stat = lstatSync(this.dir);
|
|
841
|
+
if (!stat.isDirectory() || stat.isSymbolicLink())
|
|
842
|
+
throw new Error('memory_graph_dir_rejected');
|
|
843
|
+
}
|
|
844
|
+
catch (error) {
|
|
845
|
+
if (isObject(error) && error['code'] === 'ENOENT')
|
|
846
|
+
return emptyHealth();
|
|
847
|
+
throw new Error('memory_graph_dir_rejected');
|
|
848
|
+
}
|
|
849
|
+
try {
|
|
850
|
+
return this.withGraphLock(() => {
|
|
851
|
+
const health = this.inspectHealthUnlocked();
|
|
852
|
+
return this.rotationCleanupFailed ? { ...health, recovery: 'degraded' } : health;
|
|
853
|
+
});
|
|
854
|
+
}
|
|
855
|
+
catch (error) {
|
|
856
|
+
if (error instanceof MemoryGraphBusyError) {
|
|
857
|
+
return { ...emptyHealth(), recovery: 'degraded', busy: true };
|
|
858
|
+
}
|
|
859
|
+
throw error;
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
inspectHealthUnlocked() {
|
|
863
|
+
let dirStat;
|
|
864
|
+
try {
|
|
865
|
+
dirStat = lstatSync(this.dir);
|
|
866
|
+
}
|
|
867
|
+
catch (error) {
|
|
868
|
+
if (isObject(error) && error['code'] === 'ENOENT')
|
|
869
|
+
return emptyHealth();
|
|
870
|
+
throw new Error('memory_graph_dir_rejected');
|
|
871
|
+
}
|
|
872
|
+
if (!dirStat.isDirectory() || dirStat.isSymbolicLink())
|
|
873
|
+
throw new Error('memory_graph_dir_rejected');
|
|
874
|
+
this.managedGraphStateFiles();
|
|
875
|
+
const epoch = this.readEpochState();
|
|
876
|
+
const epochId = epoch.epochId;
|
|
877
|
+
const compactDiagnostics = emptyDiagnostics();
|
|
878
|
+
const activeDiagnostics = emptyDiagnostics();
|
|
879
|
+
const compactPath = join(this.dir, COMPACT_FILE);
|
|
880
|
+
const activePath = join(this.dir, ACTIVE_FILE);
|
|
881
|
+
const compactedRecords = this.readCompactForEpoch(epoch, compactDiagnostics)
|
|
882
|
+
.filter((record) => recordEpochId(record) === epochId).length;
|
|
883
|
+
const activeRecords = this.readActiveForEpoch(epoch, activeDiagnostics, this.maxActiveBytes)
|
|
884
|
+
.filter((record) => recordEpochId(record) === epochId).length;
|
|
885
|
+
const archives = this.archiveFiles().length;
|
|
886
|
+
let activeOversized = false;
|
|
887
|
+
if (existsSync(activePath) && this.secureRegularFile(activePath)) {
|
|
888
|
+
const activeIdentity = lstatSync(activePath, { bigint: true });
|
|
889
|
+
const window = this.activeLogicalWindow(epoch, activeIdentity);
|
|
890
|
+
activeOversized = window.invalid || window.size > this.maxActiveBytes;
|
|
891
|
+
}
|
|
892
|
+
const oversizedFiles = Number(!this.compactMatchesEpochBaseline(epoch)
|
|
893
|
+
&& fileExceeds(compactPath, this.maxCompactBytes))
|
|
894
|
+
+ Number(activeOversized);
|
|
895
|
+
const rejectedFiles = Number(existsSync(compactPath) && !this.secureRegularFile(compactPath))
|
|
896
|
+
+ Number(existsSync(activePath) && !this.secureRegularFile(activePath));
|
|
897
|
+
const corruptLines = compactDiagnostics.corruptLines + activeDiagnostics.corruptLines + rejectedFiles;
|
|
898
|
+
const oversizedLines = compactDiagnostics.oversizedLines + activeDiagnostics.oversizedLines;
|
|
899
|
+
const archiveProbe = compactedRecords === 0 && archives > 0
|
|
900
|
+
? this.inspectArchivesForEpoch(epoch)
|
|
901
|
+
: { containsCurrent: false, unreadable: false };
|
|
902
|
+
const compactMissingWithArchives = archiveProbe.containsCurrent || archiveProbe.unreadable;
|
|
903
|
+
const marker = this.recoveryMarkerState(epoch);
|
|
904
|
+
const degraded = corruptLines > 0 || oversizedLines > 0 || oversizedFiles > 0
|
|
905
|
+
|| compactMissingWithArchives || marker === 'degraded';
|
|
906
|
+
const records = compactedRecords + activeRecords;
|
|
907
|
+
return {
|
|
908
|
+
recovery: degraded ? 'degraded' : records === 0 ? 'empty' : marker === 'recovered' ? 'recovered' : 'healthy',
|
|
909
|
+
compactedRecords,
|
|
910
|
+
activeRecords,
|
|
911
|
+
corruptLines,
|
|
912
|
+
oversizedLines,
|
|
913
|
+
oversizedFiles,
|
|
914
|
+
archives,
|
|
915
|
+
};
|
|
916
|
+
}
|
|
917
|
+
withGraphLock(operation) {
|
|
918
|
+
this.ensureSecureDir();
|
|
919
|
+
const lockPath = join(this.dir, LOCK_FILE);
|
|
920
|
+
try {
|
|
921
|
+
util.acquireLock(lockPath);
|
|
922
|
+
}
|
|
923
|
+
catch (error) {
|
|
924
|
+
if (error instanceof util.LockTimeoutError)
|
|
925
|
+
throw new MemoryGraphBusyError();
|
|
926
|
+
throw error;
|
|
927
|
+
}
|
|
928
|
+
this.rotationCleanupFailed = false;
|
|
929
|
+
let value;
|
|
930
|
+
let operationError;
|
|
931
|
+
let operationFailed = false;
|
|
932
|
+
try {
|
|
933
|
+
this.ensureSecureDir();
|
|
934
|
+
this.reconcileRotationUnlocked();
|
|
935
|
+
value = operation();
|
|
936
|
+
}
|
|
937
|
+
catch (error) {
|
|
938
|
+
operationFailed = true;
|
|
939
|
+
operationError = error;
|
|
940
|
+
}
|
|
941
|
+
let releaseError;
|
|
942
|
+
try {
|
|
943
|
+
const released = util.releaseLock(lockPath);
|
|
944
|
+
const reliable = released.released
|
|
945
|
+
&& (released.reason === 'released' || released.reason === 'released_with_cleanup_error');
|
|
946
|
+
if (!reliable)
|
|
947
|
+
releaseError = new util.LockReleaseError(released.reason);
|
|
948
|
+
}
|
|
949
|
+
catch (error) {
|
|
950
|
+
releaseError = error;
|
|
951
|
+
}
|
|
952
|
+
if (operationFailed)
|
|
953
|
+
throw operationError;
|
|
954
|
+
if (releaseError !== undefined)
|
|
955
|
+
throw releaseError;
|
|
956
|
+
return value;
|
|
957
|
+
}
|
|
958
|
+
importFingerprintCache(dedupeScope, workspaceScope, sourceScope) {
|
|
959
|
+
const stateFingerprint = this.importStateFingerprint();
|
|
960
|
+
let cache = this.importedFingerprints.get(dedupeScope);
|
|
961
|
+
if (!cache || cache.stateFingerprint !== stateFingerprint) {
|
|
962
|
+
cache = {
|
|
963
|
+
stateFingerprint,
|
|
964
|
+
values: collectImportFingerprints(this.readImportRecords(), workspaceScope, this.userScope, sourceScope),
|
|
965
|
+
};
|
|
966
|
+
this.importedFingerprints.set(dedupeScope, cache);
|
|
967
|
+
}
|
|
968
|
+
return cache;
|
|
969
|
+
}
|
|
970
|
+
readStableImportState() {
|
|
971
|
+
let directoryIdentity;
|
|
972
|
+
try {
|
|
973
|
+
directoryIdentity = lstatSync(this.dir, { bigint: true });
|
|
974
|
+
}
|
|
975
|
+
catch (error) {
|
|
976
|
+
if (isObject(error) && error['code'] === 'ENOENT') {
|
|
977
|
+
return { epochId: LEGACY_EPOCH_ID, records: [] };
|
|
978
|
+
}
|
|
979
|
+
throw new MemoryGraphImportStateRejectedError();
|
|
980
|
+
}
|
|
981
|
+
if (!directoryIdentity.isDirectory() || directoryIdentity.isSymbolicLink()) {
|
|
982
|
+
throw new MemoryGraphImportStateRejectedError();
|
|
983
|
+
}
|
|
984
|
+
const before = this.importStateFingerprint();
|
|
985
|
+
const epochId = this.currentEpochId();
|
|
986
|
+
const records = this.readImportRecordsFromExistingDir();
|
|
987
|
+
let afterDirectoryIdentity;
|
|
988
|
+
try {
|
|
989
|
+
afterDirectoryIdentity = lstatSync(this.dir, { bigint: true });
|
|
990
|
+
}
|
|
991
|
+
catch {
|
|
992
|
+
throw new MemoryGraphImportStateRejectedError();
|
|
993
|
+
}
|
|
994
|
+
const after = this.importStateFingerprint();
|
|
995
|
+
if (!sameGraphFileSnapshot(directoryIdentity, afterDirectoryIdentity) || before !== after) {
|
|
996
|
+
throw new MemoryGraphImportStateRejectedError();
|
|
997
|
+
}
|
|
998
|
+
return { epochId, records };
|
|
999
|
+
}
|
|
1000
|
+
persistedRecordLine(record, epochId) {
|
|
1001
|
+
return Buffer.from(JSON.stringify({ ...record, epochId }) + '\n', 'utf8');
|
|
1002
|
+
}
|
|
1003
|
+
importRecordFits(record, epochId) {
|
|
1004
|
+
const line = this.persistedRecordLine(record, epochId);
|
|
1005
|
+
return line.length <= this.maxLineBytes && line.length <= this.maxActiveBytes;
|
|
1006
|
+
}
|
|
1007
|
+
importStateFingerprint() {
|
|
1008
|
+
const epochId = this.currentEpochId();
|
|
1009
|
+
return [EPOCH_FILE, COMPACT_FILE, ACTIVE_FILE].map((file) => {
|
|
1010
|
+
const path = join(this.dir, file);
|
|
1011
|
+
let stat;
|
|
1012
|
+
try {
|
|
1013
|
+
stat = lstatSync(path, { bigint: true });
|
|
1014
|
+
}
|
|
1015
|
+
catch (error) {
|
|
1016
|
+
if (isObject(error) && error['code'] === 'ENOENT')
|
|
1017
|
+
return `${file}:missing`;
|
|
1018
|
+
throw new MemoryGraphImportStateRejectedError();
|
|
1019
|
+
}
|
|
1020
|
+
if (!stat.isFile() || stat.isSymbolicLink())
|
|
1021
|
+
throw new MemoryGraphImportStateRejectedError();
|
|
1022
|
+
return `${file}:${stat.dev}:${stat.ino}:${stat.mode}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}`;
|
|
1023
|
+
}).concat(`epoch:${epochId}`).join('|');
|
|
1024
|
+
}
|
|
1025
|
+
appendRecordUnlocked(record) {
|
|
1026
|
+
this.ensureSecureDir();
|
|
1027
|
+
const state = this.managedGraphStateFiles();
|
|
1028
|
+
const epoch = this.readEpochState();
|
|
1029
|
+
const line = this.persistedRecordLine(record, epoch.epochId);
|
|
1030
|
+
if (line.length > this.maxLineBytes || line.length > this.maxActiveBytes)
|
|
1031
|
+
return false;
|
|
1032
|
+
const activePath = join(this.dir, ACTIVE_FILE);
|
|
1033
|
+
let activeState = state.find((file) => file.name === ACTIVE_FILE);
|
|
1034
|
+
const activeWindow = activeState
|
|
1035
|
+
? this.activeLogicalWindow(epoch, activeState.identity)
|
|
1036
|
+
: { offset: 0, size: 0, invalid: false };
|
|
1037
|
+
if (activeWindow.invalid)
|
|
1038
|
+
throw new Error('memory_graph_epoch_rejected');
|
|
1039
|
+
if (activeWindow.size + line.length > this.maxActiveBytes) {
|
|
1040
|
+
const maintenance = this.rotateAndCompactUnlocked(epoch);
|
|
1041
|
+
if (!maintenance.rotated)
|
|
1042
|
+
return false;
|
|
1043
|
+
activeState = this.managedGraphStateFiles().find((file) => file.name === ACTIVE_FILE);
|
|
1044
|
+
}
|
|
1045
|
+
const fd = openNoFollow(activePath, constants.O_WRONLY | constants.O_CREAT, 0o600);
|
|
1046
|
+
try {
|
|
1047
|
+
const stat = fstatSync(fd, { bigint: true });
|
|
1048
|
+
if (!stat.isFile() || stat.isSymbolicLink()
|
|
1049
|
+
|| (activeState && !sameGraphFileSnapshot(activeState.identity, stat))
|
|
1050
|
+
|| (!activeState && stat.size !== 0n)
|
|
1051
|
+
|| stat.size > BigInt(Number.MAX_SAFE_INTEGER))
|
|
1052
|
+
return false;
|
|
1053
|
+
const originalSize = Number(stat.size);
|
|
1054
|
+
try {
|
|
1055
|
+
writeAll(fd, line, originalSize);
|
|
1056
|
+
fsyncSync(fd);
|
|
1057
|
+
return true;
|
|
1058
|
+
}
|
|
1059
|
+
catch (error) {
|
|
1060
|
+
try {
|
|
1061
|
+
ftruncateSync(fd, originalSize);
|
|
1062
|
+
fsyncSync(fd);
|
|
1063
|
+
}
|
|
1064
|
+
catch {
|
|
1065
|
+
throw new Error('memory_graph_append_rollback_failed');
|
|
1066
|
+
}
|
|
1067
|
+
throw error;
|
|
1068
|
+
}
|
|
1069
|
+
}
|
|
1070
|
+
finally {
|
|
1071
|
+
closeSync(fd);
|
|
1072
|
+
}
|
|
1073
|
+
}
|
|
1074
|
+
rotateAndCompactUnlocked(epochState) {
|
|
1075
|
+
this.ensureSecureDir();
|
|
1076
|
+
const state = this.managedGraphStateFiles();
|
|
1077
|
+
const epoch = epochState ?? this.readEpochState();
|
|
1078
|
+
const currentEpoch = epoch.epochId;
|
|
1079
|
+
const diagnostics = emptyDiagnostics();
|
|
1080
|
+
const compactPath = join(this.dir, COMPACT_FILE);
|
|
1081
|
+
const activeState = state.find((file) => file.name === ACTIVE_FILE);
|
|
1082
|
+
const compactState = state.find((file) => file.name === COMPACT_FILE);
|
|
1083
|
+
const activePayload = this.activePayloadForEpoch(epoch, this.maxActiveBytes);
|
|
1084
|
+
if (!activeState || activePayload.logicalSize === 0) {
|
|
1085
|
+
throw new Error('memory_graph_rotation_backup_failed');
|
|
1086
|
+
}
|
|
1087
|
+
const activeWindow = this.activeLogicalWindow(epoch, activeState.identity);
|
|
1088
|
+
if (activeWindow.invalid || activeWindow.size !== activePayload.logicalSize) {
|
|
1089
|
+
throw new Error('memory_graph_rotation_backup_failed');
|
|
1090
|
+
}
|
|
1091
|
+
const activeSource = {
|
|
1092
|
+
snapshot: serializeGraphFileSnapshot(activeState.identity),
|
|
1093
|
+
offset: activeWindow.offset,
|
|
1094
|
+
...rotationFileDigest(activePayload.payload),
|
|
1095
|
+
};
|
|
1096
|
+
let compactSource = null;
|
|
1097
|
+
if (compactState) {
|
|
1098
|
+
const compactBound = this.compactMatchesEpochBaseline(epoch)
|
|
1099
|
+
? this.maxCompactBytes + this.maxLineBytes
|
|
1100
|
+
: this.maxCompactBytes;
|
|
1101
|
+
const verified = this.readVerifiedRotationFile(compactPath, compactBound, false, 'memory_graph_rotation_backup_failed');
|
|
1102
|
+
if (!verified || !sameGraphFileSnapshot(compactState.identity, verified.identity)) {
|
|
1103
|
+
throw new Error('memory_graph_rotation_backup_failed');
|
|
1104
|
+
}
|
|
1105
|
+
compactSource = {
|
|
1106
|
+
snapshot: serializeGraphFileSnapshot(verified.identity),
|
|
1107
|
+
...rotationFileDigest(verified.payload),
|
|
1108
|
+
};
|
|
1109
|
+
}
|
|
1110
|
+
const records = [
|
|
1111
|
+
...this.readCompactForEpoch(epoch, diagnostics),
|
|
1112
|
+
...this.parseBuffer(activePayload.payload, diagnostics),
|
|
1113
|
+
]
|
|
1114
|
+
.filter((record) => recordEpochId(record) === currentEpoch);
|
|
1115
|
+
const compacted = compactRecords(records, this.maxCompactEdges);
|
|
1116
|
+
const fitted = fitCompactRecords(compacted, this.maxCompactBytes);
|
|
1117
|
+
if (compacted.length > 0 && fitted.records.length === 0) {
|
|
1118
|
+
return {
|
|
1119
|
+
rotated: false,
|
|
1120
|
+
compactedRecords: 0,
|
|
1121
|
+
corruptLines: diagnostics.corruptLines,
|
|
1122
|
+
oversizedLines: diagnostics.oversizedLines,
|
|
1123
|
+
archives: this.archiveFiles().length,
|
|
1124
|
+
recovery: 'degraded',
|
|
1125
|
+
};
|
|
1126
|
+
}
|
|
1127
|
+
const compactPayload = fitted.payload;
|
|
1128
|
+
const archivePayload = gzipSync(activePayload.payload);
|
|
1129
|
+
const emptyActive = Buffer.alloc(0);
|
|
1130
|
+
const archivePath = this.nextArchivePath();
|
|
1131
|
+
const generation = ARCHIVE_PATTERN.exec(basename(archivePath))?.[1];
|
|
1132
|
+
if (!generation)
|
|
1133
|
+
throw new Error('memory_graph_rotation_backup_failed');
|
|
1134
|
+
const stageNames = rotationStageNames(generation);
|
|
1135
|
+
const preparedWithoutId = {
|
|
1136
|
+
version: 1,
|
|
1137
|
+
targetGeneration: generation,
|
|
1138
|
+
phase: 'prepared',
|
|
1139
|
+
epochId: currentEpoch,
|
|
1140
|
+
createdAt: new Date(this.now()).toISOString(),
|
|
1141
|
+
limits: {
|
|
1142
|
+
maxActiveBytes: this.maxActiveBytes,
|
|
1143
|
+
maxCompactBytes: this.maxCompactBytes,
|
|
1144
|
+
maxLineBytes: this.maxLineBytes,
|
|
1145
|
+
archiveRetention: this.archiveRetention,
|
|
1146
|
+
},
|
|
1147
|
+
source: { active: activeSource, compact: compactSource },
|
|
1148
|
+
target: {
|
|
1149
|
+
compact: {
|
|
1150
|
+
stageName: stageNames.compact,
|
|
1151
|
+
finalName: COMPACT_FILE,
|
|
1152
|
+
records: fitted.records.length,
|
|
1153
|
+
...rotationFileDigest(compactPayload),
|
|
1154
|
+
},
|
|
1155
|
+
archive: {
|
|
1156
|
+
stageName: stageNames.archive,
|
|
1157
|
+
finalName: basename(archivePath),
|
|
1158
|
+
...rotationFileDigest(archivePayload),
|
|
1159
|
+
},
|
|
1160
|
+
active: {
|
|
1161
|
+
stageName: stageNames.active,
|
|
1162
|
+
finalName: ACTIVE_FILE,
|
|
1163
|
+
...rotationFileDigest(emptyActive),
|
|
1164
|
+
},
|
|
1165
|
+
},
|
|
1166
|
+
};
|
|
1167
|
+
const preparedWithId = {
|
|
1168
|
+
...preparedWithoutId,
|
|
1169
|
+
transactionId: rotationTransactionId(preparedWithoutId),
|
|
1170
|
+
};
|
|
1171
|
+
const prepared = {
|
|
1172
|
+
...preparedWithId,
|
|
1173
|
+
journalDigest: rotationJournalDigest(preparedWithId),
|
|
1174
|
+
};
|
|
1175
|
+
for (const name of Object.values(stageNames)) {
|
|
1176
|
+
assertPathMissing(join(this.dir, name), 'memory_graph_rotation_recovery_failed');
|
|
1177
|
+
}
|
|
1178
|
+
assertPathMissing(join(this.dir, ROTATION_JOURNAL_FILE), 'memory_graph_rotation_recovery_failed');
|
|
1179
|
+
const preparedJournalIdentity = this.writeRotationJournal(prepared);
|
|
1180
|
+
this.notifyRotationPhase(prepared, 'commit', 'journal_prepared');
|
|
1181
|
+
this.writeRotationStage(prepared, 'compact', compactPayload);
|
|
1182
|
+
this.notifyRotationPhase(prepared, 'commit', 'compact_staged');
|
|
1183
|
+
this.writeRotationStage(prepared, 'archive', archivePayload);
|
|
1184
|
+
this.notifyRotationPhase(prepared, 'commit', 'archive_staged');
|
|
1185
|
+
this.writeRotationStage(prepared, 'active', emptyActive);
|
|
1186
|
+
this.notifyRotationPhase(prepared, 'commit', 'active_staged');
|
|
1187
|
+
this.assertRotationSourceMatches(prepared);
|
|
1188
|
+
this.assertRotationStagesMatch(prepared);
|
|
1189
|
+
this.assertRotationJournalUnchanged(prepared, preparedJournalIdentity);
|
|
1190
|
+
const committedWithoutDigest = { ...prepared, phase: 'committed' };
|
|
1191
|
+
const committed = {
|
|
1192
|
+
...committedWithoutDigest,
|
|
1193
|
+
journalDigest: rotationJournalDigest(committedWithoutDigest),
|
|
1194
|
+
};
|
|
1195
|
+
this.writeRotationJournal(committed);
|
|
1196
|
+
this.notifyRotationPhase(committed, 'commit', 'journal_committed');
|
|
1197
|
+
this.reconcileCommittedRotation(committed, 'commit');
|
|
1198
|
+
const degraded = diagnostics.corruptLines > 0
|
|
1199
|
+
|| diagnostics.oversizedLines > 0
|
|
1200
|
+
|| diagnostics.truncated;
|
|
1201
|
+
return {
|
|
1202
|
+
rotated: true,
|
|
1203
|
+
compactedRecords: fitted.records.length,
|
|
1204
|
+
corruptLines: diagnostics.corruptLines,
|
|
1205
|
+
oversizedLines: diagnostics.oversizedLines,
|
|
1206
|
+
archives: this.archiveFiles().length,
|
|
1207
|
+
recovery: degraded ? 'degraded' : fitted.records.length > 0 ? 'healthy' : 'empty',
|
|
1208
|
+
};
|
|
1209
|
+
}
|
|
1210
|
+
reconcileRotationUnlocked() {
|
|
1211
|
+
const journalPath = join(this.dir, ROTATION_JOURNAL_FILE);
|
|
1212
|
+
const stageFiles = this.rotationStageFiles();
|
|
1213
|
+
const tempFiles = this.rotationTempFiles();
|
|
1214
|
+
let journalPresent = true;
|
|
1215
|
+
try {
|
|
1216
|
+
lstatSync(journalPath);
|
|
1217
|
+
}
|
|
1218
|
+
catch (error) {
|
|
1219
|
+
if (isObject(error) && error['code'] === 'ENOENT')
|
|
1220
|
+
journalPresent = false;
|
|
1221
|
+
else
|
|
1222
|
+
throw new Error('memory_graph_rotation_journal_rejected');
|
|
1223
|
+
}
|
|
1224
|
+
if (!journalPresent) {
|
|
1225
|
+
for (const name of tempFiles)
|
|
1226
|
+
this.removeRotationTemp(name);
|
|
1227
|
+
if (stageFiles.length > 0)
|
|
1228
|
+
throw new Error('memory_graph_rotation_recovery_failed');
|
|
1229
|
+
return;
|
|
1230
|
+
}
|
|
1231
|
+
const loaded = this.readRotationJournal();
|
|
1232
|
+
const journal = loaded.journal;
|
|
1233
|
+
const expectedStages = new Set(Object.values(rotationStageNames(journal.targetGeneration)));
|
|
1234
|
+
const expectedTemps = new Set(Object.values(rotationTempNames(journal.targetGeneration)));
|
|
1235
|
+
if (stageFiles.some((name) => !expectedStages.has(name))
|
|
1236
|
+
|| tempFiles.some((name) => !expectedTemps.has(name))) {
|
|
1237
|
+
throw new Error('memory_graph_rotation_recovery_failed');
|
|
1238
|
+
}
|
|
1239
|
+
const epoch = this.readEpochState();
|
|
1240
|
+
if (epoch.epochId !== journal.epochId) {
|
|
1241
|
+
throw new Error('memory_graph_rotation_journal_rejected');
|
|
1242
|
+
}
|
|
1243
|
+
if (journal.phase === 'prepared') {
|
|
1244
|
+
this.assertRotationSourceMatches(journal);
|
|
1245
|
+
for (const target of [
|
|
1246
|
+
journal.target.compact,
|
|
1247
|
+
journal.target.archive,
|
|
1248
|
+
journal.target.active,
|
|
1249
|
+
]) {
|
|
1250
|
+
this.removeRotationStage(target);
|
|
1251
|
+
}
|
|
1252
|
+
for (const name of tempFiles)
|
|
1253
|
+
this.removeRotationTemp(name);
|
|
1254
|
+
this.notifyRotationPhase(journal, 'recovery', 'before_journal_clear');
|
|
1255
|
+
this.removeVerifiedRotationFile(journalPath, loaded.identity, 'memory_graph_rotation_recovery_failed');
|
|
1256
|
+
this.notifyRotationPhase(journal, 'recovery', 'journal_cleared');
|
|
1257
|
+
return;
|
|
1258
|
+
}
|
|
1259
|
+
for (const name of tempFiles)
|
|
1260
|
+
this.removeRotationTemp(name);
|
|
1261
|
+
this.reconcileCommittedRotation(journal, 'recovery', loaded.identity);
|
|
1262
|
+
}
|
|
1263
|
+
reconcileCommittedRotation(journal, mode, journalIdentity) {
|
|
1264
|
+
let identity = journalIdentity;
|
|
1265
|
+
if (!identity) {
|
|
1266
|
+
const loaded = this.readRotationJournal();
|
|
1267
|
+
if (loaded.journal.transactionId !== journal.transactionId
|
|
1268
|
+
|| loaded.journal.phase !== 'committed') {
|
|
1269
|
+
throw new Error('memory_graph_rotation_journal_rejected');
|
|
1270
|
+
}
|
|
1271
|
+
identity = loaded.identity;
|
|
1272
|
+
}
|
|
1273
|
+
this.assertCommittedRotationCanApply(journal);
|
|
1274
|
+
this.publishRotationFile(journal, journal.target.compact, journal.source.compact, mode, 'compact_published');
|
|
1275
|
+
this.publishRotationFile(journal, journal.target.archive, null, mode, 'archive_published');
|
|
1276
|
+
this.notifyRotationPhase(journal, mode, 'before_active_publish');
|
|
1277
|
+
this.publishRotationActive(journal, mode);
|
|
1278
|
+
for (const target of [
|
|
1279
|
+
journal.target.compact,
|
|
1280
|
+
journal.target.archive,
|
|
1281
|
+
journal.target.active,
|
|
1282
|
+
]) {
|
|
1283
|
+
this.removeRotationStage(target);
|
|
1284
|
+
}
|
|
1285
|
+
const cleanupFailed = this.completeCommittedRotationCleanup(journal);
|
|
1286
|
+
this.rotationCleanupFailed = this.rotationCleanupFailed || cleanupFailed;
|
|
1287
|
+
this.notifyRotationPhase(journal, mode, 'before_journal_clear');
|
|
1288
|
+
this.assertCommittedRotationApplied(journal);
|
|
1289
|
+
this.removeVerifiedRotationFile(join(this.dir, ROTATION_JOURNAL_FILE), identity, 'memory_graph_rotation_recovery_failed');
|
|
1290
|
+
this.notifyRotationPhase(journal, mode, 'journal_cleared');
|
|
1291
|
+
}
|
|
1292
|
+
completeCommittedRotationCleanup(journal) {
|
|
1293
|
+
const epoch = this.readEpochState();
|
|
1294
|
+
if (epoch.epochId !== journal.epochId) {
|
|
1295
|
+
throw new Error('memory_graph_rotation_journal_rejected');
|
|
1296
|
+
}
|
|
1297
|
+
try {
|
|
1298
|
+
this.managedGraphStateFiles();
|
|
1299
|
+
this.clearRecoveryMarker(epoch, journal.limits.maxLineBytes);
|
|
1300
|
+
this.pruneArchives(journal.limits.archiveRetention);
|
|
1301
|
+
return false;
|
|
1302
|
+
}
|
|
1303
|
+
catch {
|
|
1304
|
+
return true;
|
|
1305
|
+
}
|
|
1306
|
+
}
|
|
1307
|
+
withRotationCleanupStatus(report) {
|
|
1308
|
+
return this.rotationCleanupFailed ? { ...report, recovery: 'degraded' } : report;
|
|
1309
|
+
}
|
|
1310
|
+
assertCommittedRotationApplied(journal) {
|
|
1311
|
+
for (const target of [
|
|
1312
|
+
journal.target.compact,
|
|
1313
|
+
journal.target.archive,
|
|
1314
|
+
journal.target.active,
|
|
1315
|
+
]) {
|
|
1316
|
+
if (!this.rotationTargetMatches(join(this.dir, target.finalName), target)) {
|
|
1317
|
+
throw new Error('memory_graph_rotation_recovery_failed');
|
|
1318
|
+
}
|
|
1319
|
+
}
|
|
1320
|
+
}
|
|
1321
|
+
assertCommittedRotationCanApply(journal) {
|
|
1322
|
+
this.assertRotationFileReady(journal.target.compact, journal.source.compact);
|
|
1323
|
+
this.assertRotationFileReady(journal.target.archive, null);
|
|
1324
|
+
const activeTarget = journal.target.active;
|
|
1325
|
+
const activePath = join(this.dir, activeTarget.finalName);
|
|
1326
|
+
if (this.rotationTargetMatches(activePath, activeTarget)) {
|
|
1327
|
+
this.assertOptionalRotationStage(activeTarget);
|
|
1328
|
+
return;
|
|
1329
|
+
}
|
|
1330
|
+
if (!this.rotationActiveSourceMatches(activePath, journal.source.active)) {
|
|
1331
|
+
throw new Error('memory_graph_rotation_recovery_failed');
|
|
1332
|
+
}
|
|
1333
|
+
this.requireRotationTarget(join(this.dir, activeTarget.stageName), activeTarget);
|
|
1334
|
+
}
|
|
1335
|
+
assertRotationFileReady(target, source) {
|
|
1336
|
+
const finalPath = join(this.dir, target.finalName);
|
|
1337
|
+
if (this.rotationTargetMatches(finalPath, target)) {
|
|
1338
|
+
this.assertOptionalRotationStage(target);
|
|
1339
|
+
return;
|
|
1340
|
+
}
|
|
1341
|
+
if (source === null) {
|
|
1342
|
+
assertPathMissing(finalPath, 'memory_graph_rotation_recovery_failed');
|
|
1343
|
+
}
|
|
1344
|
+
else if (!this.rotationSourceMatches(finalPath, source)) {
|
|
1345
|
+
throw new Error('memory_graph_rotation_recovery_failed');
|
|
1346
|
+
}
|
|
1347
|
+
this.requireRotationTarget(join(this.dir, target.stageName), target);
|
|
1348
|
+
}
|
|
1349
|
+
assertOptionalRotationStage(target) {
|
|
1350
|
+
const path = join(this.dir, target.stageName);
|
|
1351
|
+
const staged = this.readVerifiedRotationFile(path, target.size, true, 'memory_graph_rotation_recovery_failed');
|
|
1352
|
+
if (staged && !rotationDigestMatches(staged.payload, target)) {
|
|
1353
|
+
throw new Error('memory_graph_rotation_recovery_failed');
|
|
1354
|
+
}
|
|
1355
|
+
}
|
|
1356
|
+
publishRotationFile(journal, target, source, mode, phase) {
|
|
1357
|
+
const finalPath = join(this.dir, target.finalName);
|
|
1358
|
+
if (this.rotationTargetMatches(finalPath, target)) {
|
|
1359
|
+
this.removeRotationStage(target);
|
|
1360
|
+
this.notifyRotationPhase(journal, mode, phase);
|
|
1361
|
+
return;
|
|
1362
|
+
}
|
|
1363
|
+
if (source === null) {
|
|
1364
|
+
assertPathMissing(finalPath, 'memory_graph_rotation_recovery_failed');
|
|
1365
|
+
}
|
|
1366
|
+
else if (!this.rotationSourceMatches(finalPath, source)) {
|
|
1367
|
+
throw new Error('memory_graph_rotation_recovery_failed');
|
|
1368
|
+
}
|
|
1369
|
+
const staged = this.requireRotationTarget(join(this.dir, target.stageName), target);
|
|
1370
|
+
try {
|
|
1371
|
+
renameSync(join(this.dir, target.stageName), finalPath);
|
|
1372
|
+
this.syncGraphDirectory();
|
|
1373
|
+
}
|
|
1374
|
+
catch {
|
|
1375
|
+
throw new Error('memory_graph_rotation_recovery_failed');
|
|
1376
|
+
}
|
|
1377
|
+
const published = this.requireRotationTarget(finalPath, target);
|
|
1378
|
+
if (!sameGraphFileIdentity(staged.identity, published.identity)) {
|
|
1379
|
+
throw new Error('memory_graph_rotation_recovery_failed');
|
|
1380
|
+
}
|
|
1381
|
+
this.notifyRotationPhase(journal, mode, phase);
|
|
1382
|
+
}
|
|
1383
|
+
publishRotationActive(journal, mode) {
|
|
1384
|
+
const target = journal.target.active;
|
|
1385
|
+
const activePath = join(this.dir, target.finalName);
|
|
1386
|
+
if (this.rotationTargetMatches(activePath, target)) {
|
|
1387
|
+
this.removeRotationStage(target);
|
|
1388
|
+
this.notifyRotationPhase(journal, mode, 'active_published');
|
|
1389
|
+
return;
|
|
1390
|
+
}
|
|
1391
|
+
if (!this.rotationActiveSourceMatches(activePath, journal.source.active)) {
|
|
1392
|
+
throw new Error('memory_graph_rotation_recovery_failed');
|
|
1393
|
+
}
|
|
1394
|
+
const staged = this.requireRotationTarget(join(this.dir, target.stageName), target);
|
|
1395
|
+
try {
|
|
1396
|
+
renameSync(join(this.dir, target.stageName), activePath);
|
|
1397
|
+
this.syncGraphDirectory();
|
|
1398
|
+
}
|
|
1399
|
+
catch {
|
|
1400
|
+
throw new Error('memory_graph_rotation_recovery_failed');
|
|
1401
|
+
}
|
|
1402
|
+
const published = this.requireRotationTarget(activePath, target);
|
|
1403
|
+
if (!sameGraphFileIdentity(staged.identity, published.identity)) {
|
|
1404
|
+
throw new Error('memory_graph_rotation_recovery_failed');
|
|
1405
|
+
}
|
|
1406
|
+
this.notifyRotationPhase(journal, mode, 'active_published');
|
|
1407
|
+
}
|
|
1408
|
+
writeRotationJournal(journal) {
|
|
1409
|
+
const payload = Buffer.from(JSON.stringify(journal) + '\n', 'utf8');
|
|
1410
|
+
if (payload.length > MAX_ROTATION_JOURNAL_BYTES) {
|
|
1411
|
+
throw new Error('memory_graph_rotation_journal_rejected');
|
|
1412
|
+
}
|
|
1413
|
+
const committedIdentity = this.writeAtomic(join(this.dir, ROTATION_JOURNAL_FILE), payload, true, journal.targetGeneration);
|
|
1414
|
+
const loaded = this.readRotationJournal();
|
|
1415
|
+
if (!sameGraphFileIdentity(committedIdentity, loaded.identity)
|
|
1416
|
+
|| loaded.journal.transactionId !== journal.transactionId
|
|
1417
|
+
|| loaded.journal.phase !== journal.phase) {
|
|
1418
|
+
throw new Error('memory_graph_rotation_journal_rejected');
|
|
1419
|
+
}
|
|
1420
|
+
return loaded.identity;
|
|
1421
|
+
}
|
|
1422
|
+
assertRotationJournalUnchanged(journal, expectedIdentity) {
|
|
1423
|
+
const loaded = this.readRotationJournal();
|
|
1424
|
+
if (!sameGraphFileSnapshot(expectedIdentity, loaded.identity)
|
|
1425
|
+
|| loaded.journal.transactionId !== journal.transactionId
|
|
1426
|
+
|| loaded.journal.phase !== journal.phase) {
|
|
1427
|
+
throw new Error('memory_graph_rotation_journal_rejected');
|
|
1428
|
+
}
|
|
1429
|
+
}
|
|
1430
|
+
readRotationJournal() {
|
|
1431
|
+
const verified = this.readVerifiedRotationFile(join(this.dir, ROTATION_JOURNAL_FILE), MAX_ROTATION_JOURNAL_BYTES, false, 'memory_graph_rotation_journal_rejected');
|
|
1432
|
+
if (!verified)
|
|
1433
|
+
throw new Error('memory_graph_rotation_journal_rejected');
|
|
1434
|
+
try {
|
|
1435
|
+
const value = JSON.parse(verified.payload.toString('utf8'));
|
|
1436
|
+
const journal = parseRotationJournal(value);
|
|
1437
|
+
if (!journal)
|
|
1438
|
+
throw new Error('memory_graph_rotation_journal_rejected');
|
|
1439
|
+
return { journal, identity: verified.identity };
|
|
1440
|
+
}
|
|
1441
|
+
catch {
|
|
1442
|
+
throw new Error('memory_graph_rotation_journal_rejected');
|
|
1443
|
+
}
|
|
1444
|
+
}
|
|
1445
|
+
writeRotationStage(journal, kind, payload) {
|
|
1446
|
+
const target = journal.target[kind];
|
|
1447
|
+
if (!rotationDigestMatches(payload, target)) {
|
|
1448
|
+
throw new Error('memory_graph_rotation_recovery_failed');
|
|
1449
|
+
}
|
|
1450
|
+
const committedIdentity = this.writeAtomic(join(this.dir, target.stageName), payload, true, journal.targetGeneration);
|
|
1451
|
+
const staged = this.requireRotationTarget(join(this.dir, target.stageName), target);
|
|
1452
|
+
if (!sameGraphFileIdentity(committedIdentity, staged.identity)) {
|
|
1453
|
+
throw new Error('memory_graph_rotation_recovery_failed');
|
|
1454
|
+
}
|
|
1455
|
+
}
|
|
1456
|
+
assertRotationStagesMatch(journal) {
|
|
1457
|
+
for (const target of [
|
|
1458
|
+
journal.target.compact,
|
|
1459
|
+
journal.target.archive,
|
|
1460
|
+
journal.target.active,
|
|
1461
|
+
]) {
|
|
1462
|
+
this.requireRotationTarget(join(this.dir, target.stageName), target);
|
|
1463
|
+
}
|
|
1464
|
+
}
|
|
1465
|
+
assertRotationSourceMatches(journal) {
|
|
1466
|
+
if (!this.rotationActiveSourceMatches(join(this.dir, ACTIVE_FILE), journal.source.active)) {
|
|
1467
|
+
throw new Error('memory_graph_rotation_recovery_failed');
|
|
1468
|
+
}
|
|
1469
|
+
const compactPath = join(this.dir, COMPACT_FILE);
|
|
1470
|
+
if (journal.source.compact === null) {
|
|
1471
|
+
assertPathMissing(compactPath, 'memory_graph_rotation_recovery_failed');
|
|
1472
|
+
}
|
|
1473
|
+
else if (!this.rotationSourceMatches(compactPath, journal.source.compact)) {
|
|
1474
|
+
throw new Error('memory_graph_rotation_recovery_failed');
|
|
1475
|
+
}
|
|
1476
|
+
}
|
|
1477
|
+
rotationActiveSourceMatches(path, source) {
|
|
1478
|
+
const physicalSize = Number(source.snapshot.size);
|
|
1479
|
+
const verified = this.readVerifiedRotationFile(path, physicalSize, true, 'memory_graph_rotation_recovery_failed', { offset: source.offset, size: source.size });
|
|
1480
|
+
if (!verified || !serializedSnapshotMatches(source.snapshot, verified.identity))
|
|
1481
|
+
return false;
|
|
1482
|
+
if (BigInt(source.offset) + BigInt(source.size) !== verified.identity.size)
|
|
1483
|
+
return false;
|
|
1484
|
+
return rotationDigestMatches(verified.payload, source);
|
|
1485
|
+
}
|
|
1486
|
+
rotationSourceMatches(path, source) {
|
|
1487
|
+
const verified = this.readVerifiedRotationFile(path, source.size, true, 'memory_graph_rotation_recovery_failed');
|
|
1488
|
+
return verified !== null
|
|
1489
|
+
&& serializedSnapshotMatches(source.snapshot, verified.identity)
|
|
1490
|
+
&& rotationDigestMatches(verified.payload, source);
|
|
1491
|
+
}
|
|
1492
|
+
rotationTargetMatches(path, target) {
|
|
1493
|
+
let identity;
|
|
1494
|
+
try {
|
|
1495
|
+
identity = lstatSync(path, { bigint: true });
|
|
1496
|
+
}
|
|
1497
|
+
catch (error) {
|
|
1498
|
+
if (isObject(error) && error['code'] === 'ENOENT')
|
|
1499
|
+
return false;
|
|
1500
|
+
throw new Error('memory_graph_rotation_recovery_failed');
|
|
1501
|
+
}
|
|
1502
|
+
if (!identity.isFile() || identity.isSymbolicLink()) {
|
|
1503
|
+
throw new Error('memory_graph_rotation_recovery_failed');
|
|
1504
|
+
}
|
|
1505
|
+
if (identity.size !== BigInt(target.size))
|
|
1506
|
+
return false;
|
|
1507
|
+
const verified = this.readVerifiedRotationFile(path, target.size, true, 'memory_graph_rotation_recovery_failed');
|
|
1508
|
+
return verified !== null && rotationDigestMatches(verified.payload, target);
|
|
1509
|
+
}
|
|
1510
|
+
requireRotationTarget(path, target) {
|
|
1511
|
+
const verified = this.readVerifiedRotationFile(path, target.size, false, 'memory_graph_rotation_recovery_failed');
|
|
1512
|
+
if (!verified || !rotationDigestMatches(verified.payload, target)) {
|
|
1513
|
+
throw new Error('memory_graph_rotation_recovery_failed');
|
|
1514
|
+
}
|
|
1515
|
+
return verified;
|
|
1516
|
+
}
|
|
1517
|
+
removeRotationStage(target) {
|
|
1518
|
+
const path = join(this.dir, target.stageName);
|
|
1519
|
+
const verified = this.readVerifiedRotationFile(path, target.size, true, 'memory_graph_rotation_recovery_failed');
|
|
1520
|
+
if (!verified)
|
|
1521
|
+
return;
|
|
1522
|
+
if (!rotationDigestMatches(verified.payload, target)) {
|
|
1523
|
+
throw new Error('memory_graph_rotation_recovery_failed');
|
|
1524
|
+
}
|
|
1525
|
+
this.removeVerifiedRotationFile(path, verified.identity, 'memory_graph_rotation_recovery_failed');
|
|
1526
|
+
}
|
|
1527
|
+
removeVerifiedRotationFile(path, identity, reason) {
|
|
1528
|
+
let current;
|
|
1529
|
+
try {
|
|
1530
|
+
current = lstatSync(path, { bigint: true });
|
|
1531
|
+
}
|
|
1532
|
+
catch {
|
|
1533
|
+
throw new Error(reason);
|
|
1534
|
+
}
|
|
1535
|
+
if (!current.isFile() || current.isSymbolicLink()
|
|
1536
|
+
|| !sameGraphFileSnapshot(identity, current)) {
|
|
1537
|
+
throw new Error(reason);
|
|
1538
|
+
}
|
|
1539
|
+
try {
|
|
1540
|
+
unlinkSync(path);
|
|
1541
|
+
this.syncGraphDirectory();
|
|
1542
|
+
}
|
|
1543
|
+
catch {
|
|
1544
|
+
throw new Error(reason);
|
|
1545
|
+
}
|
|
1546
|
+
}
|
|
1547
|
+
readVerifiedRotationFile(path, maxBytes, optional, reason, range) {
|
|
1548
|
+
let pathBefore;
|
|
1549
|
+
try {
|
|
1550
|
+
pathBefore = lstatSync(path, { bigint: true });
|
|
1551
|
+
}
|
|
1552
|
+
catch (error) {
|
|
1553
|
+
if (optional && isObject(error) && error['code'] === 'ENOENT')
|
|
1554
|
+
return null;
|
|
1555
|
+
throw new Error(reason);
|
|
1556
|
+
}
|
|
1557
|
+
if (!pathBefore.isFile() || pathBefore.isSymbolicLink()
|
|
1558
|
+
|| pathBefore.size > BigInt(maxBytes)
|
|
1559
|
+
|| pathBefore.size > BigInt(Number.MAX_SAFE_INTEGER)) {
|
|
1560
|
+
throw new Error(reason);
|
|
1561
|
+
}
|
|
1562
|
+
let fd;
|
|
1563
|
+
try {
|
|
1564
|
+
fd = openNoFollow(path, constants.O_RDONLY, 0o600);
|
|
1565
|
+
}
|
|
1566
|
+
catch {
|
|
1567
|
+
throw new Error(reason);
|
|
1568
|
+
}
|
|
1569
|
+
try {
|
|
1570
|
+
const openedBefore = fstatSync(fd, { bigint: true });
|
|
1571
|
+
if (!openedBefore.isFile() || openedBefore.isSymbolicLink()
|
|
1572
|
+
|| !sameGraphFileSnapshot(pathBefore, openedBefore)) {
|
|
1573
|
+
throw new Error(reason);
|
|
1574
|
+
}
|
|
1575
|
+
const readOffset = range?.offset ?? 0;
|
|
1576
|
+
const readSize = range?.size ?? Number(openedBefore.size);
|
|
1577
|
+
if (!Number.isSafeInteger(readOffset) || readOffset < 0
|
|
1578
|
+
|| !Number.isSafeInteger(readSize) || readSize < 0
|
|
1579
|
+
|| BigInt(readOffset) + BigInt(readSize) > openedBefore.size) {
|
|
1580
|
+
throw new Error(reason);
|
|
1581
|
+
}
|
|
1582
|
+
const payload = readFdBytes(fd, readSize, readOffset);
|
|
1583
|
+
const openedAfter = fstatSync(fd, { bigint: true });
|
|
1584
|
+
let pathAfter;
|
|
1585
|
+
try {
|
|
1586
|
+
pathAfter = lstatSync(path, { bigint: true });
|
|
1587
|
+
}
|
|
1588
|
+
catch {
|
|
1589
|
+
throw new Error(reason);
|
|
1590
|
+
}
|
|
1591
|
+
if (payload.length !== readSize
|
|
1592
|
+
|| !sameGraphFileSnapshot(openedBefore, openedAfter)
|
|
1593
|
+
|| !sameGraphFileSnapshot(openedAfter, pathAfter)) {
|
|
1594
|
+
throw new Error(reason);
|
|
1595
|
+
}
|
|
1596
|
+
return { identity: openedAfter, payload };
|
|
1597
|
+
}
|
|
1598
|
+
finally {
|
|
1599
|
+
closeSync(fd);
|
|
1600
|
+
}
|
|
1601
|
+
}
|
|
1602
|
+
rotationStageFiles() {
|
|
1603
|
+
try {
|
|
1604
|
+
return readdirSync(this.dir).filter((name) => ROTATION_STAGE_PATTERN.test(name));
|
|
1605
|
+
}
|
|
1606
|
+
catch {
|
|
1607
|
+
throw new Error('memory_graph_rotation_recovery_failed');
|
|
1608
|
+
}
|
|
1609
|
+
}
|
|
1610
|
+
rotationTempFiles() {
|
|
1611
|
+
try {
|
|
1612
|
+
return readdirSync(this.dir).filter((name) => ROTATION_TEMP_PATTERN.test(name));
|
|
1613
|
+
}
|
|
1614
|
+
catch {
|
|
1615
|
+
throw new Error('memory_graph_rotation_recovery_failed');
|
|
1616
|
+
}
|
|
1617
|
+
}
|
|
1618
|
+
removeRotationTemp(name) {
|
|
1619
|
+
if (!ROTATION_TEMP_PATTERN.test(name)) {
|
|
1620
|
+
throw new Error('memory_graph_rotation_recovery_failed');
|
|
1621
|
+
}
|
|
1622
|
+
const path = join(this.dir, name);
|
|
1623
|
+
let identity;
|
|
1624
|
+
try {
|
|
1625
|
+
identity = lstatSync(path, { bigint: true });
|
|
1626
|
+
}
|
|
1627
|
+
catch (error) {
|
|
1628
|
+
if (isObject(error) && error['code'] === 'ENOENT')
|
|
1629
|
+
return;
|
|
1630
|
+
throw new Error('memory_graph_rotation_recovery_failed');
|
|
1631
|
+
}
|
|
1632
|
+
if (!identity.isFile() || identity.isSymbolicLink()) {
|
|
1633
|
+
throw new Error('memory_graph_rotation_recovery_failed');
|
|
1634
|
+
}
|
|
1635
|
+
this.removeVerifiedRotationFile(path, identity, 'memory_graph_rotation_recovery_failed');
|
|
1636
|
+
}
|
|
1637
|
+
notifyRotationPhase(journal, mode, phase) {
|
|
1638
|
+
this.onRotationPhase?.({
|
|
1639
|
+
mode,
|
|
1640
|
+
phase,
|
|
1641
|
+
transactionId: journal.transactionId,
|
|
1642
|
+
generation: journal.targetGeneration,
|
|
1643
|
+
});
|
|
1644
|
+
}
|
|
1645
|
+
syncGraphDirectory() {
|
|
1646
|
+
if (process.platform === 'win32')
|
|
1647
|
+
return;
|
|
1648
|
+
const fd = openSync(this.dir, constants.O_RDONLY);
|
|
1649
|
+
try {
|
|
1650
|
+
fsyncSync(fd);
|
|
1651
|
+
}
|
|
1652
|
+
finally {
|
|
1653
|
+
closeSync(fd);
|
|
1654
|
+
}
|
|
1655
|
+
}
|
|
1656
|
+
compactRequiresRecovery(epoch) {
|
|
1657
|
+
if (this.recoveryMarkerState(epoch) === 'degraded')
|
|
1658
|
+
return true;
|
|
1659
|
+
const path = join(this.dir, COMPACT_FILE);
|
|
1660
|
+
const diagnostics = emptyDiagnostics();
|
|
1661
|
+
const currentRecords = this.readCompactForEpoch(epoch, diagnostics)
|
|
1662
|
+
.filter((record) => recordEpochId(record) === epoch.epochId);
|
|
1663
|
+
const compactBaseline = this.compactMatchesEpochBaseline(epoch);
|
|
1664
|
+
const compactUnusable = compactBaseline || !existsSync(path)
|
|
1665
|
+
|| !this.secureRegularFile(path)
|
|
1666
|
+
|| statSync(path).size === 0
|
|
1667
|
+
|| currentRecords.length === 0
|
|
1668
|
+
|| diagnostics.corruptLines > 0
|
|
1669
|
+
|| diagnostics.oversizedLines > 0
|
|
1670
|
+
|| diagnostics.truncated;
|
|
1671
|
+
if (!compactUnusable)
|
|
1672
|
+
return false;
|
|
1673
|
+
const archives = this.inspectArchivesForEpoch(epoch);
|
|
1674
|
+
return archives.containsCurrent || archives.unreadable;
|
|
1675
|
+
}
|
|
1676
|
+
readQueryableRecords(diagnostics) {
|
|
1677
|
+
this.ensureSecureDir();
|
|
1678
|
+
this.managedGraphStateFiles();
|
|
1679
|
+
const epoch = this.readEpochState();
|
|
1680
|
+
const epochId = epoch.epochId;
|
|
1681
|
+
const compactPath = join(this.dir, COMPACT_FILE);
|
|
1682
|
+
const compactDiagnostics = emptyDiagnostics();
|
|
1683
|
+
let records = this.readCompactForEpoch(epoch, compactDiagnostics)
|
|
1684
|
+
.filter((record) => recordEpochId(record) === epochId);
|
|
1685
|
+
const archives = this.archiveFiles().length;
|
|
1686
|
+
const compactExists = existsSync(compactPath);
|
|
1687
|
+
const compactSecure = compactExists && this.secureRegularFile(compactPath);
|
|
1688
|
+
const compactUnusable = (this.compactMatchesEpochBaseline(epoch)
|
|
1689
|
+
|| !compactExists
|
|
1690
|
+
|| !compactSecure
|
|
1691
|
+
|| (compactSecure && statSync(compactPath).size === 0)
|
|
1692
|
+
|| records.length === 0
|
|
1693
|
+
|| compactDiagnostics.corruptLines > 0
|
|
1694
|
+
|| compactDiagnostics.oversizedLines > 0
|
|
1695
|
+
|| compactDiagnostics.truncated);
|
|
1696
|
+
const archiveProbe = archives > 0 && compactUnusable
|
|
1697
|
+
? this.inspectArchivesForEpoch(epoch)
|
|
1698
|
+
: { containsCurrent: false, unreadable: false };
|
|
1699
|
+
const compactNeedsRecovery = compactUnusable
|
|
1700
|
+
&& (archiveProbe.containsCurrent || archiveProbe.unreadable);
|
|
1701
|
+
mergeDiagnostics(diagnostics, compactDiagnostics);
|
|
1702
|
+
if (compactNeedsRecovery) {
|
|
1703
|
+
try {
|
|
1704
|
+
const recovery = this.recoverFromArchivesUnlocked(epoch);
|
|
1705
|
+
diagnostics.corruptLines += recovery.corruptLines;
|
|
1706
|
+
diagnostics.oversizedLines += recovery.oversizedLines;
|
|
1707
|
+
if (recovery.recovery === 'recovered'
|
|
1708
|
+
|| (recovery.recovery === 'degraded' && recovery.compactedRecords > 0)) {
|
|
1709
|
+
const recoveredDiagnostics = emptyDiagnostics();
|
|
1710
|
+
records = this.readCompactForEpoch(epoch, recoveredDiagnostics)
|
|
1711
|
+
.filter((record) => recordEpochId(record) === epochId);
|
|
1712
|
+
mergeDiagnostics(diagnostics, recoveredDiagnostics);
|
|
1713
|
+
diagnostics.recovery = recovery.recovery;
|
|
1714
|
+
}
|
|
1715
|
+
else if (recovery.recovery === 'empty') {
|
|
1716
|
+
records = [];
|
|
1717
|
+
diagnostics.recovery = 'empty';
|
|
1718
|
+
}
|
|
1719
|
+
else {
|
|
1720
|
+
diagnostics.recovery = 'degraded';
|
|
1721
|
+
}
|
|
1722
|
+
}
|
|
1723
|
+
catch {
|
|
1724
|
+
diagnostics.recovery = 'degraded';
|
|
1725
|
+
}
|
|
1726
|
+
}
|
|
1727
|
+
records.push(...this.readActiveForEpoch(epoch, diagnostics, this.maxActiveBytes)
|
|
1728
|
+
.filter((record) => recordEpochId(record) === epochId));
|
|
1729
|
+
if (this.recoveryMarkerState(epoch) === 'degraded')
|
|
1730
|
+
diagnostics.recovery = 'degraded';
|
|
1731
|
+
if (diagnostics.recovery !== 'recovered' && (diagnostics.corruptLines > 0 || diagnostics.oversizedLines > 0 || diagnostics.truncated))
|
|
1732
|
+
diagnostics.recovery = 'degraded';
|
|
1733
|
+
return records;
|
|
1734
|
+
}
|
|
1735
|
+
readImportRecords() {
|
|
1736
|
+
this.ensureSecureDir();
|
|
1737
|
+
return this.readImportRecordsFromExistingDir();
|
|
1738
|
+
}
|
|
1739
|
+
readImportRecordsFromExistingDir() {
|
|
1740
|
+
this.managedGraphStateFiles();
|
|
1741
|
+
const epoch = this.readEpochState();
|
|
1742
|
+
const epochId = epoch.epochId;
|
|
1743
|
+
const diagnostics = emptyDiagnostics();
|
|
1744
|
+
const activePath = join(this.dir, ACTIVE_FILE);
|
|
1745
|
+
if (existsSync(activePath)) {
|
|
1746
|
+
if (!this.secureRegularFile(activePath)) {
|
|
1747
|
+
throw new MemoryGraphImportStateRejectedError();
|
|
1748
|
+
}
|
|
1749
|
+
const activeWindow = this.activeLogicalWindow(epoch, lstatSync(activePath, { bigint: true }));
|
|
1750
|
+
if (activeWindow.invalid || activeWindow.size > this.maxActiveBytes) {
|
|
1751
|
+
throw new MemoryGraphImportStateRejectedError();
|
|
1752
|
+
}
|
|
1753
|
+
}
|
|
1754
|
+
return [...this.readCompactForEpoch(epoch, diagnostics), ...this.readActiveForEpoch(epoch, diagnostics, this.maxActiveBytes)]
|
|
1755
|
+
.filter((record) => recordEpochId(record) === epochId);
|
|
1756
|
+
}
|
|
1757
|
+
readCompact(diagnostics) {
|
|
1758
|
+
const path = join(this.dir, COMPACT_FILE);
|
|
1759
|
+
if (!existsSync(path) || !this.secureRegularFile(path))
|
|
1760
|
+
return [];
|
|
1761
|
+
if (statSync(path).size > this.maxCompactBytes) {
|
|
1762
|
+
diagnostics.truncated = true;
|
|
1763
|
+
diagnostics.oversizedLines += 1;
|
|
1764
|
+
return [];
|
|
1765
|
+
}
|
|
1766
|
+
return this.readWholeBounded(path, diagnostics, this.maxCompactBytes);
|
|
1767
|
+
}
|
|
1768
|
+
readWholeBounded(path, diagnostics, maxBytes) {
|
|
1769
|
+
if (!existsSync(path) || !this.secureRegularFile(path))
|
|
1770
|
+
return [];
|
|
1771
|
+
const fd = openNoFollow(path, constants.O_RDONLY, 0o600);
|
|
1772
|
+
try {
|
|
1773
|
+
const stat = fstatSync(fd);
|
|
1774
|
+
if (!stat.isFile())
|
|
1775
|
+
return [];
|
|
1776
|
+
if (stat.size > maxBytes) {
|
|
1777
|
+
diagnostics.truncated = true;
|
|
1778
|
+
return this.readTailFromFd(fd, stat.size, diagnostics, maxBytes);
|
|
1779
|
+
}
|
|
1780
|
+
const raw = readFdBytes(fd, stat.size, 0);
|
|
1781
|
+
diagnostics.bytesRead += raw.length;
|
|
1782
|
+
return this.parseBuffer(raw, diagnostics);
|
|
1783
|
+
}
|
|
1784
|
+
finally {
|
|
1785
|
+
closeSync(fd);
|
|
1786
|
+
}
|
|
1787
|
+
}
|
|
1788
|
+
readTail(path, diagnostics, maxBytes = this.maxTailBytes) {
|
|
1789
|
+
if (!existsSync(path) || !this.secureRegularFile(path))
|
|
1790
|
+
return [];
|
|
1791
|
+
const fd = openNoFollow(path, constants.O_RDONLY, 0o600);
|
|
1792
|
+
try {
|
|
1793
|
+
const size = fstatSync(fd).size;
|
|
1794
|
+
return this.readTailFromFd(fd, size, diagnostics, maxBytes);
|
|
1795
|
+
}
|
|
1796
|
+
finally {
|
|
1797
|
+
closeSync(fd);
|
|
1798
|
+
}
|
|
1799
|
+
}
|
|
1800
|
+
readTailFromFd(fd, size, diagnostics, maxBytes) {
|
|
1801
|
+
const bytes = Math.min(size, maxBytes);
|
|
1802
|
+
const buffer = readFdBytes(fd, bytes, size - bytes);
|
|
1803
|
+
diagnostics.bytesRead += buffer.length;
|
|
1804
|
+
diagnostics.truncated ||= size > buffer.length;
|
|
1805
|
+
if (size <= buffer.length)
|
|
1806
|
+
return this.parseBuffer(buffer, diagnostics);
|
|
1807
|
+
const newline = buffer.indexOf(0x0a);
|
|
1808
|
+
return this.parseBuffer(newline >= 0 ? buffer.subarray(newline + 1) : Buffer.alloc(0), diagnostics);
|
|
1809
|
+
}
|
|
1810
|
+
parseBuffer(buffer, diagnostics) {
|
|
1811
|
+
const out = [];
|
|
1812
|
+
for (const line of buffer.toString('utf8').split('\n')) {
|
|
1813
|
+
if (!line.trim())
|
|
1814
|
+
continue;
|
|
1815
|
+
if (Buffer.byteLength(line) > this.maxLineBytes) {
|
|
1816
|
+
diagnostics.oversizedLines += 1;
|
|
1817
|
+
continue;
|
|
1818
|
+
}
|
|
1819
|
+
try {
|
|
1820
|
+
const raw = JSON.parse(line);
|
|
1821
|
+
if (isObject(raw) && raw['version'] === 2 && raw['kind'] === 'outcome' && raw['provenance'] !== 'v2_local' && raw['provenance'] !== 'v1_import') {
|
|
1822
|
+
diagnostics.provenanceRejected += 1;
|
|
1823
|
+
continue;
|
|
1824
|
+
}
|
|
1825
|
+
const parsed = parseV2Record(raw);
|
|
1826
|
+
if (parsed) {
|
|
1827
|
+
out.push(parsed);
|
|
1828
|
+
diagnostics.recordsRead += 1;
|
|
1829
|
+
}
|
|
1830
|
+
else {
|
|
1831
|
+
diagnostics.corruptLines += 1;
|
|
1832
|
+
}
|
|
1833
|
+
}
|
|
1834
|
+
catch {
|
|
1835
|
+
diagnostics.corruptLines += 1;
|
|
1836
|
+
}
|
|
1837
|
+
}
|
|
1838
|
+
return out;
|
|
1839
|
+
}
|
|
1840
|
+
writeCompact(records) {
|
|
1841
|
+
const fitted = fitCompactRecords(records, this.maxCompactBytes);
|
|
1842
|
+
if (records.length > 0 && fitted.records.length === 0) {
|
|
1843
|
+
return { records: 0, committedIdentity: null };
|
|
1844
|
+
}
|
|
1845
|
+
const committedIdentity = this.writeAtomic(join(this.dir, COMPACT_FILE), fitted.payload);
|
|
1846
|
+
return { records: fitted.records.length, committedIdentity };
|
|
1847
|
+
}
|
|
1848
|
+
writeAtomic(path, payload, syncDirectory = false, tempTag = String(this.now())) {
|
|
1849
|
+
this.ensureSecureDir();
|
|
1850
|
+
if (existsSync(path) && !this.secureRegularFile(path))
|
|
1851
|
+
throw new Error('memory_graph_path_rejected');
|
|
1852
|
+
const temp = join(dirname(path), `.${basename(path)}.${tempTag}.tmp`);
|
|
1853
|
+
const fd = openNoFollow(temp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, 0o600);
|
|
1854
|
+
let tempIdentity = null;
|
|
1855
|
+
let closed = false;
|
|
1856
|
+
let published = false;
|
|
1857
|
+
try {
|
|
1858
|
+
tempIdentity = lstatSync(temp, { bigint: true });
|
|
1859
|
+
const descriptorIdentity = fstatSync(fd, { bigint: true });
|
|
1860
|
+
if (!tempIdentity.isFile() || tempIdentity.isSymbolicLink()
|
|
1861
|
+
|| !descriptorIdentity.isFile() || descriptorIdentity.isSymbolicLink()
|
|
1862
|
+
|| !sameGraphFileIdentity(tempIdentity, descriptorIdentity)) {
|
|
1863
|
+
throw new Error('memory_graph_write_failed');
|
|
1864
|
+
}
|
|
1865
|
+
writeAll(fd, payload);
|
|
1866
|
+
fsyncSync(fd);
|
|
1867
|
+
closeSync(fd);
|
|
1868
|
+
closed = true;
|
|
1869
|
+
renameSync(temp, path);
|
|
1870
|
+
published = true;
|
|
1871
|
+
if (syncDirectory)
|
|
1872
|
+
this.syncGraphDirectory();
|
|
1873
|
+
}
|
|
1874
|
+
finally {
|
|
1875
|
+
if (!closed) {
|
|
1876
|
+
try {
|
|
1877
|
+
closeSync(fd);
|
|
1878
|
+
}
|
|
1879
|
+
catch {
|
|
1880
|
+
// Preserve the original write/fsync failure.
|
|
1881
|
+
}
|
|
1882
|
+
}
|
|
1883
|
+
if (!published && tempIdentity !== null) {
|
|
1884
|
+
try {
|
|
1885
|
+
const currentIdentity = lstatSync(temp, { bigint: true });
|
|
1886
|
+
if (currentIdentity.isFile() && !currentIdentity.isSymbolicLink()
|
|
1887
|
+
&& sameGraphFileIdentity(tempIdentity, currentIdentity))
|
|
1888
|
+
unlinkSync(temp);
|
|
1889
|
+
}
|
|
1890
|
+
catch {
|
|
1891
|
+
// Never remove an unknown replacement; a same-name leftover is safer than clobbering it.
|
|
1892
|
+
}
|
|
1893
|
+
}
|
|
1894
|
+
}
|
|
1895
|
+
if (tempIdentity === null || !published)
|
|
1896
|
+
throw new Error('memory_graph_write_failed');
|
|
1897
|
+
return tempIdentity;
|
|
1898
|
+
}
|
|
1899
|
+
ensureSecureDir() {
|
|
1900
|
+
let stat;
|
|
1901
|
+
try {
|
|
1902
|
+
stat = lstatSync(this.dir);
|
|
1903
|
+
}
|
|
1904
|
+
catch (error) {
|
|
1905
|
+
if (!isObject(error) || error['code'] !== 'ENOENT')
|
|
1906
|
+
throw new Error('memory_graph_dir_rejected');
|
|
1907
|
+
try {
|
|
1908
|
+
mkdirSync(this.dir, { recursive: true, mode: 0o700 });
|
|
1909
|
+
stat = lstatSync(this.dir);
|
|
1910
|
+
}
|
|
1911
|
+
catch {
|
|
1912
|
+
throw new Error('memory_graph_dir_rejected');
|
|
1913
|
+
}
|
|
1914
|
+
}
|
|
1915
|
+
if (!stat.isDirectory() || stat.isSymbolicLink())
|
|
1916
|
+
throw new Error('memory_graph_dir_rejected');
|
|
1917
|
+
}
|
|
1918
|
+
secureRegularFile(path) {
|
|
1919
|
+
const stat = lstatSync(path);
|
|
1920
|
+
return stat.isFile() && !stat.isSymbolicLink();
|
|
1921
|
+
}
|
|
1922
|
+
workspaceScope(workspace) {
|
|
1923
|
+
try {
|
|
1924
|
+
const absolute = resolve(workspace);
|
|
1925
|
+
const linkStat = lstatSync(absolute);
|
|
1926
|
+
if (!linkStat.isDirectory() || linkStat.isSymbolicLink())
|
|
1927
|
+
return null;
|
|
1928
|
+
const canonical = realpathSync(absolute);
|
|
1929
|
+
return scopeHash(`workspace:${canonical}`);
|
|
1930
|
+
}
|
|
1931
|
+
catch {
|
|
1932
|
+
return null;
|
|
1933
|
+
}
|
|
1934
|
+
}
|
|
1935
|
+
archiveFiles() {
|
|
1936
|
+
if (!existsSync(this.dir))
|
|
1937
|
+
return [];
|
|
1938
|
+
return readdirSync(this.dir).filter((file) => ARCHIVE_PATTERN.test(file)).sort();
|
|
1939
|
+
}
|
|
1940
|
+
nextArchivePath() {
|
|
1941
|
+
const latest = this.archiveFiles().at(-1);
|
|
1942
|
+
const latestTimestamp = latest ? Number(ARCHIVE_PATTERN.exec(latest)?.[1] ?? 0) : 0;
|
|
1943
|
+
const timestamp = Math.max(Math.floor(this.now()), latestTimestamp + 1);
|
|
1944
|
+
return join(this.dir, `memory_graph.v2.${timestamp}.jsonl.gz`);
|
|
1945
|
+
}
|
|
1946
|
+
pruneArchives(retention = this.archiveRetention) {
|
|
1947
|
+
const files = this.archiveFiles();
|
|
1948
|
+
for (const file of files.slice(0, Math.max(0, files.length - retention))) {
|
|
1949
|
+
unlinkSync(join(this.dir, file));
|
|
1950
|
+
}
|
|
1951
|
+
}
|
|
1952
|
+
writeRecoveryMarker(epochId, state) {
|
|
1953
|
+
this.writeAtomic(join(this.dir, RECOVERY_FILE), Buffer.from(JSON.stringify({
|
|
1954
|
+
version: 1,
|
|
1955
|
+
recoveredAt: new Date(this.now()).toISOString(),
|
|
1956
|
+
epochId,
|
|
1957
|
+
state,
|
|
1958
|
+
}) + '\n', 'utf8'));
|
|
1959
|
+
}
|
|
1960
|
+
inspectArchivesForEpoch(epoch) {
|
|
1961
|
+
let unreadable = false;
|
|
1962
|
+
const maxArchiveBytes = gzipRotationByteBound(this.maxActiveBytes);
|
|
1963
|
+
const maxArchiveOutputBytes = safeRotationByteSum(this.maxActiveBytes, this.maxLineBytes);
|
|
1964
|
+
for (const file of this.currentArchiveFiles(epoch)) {
|
|
1965
|
+
const path = join(this.dir, file);
|
|
1966
|
+
try {
|
|
1967
|
+
if (maxArchiveBytes === null || maxArchiveOutputBytes === null) {
|
|
1968
|
+
unreadable = true;
|
|
1969
|
+
continue;
|
|
1970
|
+
}
|
|
1971
|
+
if (!this.secureRegularFile(path)) {
|
|
1972
|
+
unreadable = true;
|
|
1973
|
+
continue;
|
|
1974
|
+
}
|
|
1975
|
+
const compressed = this.readRawBounded(path, maxArchiveBytes);
|
|
1976
|
+
if (compressed === null) {
|
|
1977
|
+
unreadable = true;
|
|
1978
|
+
continue;
|
|
1979
|
+
}
|
|
1980
|
+
const raw = gunzipSync(compressed, { maxOutputLength: maxArchiveOutputBytes });
|
|
1981
|
+
const diagnostics = emptyDiagnostics();
|
|
1982
|
+
const records = this.parseBuffer(raw, diagnostics);
|
|
1983
|
+
unreadable ||= diagnostics.corruptLines > 0
|
|
1984
|
+
|| diagnostics.oversizedLines > 0
|
|
1985
|
+
|| diagnostics.truncated;
|
|
1986
|
+
if (records.some((record) => recordEpochId(record) === epoch.epochId)) {
|
|
1987
|
+
return { containsCurrent: true, unreadable };
|
|
1988
|
+
}
|
|
1989
|
+
}
|
|
1990
|
+
catch {
|
|
1991
|
+
unreadable = true;
|
|
1992
|
+
}
|
|
1993
|
+
}
|
|
1994
|
+
return { containsCurrent: false, unreadable };
|
|
1995
|
+
}
|
|
1996
|
+
recoveryMarkerState(epoch, maxBytes = this.maxLineBytes) {
|
|
1997
|
+
const path = join(this.dir, RECOVERY_FILE);
|
|
1998
|
+
if (!existsSync(path))
|
|
1999
|
+
return null;
|
|
2000
|
+
try {
|
|
2001
|
+
const identity = lstatSync(path, { bigint: true });
|
|
2002
|
+
if (epoch.baseline?.recovery
|
|
2003
|
+
&& serializedSnapshotMatches(epoch.baseline.recovery, identity))
|
|
2004
|
+
return null;
|
|
2005
|
+
if (!identity.isFile() || identity.isSymbolicLink())
|
|
2006
|
+
return 'degraded';
|
|
2007
|
+
const bytes = this.readRawBounded(path, maxBytes);
|
|
2008
|
+
if (bytes === null)
|
|
2009
|
+
return 'degraded';
|
|
2010
|
+
const raw = JSON.parse(bytes.toString('utf8'));
|
|
2011
|
+
if (!isObject(raw) || raw['version'] !== 1
|
|
2012
|
+
|| typeof raw['recoveredAt'] !== 'string' || validIso(raw['recoveredAt']) === null)
|
|
2013
|
+
return 'degraded';
|
|
2014
|
+
const markerEpoch = Object.prototype.hasOwnProperty.call(raw, 'epochId')
|
|
2015
|
+
? safeEpochId(raw['epochId'])
|
|
2016
|
+
: LEGACY_EPOCH_ID;
|
|
2017
|
+
if (markerEpoch !== epoch.epochId)
|
|
2018
|
+
return 'degraded';
|
|
2019
|
+
const state = raw['state'];
|
|
2020
|
+
if (state === undefined)
|
|
2021
|
+
return 'recovered';
|
|
2022
|
+
return state === 'empty' || state === 'recovered' || state === 'degraded' ? state : 'degraded';
|
|
2023
|
+
}
|
|
2024
|
+
catch {
|
|
2025
|
+
return 'degraded';
|
|
2026
|
+
}
|
|
2027
|
+
}
|
|
2028
|
+
clearRecoveryMarker(epoch, maxBytes = this.maxLineBytes) {
|
|
2029
|
+
if (this.recoveryMarkerState(epoch, maxBytes) === 'degraded')
|
|
2030
|
+
return;
|
|
2031
|
+
const path = join(this.dir, RECOVERY_FILE);
|
|
2032
|
+
if (existsSync(path) && this.secureRegularFile(path))
|
|
2033
|
+
unlinkSync(path);
|
|
2034
|
+
}
|
|
2035
|
+
readRawBounded(path, maxBytes) {
|
|
2036
|
+
if (!existsSync(path) || !this.secureRegularFile(path))
|
|
2037
|
+
return null;
|
|
2038
|
+
const fd = openNoFollow(path, constants.O_RDONLY, 0o600);
|
|
2039
|
+
try {
|
|
2040
|
+
const stat = fstatSync(fd);
|
|
2041
|
+
if (!stat.isFile() || stat.size > maxBytes)
|
|
2042
|
+
return null;
|
|
2043
|
+
return readFdBytes(fd, stat.size, 0);
|
|
2044
|
+
}
|
|
2045
|
+
finally {
|
|
2046
|
+
closeSync(fd);
|
|
2047
|
+
}
|
|
2048
|
+
}
|
|
2049
|
+
}
|
|
2050
|
+
function rotationStageNames(generation) {
|
|
2051
|
+
return {
|
|
2052
|
+
compact: 'memory_graph.rotation.' + generation + '.compact.stage',
|
|
2053
|
+
archive: 'memory_graph.rotation.' + generation + '.archive.stage',
|
|
2054
|
+
active: 'memory_graph.rotation.' + generation + '.active.stage',
|
|
2055
|
+
};
|
|
2056
|
+
}
|
|
2057
|
+
function rotationTempNames(generation) {
|
|
2058
|
+
const stages = rotationStageNames(generation);
|
|
2059
|
+
return {
|
|
2060
|
+
journal: '.' + ROTATION_JOURNAL_FILE + '.' + generation + '.tmp',
|
|
2061
|
+
compact: '.' + stages.compact + '.' + generation + '.tmp',
|
|
2062
|
+
archive: '.' + stages.archive + '.' + generation + '.tmp',
|
|
2063
|
+
active: '.' + stages.active + '.' + generation + '.tmp',
|
|
2064
|
+
};
|
|
2065
|
+
}
|
|
2066
|
+
function rotationFileDigest(payload) {
|
|
2067
|
+
return {
|
|
2068
|
+
size: payload.length,
|
|
2069
|
+
sha256: createHash('sha256').update(payload).digest('hex'),
|
|
2070
|
+
};
|
|
2071
|
+
}
|
|
2072
|
+
function rotationDigestMatches(payload, expected) {
|
|
2073
|
+
const actual = rotationFileDigest(payload);
|
|
2074
|
+
return actual.size === expected.size && actual.sha256 === expected.sha256;
|
|
2075
|
+
}
|
|
2076
|
+
function rotationJournalImmutable(journal) {
|
|
2077
|
+
return {
|
|
2078
|
+
version: journal.version,
|
|
2079
|
+
targetGeneration: journal.targetGeneration,
|
|
2080
|
+
epochId: journal.epochId,
|
|
2081
|
+
createdAt: journal.createdAt,
|
|
2082
|
+
limits: {
|
|
2083
|
+
maxActiveBytes: journal.limits.maxActiveBytes,
|
|
2084
|
+
maxCompactBytes: journal.limits.maxCompactBytes,
|
|
2085
|
+
maxLineBytes: journal.limits.maxLineBytes,
|
|
2086
|
+
archiveRetention: journal.limits.archiveRetention,
|
|
2087
|
+
},
|
|
2088
|
+
source: {
|
|
2089
|
+
active: {
|
|
2090
|
+
snapshot: journal.source.active.snapshot,
|
|
2091
|
+
offset: journal.source.active.offset,
|
|
2092
|
+
size: journal.source.active.size,
|
|
2093
|
+
sha256: journal.source.active.sha256,
|
|
2094
|
+
},
|
|
2095
|
+
compact: journal.source.compact === null ? null : {
|
|
2096
|
+
snapshot: journal.source.compact.snapshot,
|
|
2097
|
+
size: journal.source.compact.size,
|
|
2098
|
+
sha256: journal.source.compact.sha256,
|
|
2099
|
+
},
|
|
2100
|
+
},
|
|
2101
|
+
target: {
|
|
2102
|
+
compact: {
|
|
2103
|
+
stageName: journal.target.compact.stageName,
|
|
2104
|
+
finalName: journal.target.compact.finalName,
|
|
2105
|
+
size: journal.target.compact.size,
|
|
2106
|
+
sha256: journal.target.compact.sha256,
|
|
2107
|
+
records: journal.target.compact.records,
|
|
2108
|
+
},
|
|
2109
|
+
archive: {
|
|
2110
|
+
stageName: journal.target.archive.stageName,
|
|
2111
|
+
finalName: journal.target.archive.finalName,
|
|
2112
|
+
size: journal.target.archive.size,
|
|
2113
|
+
sha256: journal.target.archive.sha256,
|
|
2114
|
+
},
|
|
2115
|
+
active: {
|
|
2116
|
+
stageName: journal.target.active.stageName,
|
|
2117
|
+
finalName: journal.target.active.finalName,
|
|
2118
|
+
size: journal.target.active.size,
|
|
2119
|
+
sha256: journal.target.active.sha256,
|
|
2120
|
+
},
|
|
2121
|
+
},
|
|
2122
|
+
};
|
|
2123
|
+
}
|
|
2124
|
+
function rotationTransactionId(journal) {
|
|
2125
|
+
return 'txn_' + createHash('sha256')
|
|
2126
|
+
.update(JSON.stringify(rotationJournalImmutable(journal)))
|
|
2127
|
+
.digest('hex');
|
|
2128
|
+
}
|
|
2129
|
+
function rotationJournalDigest(journal) {
|
|
2130
|
+
return createHash('sha256').update(JSON.stringify({
|
|
2131
|
+
...rotationJournalImmutable(journal),
|
|
2132
|
+
transactionId: journal.transactionId,
|
|
2133
|
+
phase: journal.phase,
|
|
2134
|
+
})).digest('hex');
|
|
2135
|
+
}
|
|
2136
|
+
function parseRotationJournal(value) {
|
|
2137
|
+
if (!isObject(value) || value['version'] !== 1)
|
|
2138
|
+
return null;
|
|
2139
|
+
const targetGeneration = typeof value['targetGeneration'] === 'string'
|
|
2140
|
+
&& ROTATION_GENERATION_PATTERN.test(value['targetGeneration'])
|
|
2141
|
+
? value['targetGeneration']
|
|
2142
|
+
: null;
|
|
2143
|
+
const transactionId = typeof value['transactionId'] === 'string'
|
|
2144
|
+
&& ROTATION_TRANSACTION_PATTERN.test(value['transactionId'])
|
|
2145
|
+
? value['transactionId']
|
|
2146
|
+
: null;
|
|
2147
|
+
const journalDigest = typeof value['journalDigest'] === 'string'
|
|
2148
|
+
&& /^[a-f0-9]{64}$/.test(value['journalDigest'])
|
|
2149
|
+
? value['journalDigest']
|
|
2150
|
+
: null;
|
|
2151
|
+
const phase = value['phase'] === 'prepared' || value['phase'] === 'committed'
|
|
2152
|
+
? value['phase']
|
|
2153
|
+
: null;
|
|
2154
|
+
const epochId = safeEpochId(value['epochId']);
|
|
2155
|
+
const createdAt = typeof value['createdAt'] === 'string' ? validIso(value['createdAt']) : null;
|
|
2156
|
+
if (!targetGeneration || !transactionId || !journalDigest
|
|
2157
|
+
|| !phase || !epochId || !createdAt)
|
|
2158
|
+
return null;
|
|
2159
|
+
const limitsValue = value['limits'];
|
|
2160
|
+
if (!isObject(limitsValue))
|
|
2161
|
+
return null;
|
|
2162
|
+
const maxActiveBytes = parseRotationLimit(limitsValue['maxActiveBytes']);
|
|
2163
|
+
const maxCompactBytes = parseRotationLimit(limitsValue['maxCompactBytes']);
|
|
2164
|
+
const maxLineBytes = parseRotationLimit(limitsValue['maxLineBytes']);
|
|
2165
|
+
const archiveRetention = parseRotationLimit(limitsValue['archiveRetention']);
|
|
2166
|
+
if (maxActiveBytes === null || maxCompactBytes === null || maxLineBytes === null
|
|
2167
|
+
|| archiveRetention === null)
|
|
2168
|
+
return null;
|
|
2169
|
+
const maxArchiveBytes = gzipRotationByteBound(maxActiveBytes);
|
|
2170
|
+
const maxCompactWithLineBytes = safeRotationByteSum(maxCompactBytes, maxLineBytes);
|
|
2171
|
+
if (maxArchiveBytes === null || maxCompactWithLineBytes === null)
|
|
2172
|
+
return null;
|
|
2173
|
+
const limits = {
|
|
2174
|
+
maxActiveBytes,
|
|
2175
|
+
maxCompactBytes,
|
|
2176
|
+
maxLineBytes,
|
|
2177
|
+
archiveRetention,
|
|
2178
|
+
};
|
|
2179
|
+
const sourceValue = value['source'];
|
|
2180
|
+
const targetValue = value['target'];
|
|
2181
|
+
if (!isObject(sourceValue) || !isObject(targetValue))
|
|
2182
|
+
return null;
|
|
2183
|
+
const activeSourceValue = sourceValue['active'];
|
|
2184
|
+
if (!isObject(activeSourceValue))
|
|
2185
|
+
return null;
|
|
2186
|
+
const activeSnapshot = parseGraphFileSnapshot(activeSourceValue['snapshot']);
|
|
2187
|
+
const activeDigest = parseRotationFileDigest(activeSourceValue, maxActiveBytes);
|
|
2188
|
+
const activeOffset = activeSourceValue['offset'];
|
|
2189
|
+
const activeSnapshotSize = activeSnapshot ? BigInt(activeSnapshot.size) : null;
|
|
2190
|
+
if (!activeSnapshot || !activeDigest || !Number.isSafeInteger(activeOffset)
|
|
2191
|
+
|| Number(activeOffset) < 0
|
|
2192
|
+
|| activeSnapshotSize === null
|
|
2193
|
+
|| activeSnapshotSize > BigInt(Number.MAX_SAFE_INTEGER)
|
|
2194
|
+
|| BigInt(Number(activeOffset)) + BigInt(activeDigest.size) !== activeSnapshotSize)
|
|
2195
|
+
return null;
|
|
2196
|
+
const activeSource = {
|
|
2197
|
+
snapshot: activeSnapshot,
|
|
2198
|
+
offset: Number(activeOffset),
|
|
2199
|
+
...activeDigest,
|
|
2200
|
+
};
|
|
2201
|
+
let compactSource = null;
|
|
2202
|
+
if (sourceValue['compact'] !== null) {
|
|
2203
|
+
if (!isObject(sourceValue['compact']))
|
|
2204
|
+
return null;
|
|
2205
|
+
const compactSnapshot = parseGraphFileSnapshot(sourceValue['compact']['snapshot']);
|
|
2206
|
+
const compactDigest = parseRotationFileDigest(sourceValue['compact'], maxCompactWithLineBytes);
|
|
2207
|
+
if (!compactSnapshot || !compactDigest
|
|
2208
|
+
|| compactSnapshot.size !== String(compactDigest.size))
|
|
2209
|
+
return null;
|
|
2210
|
+
compactSource = { snapshot: compactSnapshot, ...compactDigest };
|
|
2211
|
+
}
|
|
2212
|
+
const stages = rotationStageNames(targetGeneration);
|
|
2213
|
+
const compactTarget = parseRotationTarget(targetValue['compact'], maxCompactBytes, stages.compact, COMPACT_FILE);
|
|
2214
|
+
const archiveTarget = parseRotationTarget(targetValue['archive'], maxArchiveBytes, stages.archive, 'memory_graph.v2.' + targetGeneration + '.jsonl.gz');
|
|
2215
|
+
const activeTarget = parseRotationTarget(targetValue['active'], 0, stages.active, ACTIVE_FILE);
|
|
2216
|
+
const records = isObject(targetValue['compact']) ? targetValue['compact']['records'] : null;
|
|
2217
|
+
if (!compactTarget || !archiveTarget || !activeTarget
|
|
2218
|
+
|| !Number.isSafeInteger(records) || Number(records) < 0
|
|
2219
|
+
|| activeTarget.sha256 !== rotationFileDigest(Buffer.alloc(0)).sha256)
|
|
2220
|
+
return null;
|
|
2221
|
+
const journal = {
|
|
2222
|
+
version: 1,
|
|
2223
|
+
transactionId,
|
|
2224
|
+
journalDigest,
|
|
2225
|
+
targetGeneration,
|
|
2226
|
+
phase,
|
|
2227
|
+
epochId,
|
|
2228
|
+
createdAt,
|
|
2229
|
+
limits,
|
|
2230
|
+
source: { active: activeSource, compact: compactSource },
|
|
2231
|
+
target: {
|
|
2232
|
+
compact: { ...compactTarget, records: Number(records) },
|
|
2233
|
+
archive: archiveTarget,
|
|
2234
|
+
active: activeTarget,
|
|
2235
|
+
},
|
|
2236
|
+
};
|
|
2237
|
+
return rotationTransactionId(journal) === journal.transactionId
|
|
2238
|
+
&& rotationJournalDigest(journal) === journal.journalDigest
|
|
2239
|
+
? journal
|
|
2240
|
+
: null;
|
|
2241
|
+
}
|
|
2242
|
+
function parseRotationLimit(value) {
|
|
2243
|
+
return Number.isSafeInteger(value) && Number(value) > 0 ? Number(value) : null;
|
|
2244
|
+
}
|
|
2245
|
+
function safeRotationByteSum(left, right) {
|
|
2246
|
+
const sum = left + right;
|
|
2247
|
+
return Number.isSafeInteger(sum) ? sum : null;
|
|
2248
|
+
}
|
|
2249
|
+
function gzipRotationByteBound(sourceBytes) {
|
|
2250
|
+
if (!Number.isSafeInteger(sourceBytes) || sourceBytes < 0)
|
|
2251
|
+
return null;
|
|
2252
|
+
const source = BigInt(sourceBytes);
|
|
2253
|
+
// Mirrors zlib deflateBound's conservative stream bounds plus the gzip wrapper.
|
|
2254
|
+
const fixed = source + (source >> 3n) + (source >> 8n) + (source >> 9n) + 4n;
|
|
2255
|
+
const stored = source + (source >> 5n) + (source >> 7n) + (source >> 11n) + 7n;
|
|
2256
|
+
const bound = (fixed > stored ? fixed : stored) + 18n;
|
|
2257
|
+
return bound <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(bound) : null;
|
|
2258
|
+
}
|
|
2259
|
+
function parseRotationTarget(value, maxBytes, stageName, finalName) {
|
|
2260
|
+
if (!isObject(value) || value['stageName'] !== stageName || value['finalName'] !== finalName) {
|
|
2261
|
+
return null;
|
|
2262
|
+
}
|
|
2263
|
+
const digest = parseRotationFileDigest(value, maxBytes);
|
|
2264
|
+
return digest ? { stageName, finalName, ...digest } : null;
|
|
2265
|
+
}
|
|
2266
|
+
function parseRotationFileDigest(value, maxBytes) {
|
|
2267
|
+
if (!isObject(value))
|
|
2268
|
+
return null;
|
|
2269
|
+
const size = value['size'];
|
|
2270
|
+
const sha256 = value['sha256'];
|
|
2271
|
+
if (!Number.isSafeInteger(size) || Number(size) < 0 || Number(size) > maxBytes
|
|
2272
|
+
|| typeof sha256 !== 'string' || !/^[a-f0-9]{64}$/.test(sha256))
|
|
2273
|
+
return null;
|
|
2274
|
+
return { size: Number(size), sha256 };
|
|
2275
|
+
}
|
|
2276
|
+
const MEMORY_GRAPH_REASON_PATTERN = /scoped memory-graph outcome ([+-]\d+\.\d{3}) \(boost=([+-]?\d+\.\d{2})\)/;
|
|
2277
|
+
export function sanitizeMemoryGraphSelectionReason(value) {
|
|
2278
|
+
if (typeof value !== 'string')
|
|
2279
|
+
return undefined;
|
|
2280
|
+
const match = MEMORY_GRAPH_REASON_PATTERN.exec(value);
|
|
2281
|
+
if (!match?.[1] || !match[2])
|
|
2282
|
+
return undefined;
|
|
2283
|
+
const outcome = Number(match[1]);
|
|
2284
|
+
const boost = Number(match[2]);
|
|
2285
|
+
if (!Number.isFinite(outcome) || !Number.isFinite(boost) || Math.abs(outcome) > 1 || Math.abs(boost) > 1)
|
|
2286
|
+
return undefined;
|
|
2287
|
+
return `scoped memory-graph outcome ${match[1]} (boost=${match[2]})`;
|
|
2288
|
+
}
|
|
2289
|
+
export function formatMemoryGraphOperatorStatus(status) {
|
|
2290
|
+
const state = status.recovery === 'healthy' || status.recovery === 'degraded'
|
|
2291
|
+
|| status.recovery === 'recovered' || status.recovery === 'empty'
|
|
2292
|
+
? status.recovery
|
|
2293
|
+
: 'degraded';
|
|
2294
|
+
const reason = sanitizeMemoryGraphSelectionReason(status.selectionReason);
|
|
2295
|
+
return [
|
|
2296
|
+
`state=${state}`,
|
|
2297
|
+
...(status.busy === true ? ['busy=1'] : []),
|
|
2298
|
+
`corrupt=${boundedOperatorCount(status.corruptLines)}`,
|
|
2299
|
+
`oversized_lines=${boundedOperatorCount(status.oversizedLines)}`,
|
|
2300
|
+
`oversized_files=${boundedOperatorCount(status.oversizedFiles)}`,
|
|
2301
|
+
`archives=${boundedOperatorCount(status.archives)}`,
|
|
2302
|
+
...(reason ? [`selection=${reason}`] : []),
|
|
2303
|
+
].join(' ');
|
|
2304
|
+
}
|
|
2305
|
+
export function loadMemoryGraphOperatorStatus(env = process.env) {
|
|
2306
|
+
const home = events.evomapHome(env);
|
|
2307
|
+
const graphDir = join(home, 'evolution');
|
|
2308
|
+
let health;
|
|
2309
|
+
try {
|
|
2310
|
+
health = new LocalMemoryGraph({
|
|
2311
|
+
dir: graphDir,
|
|
2312
|
+
...resolveLocalMemoryUserIdentity(graphDir),
|
|
2313
|
+
}).inspectHealth();
|
|
2314
|
+
}
|
|
2315
|
+
catch {
|
|
2316
|
+
health = { ...emptyHealth(), recovery: 'degraded', corruptLines: 1 };
|
|
2317
|
+
}
|
|
2318
|
+
let selectionReason;
|
|
2319
|
+
try {
|
|
2320
|
+
const rootEvents = events.readEvents(join(home, 'evolution', 'root_events.jsonl'));
|
|
2321
|
+
for (let index = rootEvents.length - 1; index >= 0; index -= 1) {
|
|
2322
|
+
const event = rootEvents[index];
|
|
2323
|
+
if (event?.type !== 'decision.gene_selected')
|
|
2324
|
+
continue;
|
|
2325
|
+
selectionReason = sanitizeMemoryGraphSelectionReason(event.payload?.['selectedReason']);
|
|
2326
|
+
if (selectionReason)
|
|
2327
|
+
break;
|
|
2328
|
+
}
|
|
2329
|
+
}
|
|
2330
|
+
catch {
|
|
2331
|
+
// Health remains available even when the optional event rationale cannot be read.
|
|
2332
|
+
}
|
|
2333
|
+
return { ...health, ...(selectionReason ? { selectionReason } : {}) };
|
|
2334
|
+
}
|
|
2335
|
+
function parseV2Record(value) {
|
|
2336
|
+
if (!isObject(value) || value['version'] !== 2 || value['kind'] !== 'outcome')
|
|
2337
|
+
return null;
|
|
2338
|
+
const provenance = value['provenance'];
|
|
2339
|
+
if (provenance !== 'v2_local' && provenance !== 'v1_import')
|
|
2340
|
+
return null;
|
|
2341
|
+
const workspaceScope = safeToken(value['workspaceScope'], 128);
|
|
2342
|
+
const userScope = safeToken(value['userScope'], 128);
|
|
2343
|
+
const signalFingerprint = safeToken(value['signalFingerprint'], 4096);
|
|
2344
|
+
const geneId = typeof value['geneId'] === 'string' ? algo.safeMemoryGeneId(value['geneId']) : '';
|
|
2345
|
+
const status = value['status'];
|
|
2346
|
+
const at = typeof value['at'] === 'string' ? validIso(value['at']) : null;
|
|
2347
|
+
const hasEpoch = Object.prototype.hasOwnProperty.call(value, 'epochId');
|
|
2348
|
+
const epochId = hasEpoch ? safeEpochId(value['epochId']) : null;
|
|
2349
|
+
if (!workspaceScope || !userScope || !signalFingerprint || !geneId
|
|
2350
|
+
|| (status !== 'success' && status !== 'failed') || !at || (hasEpoch && !epochId))
|
|
2351
|
+
return null;
|
|
2352
|
+
return {
|
|
2353
|
+
version: 2,
|
|
2354
|
+
kind: 'outcome',
|
|
2355
|
+
provenance,
|
|
2356
|
+
workspaceScope,
|
|
2357
|
+
userScope,
|
|
2358
|
+
signalFingerprint,
|
|
2359
|
+
signals: algo.normalizeMemorySignals(Array.isArray(value['signals']) ? value['signals'].filter((item) => typeof item === 'string') : []),
|
|
2360
|
+
geneId,
|
|
2361
|
+
status,
|
|
2362
|
+
score: clampScore(Number(value['score'])),
|
|
2363
|
+
at,
|
|
2364
|
+
...(epochId ? { epochId } : {}),
|
|
2365
|
+
...(safeToken(value['sourceFingerprint'], 128) ? { sourceFingerprint: safeToken(value['sourceFingerprint'], 128) } : {}),
|
|
2366
|
+
...(safeToken(value['sourceScope'], 128) ? { sourceScope: safeToken(value['sourceScope'], 128) } : {}),
|
|
2367
|
+
...(safeToken(value['legacySourceFingerprint'], 128) ? { legacySourceFingerprint: safeToken(value['legacySourceFingerprint'], 128) } : {}),
|
|
2368
|
+
...(positiveCount(value['successCount']) !== undefined ? { successCount: positiveCount(value['successCount']) } : {}),
|
|
2369
|
+
...(positiveCount(value['failCount']) !== undefined ? { failCount: positiveCount(value['failCount']) } : {}),
|
|
2370
|
+
};
|
|
2371
|
+
}
|
|
2372
|
+
function sealV1OutcomePlan(summary, data) {
|
|
2373
|
+
const plan = Object.freeze({ ...summary });
|
|
2374
|
+
if (data)
|
|
2375
|
+
memoryGraphV1OutcomePlans.set(plan, data);
|
|
2376
|
+
return plan;
|
|
2377
|
+
}
|
|
2378
|
+
function collectImportFingerprints(records, workspaceScope, userScope, sourceScope) {
|
|
2379
|
+
const values = new Set();
|
|
2380
|
+
for (const record of records) {
|
|
2381
|
+
if (record.workspaceScope !== workspaceScope || record.userScope !== userScope)
|
|
2382
|
+
continue;
|
|
2383
|
+
if (record.sourceScope && record.sourceScope !== sourceScope)
|
|
2384
|
+
continue;
|
|
2385
|
+
addImportFingerprints(values, record);
|
|
2386
|
+
}
|
|
2387
|
+
return values;
|
|
2388
|
+
}
|
|
2389
|
+
function hasImportFingerprint(values, record) {
|
|
2390
|
+
return Boolean((record.sourceFingerprint && values.has(record.sourceFingerprint))
|
|
2391
|
+
|| (record.legacySourceFingerprint && values.has(record.legacySourceFingerprint)));
|
|
2392
|
+
}
|
|
2393
|
+
function addImportFingerprints(values, record) {
|
|
2394
|
+
if (record.sourceFingerprint)
|
|
2395
|
+
values.add(record.sourceFingerprint);
|
|
2396
|
+
if (record.legacySourceFingerprint)
|
|
2397
|
+
values.add(record.legacySourceFingerprint);
|
|
2398
|
+
}
|
|
2399
|
+
function parseV1Outcome(value, workspaceScope, userScope, sourceScope) {
|
|
2400
|
+
if (!workspaceScope || !isObject(value) || value['type'] !== 'MemoryGraphEvent' || value['kind'] !== 'outcome')
|
|
2401
|
+
return null;
|
|
2402
|
+
const gene = isObject(value['gene']) ? value['gene'] : null;
|
|
2403
|
+
const signal = isObject(value['signal']) ? value['signal'] : null;
|
|
2404
|
+
const outcome = isObject(value['outcome']) ? value['outcome'] : null;
|
|
2405
|
+
const geneId = typeof gene?.['id'] === 'string' ? algo.safeMemoryGeneId(gene['id']) : '';
|
|
2406
|
+
const status = outcome?.['status'];
|
|
2407
|
+
const at = typeof value['ts'] === 'string' ? validIso(value['ts']) : null;
|
|
2408
|
+
if (!geneId || (status !== 'success' && status !== 'failed') || !at)
|
|
2409
|
+
return null;
|
|
2410
|
+
const signals = algo.normalizeMemorySignals(Array.isArray(signal?.['signals']) ? signal['signals'].filter((item) => typeof item === 'string') : []);
|
|
2411
|
+
const score = clampScore(Number(outcome?.['score']));
|
|
2412
|
+
const legacySourceFingerprint = scopeHash(JSON.stringify({
|
|
2413
|
+
id: safeToken(value['id'], 240) ?? '',
|
|
2414
|
+
at,
|
|
2415
|
+
geneId,
|
|
2416
|
+
status,
|
|
2417
|
+
score,
|
|
2418
|
+
signals,
|
|
2419
|
+
}));
|
|
2420
|
+
const sourceFingerprint = scopeHash(JSON.stringify({
|
|
2421
|
+
workspaceScope,
|
|
2422
|
+
userScope,
|
|
2423
|
+
sourceScope,
|
|
2424
|
+
legacySourceFingerprint,
|
|
2425
|
+
}));
|
|
2426
|
+
return {
|
|
2427
|
+
version: 2,
|
|
2428
|
+
kind: 'outcome',
|
|
2429
|
+
provenance: 'v1_import',
|
|
2430
|
+
workspaceScope,
|
|
2431
|
+
userScope,
|
|
2432
|
+
sourceScope,
|
|
2433
|
+
signalFingerprint: algo.memorySignalFingerprint(signals),
|
|
2434
|
+
signals,
|
|
2435
|
+
geneId,
|
|
2436
|
+
status,
|
|
2437
|
+
score,
|
|
2438
|
+
at,
|
|
2439
|
+
sourceFingerprint,
|
|
2440
|
+
legacySourceFingerprint,
|
|
2441
|
+
};
|
|
2442
|
+
}
|
|
2443
|
+
function compactRecords(records, maxEdges) {
|
|
2444
|
+
const byEdge = new Map();
|
|
2445
|
+
for (const record of records) {
|
|
2446
|
+
const key = compactRecordKey(record);
|
|
2447
|
+
const current = byEdge.get(key);
|
|
2448
|
+
const successCount = (record.successCount ?? (record.status === 'success' ? 1 : 0)) + (current?.successCount ?? (current?.status === 'success' ? 1 : 0));
|
|
2449
|
+
const failCount = (record.failCount ?? (record.status === 'failed' ? 1 : 0)) + (current?.failCount ?? (current?.status === 'failed' ? 1 : 0));
|
|
2450
|
+
const newest = !current || Date.parse(record.at) >= Date.parse(current.at) ? record : current;
|
|
2451
|
+
byEdge.set(key, { ...newest, successCount, failCount });
|
|
2452
|
+
}
|
|
2453
|
+
return [...byEdge.values()]
|
|
2454
|
+
.sort((left, right) => Date.parse(right.at) - Date.parse(left.at) || left.geneId.localeCompare(right.geneId))
|
|
2455
|
+
.slice(0, maxEdges);
|
|
2456
|
+
}
|
|
2457
|
+
function compactRecordKey(record) {
|
|
2458
|
+
const epoch = recordEpochId(record);
|
|
2459
|
+
return record.provenance === 'v1_import' && record.sourceFingerprint
|
|
2460
|
+
? `${epoch}\u0000import\u0000${record.workspaceScope}\u0000${record.userScope}\u0000${record.sourceScope ?? 'legacy-unscoped'}\u0000${record.sourceFingerprint}`
|
|
2461
|
+
: `${epoch}\u0000${record.workspaceScope}\u0000${record.userScope}\u0000${record.signalFingerprint}\u0000${record.geneId}`;
|
|
2462
|
+
}
|
|
2463
|
+
function mergeRecoveryRecords(compact, archives, maxEdges) {
|
|
2464
|
+
const preserved = compactRecords(compact, compact.length);
|
|
2465
|
+
const preservedKeys = new Set(preserved.map(compactRecordKey));
|
|
2466
|
+
const recovered = compactRecords(archives, archives.length)
|
|
2467
|
+
.filter((record) => !preservedKeys.has(compactRecordKey(record)));
|
|
2468
|
+
return compactRecords([...preserved, ...recovered], maxEdges);
|
|
2469
|
+
}
|
|
2470
|
+
function fitCompactRecords(records, maxBytes) {
|
|
2471
|
+
const kept = [];
|
|
2472
|
+
const lines = [];
|
|
2473
|
+
let bytes = 0;
|
|
2474
|
+
for (const record of records) {
|
|
2475
|
+
const line = Buffer.from(`${JSON.stringify(record)}\n`, 'utf8');
|
|
2476
|
+
if (bytes + line.length > maxBytes)
|
|
2477
|
+
break;
|
|
2478
|
+
kept.push(record);
|
|
2479
|
+
lines.push(line);
|
|
2480
|
+
bytes += line.length;
|
|
2481
|
+
}
|
|
2482
|
+
return { records: kept, payload: Buffer.concat(lines, bytes) };
|
|
2483
|
+
}
|
|
2484
|
+
function emptyDiagnostics() {
|
|
2485
|
+
return { bytesRead: 0, recordsRead: 0, corruptLines: 0, oversizedLines: 0, scopeRejected: 0, provenanceRejected: 0, truncated: false, recovery: 'healthy' };
|
|
2486
|
+
}
|
|
2487
|
+
function mergeDiagnostics(target, source) {
|
|
2488
|
+
target.bytesRead += source.bytesRead;
|
|
2489
|
+
target.recordsRead += source.recordsRead;
|
|
2490
|
+
target.corruptLines += source.corruptLines;
|
|
2491
|
+
target.oversizedLines += source.oversizedLines;
|
|
2492
|
+
target.scopeRejected += source.scopeRejected;
|
|
2493
|
+
target.provenanceRejected += source.provenanceRejected;
|
|
2494
|
+
target.truncated ||= source.truncated;
|
|
2495
|
+
if (source.busy === true)
|
|
2496
|
+
target.busy = true;
|
|
2497
|
+
if (target.recovery !== 'recovered' && source.recovery !== 'healthy')
|
|
2498
|
+
target.recovery = source.recovery;
|
|
2499
|
+
}
|
|
2500
|
+
function emptyHealth() {
|
|
2501
|
+
return {
|
|
2502
|
+
recovery: 'empty',
|
|
2503
|
+
compactedRecords: 0,
|
|
2504
|
+
activeRecords: 0,
|
|
2505
|
+
corruptLines: 0,
|
|
2506
|
+
oversizedLines: 0,
|
|
2507
|
+
oversizedFiles: 0,
|
|
2508
|
+
archives: 0,
|
|
2509
|
+
};
|
|
2510
|
+
}
|
|
2511
|
+
function fileExceeds(path, maxBytes) {
|
|
2512
|
+
try {
|
|
2513
|
+
const stat = lstatSync(path);
|
|
2514
|
+
return stat.isFile() && !stat.isSymbolicLink() && stat.size > maxBytes;
|
|
2515
|
+
}
|
|
2516
|
+
catch {
|
|
2517
|
+
return false;
|
|
2518
|
+
}
|
|
2519
|
+
}
|
|
2520
|
+
function openNoFollow(path, flags, mode) {
|
|
2521
|
+
return openSync(path, flags | constants.O_NOFOLLOW, mode);
|
|
2522
|
+
}
|
|
2523
|
+
function writeAll(fd, payload, position = null) {
|
|
2524
|
+
let offset = 0;
|
|
2525
|
+
while (offset < payload.length) {
|
|
2526
|
+
const written = writeSync(fd, payload, offset, payload.length - offset, position === null ? null : position + offset);
|
|
2527
|
+
if (written <= 0)
|
|
2528
|
+
throw new Error('memory_graph_write_failed');
|
|
2529
|
+
offset += written;
|
|
2530
|
+
}
|
|
2531
|
+
}
|
|
2532
|
+
function sameGraphFileIdentity(left, right) {
|
|
2533
|
+
const hasStableFileId = left.dev !== 0n || left.ino !== 0n || right.dev !== 0n || right.ino !== 0n;
|
|
2534
|
+
if (hasStableFileId)
|
|
2535
|
+
return left.dev === right.dev && left.ino === right.ino;
|
|
2536
|
+
return left.birthtimeNs === right.birthtimeNs && left.mode === right.mode;
|
|
2537
|
+
}
|
|
2538
|
+
function sameGraphFileSnapshot(left, right) {
|
|
2539
|
+
return sameGraphFileIdentity(left, right)
|
|
2540
|
+
&& left.mode === right.mode
|
|
2541
|
+
&& left.size === right.size
|
|
2542
|
+
&& left.mtimeNs === right.mtimeNs
|
|
2543
|
+
&& left.ctimeNs === right.ctimeNs;
|
|
2544
|
+
}
|
|
2545
|
+
function serializeGraphFileSnapshot(stat) {
|
|
2546
|
+
return {
|
|
2547
|
+
dev: String(stat.dev),
|
|
2548
|
+
ino: String(stat.ino),
|
|
2549
|
+
birthtimeNs: String(stat.birthtimeNs),
|
|
2550
|
+
mode: String(stat.mode),
|
|
2551
|
+
size: String(stat.size),
|
|
2552
|
+
mtimeNs: String(stat.mtimeNs),
|
|
2553
|
+
ctimeNs: String(stat.ctimeNs),
|
|
2554
|
+
};
|
|
2555
|
+
}
|
|
2556
|
+
function serializedIdentityMatches(snapshot, stat) {
|
|
2557
|
+
const hasStableFileId = snapshot.dev !== '0' || snapshot.ino !== '0'
|
|
2558
|
+
|| stat.dev !== 0n || stat.ino !== 0n;
|
|
2559
|
+
if (hasStableFileId)
|
|
2560
|
+
return snapshot.dev === String(stat.dev) && snapshot.ino === String(stat.ino);
|
|
2561
|
+
return snapshot.birthtimeNs === String(stat.birthtimeNs) && snapshot.mode === String(stat.mode);
|
|
2562
|
+
}
|
|
2563
|
+
function serializedSnapshotMatches(snapshot, stat) {
|
|
2564
|
+
return serializedIdentityMatches(snapshot, stat)
|
|
2565
|
+
&& snapshot.mode === String(stat.mode)
|
|
2566
|
+
&& snapshot.size === String(stat.size)
|
|
2567
|
+
&& snapshot.mtimeNs === String(stat.mtimeNs)
|
|
2568
|
+
&& snapshot.ctimeNs === String(stat.ctimeNs);
|
|
2569
|
+
}
|
|
2570
|
+
function parseGraphFileSnapshot(value) {
|
|
2571
|
+
if (!isObject(value))
|
|
2572
|
+
return null;
|
|
2573
|
+
const fields = ['dev', 'ino', 'birthtimeNs', 'mode', 'size', 'mtimeNs', 'ctimeNs'];
|
|
2574
|
+
for (const field of fields) {
|
|
2575
|
+
const candidate = value[field];
|
|
2576
|
+
if (typeof candidate !== 'string' || !/^\d{1,40}$/.test(candidate))
|
|
2577
|
+
return null;
|
|
2578
|
+
}
|
|
2579
|
+
return {
|
|
2580
|
+
dev: value['dev'],
|
|
2581
|
+
ino: value['ino'],
|
|
2582
|
+
birthtimeNs: value['birthtimeNs'],
|
|
2583
|
+
mode: value['mode'],
|
|
2584
|
+
size: value['size'],
|
|
2585
|
+
mtimeNs: value['mtimeNs'],
|
|
2586
|
+
ctimeNs: value['ctimeNs'],
|
|
2587
|
+
};
|
|
2588
|
+
}
|
|
2589
|
+
function parseEpochBaseline(value) {
|
|
2590
|
+
if (!isObject(value) || !Object.prototype.hasOwnProperty.call(value, 'active')
|
|
2591
|
+
|| !Object.prototype.hasOwnProperty.call(value, 'compact')
|
|
2592
|
+
|| !Array.isArray(value['archives']))
|
|
2593
|
+
return null;
|
|
2594
|
+
let active = null;
|
|
2595
|
+
if (value['active'] !== null) {
|
|
2596
|
+
if (!isObject(value['active']))
|
|
2597
|
+
return null;
|
|
2598
|
+
const snapshot = parseGraphFileSnapshot(value['active']['snapshot']);
|
|
2599
|
+
const offset = value['active']['offset'];
|
|
2600
|
+
if (!snapshot || !Number.isSafeInteger(offset) || Number(offset) < 0
|
|
2601
|
+
|| snapshot.size !== String(offset))
|
|
2602
|
+
return null;
|
|
2603
|
+
active = { snapshot, offset: Number(offset) };
|
|
2604
|
+
}
|
|
2605
|
+
const compact = value['compact'] === null
|
|
2606
|
+
? null
|
|
2607
|
+
: parseGraphFileSnapshot(value['compact']);
|
|
2608
|
+
if (value['compact'] !== null && !compact)
|
|
2609
|
+
return null;
|
|
2610
|
+
const hasRecovery = Object.prototype.hasOwnProperty.call(value, 'recovery');
|
|
2611
|
+
const recovery = !hasRecovery || value['recovery'] === null
|
|
2612
|
+
? null
|
|
2613
|
+
: parseGraphFileSnapshot(value['recovery']);
|
|
2614
|
+
if (hasRecovery && value['recovery'] !== null && !recovery)
|
|
2615
|
+
return null;
|
|
2616
|
+
const archives = [];
|
|
2617
|
+
const names = new Set();
|
|
2618
|
+
for (const entry of value['archives']) {
|
|
2619
|
+
if (!isObject(entry) || typeof entry['name'] !== 'string'
|
|
2620
|
+
|| !ARCHIVE_PATTERN.test(entry['name']) || names.has(entry['name']))
|
|
2621
|
+
return null;
|
|
2622
|
+
const snapshot = parseGraphFileSnapshot(entry['snapshot']);
|
|
2623
|
+
if (!snapshot)
|
|
2624
|
+
return null;
|
|
2625
|
+
names.add(entry['name']);
|
|
2626
|
+
archives.push({ name: entry['name'], snapshot });
|
|
2627
|
+
}
|
|
2628
|
+
return { active, compact, ...(hasRecovery ? { recovery } : {}), archives };
|
|
2629
|
+
}
|
|
2630
|
+
function assertPathMissing(path, reason) {
|
|
2631
|
+
try {
|
|
2632
|
+
lstatSync(path);
|
|
2633
|
+
}
|
|
2634
|
+
catch (error) {
|
|
2635
|
+
if (isObject(error) && error['code'] === 'ENOENT')
|
|
2636
|
+
return;
|
|
2637
|
+
throw new Error(reason);
|
|
2638
|
+
}
|
|
2639
|
+
throw new Error(reason);
|
|
2640
|
+
}
|
|
2641
|
+
function recordEpochId(record) {
|
|
2642
|
+
return record.epochId ?? LEGACY_EPOCH_ID;
|
|
2643
|
+
}
|
|
2644
|
+
function readFdBytes(fd, length, position) {
|
|
2645
|
+
const buffer = Buffer.alloc(length);
|
|
2646
|
+
let offset = 0;
|
|
2647
|
+
while (offset < length) {
|
|
2648
|
+
const read = readSync(fd, buffer, offset, length - offset, position + offset);
|
|
2649
|
+
if (read === 0)
|
|
2650
|
+
break;
|
|
2651
|
+
offset += read;
|
|
2652
|
+
}
|
|
2653
|
+
return offset === length ? buffer : buffer.subarray(0, offset);
|
|
2654
|
+
}
|
|
2655
|
+
function scopeHash(value) {
|
|
2656
|
+
return `sha256:${createHash('sha256').update(value).digest('hex')}`;
|
|
2657
|
+
}
|
|
2658
|
+
function safeToken(value, maxChars) {
|
|
2659
|
+
if (typeof value !== 'string')
|
|
2660
|
+
return null;
|
|
2661
|
+
const trimmed = value.trim();
|
|
2662
|
+
return trimmed.length > 0 && trimmed.length <= maxChars ? trimmed : null;
|
|
2663
|
+
}
|
|
2664
|
+
function safeEpochId(value) {
|
|
2665
|
+
const token = safeToken(value, 128);
|
|
2666
|
+
return token && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(token) ? token : null;
|
|
2667
|
+
}
|
|
2668
|
+
function boundedOperatorCount(value) {
|
|
2669
|
+
const count = Number(value);
|
|
2670
|
+
return Number.isFinite(count) && count > 0 ? Math.min(1_000_000, Math.floor(count)) : 0;
|
|
2671
|
+
}
|
|
2672
|
+
function positiveCount(value) {
|
|
2673
|
+
const count = Number(value);
|
|
2674
|
+
return Number.isFinite(count) && count > 0 ? Math.min(1_000_000, Math.floor(count)) : undefined;
|
|
2675
|
+
}
|
|
2676
|
+
function positiveInt(value, fallback) {
|
|
2677
|
+
const parsed = Math.floor(Number(value));
|
|
2678
|
+
return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : fallback;
|
|
2679
|
+
}
|
|
2680
|
+
function clampScore(value) {
|
|
2681
|
+
return Number.isFinite(value) ? Math.max(0, Math.min(1, value)) : 0;
|
|
2682
|
+
}
|
|
2683
|
+
function validIso(value) {
|
|
2684
|
+
const parsed = Date.parse(value);
|
|
2685
|
+
return Number.isFinite(parsed) ? new Date(parsed).toISOString() : null;
|
|
2686
|
+
}
|
|
2687
|
+
function isObject(value) {
|
|
2688
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
2689
|
+
}
|