@evomap/evolver-cli 2.0.0-beta.2 → 2.0.0-beta.22
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/antiGeneBenchmark.js +2 -0
- package/dist/antiGeneRollout.js +9 -3
- package/dist/assetHealth.d.ts +6 -0
- package/dist/assetHealth.js +107 -0
- package/dist/assetRepair.d.ts +24 -0
- package/dist/assetRepair.js +172 -0
- package/dist/assetSidecarRecovery.d.ts +14 -0
- package/dist/assetSidecarRecovery.js +171 -0
- package/dist/assetTrust.d.ts +24 -0
- package/dist/assetTrust.js +231 -0
- package/dist/atp.d.ts +10 -5
- package/dist/atp.js +119 -26
- package/dist/atpAutoBuyer.d.ts +120 -0
- package/dist/atpAutoBuyer.js +814 -0
- package/dist/atpAutoDeliver.js +2 -2
- package/dist/autoDistillAntiGene.js +7 -5
- package/dist/autoDistillLlm.d.ts +26 -0
- package/dist/autoDistillLlm.js +119 -22
- package/dist/autoDistillTranscript.js +3 -2
- package/dist/autoexec.d.ts +111 -24
- package/dist/autoexec.js +887 -120
- package/dist/autoexecConfig.d.ts +10 -0
- package/dist/autoexecConfig.js +69 -0
- package/dist/cli.js +13 -0
- package/dist/cliContracts.d.ts +33 -2
- package/dist/cliContracts.js +818 -78
- package/dist/commandCatalog.d.ts +72 -0
- package/dist/commandCatalog.js +120 -0
- package/dist/commands.d.ts +1 -0
- package/dist/commands.js +1 -0
- package/dist/curriculumCapabilityGaps.d.ts +6 -0
- package/dist/curriculumCapabilityGaps.js +24 -0
- package/dist/cycleConsumer.d.ts +17 -2
- package/dist/cycleConsumer.js +374 -50
- package/dist/dashboard.d.ts +13 -1
- package/dist/dashboard.js +235 -18
- package/dist/dispatch.d.ts +9 -2
- package/dist/dispatch.js +29 -6
- package/dist/distillAdmission.d.ts +13 -0
- package/dist/distillAdmission.js +35 -0
- package/dist/distillObserver.js +27 -12
- package/dist/distillPrimitives.d.ts +11 -8
- package/dist/distillPrimitives.js +116 -22
- package/dist/doctor.d.ts +13 -0
- package/dist/doctor.js +177 -10
- package/dist/identityHome.d.ts +9 -0
- package/dist/identityHome.js +47 -0
- package/dist/index.d.ts +73 -40
- package/dist/index.js +745 -207
- package/dist/issueReport.d.ts +7 -0
- package/dist/issueReport.js +291 -0
- package/dist/learningTrace.d.ts +15 -0
- package/dist/learningTrace.js +73 -0
- package/dist/lifecycle.d.ts +199 -2
- package/dist/lifecycle.js +4999 -152
- package/dist/lifecycleBootstrapTransaction.d.ts +235 -0
- package/dist/lifecycleBootstrapTransaction.js +2182 -0
- package/dist/localMemoryGraph.d.ts +184 -0
- package/dist/localMemoryGraph.js +2689 -0
- package/dist/login.d.ts +1 -1
- package/dist/login.js +3 -3
- package/dist/materialPackage.js +3 -6
- package/dist/materialSnapshot.d.ts +35 -1
- package/dist/materialSnapshot.js +265 -18
- package/dist/memoryGraphOps.d.ts +8 -0
- package/dist/memoryGraphOps.js +140 -0
- package/dist/migrate/assetFormatMap.d.ts +61 -0
- package/dist/migrate/assetFormatMap.js +53 -0
- package/dist/migrate/envTranslate.d.ts +26 -0
- package/dist/migrate/envTranslate.js +147 -0
- package/dist/migrate/fieldMap.d.ts +7 -5
- package/dist/migrate/fieldMap.js +20 -14
- package/dist/migrate/oauthImport.d.ts +66 -0
- package/dist/migrate/oauthImport.js +667 -0
- package/dist/migrate/v1Import.d.ts +98 -1
- package/dist/migrate/v1Import.js +1532 -71
- package/dist/modelCompatibility.d.ts +10 -0
- package/dist/modelCompatibility.js +296 -0
- package/dist/promptRecallHook.d.ts +24 -0
- package/dist/promptRecallHook.js +425 -0
- package/dist/recallVerifyReport.d.ts +37 -0
- package/dist/recallVerifyReport.js +244 -0
- package/dist/recipe.d.ts +14 -2
- package/dist/recipe.js +543 -65
- package/dist/repairedAssetStore.d.ts +2 -0
- package/dist/repairedAssetStore.js +12 -0
- package/dist/requiredSandboxValidation.d.ts +5 -0
- package/dist/requiredSandboxValidation.js +4 -0
- package/dist/reuse.d.ts +18 -4
- package/dist/reuse.js +375 -107
- package/dist/reviewFilter.d.ts +3 -1
- package/dist/reviewFilter.js +3 -1
- package/dist/runtimeCapabilities.d.ts +18 -0
- package/dist/runtimeCapabilities.js +81 -0
- package/dist/runtimeSessionSource.d.ts +8 -2
- package/dist/runtimeSessionSource.js +63 -11
- package/dist/selectionPolicyConfig.d.ts +8 -0
- package/dist/selectionPolicyConfig.js +18 -0
- package/dist/semanticIdfConfig.d.ts +2 -0
- package/dist/semanticIdfConfig.js +4 -0
- package/dist/sessionIngest.d.ts +43 -0
- package/dist/sessionIngest.js +180 -0
- package/dist/setupHooks.d.ts +5 -0
- package/dist/setupHooks.js +330 -14
- package/dist/skill2gep.d.ts +13 -9
- package/dist/skill2gep.js +99 -36
- package/dist/skillDistill.d.ts +8 -4
- package/dist/skillDistill.js +39 -9
- package/dist/solo/mode.js +1 -0
- package/dist/sync.d.ts +13 -1
- package/dist/sync.js +1947 -265
- package/dist/thesis.d.ts +1 -1
- package/dist/thesis.js +20 -3
- package/dist/trajectoryExport.js +21 -3
- package/dist/v1Compat.d.ts +1 -0
- package/dist/v1Compat.js +9 -0
- package/dist/valueDigest.js +8 -1
- package/dist/windowsLegacyTaskCleanup.d.ts +228 -0
- package/dist/windowsLegacyTaskCleanup.js +1475 -0
- package/dist/workflow.d.ts +39 -0
- package/dist/workflow.js +386 -0
- package/dist/workflowRuntime.d.ts +66 -0
- package/dist/workflowRuntime.js +638 -0
- package/package.json +14 -7
package/dist/migrate/v1Import.js
CHANGED
|
@@ -1,46 +1,361 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { existsSync, mkdirSync,
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
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';
|
|
5
6
|
import { mapV1Asset } from './fieldMap.js';
|
|
6
|
-
|
|
7
|
+
import { V1_GEP_SOURCE_LAYOUT, V1_GEP_WIRE_SOURCES } from './assetFormatMap.js';
|
|
8
|
+
import { LocalMemoryGraph, MemoryGraphBusyError, MemoryGraphImportStateRejectedError, resolveLocalMemoryUserId, } from '../localMemoryGraph.js';
|
|
7
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;
|
|
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
|
+
}
|
|
8
42
|
function maxJsonlLineBytes() {
|
|
9
|
-
|
|
10
|
-
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);
|
|
11
44
|
}
|
|
12
|
-
|
|
13
|
-
|
|
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))
|
|
14
289
|
return;
|
|
15
290
|
const maxLineBytes = maxJsonlLineBytes();
|
|
291
|
+
const buffer = Buffer.allocUnsafe(JSONL_READ_CHUNK_BYTES);
|
|
292
|
+
let fd;
|
|
293
|
+
let ownsFd = false;
|
|
294
|
+
let position = 0;
|
|
16
295
|
let parts = [];
|
|
17
296
|
let lineBytes = 0;
|
|
18
297
|
let dropping = false;
|
|
19
298
|
const finish = function* () {
|
|
20
|
-
if (dropping
|
|
299
|
+
if (dropping) {
|
|
21
300
|
parts = [];
|
|
22
301
|
lineBytes = 0;
|
|
23
302
|
dropping = false;
|
|
24
|
-
|
|
303
|
+
throw new Error('migration_v1_jsonl_line_too_large');
|
|
25
304
|
}
|
|
26
|
-
|
|
305
|
+
if (lineBytes === 0)
|
|
306
|
+
return;
|
|
307
|
+
const text = decodeImportUtf8(Buffer.concat(parts, lineBytes), 'migration_v1_jsonl_invalid_utf8').trim();
|
|
27
308
|
parts = [];
|
|
28
309
|
lineBytes = 0;
|
|
29
310
|
if (!text)
|
|
30
311
|
return;
|
|
31
312
|
try {
|
|
32
|
-
|
|
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');
|
|
33
322
|
}
|
|
34
|
-
catch { /* skip corrupt rows */ }
|
|
35
323
|
};
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
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);
|
|
44
359
|
if (lineBytes + segment.length > maxLineBytes) {
|
|
45
360
|
parts = [];
|
|
46
361
|
lineBytes = 0;
|
|
@@ -51,68 +366,1214 @@ async function* readJsonl(path) {
|
|
|
51
366
|
lineBytes += segment.length;
|
|
52
367
|
}
|
|
53
368
|
}
|
|
54
|
-
for (const record of finish())
|
|
55
|
-
yield record;
|
|
56
|
-
start = i + 1;
|
|
57
369
|
}
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
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');
|
|
64
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;
|
|
65
593
|
else {
|
|
66
|
-
|
|
67
|
-
|
|
594
|
+
kindCounts.writes += 1;
|
|
595
|
+
existingAssets.set(record.asset_id, record);
|
|
68
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
|
+
});
|
|
69
622
|
}
|
|
70
623
|
}
|
|
71
|
-
|
|
72
|
-
|
|
624
|
+
return {
|
|
625
|
+
assets: counts,
|
|
626
|
+
provenance: { candidates: provenanceCandidates, writes: provenanceWrites, preserved: provenancePreserved },
|
|
627
|
+
};
|
|
73
628
|
}
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
const
|
|
81
|
-
|
|
82
|
-
|
|
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,
|
|
83
652
|
};
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
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);
|
|
100
673
|
}
|
|
101
|
-
|
|
102
|
-
|
|
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;
|
|
103
714
|
}
|
|
104
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;
|
|
105
832
|
}
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
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;
|
|
907
|
+
}
|
|
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
|
+
}
|
|
939
|
+
}
|
|
940
|
+
if (state.memorySnapshot && state.memorySource) {
|
|
941
|
+
archiveMemoryGraphSnapshot(state.memorySnapshot, migrationDir);
|
|
112
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;
|
|
962
|
+
rep.memoryGraphDeferred = true;
|
|
963
|
+
}
|
|
964
|
+
if (!rep.memoryGraphDeferred && !markerExists) {
|
|
965
|
+
writeMemoryGraphMarker(marker, `${rep.memoryGraphImported}\n`, options.memoryGraphMarkerTestHook);
|
|
966
|
+
}
|
|
967
|
+
}
|
|
113
968
|
}
|
|
114
|
-
// candidates 候选池非 wire 资产 → 不迁移(留作 selection 输入)
|
|
115
|
-
if (existsSync(join(gepDir, 'candidates.jsonl')))
|
|
116
|
-
rep.candidatesSkipped = true;
|
|
117
969
|
return rep;
|
|
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
|
+
}
|
|
992
|
+
function canonicalDirectory(path) {
|
|
993
|
+
try {
|
|
994
|
+
const absolute = resolve(path);
|
|
995
|
+
const stat = lstatSync(absolute);
|
|
996
|
+
return stat.isDirectory() && !stat.isSymbolicLink() ? realpathSync(absolute) : null;
|
|
997
|
+
}
|
|
998
|
+
catch {
|
|
999
|
+
return null;
|
|
1000
|
+
}
|
|
1001
|
+
}
|
|
1002
|
+
function isPlainRecord(value) {
|
|
1003
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
1004
|
+
}
|
|
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;
|
|
1183
|
+
try {
|
|
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')
|
|
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 {
|
|
1289
|
+
const canonicalRoot = realpathSync(absoluteRoot);
|
|
1290
|
+
const canonicalPath = realpathSync(absolutePath);
|
|
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 };
|
|
1295
|
+
}
|
|
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');
|
|
1300
|
+
}
|
|
1301
|
+
}
|
|
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');
|
|
1323
|
+
}
|
|
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;
|
|
1331
|
+
try {
|
|
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');
|
|
1344
|
+
const buffer = Buffer.alloc(64 * 1024);
|
|
1345
|
+
let snapshotOffset = 0;
|
|
1346
|
+
for (;;) {
|
|
1347
|
+
const bytesRead = readSync(sourceFd, buffer, 0, buffer.length, null);
|
|
1348
|
+
if (bytesRead === 0)
|
|
1349
|
+
break;
|
|
1350
|
+
if (limit && snapshotOffset > limit.maxBytes - bytesRead)
|
|
1351
|
+
throw new Error(limit.error);
|
|
1352
|
+
digest.update(buffer.subarray(0, bytesRead));
|
|
1353
|
+
let offset = 0;
|
|
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;
|
|
1361
|
+
}
|
|
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 };
|
|
1399
|
+
}
|
|
1400
|
+
finally {
|
|
1401
|
+
closeSync(sourceFd);
|
|
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
|
+
}
|
|
1417
|
+
}
|
|
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);
|
|
1427
|
+
}
|
|
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);
|
|
1473
|
+
}
|
|
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;
|
|
1486
|
+
}
|
|
1487
|
+
const temp = join(dirname(path), `.${basename(path)}.${randomUUID()}.tmp`);
|
|
1488
|
+
let fd;
|
|
1489
|
+
let tempStat;
|
|
1490
|
+
try {
|
|
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())
|
|
1523
|
+
throw new Error('memory_graph_archive_path_rejected');
|
|
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');
|
|
1553
|
+
}
|
|
1554
|
+
}
|
|
1555
|
+
finally {
|
|
1556
|
+
if (fd !== undefined)
|
|
1557
|
+
closeSync(fd);
|
|
1558
|
+
try {
|
|
1559
|
+
const atPath = lstatSync(temp, { bigint: true });
|
|
1560
|
+
if (tempStat && atPath.isFile() && !atPath.isSymbolicLink()
|
|
1561
|
+
&& sameMigrationSourceIdentity(tempStat, atPath))
|
|
1562
|
+
unlinkSync(temp);
|
|
1563
|
+
}
|
|
1564
|
+
catch {
|
|
1565
|
+
// Keep the archive result authoritative; the random, mode-0600 temp is safe to clean on a later run.
|
|
1566
|
+
}
|
|
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);
|
|
118
1579
|
}
|