@evomap/evolver-cli 2.0.0-beta.9 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/dist/antiGeneBenchmark.js +2 -0
  2. package/dist/antiGeneRollout.js +9 -3
  3. package/dist/assetHealth.js +2 -0
  4. package/dist/assetTrust.js +14 -1
  5. package/dist/atp.d.ts +10 -5
  6. package/dist/atp.js +119 -26
  7. package/dist/atpAutoBuyer.d.ts +120 -0
  8. package/dist/atpAutoBuyer.js +814 -0
  9. package/dist/atpAutoDeliver.js +2 -2
  10. package/dist/autoDistillLlm.js +2 -1
  11. package/dist/autoDistillTranscript.js +3 -2
  12. package/dist/autoexec.d.ts +101 -13
  13. package/dist/autoexec.js +794 -91
  14. package/dist/cli.js +13 -0
  15. package/dist/cliContracts.d.ts +23 -2
  16. package/dist/cliContracts.js +504 -54
  17. package/dist/commands.d.ts +1 -0
  18. package/dist/commands.js +1 -0
  19. package/dist/curriculumCapabilityGaps.d.ts +6 -0
  20. package/dist/curriculumCapabilityGaps.js +24 -0
  21. package/dist/cycleConsumer.d.ts +13 -0
  22. package/dist/cycleConsumer.js +186 -20
  23. package/dist/dashboard.js +47 -9
  24. package/dist/dispatch.js +8 -2
  25. package/dist/distillPrimitives.d.ts +3 -2
  26. package/dist/distillPrimitives.js +80 -12
  27. package/dist/doctor.js +120 -11
  28. package/dist/identityHome.d.ts +9 -0
  29. package/dist/identityHome.js +47 -0
  30. package/dist/index.d.ts +70 -40
  31. package/dist/index.js +581 -193
  32. package/dist/learningTrace.d.ts +15 -0
  33. package/dist/learningTrace.js +73 -0
  34. package/dist/lifecycle.d.ts +67 -1
  35. package/dist/lifecycle.js +738 -44
  36. package/dist/localMemoryGraph.d.ts +90 -3
  37. package/dist/localMemoryGraph.js +2031 -231
  38. package/dist/login.d.ts +1 -1
  39. package/dist/login.js +3 -3
  40. package/dist/materialSnapshot.d.ts +9 -1
  41. package/dist/materialSnapshot.js +23 -6
  42. package/dist/memoryGraphOps.d.ts +8 -0
  43. package/dist/memoryGraphOps.js +140 -0
  44. package/dist/migrate/assetFormatMap.d.ts +61 -0
  45. package/dist/migrate/assetFormatMap.js +53 -0
  46. package/dist/migrate/envTranslate.d.ts +26 -0
  47. package/dist/migrate/envTranslate.js +147 -0
  48. package/dist/migrate/fieldMap.d.ts +4 -2
  49. package/dist/migrate/fieldMap.js +9 -5
  50. package/dist/migrate/oauthImport.d.ts +66 -0
  51. package/dist/migrate/oauthImport.js +667 -0
  52. package/dist/migrate/v1Import.d.ts +92 -1
  53. package/dist/migrate/v1Import.js +1481 -141
  54. package/dist/promptRecallHook.d.ts +24 -0
  55. package/dist/promptRecallHook.js +425 -0
  56. package/dist/recallVerifyReport.d.ts +37 -0
  57. package/dist/recallVerifyReport.js +244 -0
  58. package/dist/recipe.d.ts +7 -1
  59. package/dist/recipe.js +426 -56
  60. package/dist/requiredSandboxValidation.d.ts +5 -0
  61. package/dist/requiredSandboxValidation.js +4 -0
  62. package/dist/reuse.d.ts +9 -0
  63. package/dist/reuse.js +151 -56
  64. package/dist/runtimeCapabilities.js +15 -15
  65. package/dist/runtimeSessionSource.d.ts +3 -2
  66. package/dist/runtimeSessionSource.js +63 -11
  67. package/dist/selectionPolicyConfig.d.ts +8 -0
  68. package/dist/selectionPolicyConfig.js +18 -0
  69. package/dist/semanticIdfConfig.d.ts +2 -0
  70. package/dist/semanticIdfConfig.js +4 -0
  71. package/dist/sessionIngest.d.ts +37 -0
  72. package/dist/sessionIngest.js +156 -0
  73. package/dist/setupHooks.js +95 -1
  74. package/dist/skill2gep.d.ts +13 -9
  75. package/dist/skill2gep.js +42 -30
  76. package/dist/skillDistill.d.ts +8 -4
  77. package/dist/skillDistill.js +38 -9
  78. package/dist/solo/mode.js +1 -0
  79. package/dist/sync.d.ts +12 -0
  80. package/dist/sync.js +1246 -151
  81. package/dist/thesis.d.ts +1 -1
  82. package/dist/thesis.js +20 -3
  83. package/dist/trajectoryExport.js +21 -3
  84. package/dist/v1Compat.d.ts +1 -0
  85. package/dist/v1Compat.js +9 -0
  86. package/dist/workflowRuntime.js +24 -18
  87. package/package.json +11 -8
@@ -1,49 +1,361 @@
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';
4
- import { basename, dirname, join, resolve, sep } from 'node:path';
5
- import { assetstore } from '@evomap/evolver-core';
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { chmodSync, closeSync, constants, existsSync, fstatSync, fsyncSync, linkSync, lstatSync, mkdirSync, mkdtempSync, openSync, readSync, readdirSync, realpathSync, renameSync, rmSync, unlinkSync, writeFileSync, writeSync, } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import { basename, dirname, join, relative, resolve, sep } from 'node:path';
5
+ import { assetstore, mailbox, util, wire } from '@evomap/evolver-core';
6
6
  import { mapV1Asset } from './fieldMap.js';
7
+ import { V1_GEP_SOURCE_LAYOUT, V1_GEP_WIRE_SOURCES } from './assetFormatMap.js';
7
8
  import { LocalMemoryGraph, MemoryGraphBusyError, MemoryGraphImportStateRejectedError, resolveLocalMemoryUserId, } from '../localMemoryGraph.js';
8
- const FILES = { Gene: 'genes.jsonl', Capsule: 'capsules.jsonl', EvolutionEvent: 'events.jsonl' };
9
9
  const DEFAULT_IMPORT_JSONL_MAX_LINE_BYTES = 16 * 1024 * 1024;
10
- let migrationArchiveNonce = 0;
10
+ const DEFAULT_IMPORT_JSON_MAX_BYTES = 64 * 1024 * 1024;
11
+ const DEFAULT_IMPORT_ASSET_BUFFER_MAX_BYTES = 128 * 1024 * 1024;
12
+ const DEFAULT_IMPORT_ASSET_MAX_RECORDS = 100_000;
13
+ const DEFAULT_IMPORT_SOURCE_MAX_BYTES = 128 * 1024 * 1024;
14
+ const DEFAULT_IMPORT_TOTAL_MAX_BYTES = 256 * 1024 * 1024;
15
+ const DEFAULT_IMPORT_TOTAL_MAX_RECORDS = 200_000;
16
+ const JSONL_READ_CHUNK_BYTES = 64 * 1024;
17
+ const IMPORT_V1_PLAN_SCHEMA = 'evolver.migration.import-v1-plan.v1';
18
+ const IMPORT_V1_SOURCE_ROLES = [
19
+ 'gene-envelope', 'gene-jsonl', 'capsule-envelope', 'capsule-jsonl', 'event-jsonl',
20
+ 'mailbox-jsonl', 'memory-graph-jsonl', 'candidates-jsonl', 'failed-capsules-json',
21
+ ];
22
+ const importV1PlanStates = new WeakMap();
23
+ function deepFreezeImportPlanValue(value) {
24
+ if (value !== null && typeof value === 'object' && !Object.isFrozen(value)) {
25
+ for (const nested of Object.values(value)) {
26
+ deepFreezeImportPlanValue(nested);
27
+ }
28
+ Object.freeze(value);
29
+ }
30
+ return value;
31
+ }
32
+ function configuredImportLimit(name, fallback, hardMaximum) {
33
+ const value = process.env[name];
34
+ if (value === undefined || value === '')
35
+ return fallback;
36
+ const parsed = Number(value);
37
+ if (!Number.isSafeInteger(parsed) || parsed <= 0 || parsed > hardMaximum) {
38
+ throw new Error('migration_limit_invalid');
39
+ }
40
+ return parsed;
41
+ }
11
42
  function maxJsonlLineBytes() {
12
- const raw = Number(process.env['EVOLVER_IMPORT_JSONL_MAX_LINE_BYTES']);
13
- return Number.isFinite(raw) && raw > 0 ? Math.floor(raw) : DEFAULT_IMPORT_JSONL_MAX_LINE_BYTES;
43
+ return configuredImportLimit('EVOLVER_IMPORT_JSONL_MAX_LINE_BYTES', DEFAULT_IMPORT_JSONL_MAX_LINE_BYTES, 64 * 1024 * 1024);
14
44
  }
15
- async function* readJsonl(path) {
16
- if (!existsSync(path))
45
+ function maxJsonBytes() {
46
+ return configuredImportLimit('EVOLVER_IMPORT_JSON_MAX_BYTES', DEFAULT_IMPORT_JSON_MAX_BYTES, 256 * 1024 * 1024);
47
+ }
48
+ function maxAssetBufferBytes() {
49
+ return configuredImportLimit('EVOLVER_IMPORT_ASSET_BUFFER_MAX_BYTES', DEFAULT_IMPORT_ASSET_BUFFER_MAX_BYTES, 512 * 1024 * 1024);
50
+ }
51
+ function maxAssetRecords() {
52
+ return configuredImportLimit('EVOLVER_IMPORT_ASSET_MAX_RECORDS', DEFAULT_IMPORT_ASSET_MAX_RECORDS, 1_000_000);
53
+ }
54
+ function maxSourceBytes() {
55
+ return configuredImportLimit('EVOLVER_IMPORT_SOURCE_MAX_BYTES', DEFAULT_IMPORT_SOURCE_MAX_BYTES, 512 * 1024 * 1024);
56
+ }
57
+ function maxTotalBytes() {
58
+ return configuredImportLimit('EVOLVER_IMPORT_TOTAL_MAX_BYTES', DEFAULT_IMPORT_TOTAL_MAX_BYTES, 1024 * 1024 * 1024);
59
+ }
60
+ function maxTotalRecords() {
61
+ return configuredImportLimit('EVOLVER_IMPORT_TOTAL_MAX_RECORDS', DEFAULT_IMPORT_TOTAL_MAX_RECORDS, 1_000_000);
62
+ }
63
+ const fatalUtf8Decoder = new TextDecoder('utf-8', { fatal: true });
64
+ function decodeImportUtf8(bytes, errorCode) {
65
+ try {
66
+ return fatalUtf8Decoder.decode(bytes);
67
+ }
68
+ catch {
69
+ throw new Error(errorCode);
70
+ }
71
+ }
72
+ function resolveV1SourceLayout(v1Dir) {
73
+ const workspacePath = join(v1Dir, 'workspace');
74
+ let workspaceStat;
75
+ try {
76
+ workspaceStat = lstatSync(workspacePath);
77
+ }
78
+ catch (error) {
79
+ if (error.code === 'ENOENT') {
80
+ return {
81
+ workspaceRoot: v1Dir,
82
+ gepSourceDirs: [V1_GEP_SOURCE_LAYOUT.rootCurrent, V1_GEP_SOURCE_LAYOUT.legacy],
83
+ };
84
+ }
85
+ throw new Error('migration_source_path_rejected');
86
+ }
87
+ if (!workspaceStat.isDirectory() || workspaceStat.isSymbolicLink()) {
88
+ throw new Error('migration_source_path_rejected');
89
+ }
90
+ try {
91
+ const canonicalRoot = realpathSync(v1Dir);
92
+ const canonicalWorkspace = realpathSync(workspacePath);
93
+ if (!canonicalWorkspace.startsWith(canonicalRoot.endsWith(sep) ? canonicalRoot : `${canonicalRoot}${sep}`)) {
94
+ throw new Error('migration_source_path_rejected');
95
+ }
96
+ }
97
+ catch (error) {
98
+ if (error instanceof Error && error.message === 'migration_source_path_rejected')
99
+ throw error;
100
+ throw new Error('migration_source_path_rejected');
101
+ }
102
+ return {
103
+ workspaceRoot: workspacePath,
104
+ gepSourceDirs: [V1_GEP_SOURCE_LAYOUT.workspaceCurrent, V1_GEP_SOURCE_LAYOUT.legacy],
105
+ };
106
+ }
107
+ function resolveV1GepSource(v1Dir, sourceDirs, sourceBasename) {
108
+ for (const sourceDir of sourceDirs) {
109
+ const sourcePath = join(v1Dir, ...sourceDir, sourceBasename);
110
+ const source = secureRegularFileWithin(v1Dir, sourcePath);
111
+ if (source)
112
+ return { source, basename: sourceBasename };
113
+ }
114
+ return null;
115
+ }
116
+ function* readV1JsonEnvelope(fd, envelopeKey) {
117
+ const size = fstatSync(fd).size;
118
+ if (size > maxJsonBytes())
119
+ throw new Error('migration_v1_json_too_large');
120
+ const buffer = Buffer.alloc(size);
121
+ let position = 0;
122
+ while (position < size) {
123
+ const bytesRead = readSync(fd, buffer, position, size - position, position);
124
+ if (bytesRead === 0)
125
+ throw new Error('migration_snapshot_changed');
126
+ position += bytesRead;
127
+ }
128
+ const raw = decodeImportUtf8(buffer, 'migration_v1_json_invalid_utf8').trim();
129
+ if (!raw)
130
+ return;
131
+ let parsed;
132
+ try {
133
+ parsed = JSON.parse(raw);
134
+ }
135
+ catch {
136
+ throw new Error('migration_v1_json_invalid');
137
+ }
138
+ const records = Array.isArray(parsed)
139
+ ? parsed
140
+ : isPlainRecord(parsed) && Array.isArray(parsed[envelopeKey])
141
+ ? parsed[envelopeKey]
142
+ : null;
143
+ if (!records)
144
+ throw new Error('migration_v1_json_invalid');
145
+ for (const record of records) {
146
+ if (!isPlainRecord(record))
147
+ throw new Error('migration_v1_json_record_invalid');
148
+ yield record;
149
+ }
150
+ }
151
+ function v1LogicalId(record) {
152
+ const id = record['id'];
153
+ return (typeof id === 'string' && id.length > 0) || (typeof id === 'number' && id !== 0)
154
+ ? String(id)
155
+ : null;
156
+ }
157
+ function sourceRole(kind, format) {
158
+ if (kind === 'Gene')
159
+ return format === 'envelope' ? 'gene-envelope' : 'gene-jsonl';
160
+ if (kind === 'Capsule')
161
+ return format === 'envelope' ? 'capsule-envelope' : 'capsule-jsonl';
162
+ return 'event-jsonl';
163
+ }
164
+ function snapshotForPlan(accumulator, resolvedSource, role, testHook, limit) {
165
+ const sourceLimit = maxSourceBytes();
166
+ const effectiveLimit = limit
167
+ ? { maxBytes: Math.min(sourceLimit, limit.maxBytes), error: limit.error }
168
+ : { maxBytes: sourceLimit, error: 'migration_v1_source_too_large' };
169
+ const snapshot = createMigrationSnapshot(resolvedSource.source, accumulator.snapshotDir, resolvedSource.basename, testHook, effectiveLimit);
170
+ const bytes = Number(snapshot.stat.size);
171
+ const nextTotal = accumulator.totalBytes + bytes;
172
+ if (nextTotal > maxTotalBytes()) {
173
+ closeMigrationSnapshot(snapshot);
174
+ throw new Error('migration_v1_total_bytes_too_large');
175
+ }
176
+ accumulator.totalBytes = nextTotal;
177
+ accumulator.snapshots.push(snapshot);
178
+ const report = {
179
+ role,
180
+ path: relative(accumulator.sourceRoot, resolvedSource.source.requestedPath).split(sep).join('/'),
181
+ bytes,
182
+ sha256: snapshot.digest,
183
+ records: 0,
184
+ };
185
+ accumulator.sources.push(report);
186
+ return { snapshot, report };
187
+ }
188
+ function countPlannedRecord(accumulator, source) {
189
+ accumulator.totalRecords += 1;
190
+ if (accumulator.totalRecords > maxTotalRecords())
191
+ throw new Error('migration_v1_records_too_many');
192
+ source.records += 1;
193
+ }
194
+ function assertExpectedV1Kind(record, kind) {
195
+ if (record['type'] !== kind)
196
+ throw new Error('migration_v1_asset_type_mismatch');
197
+ }
198
+ function validatedV1SchemaVersion(record) {
199
+ const value = record['schema_version'];
200
+ if (value !== undefined && (typeof value !== 'string' || value.trim().length === 0)) {
201
+ throw new Error('migration_v1_schema_version_invalid');
202
+ }
203
+ return value;
204
+ }
205
+ function assertValidV1ValidationReport(record) {
206
+ if (record['type'] !== 'ValidationReport'
207
+ || typeof record['id'] !== 'string'
208
+ || record['id'].length === 0
209
+ || !Array.isArray(record['commands'])
210
+ || typeof record['overall_ok'] !== 'boolean') {
211
+ throw new Error('migration_v1_validation_report_invalid');
212
+ }
213
+ validatedV1SchemaVersion(record);
214
+ }
215
+ function addPlannedAsset(accumulator, kind, record) {
216
+ assertExpectedV1Kind(record, kind);
217
+ const sourceSchemaVersion = validatedV1SchemaVersion(record);
218
+ const sourceSchemaVersionKey = sourceSchemaVersion ?? '(missing)';
219
+ const mapped = mapV1Asset(kind, record);
220
+ const validation = wire.validateWire(mapped.record);
221
+ if (!validation.ok)
222
+ throw new Error('migration_v1_wire_invalid');
223
+ assetstore.assertCapsuleGeneBinding(mapped.record);
224
+ const bytes = Buffer.byteLength(JSON.stringify({ record: mapped.record, dropped: mapped.dropped }), 'utf8');
225
+ if (accumulator.assets.length >= maxAssetRecords())
226
+ throw new Error('migration_v1_asset_records_too_many');
227
+ if (accumulator.assetBytes > maxAssetBufferBytes() - bytes)
228
+ throw new Error('migration_v1_asset_buffer_too_large');
229
+ accumulator.assetBytes += bytes;
230
+ accumulator.sourceSchemaVersions.set(sourceSchemaVersionKey, (accumulator.sourceSchemaVersions.get(sourceSchemaVersionKey) ?? 0) + 1);
231
+ accumulator.assets.push({ kind, mapped, hashMatches: wire.verifyAssetId(mapped.record) });
232
+ }
233
+ async function planV1AssetKind(accumulator, sourceDirs, kind, testHook) {
234
+ const spec = V1_GEP_WIRE_SOURCES[kind];
235
+ if (!('envelope' in spec)) {
236
+ const resolvedSource = resolveV1GepSource(accumulator.sourceRoot, sourceDirs, spec.jsonl);
237
+ if (!resolvedSource)
238
+ return;
239
+ const { snapshot, report } = snapshotForPlan(accumulator, resolvedSource, sourceRole(kind, 'jsonl'), testHook);
240
+ for await (const record of readJsonl(snapshot.fd)) {
241
+ countPlannedRecord(accumulator, report);
242
+ if (kind === 'EvolutionEvent' && record['type'] === 'ValidationReport') {
243
+ assertValidV1ValidationReport(record);
244
+ accumulator.validationReportRecords += 1;
245
+ continue;
246
+ }
247
+ addPlannedAsset(accumulator, kind, record);
248
+ }
249
+ return;
250
+ }
251
+ const byId = new Map();
252
+ let bufferedBytes = 0;
253
+ const setById = (record) => {
254
+ assertExpectedV1Kind(record, kind);
255
+ const id = v1LogicalId(record);
256
+ if (!id)
257
+ throw new Error('migration_v1_logical_id_missing');
258
+ const bytes = Buffer.byteLength(JSON.stringify(record), 'utf8');
259
+ const previous = byId.get(id);
260
+ if (!previous && byId.size >= maxAssetRecords())
261
+ throw new Error('migration_v1_asset_records_too_many');
262
+ const nextBytes = bufferedBytes - (previous?.bytes ?? 0) + bytes;
263
+ if (nextBytes > maxAssetBufferBytes())
264
+ throw new Error('migration_v1_asset_buffer_too_large');
265
+ byId.set(id, { record, bytes });
266
+ bufferedBytes = nextBytes;
267
+ };
268
+ const envelope = resolveV1GepSource(accumulator.sourceRoot, sourceDirs, spec.envelope.basename);
269
+ if (envelope) {
270
+ const { snapshot, report } = snapshotForPlan(accumulator, envelope, sourceRole(kind, 'envelope'), testHook, { maxBytes: maxJsonBytes(), error: 'migration_v1_json_too_large' });
271
+ for (const record of readV1JsonEnvelope(snapshot.fd, spec.envelope.key)) {
272
+ countPlannedRecord(accumulator, report);
273
+ setById(record);
274
+ }
275
+ }
276
+ const jsonl = resolveV1GepSource(accumulator.sourceRoot, sourceDirs, spec.jsonl);
277
+ if (jsonl) {
278
+ const { snapshot, report } = snapshotForPlan(accumulator, jsonl, sourceRole(kind, 'jsonl'), testHook);
279
+ for await (const record of readJsonl(snapshot.fd)) {
280
+ countPlannedRecord(accumulator, report);
281
+ setById(record);
282
+ }
283
+ }
284
+ for (const { record } of byId.values())
285
+ addPlannedAsset(accumulator, kind, record);
286
+ }
287
+ async function* readJsonl(source) {
288
+ if (typeof source === 'string' && !existsSync(source))
17
289
  return;
18
290
  const maxLineBytes = maxJsonlLineBytes();
291
+ const buffer = Buffer.allocUnsafe(JSONL_READ_CHUNK_BYTES);
292
+ let fd;
293
+ let ownsFd = false;
294
+ let position = 0;
19
295
  let parts = [];
20
296
  let lineBytes = 0;
21
297
  let dropping = false;
22
298
  const finish = function* () {
23
- if (dropping || lineBytes === 0) {
299
+ if (dropping) {
24
300
  parts = [];
25
301
  lineBytes = 0;
26
302
  dropping = false;
27
- return;
303
+ throw new Error('migration_v1_jsonl_line_too_large');
28
304
  }
29
- const text = Buffer.concat(parts, lineBytes).toString('utf8').trim();
305
+ if (lineBytes === 0)
306
+ return;
307
+ const text = decodeImportUtf8(Buffer.concat(parts, lineBytes), 'migration_v1_jsonl_invalid_utf8').trim();
30
308
  parts = [];
31
309
  lineBytes = 0;
32
310
  if (!text)
33
311
  return;
34
312
  try {
35
- yield JSON.parse(text);
313
+ const parsed = JSON.parse(text);
314
+ if (!isPlainRecord(parsed))
315
+ throw new Error('migration_v1_jsonl_record_invalid');
316
+ yield parsed;
317
+ }
318
+ catch (error) {
319
+ if (error instanceof Error && error.message === 'migration_v1_jsonl_record_invalid')
320
+ throw error;
321
+ throw new Error('migration_v1_jsonl_invalid');
36
322
  }
37
- catch { /* skip corrupt rows */ }
38
323
  };
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) {
324
+ try {
325
+ if (typeof source === 'number') {
326
+ fd = source;
327
+ }
328
+ else {
329
+ fd = openSync(source, constants.O_RDONLY | noFollowFlag());
330
+ ownsFd = true;
331
+ }
332
+ for (;;) {
333
+ const bytesRead = readSync(fd, buffer, 0, buffer.length, position);
334
+ if (bytesRead === 0)
335
+ break;
336
+ position += bytesRead;
337
+ let start = 0;
338
+ for (let i = 0; i < bytesRead; i += 1) {
339
+ if (buffer[i] !== 0x0a)
340
+ continue;
341
+ const segment = buffer.subarray(start, i);
342
+ if (!dropping) {
343
+ if (lineBytes + segment.length > maxLineBytes) {
344
+ parts = [];
345
+ lineBytes = 0;
346
+ dropping = true;
347
+ }
348
+ else {
349
+ parts.push(Buffer.from(segment));
350
+ lineBytes += segment.length;
351
+ }
352
+ }
353
+ for (const record of finish())
354
+ yield record;
355
+ start = i + 1;
356
+ }
357
+ if (start < bytesRead && !dropping) {
358
+ const segment = buffer.subarray(start, bytesRead);
47
359
  if (lineBytes + segment.length > maxLineBytes) {
48
360
  parts = [];
49
361
  lineBytes = 0;
@@ -54,92 +366,629 @@ async function* readJsonl(path) {
54
366
  lineBytes += segment.length;
55
367
  }
56
368
  }
57
- for (const record of finish())
58
- yield record;
59
- start = i + 1;
60
369
  }
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;
370
+ for (const record of finish())
371
+ yield record;
372
+ }
373
+ finally {
374
+ if (ownsFd && fd !== undefined)
375
+ closeSync(fd);
376
+ }
377
+ }
378
+ function readSnapshotJson(snapshot) {
379
+ const size = Number(snapshot.stat.size);
380
+ if (size > maxJsonBytes())
381
+ throw new Error('migration_v1_json_too_large');
382
+ const buffer = Buffer.alloc(size);
383
+ let offset = 0;
384
+ while (offset < size) {
385
+ const bytesRead = readSync(snapshot.fd, buffer, offset, size - offset, offset);
386
+ if (bytesRead === 0)
387
+ throw new Error('migration_snapshot_changed');
388
+ offset += bytesRead;
389
+ }
390
+ try {
391
+ return JSON.parse(decodeImportUtf8(buffer, 'migration_v1_json_invalid_utf8'));
392
+ }
393
+ catch {
394
+ throw new Error('migration_v1_json_invalid');
395
+ }
396
+ }
397
+ function disposeImportV1PlanState(state) {
398
+ if (state.disposed)
399
+ return;
400
+ state.disposed = true;
401
+ let firstError;
402
+ for (const snapshot of state.snapshots) {
403
+ try {
404
+ closeMigrationSnapshot(snapshot);
405
+ }
406
+ catch (error) {
407
+ firstError ??= error;
408
+ }
409
+ }
410
+ try {
411
+ state.disposeTestHook?.('before-remove', state.snapshotDir);
412
+ }
413
+ catch (error) {
414
+ firstError ??= error;
415
+ }
416
+ try {
417
+ rmSync(state.snapshotDir, { recursive: true, force: true });
418
+ }
419
+ catch (error) {
420
+ firstError ??= error;
421
+ }
422
+ if (firstError !== undefined)
423
+ throw firstError;
424
+ }
425
+ function assertSafeMigrationTargetTreeUnchecked(path) {
426
+ if (!existsSync(path))
427
+ return;
428
+ const rootStat = lstatSync(path);
429
+ if (!rootStat.isDirectory() || rootStat.isSymbolicLink())
430
+ throw new Error('migration_output_path_rejected');
431
+ const root = realpathSync(path);
432
+ const pending = [];
433
+ for (const candidate of [
434
+ join(root, 'assets'),
435
+ join(root, 'migration'),
436
+ join(root, 'evolution'),
437
+ join(root, 'proxy'),
438
+ ]) {
439
+ try {
440
+ lstatSync(candidate);
441
+ pending.push(candidate);
442
+ }
443
+ catch (error) {
444
+ if (error.code !== 'ENOENT')
445
+ throw error;
446
+ }
447
+ }
448
+ let visited = 0;
449
+ while (pending.length > 0) {
450
+ const current = pending.pop();
451
+ const currentStat = lstatSync(current, { bigint: true });
452
+ if (currentStat.isSymbolicLink())
453
+ throw new Error('migration_output_path_rejected');
454
+ if (currentStat.isFile()) {
455
+ if (currentStat.nlink > 1n)
456
+ throw new Error('migration_output_hardlink_rejected');
457
+ continue;
458
+ }
459
+ if (!currentStat.isDirectory())
460
+ throw new Error('migration_output_path_rejected');
461
+ if (!pathWithin(root, realpathSync(current)))
462
+ throw new Error('migration_output_path_rejected');
463
+ for (const name of readdirSync(current)) {
464
+ visited += 1;
465
+ if (visited > maxTotalRecords())
466
+ throw new Error('migration_output_entries_too_many');
467
+ pending.push(join(current, name));
468
+ }
469
+ }
470
+ }
471
+ function assertSafeMigrationTargetTree(path) {
472
+ try {
473
+ assertSafeMigrationTargetTreeUnchecked(path);
474
+ }
475
+ catch (error) {
476
+ if (error instanceof Error && error.message.startsWith('migration_'))
477
+ throw error;
478
+ throw new Error('migration_output_path_rejected');
479
+ }
480
+ }
481
+ async function readStableTargetJsonl(path) {
482
+ if (!existsSync(path))
483
+ return { records: [], fingerprint: { path, digest: null } };
484
+ try {
485
+ const targetLimit = { maxBytes: maxSourceBytes(), error: 'migration_target_too_large' };
486
+ const before = hashRegularFile(path, 'migration_target_changed', targetLimit);
487
+ const fd = openSync(path, constants.O_RDONLY | noFollowFlag());
488
+ const records = [];
489
+ try {
490
+ for await (const record of readJsonl(fd)) {
491
+ if (records.length >= maxTotalRecords())
492
+ throw new Error('migration_target_records_too_many');
493
+ records.push(record);
494
+ }
495
+ }
496
+ finally {
497
+ closeSync(fd);
498
+ }
499
+ const after = hashRegularFile(path, 'migration_target_changed', targetLimit);
500
+ if (before.digest !== after.digest || !sameMigrationSourceSnapshot(before.stat, after.stat)) {
501
+ throw new Error('migration_target_changed');
502
+ }
503
+ return { records, fingerprint: { path, digest: after.digest } };
504
+ }
505
+ catch (error) {
506
+ if (error instanceof Error && error.message.startsWith('migration_target_'))
507
+ throw error;
508
+ throw new Error('migration_target_jsonl_invalid');
509
+ }
510
+ }
511
+ function assertTargetFileFingerprint(expected) {
512
+ if (!existsSync(expected.path)) {
513
+ if (expected.digest !== null)
514
+ throw new Error('migration_target_changed');
515
+ return;
516
+ }
517
+ if (expected.digest === null)
518
+ throw new Error('migration_target_changed');
519
+ const current = hashRegularFile(expected.path, 'migration_target_changed', {
520
+ maxBytes: maxSourceBytes(),
521
+ error: 'migration_target_too_large',
522
+ });
523
+ if (current.digest !== expected.digest)
524
+ throw new Error('migration_target_changed');
525
+ }
526
+ async function planMigrationExtensions(outputRoot, assets) {
527
+ const path = join(outputRoot, 'migration', 'v1_extensions.jsonl');
528
+ const target = await readStableTargetJsonl(path);
529
+ const byAssetId = new Map();
530
+ for (const record of target.records) {
531
+ const assetId = record['asset_id'];
532
+ const dropped = record['dropped'];
533
+ if (typeof assetId !== 'string' || !isPlainRecord(dropped))
534
+ throw new Error('migration_target_jsonl_invalid');
535
+ const previous = byAssetId.get(assetId);
536
+ if (previous && JSON.stringify(previous) !== JSON.stringify(dropped)) {
537
+ throw new Error('migration_extension_content_conflict');
538
+ }
539
+ byAssetId.set(assetId, dropped);
540
+ }
541
+ let appends = 0;
542
+ let deduped = 0;
543
+ for (const planned of assets) {
544
+ if (Object.keys(planned.mapped.dropped).length === 0)
545
+ continue;
546
+ const assetId = String(planned.mapped.record['asset_id'] ?? '');
547
+ if (!assetId)
548
+ throw new Error('migration_extension_asset_id_missing');
549
+ const existing = byAssetId.get(assetId);
550
+ if (existing) {
551
+ if (JSON.stringify(existing) !== JSON.stringify(planned.mapped.dropped)) {
552
+ throw new Error('migration_extension_content_conflict');
67
553
  }
554
+ deduped += 1;
555
+ }
556
+ else {
557
+ byAssetId.set(assetId, planned.mapped.dropped);
558
+ appends += 1;
559
+ }
560
+ }
561
+ return { appends, deduped, fingerprint: target.fingerprint };
562
+ }
563
+ function classifyPlannedAssets(target, plannedAssets) {
564
+ const counts = {
565
+ Gene: { candidates: 0, verified: 0, unverified: 0, frozen: 0, recomputed: 0, writes: 0, deduped: 0 },
566
+ Capsule: { candidates: 0, verified: 0, unverified: 0, frozen: 0, recomputed: 0, writes: 0, deduped: 0 },
567
+ EvolutionEvent: { candidates: 0, verified: 0, unverified: 0, frozen: 0, recomputed: 0, writes: 0, deduped: 0 },
568
+ };
569
+ const existingAssets = new Map(target.assets);
570
+ const provenance = new Map(target.provenance);
571
+ let provenanceCandidates = 0;
572
+ let provenanceWrites = 0;
573
+ let provenancePreserved = 0;
574
+ for (const planned of plannedAssets) {
575
+ const kindCounts = counts[planned.kind];
576
+ kindCounts.candidates += 1;
577
+ if (planned.hashMatches)
578
+ kindCounts.verified += 1;
579
+ else
580
+ kindCounts.unverified += 1;
581
+ if (planned.mapped.recomputed)
582
+ kindCounts.recomputed += 1;
583
+ else
584
+ kindCounts.frozen += 1;
585
+ const record = planned.mapped.record;
586
+ const existing = existingAssets.get(record.asset_id) ?? null;
587
+ if (planned.hashMatches) {
588
+ if (existing && !assetstore.frozenAssetRecordsEqual(existing, record)) {
589
+ throw new Error('migration_asset_id_collision');
590
+ }
591
+ if (existing)
592
+ kindCounts.deduped += 1;
68
593
  else {
69
- parts.push(Buffer.from(segment));
70
- lineBytes += segment.length;
594
+ kindCounts.writes += 1;
595
+ existingAssets.set(record.asset_id, record);
71
596
  }
597
+ continue;
598
+ }
599
+ provenanceCandidates += 1;
600
+ const disposition = assetstore.planUnverifiedIngest(record, existing, provenance.get(record.asset_id) ?? null, assetstore.UNVERIFIED_V1_IMPORT_REASON, 'migrated');
601
+ if (disposition.status === 'collision')
602
+ throw new Error('migration_asset_id_collision');
603
+ if (disposition.status === 'create') {
604
+ kindCounts.writes += 1;
605
+ existingAssets.set(record.asset_id, record);
606
+ }
607
+ else {
608
+ kindCounts.deduped += 1;
609
+ }
610
+ if (disposition.status === 'preserve_trust')
611
+ provenancePreserved += 1;
612
+ if (disposition.provenanceAction !== 'none') {
613
+ provenanceWrites += 1;
614
+ provenance.set(record.asset_id, {
615
+ assetId: record.asset_id,
616
+ source: 'migrated',
617
+ trusted: false,
618
+ reason: assetstore.UNVERIFIED_V1_IMPORT_REASON,
619
+ frozenContentId: disposition.frozenContentId,
620
+ at: '',
621
+ });
72
622
  }
73
623
  }
74
- for (const record of finish())
75
- yield record;
624
+ return {
625
+ assets: counts,
626
+ provenance: { candidates: provenanceCandidates, writes: provenanceWrites, preserved: provenancePreserved },
627
+ };
76
628
  }
77
- export async function importV1(v1Dir, store, outDir, options = {}) {
78
- const sidecarPath = join(outDir, 'migration', 'v1_extensions.jsonl');
79
- const rep = {
80
- imported: { Gene: 0, Capsule: 0, EvolutionEvent: 0 }, frozen: 0, recomputed: 0, deduped: 0,
81
- sidecarExtensions: 0, memoryGraphArchived: false, memoryGraphImported: 0, memoryGraphDeferred: false, candidatesSkipped: false,
629
+ function planSourceOrder(source) {
630
+ return IMPORT_V1_SOURCE_ROLES.indexOf(source.role);
631
+ }
632
+ export async function planImportV1(v1Dir, outDir, options = {}) {
633
+ const roots = validateMigrationRoots(v1Dir, outDir);
634
+ assertSafeMigrationTargetTree(roots.outputRoot);
635
+ const workspace = options.workspace === undefined ? null : canonicalDirectory(options.workspace);
636
+ if (options.workspace !== undefined && !workspace)
637
+ throw new Error('migration_workspace_path_rejected');
638
+ const memoryUserId = options.userId ?? resolveLocalMemoryUserId();
639
+ const snapshotDir = mkdtempSync(join(tmpdir(), 'evolver-import-v1-plan-'));
640
+ chmodSync(snapshotDir, 0o700);
641
+ const accumulator = {
642
+ sourceRoot: roots.sourceRoot,
643
+ snapshotDir,
644
+ snapshots: [],
645
+ sources: [],
646
+ assets: [],
647
+ sourceSchemaVersions: new Map(),
648
+ totalBytes: 0,
649
+ totalRecords: 0,
650
+ assetBytes: 0,
651
+ validationReportRecords: 0,
82
652
  };
83
- const gepDir = join(v1Dir, 'assets', 'gep');
84
- 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;
94
- 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;
98
- }
653
+ let state;
654
+ try {
655
+ const sourceLayout = resolveV1SourceLayout(roots.sourceRoot);
656
+ for (const kind of ['Gene', 'Capsule', 'EvolutionEvent']) {
657
+ await planV1AssetKind(accumulator, sourceLayout.gepSourceDirs, kind, options.sourceSnapshotTestHook);
658
+ }
659
+ let mailboxSnapshot;
660
+ let mailboxBatch;
661
+ let mailboxPreview;
662
+ const mailboxSource = secureRegularFileWithin(roots.sourceRoot, join(roots.sourceRoot, 'mailbox', 'messages.jsonl'));
663
+ if (mailboxSource) {
664
+ const planned = snapshotForPlan(accumulator, { source: mailboxSource, basename: 'mailbox_messages.jsonl' }, 'mailbox-jsonl', options.sourceSnapshotTestHook);
665
+ mailboxSnapshot = planned.snapshot;
666
+ mailboxBatch = mailbox.prepareMailboxJsonlImport(mailboxSnapshot.fd, {
667
+ maxLineBytes: maxJsonlLineBytes(),
668
+ maxBytes: maxSourceBytes(),
669
+ maxRecords: maxTotalRecords(),
670
+ });
671
+ for (let index = 0; index < mailboxBatch.sourceRecords; index += 1) {
672
+ countPlannedRecord(accumulator, planned.report);
99
673
  }
100
- else {
101
- rep.deduped += 1;
674
+ mailboxPreview = Object.freeze({
675
+ ...mailbox.previewPreparedMailboxImport(mailboxBatch, join(roots.outputRoot, 'proxy', 'mailbox.db')),
676
+ });
677
+ }
678
+ let memorySnapshot;
679
+ let memorySource;
680
+ const memoryRecords = [];
681
+ let memoryPlan;
682
+ let memoryPlanDeferred = false;
683
+ const securedMemoryGraph = secureRegularFileWithin(roots.sourceRoot, join(sourceLayout.workspaceRoot, 'memory', 'evolution', 'memory_graph.jsonl'));
684
+ if (securedMemoryGraph) {
685
+ const planned = snapshotForPlan(accumulator, { source: securedMemoryGraph, basename: 'memory_graph.jsonl' }, 'memory-graph-jsonl', options.sourceSnapshotTestHook);
686
+ memorySnapshot = planned.snapshot;
687
+ memorySource = securedMemoryGraph.canonicalPath;
688
+ for await (const record of readJsonl(memorySnapshot.fd)) {
689
+ countPlannedRecord(accumulator, planned.report);
690
+ memoryRecords.push(record);
691
+ }
692
+ const graph = new LocalMemoryGraph({ dir: join(roots.outputRoot, 'evolution'), userId: memoryUserId });
693
+ try {
694
+ memoryPlan = graph.planV1Outcomes(workspace, memoryRecords, memorySource);
695
+ }
696
+ catch (error) {
697
+ if (!(error instanceof MemoryGraphImportStateRejectedError) && !(error instanceof MemoryGraphBusyError))
698
+ throw error;
699
+ memoryPlanDeferred = true;
700
+ memoryPlan = graph.planV1Outcomes(null, memoryRecords, memorySource);
701
+ }
702
+ if (memoryPlan.rejected > 0)
703
+ throw new Error('migration_v1_memory_record_invalid');
704
+ }
705
+ let candidatesFound = false;
706
+ let candidateRecords = 0;
707
+ const candidates = resolveV1GepSource(roots.sourceRoot, sourceLayout.gepSourceDirs, 'candidates.jsonl');
708
+ if (candidates) {
709
+ candidatesFound = true;
710
+ const planned = snapshotForPlan(accumulator, candidates, 'candidates-jsonl', options.sourceSnapshotTestHook);
711
+ for await (const _record of readJsonl(planned.snapshot.fd)) {
712
+ countPlannedRecord(accumulator, planned.report);
713
+ candidateRecords += 1;
714
+ }
715
+ }
716
+ let failedCapsulesFound = false;
717
+ let failedCapsuleRecords = 0;
718
+ const failedCapsules = resolveV1GepSource(roots.sourceRoot, sourceLayout.gepSourceDirs, 'failed_capsules.json');
719
+ if (failedCapsules) {
720
+ failedCapsulesFound = true;
721
+ const planned = snapshotForPlan(accumulator, failedCapsules, 'failed-capsules-json', options.sourceSnapshotTestHook, { maxBytes: maxJsonBytes(), error: 'migration_v1_json_too_large' });
722
+ const parsed = readSnapshotJson(planned.snapshot);
723
+ const records = isPlainRecord(parsed)
724
+ && parsed['version'] === 1
725
+ && Array.isArray(parsed['failed_capsules'])
726
+ ? parsed['failed_capsules']
727
+ : null;
728
+ if (!records)
729
+ throw new Error('migration_v1_json_invalid');
730
+ for (const record of records) {
731
+ if (!isPlainRecord(record))
732
+ throw new Error('migration_v1_json_record_invalid');
733
+ assertExpectedV1Kind(record, 'Capsule');
734
+ countPlannedRecord(accumulator, planned.report);
735
+ failedCapsuleRecords += 1;
736
+ }
737
+ }
738
+ if (accumulator.sources.length === 0)
739
+ throw new Error('migration_v1_no_sources');
740
+ let extensionCandidates = 0;
741
+ for (const planned of accumulator.assets) {
742
+ if (Object.keys(planned.mapped.dropped).length > 0)
743
+ extensionCandidates += 1;
744
+ }
745
+ const targetAssets = assetstore.readLocalAssetStoreSnapshot(join(roots.outputRoot, 'assets'), {
746
+ maxFileBytes: maxSourceBytes(),
747
+ maxTotalBytes: maxTotalBytes(),
748
+ maxRecords: maxTotalRecords(),
749
+ });
750
+ const assetPlan = classifyPlannedAssets(targetAssets, accumulator.assets);
751
+ const extensionPlan = await planMigrationExtensions(roots.outputRoot, accumulator.assets);
752
+ const sources = accumulator.sources
753
+ .map((source) => ({ ...source }))
754
+ .sort((left, right) => planSourceOrder(left) - planSourceOrder(right) || left.path.localeCompare(right.path));
755
+ const sourceSchemaVersions = Object.fromEntries([...accumulator.sourceSchemaVersions.entries()].sort(([left], [right]) => left.localeCompare(right)));
756
+ const reportWithoutDigest = {
757
+ schema: IMPORT_V1_PLAN_SCHEMA,
758
+ sourceSchemaVersions,
759
+ targetAuthoringSchemaVersion: wire.SCHEMA_VERSION,
760
+ sources,
761
+ assets: assetPlan.assets,
762
+ provenance: assetPlan.provenance,
763
+ extensions: {
764
+ candidates: extensionCandidates,
765
+ appends: extensionPlan.appends,
766
+ deduped: extensionPlan.deduped,
767
+ },
768
+ mailbox: {
769
+ found: mailboxSnapshot !== undefined,
770
+ candidates: mailboxBatch?.sourceRecords ?? 0,
771
+ inserts: mailboxPreview?.insertedMessages ?? 0,
772
+ updates: mailboxPreview?.updatedMessages ?? 0,
773
+ protected: mailboxPreview?.protectedMessages ?? 0,
774
+ },
775
+ memoryGraph: {
776
+ found: memorySnapshot !== undefined,
777
+ candidates: memoryRecords.length,
778
+ importable: memoryPlan?.importable ?? 0,
779
+ deduped: memoryPlan?.duplicates ?? 0,
780
+ rejected: memoryPlan?.rejected ?? 0,
781
+ deferred: memoryPlan?.deferred ?? 0,
782
+ disposition: memorySnapshot === undefined ? 'absent' : workspace && !memoryPlanDeferred ? 'import' : 'defer',
783
+ },
784
+ validationReports: {
785
+ found: accumulator.validationReportRecords > 0,
786
+ candidates: accumulator.validationReportRecords,
787
+ disposition: accumulator.validationReportRecords > 0 ? 'preserve_source_no_v2_mapping' : 'absent',
788
+ },
789
+ candidates: {
790
+ found: candidatesFound,
791
+ candidates: candidateRecords,
792
+ disposition: candidatesFound ? 'skip_non_wire' : 'absent',
793
+ },
794
+ failedCapsules: {
795
+ found: failedCapsulesFound,
796
+ candidates: failedCapsuleRecords,
797
+ disposition: failedCapsulesFound ? 'preserve_manual_recovery' : 'absent',
798
+ },
799
+ };
800
+ const report = deepFreezeImportPlanValue({
801
+ ...reportWithoutDigest,
802
+ planDigest: createHash('sha256').update(JSON.stringify(reportWithoutDigest)).digest('hex'),
803
+ });
804
+ state = {
805
+ sourceRoot: roots.sourceRoot,
806
+ outputRoot: roots.outputRoot,
807
+ workspace,
808
+ memoryUserId,
809
+ snapshotDir,
810
+ snapshots: accumulator.snapshots,
811
+ assets: accumulator.assets,
812
+ targetAssets,
813
+ extensionTarget: extensionPlan.fingerprint,
814
+ mailboxSnapshot,
815
+ mailboxBatch,
816
+ mailboxPreview,
817
+ memorySnapshot,
818
+ memorySource,
819
+ memoryPlan,
820
+ memoryPlanDeferred,
821
+ candidatesFound,
822
+ disposeTestHook: options.disposeTestHook,
823
+ disposed: false,
824
+ applied: false,
825
+ };
826
+ const plan = Object.freeze({
827
+ report,
828
+ dispose: () => disposeImportV1PlanState(state),
829
+ });
830
+ importV1PlanStates.set(plan, state);
831
+ return plan;
832
+ }
833
+ catch (error) {
834
+ const partial = state ?? {
835
+ sourceRoot: roots.sourceRoot, outputRoot: roots.outputRoot, workspace, memoryUserId,
836
+ snapshotDir, snapshots: accumulator.snapshots,
837
+ assets: accumulator.assets,
838
+ extensionTarget: { path: join(roots.outputRoot, 'migration', 'v1_extensions.jsonl'), digest: null },
839
+ candidatesFound: false, disposeTestHook: options.disposeTestHook,
840
+ memoryPlanDeferred: false, disposed: false, applied: false,
841
+ };
842
+ try {
843
+ disposeImportV1PlanState(partial);
844
+ }
845
+ catch { /* preserve the planning failure */ }
846
+ throw error;
847
+ }
848
+ }
849
+ export async function applyImportV1Plan(plan, store, outDir, options = {}) {
850
+ const state = importV1PlanStates.get(plan);
851
+ if (!state || state.disposed || state.applied)
852
+ throw new Error('migration_plan_invalid');
853
+ const outputRoot = canonicalProspectiveDirectory(outDir);
854
+ const requestedWorkspace = options.workspace === undefined ? null : canonicalDirectory(options.workspace);
855
+ const requestedUserId = options.userId ?? resolveLocalMemoryUserId();
856
+ if (outputRoot !== state.outputRoot
857
+ || (store && canonicalProspectiveDirectory(store.baseDir) !== join(outputRoot, 'assets'))
858
+ || requestedWorkspace !== state.workspace
859
+ || requestedUserId !== state.memoryUserId) {
860
+ throw new Error('migration_plan_target_mismatch');
861
+ }
862
+ assertSafeMigrationTargetTree(outputRoot);
863
+ assertTargetFileFingerprint(state.extensionTarget);
864
+ if (!state.targetAssets)
865
+ throw new Error('migration_plan_invalid');
866
+ assetstore.assertLocalAssetStoreSnapshotCurrent(state.targetAssets);
867
+ options.outputRootTestHook?.('before-secure', outDir);
868
+ const securedOutputRoot = secureOutputRoot(outDir, state.outputRoot);
869
+ assertMigrationRootsDisjoint(state.sourceRoot, securedOutputRoot);
870
+ assertSafeMigrationTargetTree(securedOutputRoot);
871
+ assertTargetFileFingerprint(state.extensionTarget);
872
+ assetstore.assertLocalAssetStoreSnapshotCurrent(state.targetAssets);
873
+ let mailboxPath;
874
+ if (state.mailboxSnapshot) {
875
+ if (!state.mailboxBatch || !state.mailboxPreview)
876
+ throw new Error('migration_plan_invalid');
877
+ const proxyDir = ensureSafeOutputDirectory(securedOutputRoot, join(securedOutputRoot, 'proxy'));
878
+ mailboxPath = join(proxyDir, 'mailbox.db');
879
+ assertSafeMailboxTarget(mailboxPath);
880
+ const currentPreview = mailbox.previewPreparedMailboxImport(state.mailboxBatch, mailboxPath);
881
+ if (currentPreview.sourceRecords !== state.mailboxPreview.sourceRecords
882
+ || currentPreview.insertedMessages !== state.mailboxPreview.insertedMessages
883
+ || currentPreview.updatedMessages !== state.mailboxPreview.updatedMessages
884
+ || currentPreview.protectedMessages !== state.mailboxPreview.protectedMessages) {
885
+ throw new Error('migration_mailbox_target_changed');
886
+ }
887
+ }
888
+ const evolutionDir = state.memorySnapshot && state.workspace && !state.memoryPlanDeferred
889
+ ? ensureSafeOutputDirectory(securedOutputRoot, join(securedOutputRoot, 'evolution'))
890
+ : undefined;
891
+ const assetsDir = ensureSafeOutputDirectory(securedOutputRoot, join(securedOutputRoot, 'assets'));
892
+ const migrationDir = ensureSafeOutputDirectory(securedOutputRoot, join(securedOutputRoot, 'migration'));
893
+ state.applied = true;
894
+ const targetStore = store ?? new assetstore.LocalJsonlProvider(assetsDir);
895
+ const sidecarPath = join(migrationDir, 'v1_extensions.jsonl');
896
+ const rep = {
897
+ imported: { Gene: 0, Capsule: 0, EvolutionEvent: 0 }, frozen: 0, recomputed: 0, unverifiedFrozen: 0, deduped: 0,
898
+ sidecarExtensions: 0, memoryGraphArchived: false, memoryGraphImported: 0, memoryGraphDeferred: false,
899
+ candidatesSkipped: state.candidatesFound, mailboxFound: state.mailboxSnapshot !== undefined, mailboxImported: 0,
900
+ };
901
+ const provenance = new assetstore.ProvenanceStore(targetStore.baseDir);
902
+ for (const planned of state.assets) {
903
+ if (Object.keys(planned.mapped.dropped).length > 0) {
904
+ const assetId = String(planned.mapped.record['asset_id'] ?? '');
905
+ if (await ensureMigrationExtension(sidecarPath, assetId, planned.mapped.dropped, options.sidecarAppendTestHook)) {
906
+ rep.sidecarExtensions += 1;
102
907
  }
103
908
  }
909
+ const record = planned.mapped.record;
910
+ const result = planned.hashMatches
911
+ ? await targetStore.put(record)
912
+ : await assetstore.ingestUnverified(targetStore, provenance, record, assetstore.UNVERIFIED_V1_IMPORT_REASON, 'migrated');
913
+ if (result.stored) {
914
+ rep.imported[planned.kind] += 1;
915
+ if (!planned.hashMatches)
916
+ rep.unverifiedFrozen += 1;
917
+ if (planned.mapped.recomputed)
918
+ rep.recomputed += 1;
919
+ else
920
+ rep.frozen += 1;
921
+ }
922
+ else {
923
+ rep.deduped += 1;
924
+ }
925
+ }
926
+ if (state.mailboxSnapshot) {
927
+ if (!mailboxPath || !state.mailboxBatch)
928
+ throw new Error('migration_plan_invalid');
929
+ let target;
930
+ try {
931
+ assertSafeMailboxTarget(mailboxPath);
932
+ target = new mailbox.MailboxStore({ path: mailboxPath });
933
+ assertSafeMailboxTarget(mailboxPath);
934
+ rep.mailboxImported = target.importPrepared(state.mailboxBatch);
935
+ }
936
+ finally {
937
+ target?.close();
938
+ }
104
939
  }
105
- // memory_graph remains a sidecar: never convert it into EvolutionEvent or mutate Gene/Capsule identity.
106
- 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);
940
+ if (state.memorySnapshot && state.memorySource) {
941
+ archiveMemoryGraphSnapshot(state.memorySnapshot, migrationDir);
111
942
  rep.memoryGraphArchived = true;
112
- const workspace = options.workspace ? canonicalDirectory(options.workspace) : null;
113
- if (!workspace) {
943
+ const workspace = state.workspace;
944
+ if (!workspace || state.memoryPlanDeferred) {
114
945
  rep.memoryGraphDeferred = true;
115
946
  }
116
947
  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;
126
- }
127
- }
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 });
948
+ const userId = state.memoryUserId;
949
+ const marker = scopedMemoryGraphMarker(migrationDir, workspace, userId, state.memorySource, state.memorySnapshot.digest);
950
+ if (!state.memoryPlan)
951
+ throw new Error('migration_plan_invalid');
952
+ const markerExists = hasSafeMemoryGraphMarker(marker);
953
+ if (!evolutionDir)
954
+ throw new Error('migration_plan_invalid');
955
+ const graph = new LocalMemoryGraph({ dir: evolutionDir, userId });
956
+ try {
957
+ rep.memoryGraphImported = graph.applyV1OutcomePlan(state.memoryPlan);
958
+ }
959
+ catch (error) {
960
+ if (!(error instanceof MemoryGraphImportStateRejectedError) && !(error instanceof MemoryGraphBusyError))
961
+ throw error;
962
+ rep.memoryGraphDeferred = true;
963
+ }
964
+ if (!rep.memoryGraphDeferred && !markerExists) {
965
+ writeMemoryGraphMarker(marker, `${rep.memoryGraphImported}\n`, options.memoryGraphMarkerTestHook);
135
966
  }
136
967
  }
137
968
  }
138
- // candidates 候选池非 wire 资产 → 不迁移(留作 selection 输入)
139
- if (existsSync(join(gepDir, 'candidates.jsonl')))
140
- rep.candidatesSkipped = true;
141
969
  return rep;
142
970
  }
971
+ export async function importV1(v1Dir, store, outDir, options = {}) {
972
+ const plan = await planImportV1(v1Dir, outDir, options);
973
+ let report;
974
+ try {
975
+ report = await applyImportV1Plan(plan, store, outDir, options);
976
+ }
977
+ catch (error) {
978
+ try {
979
+ plan.dispose();
980
+ }
981
+ catch { /* preserve the primary failure */ }
982
+ throw error;
983
+ }
984
+ try {
985
+ plan.dispose();
986
+ }
987
+ catch {
988
+ throw new Error('migration_cleanup_failed');
989
+ }
990
+ return report;
991
+ }
143
992
  function canonicalDirectory(path) {
144
993
  try {
145
994
  const absolute = resolve(path);
@@ -150,90 +999,581 @@ function canonicalDirectory(path) {
150
999
  return null;
151
1000
  }
152
1001
  }
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`);
1002
+ function isPlainRecord(value) {
1003
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
156
1004
  }
157
- function secureRegularFileWithin(root, path) {
1005
+ function pathWithin(root, candidate) {
1006
+ const comparableRoot = process.platform === 'win32' ? root.toLowerCase() : root;
1007
+ const comparableCandidate = process.platform === 'win32' ? candidate.toLowerCase() : candidate;
1008
+ const prefix = comparableRoot.endsWith(sep) ? comparableRoot : `${comparableRoot}${sep}`;
1009
+ return comparableCandidate === comparableRoot || comparableCandidate.startsWith(prefix);
1010
+ }
1011
+ function canonicalProspectiveDirectory(path) {
1012
+ let cursor = resolve(path);
1013
+ const missing = [];
1014
+ for (;;) {
1015
+ try {
1016
+ const stat = lstatSync(cursor);
1017
+ if (!stat.isDirectory() || stat.isSymbolicLink())
1018
+ throw new Error('migration_output_path_rejected');
1019
+ return resolve(realpathSync(cursor), ...missing.reverse());
1020
+ }
1021
+ catch (error) {
1022
+ if (error.code !== 'ENOENT')
1023
+ throw error;
1024
+ const parent = dirname(cursor);
1025
+ if (parent === cursor)
1026
+ throw new Error('migration_output_path_rejected');
1027
+ missing.push(basename(cursor));
1028
+ cursor = parent;
1029
+ }
1030
+ }
1031
+ }
1032
+ function assertMigrationRootsDisjoint(sourceRoot, outputRoot) {
1033
+ if (pathWithin(sourceRoot, outputRoot) || pathWithin(outputRoot, sourceRoot)) {
1034
+ throw new Error('migration_output_overlaps_source');
1035
+ }
1036
+ }
1037
+ export function validateMigrationRoots(v1Dir, outDir) {
1038
+ const sourceRoot = canonicalDirectory(v1Dir);
1039
+ if (!sourceRoot)
1040
+ throw new Error('migration_source_path_rejected');
1041
+ const outputRoot = canonicalProspectiveDirectory(outDir);
1042
+ assertMigrationRootsDisjoint(sourceRoot, outputRoot);
1043
+ return { sourceRoot, outputRoot };
1044
+ }
1045
+ function secureOutputRoot(path, expectedRoot) {
1046
+ if (canonicalProspectiveDirectory(path) !== expectedRoot)
1047
+ throw new Error('migration_target_changed');
1048
+ const absolute = resolve(path);
1049
+ mkdirSync(absolute, { recursive: true, mode: 0o700 });
1050
+ const stat = lstatSync(absolute);
1051
+ if (!stat.isDirectory() || stat.isSymbolicLink())
1052
+ throw new Error('migration_output_path_rejected');
1053
+ const canonical = realpathSync(absolute);
1054
+ if (canonical !== expectedRoot)
1055
+ throw new Error('migration_target_changed');
1056
+ return canonical;
1057
+ }
1058
+ function ensureSafeOutputDirectory(root, requested) {
1059
+ const absolute = resolve(requested);
1060
+ if (!pathWithin(root, absolute))
1061
+ throw new Error('migration_output_path_rejected');
1062
+ const relative = absolute.slice(root.length).split(sep).filter(Boolean);
1063
+ let current = root;
1064
+ for (const segment of relative) {
1065
+ const next = join(current, segment);
1066
+ try {
1067
+ const stat = lstatSync(next);
1068
+ if (!stat.isDirectory() || stat.isSymbolicLink())
1069
+ throw new Error('migration_output_path_rejected');
1070
+ }
1071
+ catch (error) {
1072
+ if (error.code !== 'ENOENT')
1073
+ throw error;
1074
+ mkdirSync(next, { mode: 0o700 });
1075
+ const created = lstatSync(next);
1076
+ if (!created.isDirectory() || created.isSymbolicLink())
1077
+ throw new Error('migration_output_path_rejected');
1078
+ }
1079
+ const canonical = realpathSync(next);
1080
+ if (!pathWithin(root, canonical))
1081
+ throw new Error('migration_output_path_rejected');
1082
+ current = canonical;
1083
+ }
1084
+ return current;
1085
+ }
1086
+ async function ensureMigrationExtension(path, assetId, dropped, testHook) {
1087
+ if (!assetId)
1088
+ throw new Error('migration_extension_asset_id_missing');
1089
+ const lockPath = `${path}.lock`;
1090
+ util.acquireLock(lockPath, { maxTries: 300, waitMs: 10 });
1091
+ let result;
1092
+ let operationError;
1093
+ try {
1094
+ result = await ensureMigrationExtensionLocked(path, assetId, dropped, testHook);
1095
+ }
1096
+ catch (error) {
1097
+ operationError = error;
1098
+ }
1099
+ const released = util.releaseLock(lockPath);
1100
+ if (!released.released)
1101
+ throw new Error('migration_extension_lock_release_failed');
1102
+ if (operationError !== undefined)
1103
+ throw operationError;
1104
+ return result;
1105
+ }
1106
+ async function ensureMigrationExtensionLocked(path, assetId, dropped, testHook) {
1107
+ if (existsSync(path)) {
1108
+ const before = lstatSync(path);
1109
+ if (!before.isFile() || before.isSymbolicLink() || before.nlink > 1) {
1110
+ throw new Error('migration_extension_path_rejected');
1111
+ }
1112
+ const fd = openSync(path, constants.O_RDONLY | noFollowFlag());
1113
+ try {
1114
+ const opened = fstatSync(fd);
1115
+ if (!opened.isFile() || opened.dev !== before.dev || opened.ino !== before.ino) {
1116
+ throw new Error('migration_extension_path_rejected');
1117
+ }
1118
+ for await (const record of readJsonl(fd)) {
1119
+ if (record['asset_id'] !== assetId)
1120
+ continue;
1121
+ if (JSON.stringify(record['dropped']) !== JSON.stringify(dropped)) {
1122
+ throw new Error('migration_extension_content_conflict');
1123
+ }
1124
+ return false;
1125
+ }
1126
+ }
1127
+ finally {
1128
+ closeSync(fd);
1129
+ }
1130
+ }
1131
+ testHook?.('before-append', path);
1132
+ const fd = openSync(path, constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT | noFollowFlag(), 0o600);
1133
+ try {
1134
+ const opened = fstatSync(fd, { bigint: true });
1135
+ const atPath = lstatSync(path, { bigint: true });
1136
+ if (!opened.isFile()
1137
+ || !atPath.isFile()
1138
+ || atPath.isSymbolicLink()
1139
+ || opened.dev !== atPath.dev
1140
+ || opened.ino !== atPath.ino
1141
+ || opened.nlink > 1n
1142
+ || atPath.nlink > 1n) {
1143
+ throw new Error('migration_extension_path_rejected');
1144
+ }
1145
+ writeFileSync(fd, `${JSON.stringify({ asset_id: assetId, dropped })}\n`, 'utf8');
1146
+ fsyncSync(fd);
1147
+ }
1148
+ finally {
1149
+ closeSync(fd);
1150
+ }
1151
+ testHook?.('after-append', path);
1152
+ return true;
1153
+ }
1154
+ function scopedMemoryGraphMarker(migrationDir, workspace, userId, source, sourceDigest) {
1155
+ const scope = createHash('sha256').update(JSON.stringify({ workspace, userId, source, sourceDigest })).digest('hex');
1156
+ return join(migrationDir, `v1_memory_graph_import.${scope}.complete`);
1157
+ }
1158
+ function assertSafeMailboxTarget(path) {
1159
+ const safeFileExists = (candidate) => {
1160
+ try {
1161
+ const stat = lstatSync(candidate, { bigint: true });
1162
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink > 1n) {
1163
+ throw new Error('migration_mailbox_path_rejected');
1164
+ }
1165
+ return true;
1166
+ }
1167
+ catch (error) {
1168
+ if (error.code === 'ENOENT')
1169
+ return false;
1170
+ throw error;
1171
+ }
1172
+ };
1173
+ const databaseExists = safeFileExists(path);
1174
+ const walExists = safeFileExists(path + '-wal');
1175
+ const shmExists = safeFileExists(path + '-shm');
1176
+ const journalExists = safeFileExists(path + '-journal');
1177
+ if (journalExists || (!databaseExists && (walExists || shmExists))) {
1178
+ throw new Error('migration_mailbox_path_rejected');
1179
+ }
1180
+ }
1181
+ function hasSafeMemoryGraphMarker(path) {
1182
+ let fd;
158
1183
  try {
159
- const absoluteRoot = resolve(root);
160
- const absolutePath = resolve(path);
161
- const rootStat = lstatSync(absoluteRoot);
162
- const fileStat = lstatSync(absolutePath);
163
- if (!rootStat.isDirectory() || rootStat.isSymbolicLink() || !fileStat.isFile() || fileStat.isSymbolicLink())
1184
+ const stat = lstatSync(path);
1185
+ if (!stat.isFile() || stat.isSymbolicLink())
1186
+ throw new Error('migration_memory_graph_marker_path_rejected');
1187
+ fd = openSync(path, constants.O_RDONLY | noFollowFlag());
1188
+ const opened = fstatSync(fd);
1189
+ if (!opened.isFile() || opened.size < 2 || opened.size > 64) {
1190
+ throw new Error('migration_memory_graph_marker_invalid');
1191
+ }
1192
+ const buffer = Buffer.alloc(opened.size);
1193
+ if (readSync(fd, buffer, 0, buffer.length, 0) !== buffer.length || !/^(0|[1-9]\d*)\n$/.test(buffer.toString('utf8'))) {
1194
+ throw new Error('migration_memory_graph_marker_invalid');
1195
+ }
1196
+ return true;
1197
+ }
1198
+ catch (error) {
1199
+ if (error.code === 'ENOENT')
164
1200
  return false;
1201
+ throw error;
1202
+ }
1203
+ finally {
1204
+ if (fd !== undefined)
1205
+ closeSync(fd);
1206
+ }
1207
+ }
1208
+ function writeMemoryGraphMarker(path, content, testHook) {
1209
+ const temporaryPath = `${path}.${randomUUID()}.tmp`;
1210
+ let fd;
1211
+ let operationError;
1212
+ try {
1213
+ fd = openSync(temporaryPath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | noFollowFlag(), 0o600);
1214
+ if (!fstatSync(fd).isFile())
1215
+ throw new Error('migration_memory_graph_marker_path_rejected');
1216
+ const data = Buffer.from(content, 'utf8');
1217
+ let offset = 0;
1218
+ while (offset < data.length) {
1219
+ const written = writeSync(fd, data, offset, data.length - offset, offset);
1220
+ if (written <= 0)
1221
+ throw new Error('migration_memory_graph_marker_write_failed');
1222
+ offset += written;
1223
+ }
1224
+ fsyncSync(fd);
1225
+ closeSync(fd);
1226
+ fd = undefined;
1227
+ testHook?.('before-publish', temporaryPath, path);
1228
+ try {
1229
+ linkSync(temporaryPath, path);
1230
+ }
1231
+ catch (error) {
1232
+ if (error.code !== 'EEXIST' || !hasSafeMemoryGraphMarker(path))
1233
+ throw error;
1234
+ }
1235
+ if (!hasSafeMemoryGraphMarker(path))
1236
+ throw new Error('migration_memory_graph_marker_invalid');
1237
+ }
1238
+ catch (error) {
1239
+ operationError = error;
1240
+ }
1241
+ let cleanupError;
1242
+ if (fd !== undefined) {
1243
+ try {
1244
+ closeSync(fd);
1245
+ }
1246
+ catch (error) {
1247
+ cleanupError = error;
1248
+ }
1249
+ }
1250
+ try {
1251
+ unlinkSync(temporaryPath);
1252
+ }
1253
+ catch (error) {
1254
+ if (error.code !== 'ENOENT' && cleanupError === undefined)
1255
+ cleanupError = error;
1256
+ }
1257
+ if (operationError !== undefined) {
1258
+ if (operationError instanceof Error && cleanupError !== undefined) {
1259
+ operationError.cleanupError = cleanupError;
1260
+ }
1261
+ throw operationError;
1262
+ }
1263
+ if (cleanupError !== undefined)
1264
+ throw cleanupError;
1265
+ }
1266
+ function secureRegularFileWithin(root, path) {
1267
+ const absoluteRoot = resolve(root);
1268
+ const absolutePath = resolve(path);
1269
+ let rootStat;
1270
+ try {
1271
+ rootStat = lstatSync(absoluteRoot);
1272
+ }
1273
+ catch {
1274
+ throw new Error('migration_source_path_rejected');
1275
+ }
1276
+ let fileStat;
1277
+ try {
1278
+ fileStat = lstatSync(absolutePath, { bigint: true });
1279
+ }
1280
+ catch (error) {
1281
+ if (error.code === 'ENOENT')
1282
+ return null;
1283
+ throw new Error('migration_source_path_rejected');
1284
+ }
1285
+ if (!rootStat.isDirectory() || rootStat.isSymbolicLink() || !fileStat.isFile() || fileStat.isSymbolicLink()) {
1286
+ throw new Error('migration_source_path_rejected');
1287
+ }
1288
+ try {
165
1289
  const canonicalRoot = realpathSync(absoluteRoot);
166
1290
  const canonicalPath = realpathSync(absolutePath);
167
- return canonicalPath.startsWith(canonicalRoot.endsWith(sep) ? canonicalRoot : `${canonicalRoot}${sep}`);
1291
+ if (!canonicalPath.startsWith(canonicalRoot.endsWith(sep) ? canonicalRoot : `${canonicalRoot}${sep}`)) {
1292
+ throw new Error('migration_source_path_rejected');
1293
+ }
1294
+ return { requestedPath: absolutePath, canonicalPath, stat: fileStat };
168
1295
  }
169
- catch {
170
- return false;
1296
+ catch (error) {
1297
+ if (error instanceof Error && error.message === 'migration_source_path_rejected')
1298
+ throw error;
1299
+ throw new Error('migration_source_path_rejected');
171
1300
  }
172
1301
  }
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;
1302
+ function sameMigrationSourceIdentity(left, right) {
1303
+ const hasStableFileId = left.dev !== 0n || left.ino !== 0n || right.dev !== 0n || right.ino !== 0n;
1304
+ if (hasStableFileId)
1305
+ return left.dev === right.dev && left.ino === right.ino;
1306
+ return left.birthtimeNs === right.birthtimeNs && left.mode === right.mode;
1307
+ }
1308
+ function sameMigrationSourceSnapshot(left, right) {
1309
+ return sameMigrationSourceIdentity(left, right)
1310
+ && left.size === right.size
1311
+ && left.mtimeNs === right.mtimeNs
1312
+ && left.ctimeNs === right.ctimeNs;
1313
+ }
1314
+ function noFollowFlag() {
1315
+ return process.platform !== 'win32' && typeof constants.O_NOFOLLOW === 'number'
1316
+ ? constants.O_NOFOLLOW
1317
+ : 0;
1318
+ }
1319
+ function createMigrationSnapshot(source, snapshotDir, label, testHook, limit) {
1320
+ const snapshotDirStat = lstatSync(snapshotDir);
1321
+ if (!snapshotDirStat.isDirectory() || snapshotDirStat.isSymbolicLink()) {
1322
+ throw new Error('migration_snapshot_dir_rejected');
179
1323
  }
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;
1324
+ const snapshotPath = join(snapshotDir, `.${basename(label)}.${randomUUID()}.tmp`);
1325
+ testHook?.('before-open', source.requestedPath);
1326
+ const sourceFd = openSync(source.canonicalPath, constants.O_RDONLY | noFollowFlag());
1327
+ let writerFd;
1328
+ let readerFd;
1329
+ let snapshotIdentity;
1330
+ let completed = false;
184
1331
  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);
1332
+ const opened = fstatSync(sourceFd, { bigint: true });
1333
+ if (!opened.isFile() || !sameMigrationSourceSnapshot(source.stat, opened)) {
1334
+ throw new Error('migration_source_changed');
1335
+ }
1336
+ if (limit && opened.size > BigInt(limit.maxBytes))
1337
+ throw new Error(limit.error);
1338
+ testHook?.('after-open', source.requestedPath);
1339
+ writerFd = openSync(snapshotPath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | noFollowFlag(), 0o600);
1340
+ snapshotIdentity = fstatSync(writerFd, { bigint: true });
1341
+ if (!snapshotIdentity.isFile())
1342
+ throw new Error('migration_snapshot_changed');
1343
+ const digest = createHash('sha256');
188
1344
  const buffer = Buffer.alloc(64 * 1024);
1345
+ let snapshotOffset = 0;
189
1346
  for (;;) {
190
1347
  const bytesRead = readSync(sourceFd, buffer, 0, buffer.length, null);
191
1348
  if (bytesRead === 0)
192
1349
  break;
1350
+ if (limit && snapshotOffset > limit.maxBytes - bytesRead)
1351
+ throw new Error(limit.error);
1352
+ digest.update(buffer.subarray(0, bytesRead));
193
1353
  let offset = 0;
194
- while (offset < bytesRead)
195
- offset += writeSync(tempFd, buffer, offset, bytesRead - offset);
1354
+ while (offset < bytesRead) {
1355
+ const written = writeSync(writerFd, buffer, offset, bytesRead - offset, snapshotOffset + offset);
1356
+ if (written <= 0)
1357
+ throw new Error('migration_snapshot_write_failed');
1358
+ offset += written;
1359
+ }
1360
+ snapshotOffset += bytesRead;
196
1361
  }
197
- fsyncSync(tempFd);
198
- }
199
- catch (error) {
200
- copyError = error;
1362
+ const afterRead = fstatSync(sourceFd, { bigint: true });
1363
+ const afterPath = lstatSync(source.requestedPath, { bigint: true });
1364
+ if (!sameMigrationSourceSnapshot(opened, afterRead)
1365
+ || !afterPath.isFile()
1366
+ || afterPath.isSymbolicLink()
1367
+ || !sameMigrationSourceSnapshot(afterRead, afterPath)
1368
+ || realpathSync(source.requestedPath) !== source.canonicalPath) {
1369
+ throw new Error('migration_source_changed');
1370
+ }
1371
+ fsyncSync(writerFd);
1372
+ snapshotIdentity = fstatSync(writerFd, { bigint: true });
1373
+ if (!snapshotIdentity.isFile() || snapshotIdentity.size !== opened.size) {
1374
+ throw new Error('migration_snapshot_changed');
1375
+ }
1376
+ closeSync(writerFd);
1377
+ writerFd = undefined;
1378
+ const expectedDigest = digest.digest('hex');
1379
+ readerFd = openSync(snapshotPath, constants.O_RDONLY | noFollowFlag());
1380
+ const reopened = hashOpenDescriptor(readerFd, 'migration_snapshot_changed');
1381
+ if (!sameMigrationSourceSnapshot(snapshotIdentity, reopened.stat) || reopened.digest !== expectedDigest) {
1382
+ throw new Error('migration_snapshot_changed');
1383
+ }
1384
+ testHook?.('after-snapshot', source.requestedPath, snapshotPath);
1385
+ const verified = hashOpenDescriptor(readerFd, 'migration_snapshot_changed');
1386
+ const atPath = lstatSync(snapshotPath, { bigint: true });
1387
+ if (!sameMigrationSourceSnapshot(reopened.stat, verified.stat)
1388
+ || verified.digest !== expectedDigest
1389
+ || !atPath.isFile()
1390
+ || atPath.isSymbolicLink()
1391
+ || !sameMigrationSourceSnapshot(verified.stat, atPath)) {
1392
+ throw new Error('migration_snapshot_changed');
1393
+ }
1394
+ chmodSync(snapshotPath, 0o400);
1395
+ if (process.platform !== 'win32')
1396
+ unlinkSync(snapshotPath);
1397
+ completed = true;
1398
+ return { fd: readerFd, path: snapshotPath, stat: verified.stat, digest: expectedDigest };
201
1399
  }
202
1400
  finally {
203
1401
  closeSync(sourceFd);
204
- if (tempFd !== undefined)
205
- closeSync(tempFd);
1402
+ if (writerFd !== undefined)
1403
+ closeSync(writerFd);
1404
+ if (!completed && readerFd !== undefined)
1405
+ closeSync(readerFd);
1406
+ if (!completed) {
1407
+ try {
1408
+ const atPath = lstatSync(snapshotPath, { bigint: true });
1409
+ if (snapshotIdentity && atPath.isFile() && !atPath.isSymbolicLink()
1410
+ && sameMigrationSourceIdentity(snapshotIdentity, atPath))
1411
+ unlinkSync(snapshotPath);
1412
+ }
1413
+ catch {
1414
+ // Preserve the source/snapshot failure; cleanup is best-effort.
1415
+ }
1416
+ }
206
1417
  }
207
- if (copyError !== undefined) {
208
- try {
209
- if (existsSync(temp))
210
- unlinkSync(temp);
1418
+ }
1419
+ function closeMigrationSnapshot(snapshot) {
1420
+ const current = fstatSync(snapshot.fd, { bigint: true });
1421
+ closeSync(snapshot.fd);
1422
+ try {
1423
+ const atPath = lstatSync(snapshot.path, { bigint: true });
1424
+ if (atPath.isFile() && !atPath.isSymbolicLink() && sameMigrationSourceIdentity(current, atPath)) {
1425
+ chmodSync(snapshot.path, 0o600);
1426
+ unlinkSync(snapshot.path);
211
1427
  }
212
- catch {
213
- // Preserve the source/copy failure; cleanup is best-effort.
1428
+ }
1429
+ catch (error) {
1430
+ if (error.code !== 'ENOENT')
1431
+ throw error;
1432
+ }
1433
+ }
1434
+ function hashOpenDescriptor(fd, errorCode, limit) {
1435
+ const before = fstatSync(fd, { bigint: true });
1436
+ if (!before.isFile())
1437
+ throw new Error(errorCode);
1438
+ if (limit && before.size > BigInt(limit.maxBytes))
1439
+ throw new Error(limit.error);
1440
+ const hash = createHash('sha256');
1441
+ const buffer = Buffer.alloc(64 * 1024);
1442
+ let position = 0;
1443
+ for (;;) {
1444
+ const bytesRead = readSync(fd, buffer, 0, buffer.length, position);
1445
+ if (bytesRead === 0)
1446
+ break;
1447
+ if (limit && position > limit.maxBytes - bytesRead)
1448
+ throw new Error(limit.error);
1449
+ position += bytesRead;
1450
+ hash.update(buffer.subarray(0, bytesRead));
1451
+ }
1452
+ const after = fstatSync(fd, { bigint: true });
1453
+ if (!sameMigrationSourceSnapshot(before, after))
1454
+ throw new Error(errorCode);
1455
+ return { digest: hash.digest('hex'), stat: after };
1456
+ }
1457
+ function hashRegularFile(path, errorCode, limit) {
1458
+ const before = lstatSync(path, { bigint: true });
1459
+ if (!before.isFile() || before.isSymbolicLink())
1460
+ throw new Error(errorCode);
1461
+ const fd = openSync(path, constants.O_RDONLY | noFollowFlag());
1462
+ try {
1463
+ const opened = fstatSync(fd, { bigint: true });
1464
+ if (!opened.isFile() || !sameMigrationSourceSnapshot(before, opened))
1465
+ throw new Error(errorCode);
1466
+ const hashed = hashOpenDescriptor(fd, errorCode, limit);
1467
+ const afterPath = lstatSync(path, { bigint: true });
1468
+ if (!sameMigrationSourceSnapshot(opened, hashed.stat)
1469
+ || !afterPath.isFile()
1470
+ || afterPath.isSymbolicLink()
1471
+ || !sameMigrationSourceSnapshot(hashed.stat, afterPath)) {
1472
+ throw new Error(errorCode);
214
1473
  }
215
- throw copyError;
1474
+ return hashed;
1475
+ }
1476
+ finally {
1477
+ closeSync(fd);
1478
+ }
1479
+ }
1480
+ function ensureArchiveContent(snapshot, path) {
1481
+ let existing;
1482
+ if (existsSync(path)) {
1483
+ existing = hashRegularFile(path, 'memory_graph_archive_path_rejected');
1484
+ if (existing.digest === snapshot.digest)
1485
+ return;
216
1486
  }
1487
+ const temp = join(dirname(path), `.${basename(path)}.${randomUUID()}.tmp`);
1488
+ let fd;
1489
+ let tempStat;
217
1490
  try {
218
- if (existsSync(destination)) {
219
- const existing = lstatSync(destination);
220
- if (!existing.isFile() || existing.isSymbolicLink())
1491
+ fd = openSync(temp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | noFollowFlag(), 0o600);
1492
+ tempStat = fstatSync(fd, { bigint: true });
1493
+ if (!tempStat.isFile())
1494
+ throw new Error('memory_graph_archive_write_failed');
1495
+ const buffer = Buffer.alloc(64 * 1024);
1496
+ let position = 0;
1497
+ while (position < Number(snapshot.stat.size)) {
1498
+ const bytesRead = readSync(snapshot.fd, buffer, 0, buffer.length, position);
1499
+ if (bytesRead === 0)
1500
+ throw new Error('migration_snapshot_changed');
1501
+ let offset = 0;
1502
+ while (offset < bytesRead) {
1503
+ const written = writeSync(fd, buffer, offset, bytesRead - offset);
1504
+ if (written <= 0)
1505
+ throw new Error('memory_graph_archive_write_failed');
1506
+ offset += written;
1507
+ }
1508
+ position += bytesRead;
1509
+ }
1510
+ fsyncSync(fd);
1511
+ const completedTemp = fstatSync(fd, { bigint: true });
1512
+ if (!sameMigrationSourceIdentity(tempStat, completedTemp)) {
1513
+ throw new Error('memory_graph_archive_write_failed');
1514
+ }
1515
+ closeSync(fd);
1516
+ fd = undefined;
1517
+ if (hashRegularFile(temp, 'memory_graph_archive_write_failed').digest !== snapshot.digest) {
1518
+ throw new Error('memory_graph_archive_write_failed');
1519
+ }
1520
+ if (existing) {
1521
+ const current = lstatSync(path, { bigint: true });
1522
+ if (!current.isFile() || current.isSymbolicLink())
221
1523
  throw new Error('memory_graph_archive_path_rejected');
222
- unlinkSync(temp);
223
- return;
1524
+ if (!sameMigrationSourceSnapshot(existing.stat, current)) {
1525
+ if (hashRegularFile(path, 'memory_graph_archive_path_rejected').digest === snapshot.digest)
1526
+ return;
1527
+ throw new Error('memory_graph_archive_content_conflict');
1528
+ }
1529
+ // Same-directory rename keeps the old archive visible until the verified replacement is published.
1530
+ renameSync(temp, path);
1531
+ }
1532
+ else {
1533
+ try {
1534
+ // Hard-link publication is a no-clobber atomic create for the common first-import case.
1535
+ linkSync(temp, path);
1536
+ }
1537
+ catch (error) {
1538
+ if (error.code !== 'EEXIST')
1539
+ throw error;
1540
+ const incumbent = hashRegularFile(path, 'memory_graph_archive_path_rejected');
1541
+ if (incumbent.digest !== snapshot.digest) {
1542
+ const current = lstatSync(path, { bigint: true });
1543
+ if (!current.isFile() || current.isSymbolicLink()
1544
+ || !sameMigrationSourceSnapshot(incumbent.stat, current)) {
1545
+ throw new Error('memory_graph_archive_content_conflict');
1546
+ }
1547
+ renameSync(temp, path);
1548
+ }
1549
+ }
1550
+ }
1551
+ if (hashRegularFile(path, 'memory_graph_archive_path_rejected').digest !== snapshot.digest) {
1552
+ throw new Error('memory_graph_archive_content_conflict');
224
1553
  }
225
- // A same-directory hard link publishes without replacing a path created by a concurrent process.
226
- linkSync(temp, destination);
227
- unlinkSync(temp);
228
1554
  }
229
- catch (error) {
1555
+ finally {
1556
+ if (fd !== undefined)
1557
+ closeSync(fd);
230
1558
  try {
231
- if (existsSync(temp))
1559
+ const atPath = lstatSync(temp, { bigint: true });
1560
+ if (tempStat && atPath.isFile() && !atPath.isSymbolicLink()
1561
+ && sameMigrationSourceIdentity(tempStat, atPath))
232
1562
  unlinkSync(temp);
233
1563
  }
234
1564
  catch {
235
- // Preserve the publication failure; cleanup is best-effort.
1565
+ // Keep the archive result authoritative; the random, mode-0600 temp is safe to clean on a later run.
236
1566
  }
237
- throw error;
238
1567
  }
1568
+ }
1569
+ function archiveMemoryGraphSnapshot(snapshot, archiveDir) {
1570
+ mkdirSync(archiveDir, { recursive: true, mode: 0o700 });
1571
+ const archiveDirStat = lstatSync(archiveDir);
1572
+ if (!archiveDirStat.isDirectory() || archiveDirStat.isSymbolicLink()) {
1573
+ throw new Error('memory_graph_archive_path_rejected');
1574
+ }
1575
+ const versioned = join(archiveDir, `legacy_memory_graph.${snapshot.digest}.jsonl`);
1576
+ ensureArchiveContent(snapshot, versioned);
1577
+ const legacy = join(archiveDir, 'legacy_memory_graph.jsonl');
1578
+ ensureArchiveContent(snapshot, legacy);
239
1579
  }