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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/dist/antiGeneBenchmark.js +2 -0
  2. package/dist/antiGeneRollout.js +2 -0
  3. package/dist/assetRepair.d.ts +24 -0
  4. package/dist/assetRepair.js +172 -0
  5. package/dist/autoDistillAntiGene.js +7 -5
  6. package/dist/autoDistillLlm.d.ts +20 -0
  7. package/dist/autoDistillLlm.js +77 -15
  8. package/dist/autoexec.d.ts +11 -0
  9. package/dist/autoexec.js +65 -10
  10. package/dist/autoexecConfig.js +2 -1
  11. package/dist/cliContracts.d.ts +10 -0
  12. package/dist/cliContracts.js +407 -81
  13. package/dist/commandCatalog.d.ts +72 -0
  14. package/dist/commandCatalog.js +120 -0
  15. package/dist/cycleConsumer.d.ts +9 -0
  16. package/dist/cycleConsumer.js +14 -3
  17. package/dist/dispatch.d.ts +0 -1
  18. package/dist/dispatch.js +10 -4
  19. package/dist/distillObserver.js +23 -6
  20. package/dist/doctor.d.ts +11 -0
  21. package/dist/doctor.js +81 -6
  22. package/dist/index.d.ts +5 -1
  23. package/dist/index.js +200 -68
  24. package/dist/lifecycle.d.ts +126 -3
  25. package/dist/lifecycle.js +4390 -188
  26. package/dist/lifecycleBootstrapTransaction.d.ts +235 -0
  27. package/dist/lifecycleBootstrapTransaction.js +2182 -0
  28. package/dist/localMemoryGraph.d.ts +90 -3
  29. package/dist/localMemoryGraph.js +2031 -231
  30. package/dist/materialSnapshot.d.ts +2 -0
  31. package/dist/materialSnapshot.js +8 -0
  32. package/dist/memoryGraphOps.d.ts +8 -0
  33. package/dist/memoryGraphOps.js +140 -0
  34. package/dist/migrate/assetFormatMap.d.ts +61 -0
  35. package/dist/migrate/assetFormatMap.js +53 -0
  36. package/dist/migrate/envTranslate.js +2 -0
  37. package/dist/migrate/fieldMap.d.ts +7 -5
  38. package/dist/migrate/fieldMap.js +20 -14
  39. package/dist/migrate/v1Import.d.ts +80 -1
  40. package/dist/migrate/v1Import.js +961 -120
  41. package/dist/modelCompatibility.d.ts +10 -0
  42. package/dist/modelCompatibility.js +296 -0
  43. package/dist/recipe.d.ts +7 -1
  44. package/dist/recipe.js +113 -11
  45. package/dist/repairedAssetStore.d.ts +2 -0
  46. package/dist/repairedAssetStore.js +12 -0
  47. package/dist/reuse.d.ts +4 -1
  48. package/dist/reuse.js +212 -107
  49. package/dist/reviewFilter.d.ts +3 -1
  50. package/dist/reviewFilter.js +3 -1
  51. package/dist/runtimeSessionSource.d.ts +5 -0
  52. package/dist/selectionPolicyConfig.d.ts +8 -0
  53. package/dist/selectionPolicyConfig.js +18 -0
  54. package/dist/semanticIdfConfig.d.ts +2 -0
  55. package/dist/semanticIdfConfig.js +4 -0
  56. package/dist/sessionIngest.d.ts +7 -1
  57. package/dist/sessionIngest.js +25 -1
  58. package/dist/setupHooks.js +12 -6
  59. package/dist/skill2gep.js +57 -6
  60. package/dist/skillDistill.js +1 -0
  61. package/dist/sync.d.ts +1 -1
  62. package/dist/sync.js +761 -174
  63. package/dist/thesis.js +2 -0
  64. package/dist/valueDigest.js +8 -1
  65. package/dist/windowsLegacyTaskCleanup.d.ts +228 -0
  66. package/dist/windowsLegacyTaskCleanup.js +1475 -0
  67. package/dist/workflowRuntime.js +7 -6
  68. package/package.json +7 -7
@@ -1,15 +1,288 @@
1
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';
3
- import { basename, dirname, join, resolve, sep } from 'node:path';
4
- import { assetstore, mailbox, util } from '@evomap/evolver-core';
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';
5
6
  import { mapV1Asset } from './fieldMap.js';
7
+ import { V1_GEP_SOURCE_LAYOUT, V1_GEP_WIRE_SOURCES } from './assetFormatMap.js';
6
8
  import { LocalMemoryGraph, MemoryGraphBusyError, MemoryGraphImportStateRejectedError, resolveLocalMemoryUserId, } from '../localMemoryGraph.js';
7
- const FILES = { Gene: 'genes.jsonl', Capsule: 'capsules.jsonl', EvolutionEvent: 'events.jsonl' };
8
9
  const DEFAULT_IMPORT_JSONL_MAX_LINE_BYTES = 16 * 1024 * 1024;
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;
9
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
+ }
10
42
  function maxJsonlLineBytes() {
11
- const raw = Number(process.env['EVOLVER_IMPORT_JSONL_MAX_LINE_BYTES']);
12
- 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);
44
+ }
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);
13
286
  }
14
287
  async function* readJsonl(source) {
15
288
  if (typeof source === 'string' && !existsSync(source))
@@ -23,23 +296,30 @@ async function* readJsonl(source) {
23
296
  let lineBytes = 0;
24
297
  let dropping = false;
25
298
  const finish = function* () {
26
- if (dropping || lineBytes === 0) {
299
+ if (dropping) {
27
300
  parts = [];
28
301
  lineBytes = 0;
29
302
  dropping = false;
30
- return;
303
+ throw new Error('migration_v1_jsonl_line_too_large');
31
304
  }
32
- 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();
33
308
  parts = [];
34
309
  lineBytes = 0;
35
310
  if (!text)
36
311
  return;
37
312
  try {
38
313
  const parsed = JSON.parse(text);
39
- if (isPlainRecord(parsed))
40
- yield parsed;
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');
41
322
  }
42
- catch { /* skip corrupt rows */ }
43
323
  };
44
324
  try {
45
325
  if (typeof source === 'number') {
@@ -95,115 +375,620 @@ async function* readJsonl(source) {
95
375
  closeSync(fd);
96
376
  }
97
377
  }
98
- export async function importV1(v1Dir, store, outDir, options = {}) {
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');
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;
593
+ else {
594
+ kindCounts.writes += 1;
595
+ existingAssets.set(record.asset_id, record);
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
+ });
622
+ }
623
+ }
624
+ return {
625
+ assets: counts,
626
+ provenance: { candidates: provenanceCandidates, writes: provenanceWrites, preserved: provenancePreserved },
627
+ };
628
+ }
629
+ function planSourceOrder(source) {
630
+ return IMPORT_V1_SOURCE_ROLES.indexOf(source.role);
631
+ }
632
+ export async function planImportV1(v1Dir, outDir, options = {}) {
99
633
  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'));
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,
652
+ };
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);
673
+ }
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);
104
895
  const sidecarPath = join(migrationDir, 'v1_extensions.jsonl');
105
896
  const rep = {
106
- imported: { Gene: 0, Capsule: 0, EvolutionEvent: 0 }, frozen: 0, recomputed: 0, deduped: 0,
107
- sidecarExtensions: 0, memoryGraphArchived: false, memoryGraphImported: 0, memoryGraphDeferred: false, candidatesSkipped: false,
108
- mailboxFound: false, mailboxImported: 0,
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,
109
900
  };
110
- const gepDir = join(v1Dir, 'assets', 'gep');
111
- for (const kind of ['Gene', 'Capsule', 'EvolutionEvent']) {
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);
120
- if (Object.keys(mapped.dropped).length > 0) {
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;
136
- }
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;
137
907
  }
138
908
  }
139
- finally {
140
- closeMigrationSnapshot(snapshot);
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;
141
924
  }
142
925
  }
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');
926
+ if (state.mailboxSnapshot) {
927
+ if (!mailboxPath || !state.mailboxBatch)
928
+ throw new Error('migration_plan_invalid');
150
929
  let target;
151
930
  try {
152
931
  assertSafeMailboxTarget(mailboxPath);
153
932
  target = new mailbox.MailboxStore({ path: mailboxPath });
154
933
  assertSafeMailboxTarget(mailboxPath);
155
- rep.mailboxImported = target.importJsonl(mailboxSnapshot.fd);
934
+ rep.mailboxImported = target.importPrepared(state.mailboxBatch);
156
935
  }
157
936
  finally {
158
937
  target?.close();
159
- closeMigrationSnapshot(mailboxSnapshot);
160
938
  }
161
939
  }
162
- // memory_graph remains a sidecar: never convert it into EvolutionEvent or mutate Gene/Capsule identity.
163
- const mg = join(v1Dir, 'memory', 'evolution', 'memory_graph.jsonl');
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) {
940
+ if (state.memorySnapshot && state.memorySource) {
941
+ archiveMemoryGraphSnapshot(state.memorySnapshot, migrationDir);
942
+ rep.memoryGraphArchived = true;
943
+ const workspace = state.workspace;
944
+ if (!workspace || state.memoryPlanDeferred) {
945
+ rep.memoryGraphDeferred = true;
946
+ }
947
+ else {
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;
172
962
  rep.memoryGraphDeferred = true;
173
963
  }
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);
194
- }
195
- }
964
+ if (!rep.memoryGraphDeferred && !markerExists) {
965
+ writeMemoryGraphMarker(marker, `${rep.memoryGraphImported}\n`, options.memoryGraphMarkerTestHook);
196
966
  }
197
967
  }
198
- finally {
199
- closeMigrationSnapshot(memorySnapshot);
200
- }
201
968
  }
202
- // candidates 候选池非 wire 资产 → 不迁移(留作 selection 输入)
203
- if (existsSync(join(gepDir, 'candidates.jsonl')))
204
- rep.candidatesSkipped = true;
205
969
  return rep;
206
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
+ }
207
992
  function canonicalDirectory(path) {
208
993
  try {
209
994
  const absolute = resolve(path);
@@ -257,13 +1042,18 @@ export function validateMigrationRoots(v1Dir, outDir) {
257
1042
  assertMigrationRootsDisjoint(sourceRoot, outputRoot);
258
1043
  return { sourceRoot, outputRoot };
259
1044
  }
260
- function secureOutputRoot(path) {
1045
+ function secureOutputRoot(path, expectedRoot) {
1046
+ if (canonicalProspectiveDirectory(path) !== expectedRoot)
1047
+ throw new Error('migration_target_changed');
261
1048
  const absolute = resolve(path);
262
1049
  mkdirSync(absolute, { recursive: true, mode: 0o700 });
263
1050
  const stat = lstatSync(absolute);
264
1051
  if (!stat.isDirectory() || stat.isSymbolicLink())
265
1052
  throw new Error('migration_output_path_rejected');
266
- return realpathSync(absolute);
1053
+ const canonical = realpathSync(absolute);
1054
+ if (canonical !== expectedRoot)
1055
+ throw new Error('migration_target_changed');
1056
+ return canonical;
267
1057
  }
268
1058
  function ensureSafeOutputDirectory(root, requested) {
269
1059
  const absolute = resolve(requested);
@@ -316,8 +1106,9 @@ async function ensureMigrationExtension(path, assetId, dropped, testHook) {
316
1106
  async function ensureMigrationExtensionLocked(path, assetId, dropped, testHook) {
317
1107
  if (existsSync(path)) {
318
1108
  const before = lstatSync(path);
319
- if (!before.isFile() || before.isSymbolicLink())
1109
+ if (!before.isFile() || before.isSymbolicLink() || before.nlink > 1) {
320
1110
  throw new Error('migration_extension_path_rejected');
1111
+ }
321
1112
  const fd = openSync(path, constants.O_RDONLY | noFollowFlag());
322
1113
  try {
323
1114
  const opened = fstatSync(fd);
@@ -340,8 +1131,17 @@ async function ensureMigrationExtensionLocked(path, assetId, dropped, testHook)
340
1131
  testHook?.('before-append', path);
341
1132
  const fd = openSync(path, constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT | noFollowFlag(), 0o600);
342
1133
  try {
343
- if (!fstatSync(fd).isFile())
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) {
344
1143
  throw new Error('migration_extension_path_rejected');
1144
+ }
345
1145
  writeFileSync(fd, `${JSON.stringify({ asset_id: assetId, dropped })}\n`, 'utf8');
346
1146
  fsyncSync(fd);
347
1147
  }
@@ -356,14 +1156,26 @@ function scopedMemoryGraphMarker(migrationDir, workspace, userId, source, source
356
1156
  return join(migrationDir, `v1_memory_graph_import.${scope}.complete`);
357
1157
  }
358
1158
  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')
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;
366
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');
367
1179
  }
368
1180
  }
369
1181
  function hasSafeMemoryGraphMarker(path) {
@@ -452,21 +1264,39 @@ function writeMemoryGraphMarker(path, content, testHook) {
452
1264
  throw cleanupError;
453
1265
  }
454
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;
455
1277
  try {
456
- const absoluteRoot = resolve(root);
457
- const absolutePath = resolve(path);
458
- const rootStat = lstatSync(absoluteRoot);
459
- const fileStat = lstatSync(absolutePath, { bigint: true });
460
- if (!rootStat.isDirectory() || rootStat.isSymbolicLink() || !fileStat.isFile() || fileStat.isSymbolicLink())
1278
+ fileStat = lstatSync(absolutePath, { bigint: true });
1279
+ }
1280
+ catch (error) {
1281
+ if (error.code === 'ENOENT')
461
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 {
462
1289
  const canonicalRoot = realpathSync(absoluteRoot);
463
1290
  const canonicalPath = realpathSync(absolutePath);
464
- if (!canonicalPath.startsWith(canonicalRoot.endsWith(sep) ? canonicalRoot : `${canonicalRoot}${sep}`))
465
- return null;
1291
+ if (!canonicalPath.startsWith(canonicalRoot.endsWith(sep) ? canonicalRoot : `${canonicalRoot}${sep}`)) {
1292
+ throw new Error('migration_source_path_rejected');
1293
+ }
466
1294
  return { requestedPath: absolutePath, canonicalPath, stat: fileStat };
467
1295
  }
468
- catch {
469
- return null;
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');
470
1300
  }
471
1301
  }
472
1302
  function sameMigrationSourceIdentity(left, right) {
@@ -486,7 +1316,7 @@ function noFollowFlag() {
486
1316
  ? constants.O_NOFOLLOW
487
1317
  : 0;
488
1318
  }
489
- function createMigrationSnapshot(source, snapshotDir, label, testHook) {
1319
+ function createMigrationSnapshot(source, snapshotDir, label, testHook, limit) {
490
1320
  const snapshotDirStat = lstatSync(snapshotDir);
491
1321
  if (!snapshotDirStat.isDirectory() || snapshotDirStat.isSymbolicLink()) {
492
1322
  throw new Error('migration_snapshot_dir_rejected');
@@ -503,8 +1333,13 @@ function createMigrationSnapshot(source, snapshotDir, label, testHook) {
503
1333
  if (!opened.isFile() || !sameMigrationSourceSnapshot(source.stat, opened)) {
504
1334
  throw new Error('migration_source_changed');
505
1335
  }
1336
+ if (limit && opened.size > BigInt(limit.maxBytes))
1337
+ throw new Error(limit.error);
506
1338
  testHook?.('after-open', source.requestedPath);
507
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');
508
1343
  const digest = createHash('sha256');
509
1344
  const buffer = Buffer.alloc(64 * 1024);
510
1345
  let snapshotOffset = 0;
@@ -512,6 +1347,8 @@ function createMigrationSnapshot(source, snapshotDir, label, testHook) {
512
1347
  const bytesRead = readSync(sourceFd, buffer, 0, buffer.length, null);
513
1348
  if (bytesRead === 0)
514
1349
  break;
1350
+ if (limit && snapshotOffset > limit.maxBytes - bytesRead)
1351
+ throw new Error(limit.error);
515
1352
  digest.update(buffer.subarray(0, bytesRead));
516
1353
  let offset = 0;
517
1354
  while (offset < bytesRead) {
@@ -594,10 +1431,12 @@ function closeMigrationSnapshot(snapshot) {
594
1431
  throw error;
595
1432
  }
596
1433
  }
597
- function hashOpenDescriptor(fd, errorCode) {
1434
+ function hashOpenDescriptor(fd, errorCode, limit) {
598
1435
  const before = fstatSync(fd, { bigint: true });
599
1436
  if (!before.isFile())
600
1437
  throw new Error(errorCode);
1438
+ if (limit && before.size > BigInt(limit.maxBytes))
1439
+ throw new Error(limit.error);
601
1440
  const hash = createHash('sha256');
602
1441
  const buffer = Buffer.alloc(64 * 1024);
603
1442
  let position = 0;
@@ -605,6 +1444,8 @@ function hashOpenDescriptor(fd, errorCode) {
605
1444
  const bytesRead = readSync(fd, buffer, 0, buffer.length, position);
606
1445
  if (bytesRead === 0)
607
1446
  break;
1447
+ if (limit && position > limit.maxBytes - bytesRead)
1448
+ throw new Error(limit.error);
608
1449
  position += bytesRead;
609
1450
  hash.update(buffer.subarray(0, bytesRead));
610
1451
  }
@@ -613,7 +1454,7 @@ function hashOpenDescriptor(fd, errorCode) {
613
1454
  throw new Error(errorCode);
614
1455
  return { digest: hash.digest('hex'), stat: after };
615
1456
  }
616
- function hashRegularFile(path, errorCode) {
1457
+ function hashRegularFile(path, errorCode, limit) {
617
1458
  const before = lstatSync(path, { bigint: true });
618
1459
  if (!before.isFile() || before.isSymbolicLink())
619
1460
  throw new Error(errorCode);
@@ -622,7 +1463,7 @@ function hashRegularFile(path, errorCode) {
622
1463
  const opened = fstatSync(fd, { bigint: true });
623
1464
  if (!opened.isFile() || !sameMigrationSourceSnapshot(before, opened))
624
1465
  throw new Error(errorCode);
625
- const hashed = hashOpenDescriptor(fd, errorCode);
1466
+ const hashed = hashOpenDescriptor(fd, errorCode, limit);
626
1467
  const afterPath = lstatSync(path, { bigint: true });
627
1468
  if (!sameMigrationSourceSnapshot(opened, hashed.stat)
628
1469
  || !afterPath.isFile()