@evomap/evolver-cli 2.0.0-beta.17 → 2.0.0-beta.19

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.
Files changed (64) hide show
  1. package/dist/antiGeneRollout.js +7 -3
  2. package/dist/assetTrust.js +14 -1
  3. package/dist/atp.d.ts +8 -3
  4. package/dist/atp.js +82 -11
  5. package/dist/atpAutoBuyer.d.ts +120 -0
  6. package/dist/atpAutoBuyer.js +814 -0
  7. package/dist/atpAutoDeliver.js +2 -2
  8. package/dist/autoDistillLlm.js +2 -1
  9. package/dist/autoDistillTranscript.js +3 -2
  10. package/dist/autoexec.d.ts +90 -13
  11. package/dist/autoexec.js +731 -84
  12. package/dist/cli.js +13 -0
  13. package/dist/cliContracts.d.ts +5 -2
  14. package/dist/cliContracts.js +135 -8
  15. package/dist/commands.d.ts +1 -0
  16. package/dist/commands.js +1 -0
  17. package/dist/curriculumCapabilityGaps.d.ts +6 -0
  18. package/dist/curriculumCapabilityGaps.js +24 -0
  19. package/dist/cycleConsumer.d.ts +4 -0
  20. package/dist/cycleConsumer.js +175 -20
  21. package/dist/dashboard.js +47 -9
  22. package/dist/dispatch.js +6 -2
  23. package/dist/distillPrimitives.js +18 -6
  24. package/dist/doctor.js +63 -5
  25. package/dist/identityHome.js +2 -1
  26. package/dist/index.d.ts +67 -39
  27. package/dist/index.js +504 -185
  28. package/dist/learningTrace.d.ts +4 -0
  29. package/dist/learningTrace.js +30 -3
  30. package/dist/lifecycle.d.ts +54 -1
  31. package/dist/lifecycle.js +489 -37
  32. package/dist/materialSnapshot.d.ts +9 -1
  33. package/dist/materialSnapshot.js +23 -6
  34. package/dist/migrate/envTranslate.d.ts +26 -0
  35. package/dist/migrate/envTranslate.js +145 -0
  36. package/dist/migrate/oauthImport.d.ts +66 -0
  37. package/dist/migrate/oauthImport.js +667 -0
  38. package/dist/migrate/v1Import.d.ts +13 -1
  39. package/dist/migrate/v1Import.js +621 -122
  40. package/dist/promptRecallHook.d.ts +24 -0
  41. package/dist/promptRecallHook.js +425 -0
  42. package/dist/recallVerifyReport.d.ts +37 -0
  43. package/dist/recallVerifyReport.js +244 -0
  44. package/dist/requiredSandboxValidation.d.ts +5 -0
  45. package/dist/requiredSandboxValidation.js +4 -0
  46. package/dist/reuse.d.ts +1 -0
  47. package/dist/reuse.js +45 -37
  48. package/dist/runtimeCapabilities.js +13 -13
  49. package/dist/runtimeSessionSource.d.ts +3 -2
  50. package/dist/runtimeSessionSource.js +63 -11
  51. package/dist/sessionIngest.d.ts +37 -0
  52. package/dist/sessionIngest.js +156 -0
  53. package/dist/setupHooks.js +95 -1
  54. package/dist/skill2gep.d.ts +4 -7
  55. package/dist/skill2gep.js +4 -21
  56. package/dist/solo/mode.js +1 -0
  57. package/dist/sync.js +125 -23
  58. package/dist/thesis.d.ts +1 -1
  59. package/dist/thesis.js +18 -3
  60. package/dist/trajectoryExport.js +21 -3
  61. package/dist/v1Compat.d.ts +1 -0
  62. package/dist/v1Compat.js +9 -0
  63. package/dist/workflowRuntime.js +24 -18
  64. package/package.json +10 -7
@@ -1,21 +1,24 @@
1
- import { createHash } from 'node:crypto';
2
- import { createReadStream } from 'node:fs';
3
- import { appendFileSync, closeSync, constants, existsSync, fstatSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, readSync, realpathSync, unlinkSync, writeFileSync, writeSync, } from 'node:fs';
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { chmodSync, closeSync, constants, existsSync, fstatSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, readSync, realpathSync, renameSync, unlinkSync, writeFileSync, writeSync, } from 'node:fs';
4
3
  import { basename, dirname, join, resolve, sep } from 'node:path';
5
- import { assetstore } from '@evomap/evolver-core';
4
+ import { assetstore, mailbox, util } from '@evomap/evolver-core';
6
5
  import { mapV1Asset } from './fieldMap.js';
7
6
  import { LocalMemoryGraph, MemoryGraphBusyError, MemoryGraphImportStateRejectedError, resolveLocalMemoryUserId, } from '../localMemoryGraph.js';
8
7
  const FILES = { Gene: 'genes.jsonl', Capsule: 'capsules.jsonl', EvolutionEvent: 'events.jsonl' };
9
8
  const DEFAULT_IMPORT_JSONL_MAX_LINE_BYTES = 16 * 1024 * 1024;
10
- let migrationArchiveNonce = 0;
9
+ const JSONL_READ_CHUNK_BYTES = 64 * 1024;
11
10
  function maxJsonlLineBytes() {
12
11
  const raw = Number(process.env['EVOLVER_IMPORT_JSONL_MAX_LINE_BYTES']);
13
12
  return Number.isFinite(raw) && raw > 0 ? Math.floor(raw) : DEFAULT_IMPORT_JSONL_MAX_LINE_BYTES;
14
13
  }
15
- async function* readJsonl(path) {
16
- if (!existsSync(path))
14
+ async function* readJsonl(source) {
15
+ if (typeof source === 'string' && !existsSync(source))
17
16
  return;
18
17
  const maxLineBytes = maxJsonlLineBytes();
18
+ const buffer = Buffer.allocUnsafe(JSONL_READ_CHUNK_BYTES);
19
+ let fd;
20
+ let ownsFd = false;
21
+ let position = 0;
19
22
  let parts = [];
20
23
  let lineBytes = 0;
21
24
  let dropping = false;
@@ -32,18 +35,47 @@ async function* readJsonl(path) {
32
35
  if (!text)
33
36
  return;
34
37
  try {
35
- yield JSON.parse(text);
38
+ const parsed = JSON.parse(text);
39
+ if (isPlainRecord(parsed))
40
+ yield parsed;
36
41
  }
37
42
  catch { /* skip corrupt rows */ }
38
43
  };
39
- for await (const chunk of createReadStream(path)) {
40
- const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
41
- let start = 0;
42
- for (let i = 0; i < buf.length; i += 1) {
43
- if (buf[i] !== 0x0a)
44
- continue;
45
- const segment = buf.subarray(start, i);
46
- if (!dropping) {
44
+ try {
45
+ if (typeof source === 'number') {
46
+ fd = source;
47
+ }
48
+ else {
49
+ fd = openSync(source, constants.O_RDONLY | noFollowFlag());
50
+ ownsFd = true;
51
+ }
52
+ for (;;) {
53
+ const bytesRead = readSync(fd, buffer, 0, buffer.length, position);
54
+ if (bytesRead === 0)
55
+ break;
56
+ position += bytesRead;
57
+ let start = 0;
58
+ for (let i = 0; i < bytesRead; i += 1) {
59
+ if (buffer[i] !== 0x0a)
60
+ continue;
61
+ const segment = buffer.subarray(start, i);
62
+ if (!dropping) {
63
+ if (lineBytes + segment.length > maxLineBytes) {
64
+ parts = [];
65
+ lineBytes = 0;
66
+ dropping = true;
67
+ }
68
+ else {
69
+ parts.push(Buffer.from(segment));
70
+ lineBytes += segment.length;
71
+ }
72
+ }
73
+ for (const record of finish())
74
+ yield record;
75
+ start = i + 1;
76
+ }
77
+ if (start < bytesRead && !dropping) {
78
+ const segment = buffer.subarray(start, bytesRead);
47
79
  if (lineBytes + segment.length > maxLineBytes) {
48
80
  parts = [];
49
81
  lineBytes = 0;
@@ -54,86 +86,118 @@ async function* readJsonl(path) {
54
86
  lineBytes += segment.length;
55
87
  }
56
88
  }
57
- for (const record of finish())
58
- yield record;
59
- start = i + 1;
60
- }
61
- if (start < buf.length && !dropping) {
62
- const segment = buf.subarray(start);
63
- if (lineBytes + segment.length > maxLineBytes) {
64
- parts = [];
65
- lineBytes = 0;
66
- dropping = true;
67
- }
68
- else {
69
- parts.push(Buffer.from(segment));
70
- lineBytes += segment.length;
71
- }
72
89
  }
90
+ for (const record of finish())
91
+ yield record;
92
+ }
93
+ finally {
94
+ if (ownsFd && fd !== undefined)
95
+ closeSync(fd);
73
96
  }
74
- for (const record of finish())
75
- yield record;
76
97
  }
77
98
  export async function importV1(v1Dir, store, outDir, options = {}) {
78
- const sidecarPath = join(outDir, 'migration', 'v1_extensions.jsonl');
99
+ const roots = validateMigrationRoots(v1Dir, outDir);
100
+ const outputRoot = secureOutputRoot(outDir);
101
+ assertMigrationRootsDisjoint(roots.sourceRoot, outputRoot);
102
+ const migrationDir = ensureSafeOutputDirectory(outputRoot, join(outputRoot, 'migration'));
103
+ const snapshotDir = ensureSafeOutputDirectory(outputRoot, join(migrationDir, '.snapshots'));
104
+ const sidecarPath = join(migrationDir, 'v1_extensions.jsonl');
79
105
  const rep = {
80
106
  imported: { Gene: 0, Capsule: 0, EvolutionEvent: 0 }, frozen: 0, recomputed: 0, deduped: 0,
81
107
  sidecarExtensions: 0, memoryGraphArchived: false, memoryGraphImported: 0, memoryGraphDeferred: false, candidatesSkipped: false,
108
+ mailboxFound: false, mailboxImported: 0,
82
109
  };
83
110
  const gepDir = join(v1Dir, 'assets', 'gep');
84
111
  for (const kind of ['Gene', 'Capsule', 'EvolutionEvent']) {
85
- for await (const v1 of readJsonl(join(gepDir, FILES[kind]))) {
86
- const mapped = mapV1Asset(kind, v1);
87
- const res = await store.putFrozen(mapped.record);
88
- if (res.stored) {
89
- rep.imported[kind] += 1;
90
- if (mapped.recomputed)
91
- rep.recomputed += 1;
92
- else
93
- rep.frozen += 1;
112
+ const sourcePath = join(gepDir, FILES[kind]);
113
+ const source = secureRegularFileWithin(v1Dir, sourcePath);
114
+ if (!source)
115
+ continue;
116
+ const snapshot = createMigrationSnapshot(source, snapshotDir, FILES[kind], options.sourceSnapshotTestHook);
117
+ try {
118
+ for await (const v1 of readJsonl(snapshot.fd)) {
119
+ const mapped = mapV1Asset(kind, v1);
94
120
  if (Object.keys(mapped.dropped).length > 0) {
95
- mkdirSync(dirname(sidecarPath), { recursive: true });
96
- appendFileSync(sidecarPath, `${JSON.stringify({ asset_id: res.asset_id, dropped: mapped.dropped })}\n`);
97
- rep.sidecarExtensions += 1;
121
+ const assetId = String(mapped.record['asset_id'] ?? '');
122
+ if (await ensureMigrationExtension(sidecarPath, assetId, mapped.dropped, options.sidecarAppendTestHook)) {
123
+ rep.sidecarExtensions += 1;
124
+ }
125
+ }
126
+ const res = await store.putFrozen(mapped.record);
127
+ if (res.stored) {
128
+ rep.imported[kind] += 1;
129
+ if (mapped.recomputed)
130
+ rep.recomputed += 1;
131
+ else
132
+ rep.frozen += 1;
133
+ }
134
+ else {
135
+ rep.deduped += 1;
98
136
  }
99
137
  }
100
- else {
101
- rep.deduped += 1;
102
- }
138
+ }
139
+ finally {
140
+ closeMigrationSnapshot(snapshot);
141
+ }
142
+ }
143
+ const mailboxSource = join(v1Dir, 'mailbox', 'messages.jsonl');
144
+ const securedMailboxSource = secureRegularFileWithin(v1Dir, mailboxSource);
145
+ if (securedMailboxSource) {
146
+ rep.mailboxFound = true;
147
+ const mailboxSnapshot = createMigrationSnapshot(securedMailboxSource, snapshotDir, 'mailbox_messages.jsonl', options.sourceSnapshotTestHook);
148
+ const proxyDir = ensureSafeOutputDirectory(outputRoot, join(outputRoot, 'proxy'));
149
+ const mailboxPath = join(proxyDir, 'mailbox.db');
150
+ let target;
151
+ try {
152
+ assertSafeMailboxTarget(mailboxPath);
153
+ target = new mailbox.MailboxStore({ path: mailboxPath });
154
+ assertSafeMailboxTarget(mailboxPath);
155
+ rep.mailboxImported = target.importJsonl(mailboxSnapshot.fd);
156
+ }
157
+ finally {
158
+ target?.close();
159
+ closeMigrationSnapshot(mailboxSnapshot);
103
160
  }
104
161
  }
105
162
  // memory_graph remains a sidecar: never convert it into EvolutionEvent or mutate Gene/Capsule identity.
106
163
  const mg = join(v1Dir, 'memory', 'evolution', 'memory_graph.jsonl');
107
- if (secureRegularFileWithin(v1Dir, mg)) {
108
- const dest = join(outDir, 'migration', 'legacy_memory_graph.jsonl');
109
- mkdirSync(dirname(dest), { recursive: true });
110
- archiveRegularFile(mg, dest);
111
- rep.memoryGraphArchived = true;
112
- const workspace = options.workspace ? canonicalDirectory(options.workspace) : null;
113
- if (!workspace) {
114
- rep.memoryGraphDeferred = true;
115
- }
116
- else {
117
- const source = realpathSync(mg);
118
- const userId = options.userId ?? resolveLocalMemoryUserId();
119
- const marker = scopedMemoryGraphMarker(outDir, workspace, userId, source);
120
- if (!existsSync(marker)) {
121
- const graph = new LocalMemoryGraph({ dir: join(outDir, 'evolution'), userId });
122
- try {
123
- for await (const record of readJsonl(mg)) {
124
- if (graph.importV1Outcome(workspace, record, source))
125
- rep.memoryGraphImported += 1;
164
+ const securedMemoryGraph = secureRegularFileWithin(v1Dir, mg);
165
+ if (securedMemoryGraph) {
166
+ const memorySnapshot = createMigrationSnapshot(securedMemoryGraph, snapshotDir, 'memory_graph.jsonl', options.sourceSnapshotTestHook);
167
+ try {
168
+ archiveMemoryGraphSnapshot(memorySnapshot, migrationDir);
169
+ rep.memoryGraphArchived = true;
170
+ const workspace = options.workspace ? canonicalDirectory(options.workspace) : null;
171
+ if (!workspace) {
172
+ rep.memoryGraphDeferred = true;
173
+ }
174
+ else {
175
+ const source = securedMemoryGraph.canonicalPath;
176
+ const userId = options.userId ?? resolveLocalMemoryUserId();
177
+ const marker = scopedMemoryGraphMarker(migrationDir, workspace, userId, source, memorySnapshot.digest);
178
+ if (!hasSafeMemoryGraphMarker(marker)) {
179
+ const evolutionDir = ensureSafeOutputDirectory(outputRoot, join(outputRoot, 'evolution'));
180
+ const graph = new LocalMemoryGraph({ dir: evolutionDir, userId });
181
+ try {
182
+ for await (const record of readJsonl(memorySnapshot.fd)) {
183
+ if (graph.importV1Outcome(workspace, record, source))
184
+ rep.memoryGraphImported += 1;
185
+ }
186
+ }
187
+ catch (error) {
188
+ if (!(error instanceof MemoryGraphImportStateRejectedError) && !(error instanceof MemoryGraphBusyError))
189
+ throw error;
190
+ rep.memoryGraphDeferred = true;
191
+ }
192
+ if (!rep.memoryGraphDeferred) {
193
+ writeMemoryGraphMarker(marker, `${rep.memoryGraphImported}\n`, options.memoryGraphMarkerTestHook);
126
194
  }
127
195
  }
128
- catch (error) {
129
- if (!(error instanceof MemoryGraphImportStateRejectedError) && !(error instanceof MemoryGraphBusyError))
130
- throw error;
131
- rep.memoryGraphDeferred = true;
132
- }
133
- if (!rep.memoryGraphDeferred)
134
- writeFileSync(marker, `${rep.memoryGraphImported}\n`, { mode: 0o600 });
135
196
  }
136
197
  }
198
+ finally {
199
+ closeMigrationSnapshot(memorySnapshot);
200
+ }
137
201
  }
138
202
  // candidates 候选池非 wire 资产 → 不迁移(留作 selection 输入)
139
203
  if (existsSync(join(gepDir, 'candidates.jsonl')))
@@ -150,90 +214,525 @@ function canonicalDirectory(path) {
150
214
  return null;
151
215
  }
152
216
  }
153
- function scopedMemoryGraphMarker(outDir, workspace, userId, source) {
154
- const scope = createHash('sha256').update(JSON.stringify({ workspace, userId, source })).digest('hex');
155
- return join(outDir, 'migration', `v1_memory_graph_import.${scope}.complete`);
217
+ function isPlainRecord(value) {
218
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
219
+ }
220
+ function pathWithin(root, candidate) {
221
+ const comparableRoot = process.platform === 'win32' ? root.toLowerCase() : root;
222
+ const comparableCandidate = process.platform === 'win32' ? candidate.toLowerCase() : candidate;
223
+ const prefix = comparableRoot.endsWith(sep) ? comparableRoot : `${comparableRoot}${sep}`;
224
+ return comparableCandidate === comparableRoot || comparableCandidate.startsWith(prefix);
225
+ }
226
+ function canonicalProspectiveDirectory(path) {
227
+ let cursor = resolve(path);
228
+ const missing = [];
229
+ for (;;) {
230
+ try {
231
+ const stat = lstatSync(cursor);
232
+ if (!stat.isDirectory() || stat.isSymbolicLink())
233
+ throw new Error('migration_output_path_rejected');
234
+ return resolve(realpathSync(cursor), ...missing.reverse());
235
+ }
236
+ catch (error) {
237
+ if (error.code !== 'ENOENT')
238
+ throw error;
239
+ const parent = dirname(cursor);
240
+ if (parent === cursor)
241
+ throw new Error('migration_output_path_rejected');
242
+ missing.push(basename(cursor));
243
+ cursor = parent;
244
+ }
245
+ }
246
+ }
247
+ function assertMigrationRootsDisjoint(sourceRoot, outputRoot) {
248
+ if (pathWithin(sourceRoot, outputRoot) || pathWithin(outputRoot, sourceRoot)) {
249
+ throw new Error('migration_output_overlaps_source');
250
+ }
251
+ }
252
+ export function validateMigrationRoots(v1Dir, outDir) {
253
+ const sourceRoot = canonicalDirectory(v1Dir);
254
+ if (!sourceRoot)
255
+ throw new Error('migration_source_path_rejected');
256
+ const outputRoot = canonicalProspectiveDirectory(outDir);
257
+ assertMigrationRootsDisjoint(sourceRoot, outputRoot);
258
+ return { sourceRoot, outputRoot };
259
+ }
260
+ function secureOutputRoot(path) {
261
+ const absolute = resolve(path);
262
+ mkdirSync(absolute, { recursive: true, mode: 0o700 });
263
+ const stat = lstatSync(absolute);
264
+ if (!stat.isDirectory() || stat.isSymbolicLink())
265
+ throw new Error('migration_output_path_rejected');
266
+ return realpathSync(absolute);
267
+ }
268
+ function ensureSafeOutputDirectory(root, requested) {
269
+ const absolute = resolve(requested);
270
+ if (!pathWithin(root, absolute))
271
+ throw new Error('migration_output_path_rejected');
272
+ const relative = absolute.slice(root.length).split(sep).filter(Boolean);
273
+ let current = root;
274
+ for (const segment of relative) {
275
+ const next = join(current, segment);
276
+ try {
277
+ const stat = lstatSync(next);
278
+ if (!stat.isDirectory() || stat.isSymbolicLink())
279
+ throw new Error('migration_output_path_rejected');
280
+ }
281
+ catch (error) {
282
+ if (error.code !== 'ENOENT')
283
+ throw error;
284
+ mkdirSync(next, { mode: 0o700 });
285
+ const created = lstatSync(next);
286
+ if (!created.isDirectory() || created.isSymbolicLink())
287
+ throw new Error('migration_output_path_rejected');
288
+ }
289
+ const canonical = realpathSync(next);
290
+ if (!pathWithin(root, canonical))
291
+ throw new Error('migration_output_path_rejected');
292
+ current = canonical;
293
+ }
294
+ return current;
295
+ }
296
+ async function ensureMigrationExtension(path, assetId, dropped, testHook) {
297
+ if (!assetId)
298
+ throw new Error('migration_extension_asset_id_missing');
299
+ const lockPath = `${path}.lock`;
300
+ util.acquireLock(lockPath, { maxTries: 300, waitMs: 10 });
301
+ let result;
302
+ let operationError;
303
+ try {
304
+ result = await ensureMigrationExtensionLocked(path, assetId, dropped, testHook);
305
+ }
306
+ catch (error) {
307
+ operationError = error;
308
+ }
309
+ const released = util.releaseLock(lockPath);
310
+ if (!released.released)
311
+ throw new Error('migration_extension_lock_release_failed');
312
+ if (operationError !== undefined)
313
+ throw operationError;
314
+ return result;
315
+ }
316
+ async function ensureMigrationExtensionLocked(path, assetId, dropped, testHook) {
317
+ if (existsSync(path)) {
318
+ const before = lstatSync(path);
319
+ if (!before.isFile() || before.isSymbolicLink())
320
+ throw new Error('migration_extension_path_rejected');
321
+ const fd = openSync(path, constants.O_RDONLY | noFollowFlag());
322
+ try {
323
+ const opened = fstatSync(fd);
324
+ if (!opened.isFile() || opened.dev !== before.dev || opened.ino !== before.ino) {
325
+ throw new Error('migration_extension_path_rejected');
326
+ }
327
+ for await (const record of readJsonl(fd)) {
328
+ if (record['asset_id'] !== assetId)
329
+ continue;
330
+ if (JSON.stringify(record['dropped']) !== JSON.stringify(dropped)) {
331
+ throw new Error('migration_extension_content_conflict');
332
+ }
333
+ return false;
334
+ }
335
+ }
336
+ finally {
337
+ closeSync(fd);
338
+ }
339
+ }
340
+ testHook?.('before-append', path);
341
+ const fd = openSync(path, constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT | noFollowFlag(), 0o600);
342
+ try {
343
+ if (!fstatSync(fd).isFile())
344
+ throw new Error('migration_extension_path_rejected');
345
+ writeFileSync(fd, `${JSON.stringify({ asset_id: assetId, dropped })}\n`, 'utf8');
346
+ fsyncSync(fd);
347
+ }
348
+ finally {
349
+ closeSync(fd);
350
+ }
351
+ testHook?.('after-append', path);
352
+ return true;
353
+ }
354
+ function scopedMemoryGraphMarker(migrationDir, workspace, userId, source, sourceDigest) {
355
+ const scope = createHash('sha256').update(JSON.stringify({ workspace, userId, source, sourceDigest })).digest('hex');
356
+ return join(migrationDir, `v1_memory_graph_import.${scope}.complete`);
357
+ }
358
+ function assertSafeMailboxTarget(path) {
359
+ try {
360
+ const stat = lstatSync(path);
361
+ if (!stat.isFile() || stat.isSymbolicLink())
362
+ throw new Error('migration_mailbox_path_rejected');
363
+ }
364
+ catch (error) {
365
+ if (error.code !== 'ENOENT')
366
+ throw error;
367
+ }
368
+ }
369
+ function hasSafeMemoryGraphMarker(path) {
370
+ let fd;
371
+ try {
372
+ const stat = lstatSync(path);
373
+ if (!stat.isFile() || stat.isSymbolicLink())
374
+ throw new Error('migration_memory_graph_marker_path_rejected');
375
+ fd = openSync(path, constants.O_RDONLY | noFollowFlag());
376
+ const opened = fstatSync(fd);
377
+ if (!opened.isFile() || opened.size < 2 || opened.size > 64) {
378
+ throw new Error('migration_memory_graph_marker_invalid');
379
+ }
380
+ const buffer = Buffer.alloc(opened.size);
381
+ if (readSync(fd, buffer, 0, buffer.length, 0) !== buffer.length || !/^(0|[1-9]\d*)\n$/.test(buffer.toString('utf8'))) {
382
+ throw new Error('migration_memory_graph_marker_invalid');
383
+ }
384
+ return true;
385
+ }
386
+ catch (error) {
387
+ if (error.code === 'ENOENT')
388
+ return false;
389
+ throw error;
390
+ }
391
+ finally {
392
+ if (fd !== undefined)
393
+ closeSync(fd);
394
+ }
395
+ }
396
+ function writeMemoryGraphMarker(path, content, testHook) {
397
+ const temporaryPath = `${path}.${randomUUID()}.tmp`;
398
+ let fd;
399
+ let operationError;
400
+ try {
401
+ fd = openSync(temporaryPath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | noFollowFlag(), 0o600);
402
+ if (!fstatSync(fd).isFile())
403
+ throw new Error('migration_memory_graph_marker_path_rejected');
404
+ const data = Buffer.from(content, 'utf8');
405
+ let offset = 0;
406
+ while (offset < data.length) {
407
+ const written = writeSync(fd, data, offset, data.length - offset, offset);
408
+ if (written <= 0)
409
+ throw new Error('migration_memory_graph_marker_write_failed');
410
+ offset += written;
411
+ }
412
+ fsyncSync(fd);
413
+ closeSync(fd);
414
+ fd = undefined;
415
+ testHook?.('before-publish', temporaryPath, path);
416
+ try {
417
+ linkSync(temporaryPath, path);
418
+ }
419
+ catch (error) {
420
+ if (error.code !== 'EEXIST' || !hasSafeMemoryGraphMarker(path))
421
+ throw error;
422
+ }
423
+ if (!hasSafeMemoryGraphMarker(path))
424
+ throw new Error('migration_memory_graph_marker_invalid');
425
+ }
426
+ catch (error) {
427
+ operationError = error;
428
+ }
429
+ let cleanupError;
430
+ if (fd !== undefined) {
431
+ try {
432
+ closeSync(fd);
433
+ }
434
+ catch (error) {
435
+ cleanupError = error;
436
+ }
437
+ }
438
+ try {
439
+ unlinkSync(temporaryPath);
440
+ }
441
+ catch (error) {
442
+ if (error.code !== 'ENOENT' && cleanupError === undefined)
443
+ cleanupError = error;
444
+ }
445
+ if (operationError !== undefined) {
446
+ if (operationError instanceof Error && cleanupError !== undefined) {
447
+ operationError.cleanupError = cleanupError;
448
+ }
449
+ throw operationError;
450
+ }
451
+ if (cleanupError !== undefined)
452
+ throw cleanupError;
156
453
  }
157
454
  function secureRegularFileWithin(root, path) {
158
455
  try {
159
456
  const absoluteRoot = resolve(root);
160
457
  const absolutePath = resolve(path);
161
458
  const rootStat = lstatSync(absoluteRoot);
162
- const fileStat = lstatSync(absolutePath);
459
+ const fileStat = lstatSync(absolutePath, { bigint: true });
163
460
  if (!rootStat.isDirectory() || rootStat.isSymbolicLink() || !fileStat.isFile() || fileStat.isSymbolicLink())
164
- return false;
461
+ return null;
165
462
  const canonicalRoot = realpathSync(absoluteRoot);
166
463
  const canonicalPath = realpathSync(absolutePath);
167
- return canonicalPath.startsWith(canonicalRoot.endsWith(sep) ? canonicalRoot : `${canonicalRoot}${sep}`);
464
+ if (!canonicalPath.startsWith(canonicalRoot.endsWith(sep) ? canonicalRoot : `${canonicalRoot}${sep}`))
465
+ return null;
466
+ return { requestedPath: absolutePath, canonicalPath, stat: fileStat };
168
467
  }
169
468
  catch {
170
- return false;
469
+ return null;
171
470
  }
172
471
  }
173
- function archiveRegularFile(source, destination) {
174
- if (existsSync(destination)) {
175
- const existing = lstatSync(destination);
176
- if (!existing.isFile() || existing.isSymbolicLink())
177
- throw new Error('memory_graph_archive_path_rejected');
178
- return;
472
+ function sameMigrationSourceIdentity(left, right) {
473
+ const hasStableFileId = left.dev !== 0n || left.ino !== 0n || right.dev !== 0n || right.ino !== 0n;
474
+ if (hasStableFileId)
475
+ return left.dev === right.dev && left.ino === right.ino;
476
+ return left.birthtimeNs === right.birthtimeNs && left.mode === right.mode;
477
+ }
478
+ function sameMigrationSourceSnapshot(left, right) {
479
+ return sameMigrationSourceIdentity(left, right)
480
+ && left.size === right.size
481
+ && left.mtimeNs === right.mtimeNs
482
+ && left.ctimeNs === right.ctimeNs;
483
+ }
484
+ function noFollowFlag() {
485
+ return process.platform !== 'win32' && typeof constants.O_NOFOLLOW === 'number'
486
+ ? constants.O_NOFOLLOW
487
+ : 0;
488
+ }
489
+ function createMigrationSnapshot(source, snapshotDir, label, testHook) {
490
+ const snapshotDirStat = lstatSync(snapshotDir);
491
+ if (!snapshotDirStat.isDirectory() || snapshotDirStat.isSymbolicLink()) {
492
+ throw new Error('migration_snapshot_dir_rejected');
179
493
  }
180
- const sourceFd = openSync(source, constants.O_RDONLY | constants.O_NOFOLLOW);
181
- const temp = join(dirname(destination), `.${basename(destination)}.${process.pid}.${Date.now()}.${migrationArchiveNonce++}.tmp`);
182
- let tempFd;
183
- let copyError;
494
+ const snapshotPath = join(snapshotDir, `.${basename(label)}.${randomUUID()}.tmp`);
495
+ testHook?.('before-open', source.requestedPath);
496
+ const sourceFd = openSync(source.canonicalPath, constants.O_RDONLY | noFollowFlag());
497
+ let writerFd;
498
+ let readerFd;
499
+ let snapshotIdentity;
500
+ let completed = false;
184
501
  try {
185
- if (!fstatSync(sourceFd).isFile())
186
- throw new Error('memory_graph_source_path_rejected');
187
- tempFd = openSync(temp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
502
+ const opened = fstatSync(sourceFd, { bigint: true });
503
+ if (!opened.isFile() || !sameMigrationSourceSnapshot(source.stat, opened)) {
504
+ throw new Error('migration_source_changed');
505
+ }
506
+ testHook?.('after-open', source.requestedPath);
507
+ writerFd = openSync(snapshotPath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | noFollowFlag(), 0o600);
508
+ const digest = createHash('sha256');
188
509
  const buffer = Buffer.alloc(64 * 1024);
510
+ let snapshotOffset = 0;
189
511
  for (;;) {
190
512
  const bytesRead = readSync(sourceFd, buffer, 0, buffer.length, null);
191
513
  if (bytesRead === 0)
192
514
  break;
515
+ digest.update(buffer.subarray(0, bytesRead));
193
516
  let offset = 0;
194
- while (offset < bytesRead)
195
- offset += writeSync(tempFd, buffer, offset, bytesRead - offset);
517
+ while (offset < bytesRead) {
518
+ const written = writeSync(writerFd, buffer, offset, bytesRead - offset, snapshotOffset + offset);
519
+ if (written <= 0)
520
+ throw new Error('migration_snapshot_write_failed');
521
+ offset += written;
522
+ }
523
+ snapshotOffset += bytesRead;
196
524
  }
197
- fsyncSync(tempFd);
198
- }
199
- catch (error) {
200
- copyError = error;
525
+ const afterRead = fstatSync(sourceFd, { bigint: true });
526
+ const afterPath = lstatSync(source.requestedPath, { bigint: true });
527
+ if (!sameMigrationSourceSnapshot(opened, afterRead)
528
+ || !afterPath.isFile()
529
+ || afterPath.isSymbolicLink()
530
+ || !sameMigrationSourceSnapshot(afterRead, afterPath)
531
+ || realpathSync(source.requestedPath) !== source.canonicalPath) {
532
+ throw new Error('migration_source_changed');
533
+ }
534
+ fsyncSync(writerFd);
535
+ snapshotIdentity = fstatSync(writerFd, { bigint: true });
536
+ if (!snapshotIdentity.isFile() || snapshotIdentity.size !== opened.size) {
537
+ throw new Error('migration_snapshot_changed');
538
+ }
539
+ closeSync(writerFd);
540
+ writerFd = undefined;
541
+ const expectedDigest = digest.digest('hex');
542
+ readerFd = openSync(snapshotPath, constants.O_RDONLY | noFollowFlag());
543
+ const reopened = hashOpenDescriptor(readerFd, 'migration_snapshot_changed');
544
+ if (!sameMigrationSourceSnapshot(snapshotIdentity, reopened.stat) || reopened.digest !== expectedDigest) {
545
+ throw new Error('migration_snapshot_changed');
546
+ }
547
+ testHook?.('after-snapshot', source.requestedPath, snapshotPath);
548
+ const verified = hashOpenDescriptor(readerFd, 'migration_snapshot_changed');
549
+ const atPath = lstatSync(snapshotPath, { bigint: true });
550
+ if (!sameMigrationSourceSnapshot(reopened.stat, verified.stat)
551
+ || verified.digest !== expectedDigest
552
+ || !atPath.isFile()
553
+ || atPath.isSymbolicLink()
554
+ || !sameMigrationSourceSnapshot(verified.stat, atPath)) {
555
+ throw new Error('migration_snapshot_changed');
556
+ }
557
+ chmodSync(snapshotPath, 0o400);
558
+ if (process.platform !== 'win32')
559
+ unlinkSync(snapshotPath);
560
+ completed = true;
561
+ return { fd: readerFd, path: snapshotPath, stat: verified.stat, digest: expectedDigest };
201
562
  }
202
563
  finally {
203
564
  closeSync(sourceFd);
204
- if (tempFd !== undefined)
205
- closeSync(tempFd);
565
+ if (writerFd !== undefined)
566
+ closeSync(writerFd);
567
+ if (!completed && readerFd !== undefined)
568
+ closeSync(readerFd);
569
+ if (!completed) {
570
+ try {
571
+ const atPath = lstatSync(snapshotPath, { bigint: true });
572
+ if (snapshotIdentity && atPath.isFile() && !atPath.isSymbolicLink()
573
+ && sameMigrationSourceIdentity(snapshotIdentity, atPath))
574
+ unlinkSync(snapshotPath);
575
+ }
576
+ catch {
577
+ // Preserve the source/snapshot failure; cleanup is best-effort.
578
+ }
579
+ }
206
580
  }
207
- if (copyError !== undefined) {
208
- try {
209
- if (existsSync(temp))
210
- unlinkSync(temp);
581
+ }
582
+ function closeMigrationSnapshot(snapshot) {
583
+ const current = fstatSync(snapshot.fd, { bigint: true });
584
+ closeSync(snapshot.fd);
585
+ try {
586
+ const atPath = lstatSync(snapshot.path, { bigint: true });
587
+ if (atPath.isFile() && !atPath.isSymbolicLink() && sameMigrationSourceIdentity(current, atPath)) {
588
+ chmodSync(snapshot.path, 0o600);
589
+ unlinkSync(snapshot.path);
211
590
  }
212
- catch {
213
- // Preserve the source/copy failure; cleanup is best-effort.
591
+ }
592
+ catch (error) {
593
+ if (error.code !== 'ENOENT')
594
+ throw error;
595
+ }
596
+ }
597
+ function hashOpenDescriptor(fd, errorCode) {
598
+ const before = fstatSync(fd, { bigint: true });
599
+ if (!before.isFile())
600
+ throw new Error(errorCode);
601
+ const hash = createHash('sha256');
602
+ const buffer = Buffer.alloc(64 * 1024);
603
+ let position = 0;
604
+ for (;;) {
605
+ const bytesRead = readSync(fd, buffer, 0, buffer.length, position);
606
+ if (bytesRead === 0)
607
+ break;
608
+ position += bytesRead;
609
+ hash.update(buffer.subarray(0, bytesRead));
610
+ }
611
+ const after = fstatSync(fd, { bigint: true });
612
+ if (!sameMigrationSourceSnapshot(before, after))
613
+ throw new Error(errorCode);
614
+ return { digest: hash.digest('hex'), stat: after };
615
+ }
616
+ function hashRegularFile(path, errorCode) {
617
+ const before = lstatSync(path, { bigint: true });
618
+ if (!before.isFile() || before.isSymbolicLink())
619
+ throw new Error(errorCode);
620
+ const fd = openSync(path, constants.O_RDONLY | noFollowFlag());
621
+ try {
622
+ const opened = fstatSync(fd, { bigint: true });
623
+ if (!opened.isFile() || !sameMigrationSourceSnapshot(before, opened))
624
+ throw new Error(errorCode);
625
+ const hashed = hashOpenDescriptor(fd, errorCode);
626
+ const afterPath = lstatSync(path, { bigint: true });
627
+ if (!sameMigrationSourceSnapshot(opened, hashed.stat)
628
+ || !afterPath.isFile()
629
+ || afterPath.isSymbolicLink()
630
+ || !sameMigrationSourceSnapshot(hashed.stat, afterPath)) {
631
+ throw new Error(errorCode);
214
632
  }
215
- throw copyError;
633
+ return hashed;
634
+ }
635
+ finally {
636
+ closeSync(fd);
216
637
  }
638
+ }
639
+ function ensureArchiveContent(snapshot, path) {
640
+ let existing;
641
+ if (existsSync(path)) {
642
+ existing = hashRegularFile(path, 'memory_graph_archive_path_rejected');
643
+ if (existing.digest === snapshot.digest)
644
+ return;
645
+ }
646
+ const temp = join(dirname(path), `.${basename(path)}.${randomUUID()}.tmp`);
647
+ let fd;
648
+ let tempStat;
217
649
  try {
218
- if (existsSync(destination)) {
219
- const existing = lstatSync(destination);
220
- if (!existing.isFile() || existing.isSymbolicLink())
650
+ fd = openSync(temp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | noFollowFlag(), 0o600);
651
+ tempStat = fstatSync(fd, { bigint: true });
652
+ if (!tempStat.isFile())
653
+ throw new Error('memory_graph_archive_write_failed');
654
+ const buffer = Buffer.alloc(64 * 1024);
655
+ let position = 0;
656
+ while (position < Number(snapshot.stat.size)) {
657
+ const bytesRead = readSync(snapshot.fd, buffer, 0, buffer.length, position);
658
+ if (bytesRead === 0)
659
+ throw new Error('migration_snapshot_changed');
660
+ let offset = 0;
661
+ while (offset < bytesRead) {
662
+ const written = writeSync(fd, buffer, offset, bytesRead - offset);
663
+ if (written <= 0)
664
+ throw new Error('memory_graph_archive_write_failed');
665
+ offset += written;
666
+ }
667
+ position += bytesRead;
668
+ }
669
+ fsyncSync(fd);
670
+ const completedTemp = fstatSync(fd, { bigint: true });
671
+ if (!sameMigrationSourceIdentity(tempStat, completedTemp)) {
672
+ throw new Error('memory_graph_archive_write_failed');
673
+ }
674
+ closeSync(fd);
675
+ fd = undefined;
676
+ if (hashRegularFile(temp, 'memory_graph_archive_write_failed').digest !== snapshot.digest) {
677
+ throw new Error('memory_graph_archive_write_failed');
678
+ }
679
+ if (existing) {
680
+ const current = lstatSync(path, { bigint: true });
681
+ if (!current.isFile() || current.isSymbolicLink())
221
682
  throw new Error('memory_graph_archive_path_rejected');
222
- unlinkSync(temp);
223
- return;
683
+ if (!sameMigrationSourceSnapshot(existing.stat, current)) {
684
+ if (hashRegularFile(path, 'memory_graph_archive_path_rejected').digest === snapshot.digest)
685
+ return;
686
+ throw new Error('memory_graph_archive_content_conflict');
687
+ }
688
+ // Same-directory rename keeps the old archive visible until the verified replacement is published.
689
+ renameSync(temp, path);
690
+ }
691
+ else {
692
+ try {
693
+ // Hard-link publication is a no-clobber atomic create for the common first-import case.
694
+ linkSync(temp, path);
695
+ }
696
+ catch (error) {
697
+ if (error.code !== 'EEXIST')
698
+ throw error;
699
+ const incumbent = hashRegularFile(path, 'memory_graph_archive_path_rejected');
700
+ if (incumbent.digest !== snapshot.digest) {
701
+ const current = lstatSync(path, { bigint: true });
702
+ if (!current.isFile() || current.isSymbolicLink()
703
+ || !sameMigrationSourceSnapshot(incumbent.stat, current)) {
704
+ throw new Error('memory_graph_archive_content_conflict');
705
+ }
706
+ renameSync(temp, path);
707
+ }
708
+ }
709
+ }
710
+ if (hashRegularFile(path, 'memory_graph_archive_path_rejected').digest !== snapshot.digest) {
711
+ throw new Error('memory_graph_archive_content_conflict');
224
712
  }
225
- // A same-directory hard link publishes without replacing a path created by a concurrent process.
226
- linkSync(temp, destination);
227
- unlinkSync(temp);
228
713
  }
229
- catch (error) {
714
+ finally {
715
+ if (fd !== undefined)
716
+ closeSync(fd);
230
717
  try {
231
- if (existsSync(temp))
718
+ const atPath = lstatSync(temp, { bigint: true });
719
+ if (tempStat && atPath.isFile() && !atPath.isSymbolicLink()
720
+ && sameMigrationSourceIdentity(tempStat, atPath))
232
721
  unlinkSync(temp);
233
722
  }
234
723
  catch {
235
- // Preserve the publication failure; cleanup is best-effort.
724
+ // Keep the archive result authoritative; the random, mode-0600 temp is safe to clean on a later run.
236
725
  }
237
- throw error;
238
726
  }
727
+ }
728
+ function archiveMemoryGraphSnapshot(snapshot, archiveDir) {
729
+ mkdirSync(archiveDir, { recursive: true, mode: 0o700 });
730
+ const archiveDirStat = lstatSync(archiveDir);
731
+ if (!archiveDirStat.isDirectory() || archiveDirStat.isSymbolicLink()) {
732
+ throw new Error('memory_graph_archive_path_rejected');
733
+ }
734
+ const versioned = join(archiveDir, `legacy_memory_graph.${snapshot.digest}.jsonl`);
735
+ ensureArchiveContent(snapshot, versioned);
736
+ const legacy = join(archiveDir, 'legacy_memory_graph.jsonl');
737
+ ensureArchiveContent(snapshot, legacy);
239
738
  }