@evomap/evolver-cli 2.0.0-beta.1 → 2.0.0-beta.4
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 +12 -0
- package/dist/antiGeneEvidence.d.ts +15 -0
- package/dist/antiGeneEvidence.js +49 -0
- package/dist/antiGeneRollout.d.ts +3 -1
- package/dist/antiGeneRollout.js +16 -2
- package/dist/assetHealth.d.ts +6 -0
- package/dist/assetHealth.js +105 -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 +218 -0
- package/dist/atp.js +4 -2
- package/dist/autoDistillLlm.js +4 -1
- package/dist/autoexec.d.ts +13 -3
- package/dist/autoexec.js +71 -13
- package/dist/cli.js +12 -5
- package/dist/cliContracts.js +8 -2
- package/dist/cliLifecycle.d.ts +7 -0
- package/dist/cliLifecycle.js +9 -0
- package/dist/cycleConsumer.d.ts +61 -1
- package/dist/cycleConsumer.js +551 -16
- package/dist/dashboard.d.ts +23 -0
- package/dist/dashboard.js +191 -0
- package/dist/dispatch.d.ts +10 -1
- package/dist/dispatch.js +36 -2
- package/dist/distillObserver.js +2 -2
- package/dist/distillPrimitives.d.ts +1 -1
- package/dist/distillPrimitives.js +29 -2
- package/dist/doctor.d.ts +2 -0
- package/dist/doctor.js +33 -3
- package/dist/index.d.ts +7 -2
- package/dist/index.js +292 -36
- package/dist/lifecycle.d.ts +19 -1
- package/dist/lifecycle.js +226 -29
- package/dist/localMemoryGraph.d.ts +97 -0
- package/dist/localMemoryGraph.js +889 -0
- package/dist/login.d.ts +20 -4
- package/dist/login.js +58 -8
- package/dist/materialPackage.d.ts +52 -0
- package/dist/materialPackage.js +404 -0
- package/dist/materialSnapshot.d.ts +30 -0
- package/dist/materialSnapshot.js +148 -0
- package/dist/memoryEventMirror.d.ts +23 -0
- package/dist/memoryEventMirror.js +140 -0
- package/dist/migrate/fieldMap.js +25 -0
- package/dist/migrate/v1Import.d.ts +7 -1
- package/dist/migrate/v1Import.js +132 -11
- package/dist/nonGitWorkspaceNotice.d.ts +24 -0
- package/dist/nonGitWorkspaceNotice.js +122 -0
- package/dist/proxyToken.d.ts +10 -0
- package/dist/proxyToken.js +80 -0
- package/dist/recipe.d.ts +10 -2
- package/dist/recipe.js +349 -7
- package/dist/reuseReport.js +16 -16
- package/dist/runtimeCapabilities.d.ts +18 -0
- package/dist/runtimeCapabilities.js +81 -0
- package/dist/runtimeSessionSource.d.ts +10 -0
- package/dist/runtimeSessionSource.js +32 -5
- package/dist/setupHooks.d.ts +6 -1
- package/dist/setupHooks.js +5 -2
- package/dist/skill2gep.d.ts +38 -9
- package/dist/skill2gep.js +147 -14
- package/dist/skillDistill.d.ts +1 -0
- package/dist/skillDistill.js +4 -4
- package/dist/skillFetch.d.ts +18 -0
- package/dist/skillFetch.js +391 -0
- package/dist/solo/mode.js +5 -0
- package/dist/sync.d.ts +26 -0
- package/dist/sync.js +988 -0
- package/dist/trajectoryExport.js +23 -12
- package/dist/v1Compat.d.ts +24 -0
- package/dist/v1Compat.js +249 -0
- package/package.json +12 -6
package/dist/sync.js
ADDED
|
@@ -0,0 +1,988 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { dirname } from 'node:path';
|
|
3
|
+
import { assetstore, events, hub as hubNs, wire } from '@evomap/evolver-core';
|
|
4
|
+
import { AuthError, connectPublicHub, HubClientError, HubUnreachableError, isHubDryRunEnabled, } from '@evomap/evolver-adapter-public';
|
|
5
|
+
import { loadEnvFileFromEnv } from '@evomap/evolver-mcp';
|
|
6
|
+
import { createRecipeHubFromEnv } from './recipe.js';
|
|
7
|
+
const DEFAULT_LIMIT = 100;
|
|
8
|
+
const MAX_LIMIT = 1000;
|
|
9
|
+
const GROUP = 'sync';
|
|
10
|
+
const USAGE = [
|
|
11
|
+
'usage: evolver sync [--write] [--force] [--scope all|purchased|published] [--type Gene|Capsule] [--status draft|promoted|all] [--limit N] [--json]',
|
|
12
|
+
' evolver sync --export <file.gepx> [--type Gene|Capsule] [--limit N] [--json]',
|
|
13
|
+
' evolver sync --import <file.gepx> [--write] [--force] [--type Gene|Capsule] [--limit N] [--json]',
|
|
14
|
+
' evolver sync --json',
|
|
15
|
+
].join('\n');
|
|
16
|
+
const VALUE_FLAGS = new Set(['--scope', '--type', '--status', '--limit', '--export', '--import']);
|
|
17
|
+
const GEPX_TYPE = 'evomap.gepx';
|
|
18
|
+
const GEPX_VERSION = 1;
|
|
19
|
+
const HUB_METADATA_KEYS = new Set([
|
|
20
|
+
'credit_cost',
|
|
21
|
+
'gdi_score',
|
|
22
|
+
'success_rate',
|
|
23
|
+
'reuse_count',
|
|
24
|
+
'ranking_score',
|
|
25
|
+
'source_node_id',
|
|
26
|
+
'fetched_at',
|
|
27
|
+
'receipt',
|
|
28
|
+
'hub_receipt',
|
|
29
|
+
'already_purchased',
|
|
30
|
+
'_semantic_similarity',
|
|
31
|
+
'semantic_similarity',
|
|
32
|
+
'_search_score',
|
|
33
|
+
'search_score',
|
|
34
|
+
'_match_score',
|
|
35
|
+
'match_score',
|
|
36
|
+
'_retrieval_rank',
|
|
37
|
+
'retrieval_rank',
|
|
38
|
+
'original_asset_id',
|
|
39
|
+
'asset_type',
|
|
40
|
+
'local_id',
|
|
41
|
+
'payload',
|
|
42
|
+
'source',
|
|
43
|
+
'status',
|
|
44
|
+
]);
|
|
45
|
+
const MISSING_ASSET_ID = '[missing]';
|
|
46
|
+
export async function runSyncCommand(argv, deps = {}) {
|
|
47
|
+
const out = deps.stdout ?? ((line) => { process.stdout.write(`${line}\n`); });
|
|
48
|
+
const err = deps.stderr ?? ((line) => { process.stderr.write(`${line}\n`); });
|
|
49
|
+
if (argv.includes('--help') || argv.includes('-h')) {
|
|
50
|
+
if (argv.includes('--json'))
|
|
51
|
+
out(JSON.stringify({ ok: true, group: GROUP, mode: 'help', usage: USAGE }));
|
|
52
|
+
else
|
|
53
|
+
out(USAGE);
|
|
54
|
+
return 0;
|
|
55
|
+
}
|
|
56
|
+
const parsed = parseSyncArgs(argv);
|
|
57
|
+
if (!parsed.ok)
|
|
58
|
+
return emitFailure(parsed.reason, parsed.message, parsed.jsonOut, out, err);
|
|
59
|
+
try {
|
|
60
|
+
const result = parsed.value.exportPath
|
|
61
|
+
? await executeSyncExport(parsed.value, deps)
|
|
62
|
+
: parsed.value.importPath
|
|
63
|
+
? parsed.value.write
|
|
64
|
+
? await executeGepxImportWrite(parsed.value, deps)
|
|
65
|
+
: await buildGepxImportPreview(parsed.value, deps)
|
|
66
|
+
: parsed.value.write
|
|
67
|
+
? await executeSyncWrite(parsed.value, deps)
|
|
68
|
+
: await buildSyncPreview(parsed.value, deps);
|
|
69
|
+
if (parsed.value.jsonOut)
|
|
70
|
+
out(JSON.stringify(result));
|
|
71
|
+
else if (result.mode === 'preview')
|
|
72
|
+
emitTextPreview(result, out);
|
|
73
|
+
else if (result.mode === 'export')
|
|
74
|
+
emitTextExport(result, out);
|
|
75
|
+
else if (result.mode === 'import_preview')
|
|
76
|
+
emitTextImportPreview(result, out);
|
|
77
|
+
else if (result.mode === 'import')
|
|
78
|
+
emitTextImport(result, out);
|
|
79
|
+
else
|
|
80
|
+
emitTextWrite(result, out);
|
|
81
|
+
return 0;
|
|
82
|
+
}
|
|
83
|
+
catch (error) {
|
|
84
|
+
const mapped = mapSyncError(error);
|
|
85
|
+
return emitFailure(mapped.reason, mapped.message, parsed.value.jsonOut, out, err);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
function parseSyncArgs(argv) {
|
|
89
|
+
let scope = 'all';
|
|
90
|
+
let type;
|
|
91
|
+
let status = 'all';
|
|
92
|
+
let limit = DEFAULT_LIMIT;
|
|
93
|
+
let jsonOut = argv.includes('--json');
|
|
94
|
+
let write = false;
|
|
95
|
+
let force = false;
|
|
96
|
+
let exportPath;
|
|
97
|
+
let importPath;
|
|
98
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
99
|
+
const token = argv[i];
|
|
100
|
+
if (!token)
|
|
101
|
+
continue;
|
|
102
|
+
if (token === '--json') {
|
|
103
|
+
jsonOut = true;
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
if (token === '--write') {
|
|
107
|
+
write = true;
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
if (token === '--force') {
|
|
111
|
+
force = true;
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
if (token.startsWith('--')) {
|
|
115
|
+
const eq = token.indexOf('=');
|
|
116
|
+
const flag = eq >= 0 ? token.slice(0, eq) : token;
|
|
117
|
+
if (!VALUE_FLAGS.has(flag)) {
|
|
118
|
+
return { ok: false, reason: 'invalid_arg', message: `unsupported sync argument: ${flag}`, jsonOut };
|
|
119
|
+
}
|
|
120
|
+
const value = eq >= 0 ? token.slice(eq + 1) : argv[i + 1];
|
|
121
|
+
if (!value || value.startsWith('--'))
|
|
122
|
+
return { ok: false, reason: 'invalid_arg', message: `${flag} requires a value`, jsonOut };
|
|
123
|
+
if (eq < 0)
|
|
124
|
+
i += 1;
|
|
125
|
+
if (flag === '--scope') {
|
|
126
|
+
if (value !== 'all' && value !== 'purchased' && value !== 'published') {
|
|
127
|
+
return { ok: false, reason: 'invalid_arg', message: '--scope must be all|purchased|published', jsonOut };
|
|
128
|
+
}
|
|
129
|
+
scope = value;
|
|
130
|
+
}
|
|
131
|
+
else if (flag === '--type') {
|
|
132
|
+
if (value !== 'Gene' && value !== 'Capsule')
|
|
133
|
+
return { ok: false, reason: 'invalid_arg', message: '--type must be Gene|Capsule', jsonOut };
|
|
134
|
+
type = value;
|
|
135
|
+
}
|
|
136
|
+
else if (flag === '--status') {
|
|
137
|
+
if (value !== 'draft' && value !== 'promoted' && value !== 'all') {
|
|
138
|
+
return { ok: false, reason: 'invalid_arg', message: '--status must be draft|promoted|all', jsonOut };
|
|
139
|
+
}
|
|
140
|
+
status = value;
|
|
141
|
+
}
|
|
142
|
+
else if (flag === '--limit') {
|
|
143
|
+
const parsedLimit = Number(value);
|
|
144
|
+
if (!Number.isSafeInteger(parsedLimit) || parsedLimit <= 0)
|
|
145
|
+
return { ok: false, reason: 'invalid_arg', message: '--limit must be a positive integer', jsonOut };
|
|
146
|
+
limit = Math.min(parsedLimit, MAX_LIMIT);
|
|
147
|
+
}
|
|
148
|
+
else if (flag === '--export') {
|
|
149
|
+
exportPath = value;
|
|
150
|
+
}
|
|
151
|
+
else if (flag === '--import') {
|
|
152
|
+
importPath = value;
|
|
153
|
+
}
|
|
154
|
+
continue;
|
|
155
|
+
}
|
|
156
|
+
return { ok: false, reason: 'invalid_arg', message: `unsupported sync argument: ${token}`, jsonOut };
|
|
157
|
+
}
|
|
158
|
+
if (force && !write) {
|
|
159
|
+
return { ok: false, reason: 'force_requires_write', message: '--force requires --write', jsonOut };
|
|
160
|
+
}
|
|
161
|
+
if (exportPath && importPath) {
|
|
162
|
+
return { ok: false, reason: 'invalid_arg', message: '--export and --import cannot be used together', jsonOut };
|
|
163
|
+
}
|
|
164
|
+
if (exportPath && write) {
|
|
165
|
+
return { ok: false, reason: 'invalid_arg', message: '--export does not use --write', jsonOut };
|
|
166
|
+
}
|
|
167
|
+
return { ok: true, value: { scope, ...(type ? { type } : {}), status, limit, jsonOut, write, force, ...(exportPath ? { exportPath } : {}), ...(importPath ? { importPath } : {}) } };
|
|
168
|
+
}
|
|
169
|
+
async function buildSyncPreview(opts, deps) {
|
|
170
|
+
const env = deps.env ?? process.env;
|
|
171
|
+
loadEnvFileFromEnv(env);
|
|
172
|
+
if (isHubDryRunEnabled(env))
|
|
173
|
+
return emptyPreview(opts.scope);
|
|
174
|
+
const hub = deps.hub ?? createDefaultHub(deps);
|
|
175
|
+
const store = deps.store ?? new assetstore.LocalJsonlProvider(deps.assetsDir ?? events.assetsDir());
|
|
176
|
+
const local = await localIndex(store);
|
|
177
|
+
const { purchased, published } = await listRemoteRows(hub, opts);
|
|
178
|
+
const counts = {
|
|
179
|
+
remotePurchased: purchased.length,
|
|
180
|
+
remotePublished: published.length,
|
|
181
|
+
uniqueRemote: 0,
|
|
182
|
+
alreadyLocal: 0,
|
|
183
|
+
idCollision: 0,
|
|
184
|
+
unsupported: 0,
|
|
185
|
+
integrityError: 0,
|
|
186
|
+
wouldImport: 0,
|
|
187
|
+
forcedImport: 0,
|
|
188
|
+
};
|
|
189
|
+
const unique = new Map();
|
|
190
|
+
const missingAssetId = [];
|
|
191
|
+
for (const row of purchased)
|
|
192
|
+
addUnique(unique, missingAssetId, row, 'purchased');
|
|
193
|
+
for (const row of published)
|
|
194
|
+
addUnique(unique, missingAssetId, row, 'published');
|
|
195
|
+
counts.uniqueRemote = unique.size + missingAssetId.length;
|
|
196
|
+
const candidates = [];
|
|
197
|
+
for (const { row, source } of [...unique.values(), ...missingAssetId]) {
|
|
198
|
+
const candidate = classifyRemote(row, source, local);
|
|
199
|
+
candidates.push(candidate);
|
|
200
|
+
if (candidate.action === 'already_local')
|
|
201
|
+
counts.alreadyLocal += 1;
|
|
202
|
+
else if (candidate.action === 'id_collision')
|
|
203
|
+
counts.idCollision += 1;
|
|
204
|
+
else if (candidate.action === 'would_import')
|
|
205
|
+
counts.wouldImport += 1;
|
|
206
|
+
else if (candidate.action === 'force_import')
|
|
207
|
+
counts.forcedImport += 1;
|
|
208
|
+
else if (candidate.action === 'unsupported_type')
|
|
209
|
+
counts.unsupported += 1;
|
|
210
|
+
else
|
|
211
|
+
counts.integrityError += 1;
|
|
212
|
+
}
|
|
213
|
+
return { ok: true, group: GROUP, mode: 'preview', scope: opts.scope, counts, candidates };
|
|
214
|
+
}
|
|
215
|
+
async function executeSyncWrite(opts, deps) {
|
|
216
|
+
const env = deps.env ?? process.env;
|
|
217
|
+
loadEnvFileFromEnv(env);
|
|
218
|
+
if (isHubDryRunEnabled(env))
|
|
219
|
+
return emptyWrite(opts.scope, 'dry_run');
|
|
220
|
+
const hub = deps.hub ?? createDefaultHub(deps);
|
|
221
|
+
if (!hasFetchAssetById(hub))
|
|
222
|
+
throw new Error('sync write requires fetchAssetById support');
|
|
223
|
+
const store = deps.store ?? new assetstore.LocalJsonlProvider(deps.assetsDir ?? events.assetsDir());
|
|
224
|
+
const preview = await buildSyncPreview(opts, { ...deps, env, hub, store });
|
|
225
|
+
if (preview.counts.integrityError > 0) {
|
|
226
|
+
throw new SyncAbortError('integrity_error', 'remote asset integrity verification failed before import');
|
|
227
|
+
}
|
|
228
|
+
const local = await localIndex(store);
|
|
229
|
+
const finalCandidates = preview.candidates.map((candidate) => ({ ...candidate }));
|
|
230
|
+
const prepared = [];
|
|
231
|
+
const pendingLogical = new Map(local.logical);
|
|
232
|
+
for (const candidate of finalCandidates) {
|
|
233
|
+
if (candidate.action !== 'would_import' && !(opts.force && candidate.action === 'id_collision'))
|
|
234
|
+
continue;
|
|
235
|
+
const fetched = await hub.fetchAssetById(candidate.assetId);
|
|
236
|
+
if (!fetched)
|
|
237
|
+
throw new SyncAbortError('not_found', 'Hub asset disappeared before import');
|
|
238
|
+
const preparedAsset = prepareFetchedAsset(candidate, fetched, local.byAssetId, pendingLogical, opts.force);
|
|
239
|
+
if ('blocked' in preparedAsset) {
|
|
240
|
+
updateFinalCandidate(finalCandidates, candidate, preparedAsset.blocked);
|
|
241
|
+
continue;
|
|
242
|
+
}
|
|
243
|
+
const logicalId = stringField(preparedAsset.asset, 'id');
|
|
244
|
+
const finalCandidate = preparedAsset.forced
|
|
245
|
+
? {
|
|
246
|
+
...candidate,
|
|
247
|
+
...(logicalId ? { logicalId } : {}),
|
|
248
|
+
action: 'force_import',
|
|
249
|
+
collisionWithAssetId: preparedAsset.collisionWithAssetId,
|
|
250
|
+
}
|
|
251
|
+
: {
|
|
252
|
+
assetId: candidate.assetId,
|
|
253
|
+
type: candidate.type,
|
|
254
|
+
source: candidate.source,
|
|
255
|
+
...(candidate.status ? { status: candidate.status } : {}),
|
|
256
|
+
...(logicalId ? { logicalId } : {}),
|
|
257
|
+
action: 'would_import',
|
|
258
|
+
};
|
|
259
|
+
updateFinalCandidate(finalCandidates, candidate, finalCandidate);
|
|
260
|
+
prepared.push({
|
|
261
|
+
candidate: finalCandidate,
|
|
262
|
+
asset: preparedAsset.asset,
|
|
263
|
+
...(preparedAsset.forced ? { forced: true, collisionWithAssetId: preparedAsset.collisionWithAssetId } : {}),
|
|
264
|
+
});
|
|
265
|
+
if (logicalId)
|
|
266
|
+
pendingLogical.set(`${preparedAsset.asset.type}:${logicalId}`, preparedAsset.asset.asset_id);
|
|
267
|
+
}
|
|
268
|
+
const baseDir = storeBaseDir(store, deps);
|
|
269
|
+
const provenance = deps.provenance ?? new assetstore.ProvenanceStore(baseDir, deps.now);
|
|
270
|
+
const syncLedger = deps.syncLedger ?? new assetstore.AssetSyncLedger(baseDir, deps.now);
|
|
271
|
+
const written = [];
|
|
272
|
+
for (const item of prepared) {
|
|
273
|
+
const stored = await assetstore.ingestUntrusted(store, provenance, item.asset, 'hub');
|
|
274
|
+
const assetId = stored.asset_id;
|
|
275
|
+
if (!stored.stored) {
|
|
276
|
+
updateFinalCandidate(finalCandidates, item.candidate, { ...item.candidate, assetId, action: 'already_local' });
|
|
277
|
+
continue;
|
|
278
|
+
}
|
|
279
|
+
syncLedger.append({
|
|
280
|
+
assetId,
|
|
281
|
+
type: item.asset.type,
|
|
282
|
+
source: 'hub',
|
|
283
|
+
scope: item.candidate.source === 'published' ? 'published' : 'purchased',
|
|
284
|
+
remoteAssetId: item.candidate.assetId,
|
|
285
|
+
...(item.candidate.logicalId ? { logicalId: item.candidate.logicalId } : {}),
|
|
286
|
+
...(item.candidate.status ? { status: item.candidate.status } : {}),
|
|
287
|
+
...(item.forced ? { forced: true } : {}),
|
|
288
|
+
...(item.collisionWithAssetId ? { collisionWithAssetId: item.collisionWithAssetId } : {}),
|
|
289
|
+
});
|
|
290
|
+
written.push({
|
|
291
|
+
assetId,
|
|
292
|
+
type: item.asset.type,
|
|
293
|
+
source: item.candidate.source,
|
|
294
|
+
stored: stored.stored,
|
|
295
|
+
trusted: false,
|
|
296
|
+
...(item.candidate.logicalId ? { logicalId: item.candidate.logicalId } : {}),
|
|
297
|
+
...(item.candidate.status ? { status: item.candidate.status } : {}),
|
|
298
|
+
...(item.forced ? { forced: true } : {}),
|
|
299
|
+
...(item.collisionWithAssetId ? { collisionWithAssetId: item.collisionWithAssetId } : {}),
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
const counts = countsFromCandidates(preview.counts, finalCandidates);
|
|
303
|
+
const blocked = finalCandidates.filter(isBlockedCandidate);
|
|
304
|
+
return {
|
|
305
|
+
ok: true,
|
|
306
|
+
group: GROUP,
|
|
307
|
+
mode: 'write',
|
|
308
|
+
scope: opts.scope,
|
|
309
|
+
counts,
|
|
310
|
+
candidates: finalCandidates,
|
|
311
|
+
written,
|
|
312
|
+
blocked,
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
async function executeSyncExport(opts, deps) {
|
|
316
|
+
if (!opts.exportPath)
|
|
317
|
+
throw new SyncAbortError('invalid_arg', '--export requires a file');
|
|
318
|
+
const store = deps.store ?? new assetstore.LocalJsonlProvider(deps.assetsDir ?? events.assetsDir());
|
|
319
|
+
const baseDir = storeBaseDir(store, deps);
|
|
320
|
+
const provenance = deps.provenance ?? new assetstore.ProvenanceStore(baseDir, deps.now);
|
|
321
|
+
const syncLedger = deps.syncLedger ?? new assetstore.AssetSyncLedger(baseDir, deps.now);
|
|
322
|
+
const provenanceSnapshot = provenance.snapshot();
|
|
323
|
+
const assets = await listLocalExportAssets(store, opts);
|
|
324
|
+
const provenanceRecords = assets
|
|
325
|
+
.map((asset) => provenanceSnapshot.get(asset.asset_id) ?? null)
|
|
326
|
+
.filter((record) => Boolean(record));
|
|
327
|
+
const syncRecords = assets
|
|
328
|
+
.map((asset) => syncLedger.get(asset.asset_id))
|
|
329
|
+
.filter((record) => Boolean(record));
|
|
330
|
+
const pkg = {
|
|
331
|
+
type: GEPX_TYPE,
|
|
332
|
+
version: GEPX_VERSION,
|
|
333
|
+
exportedAt: new Date(deps.now ? deps.now() : Date.now()).toISOString(),
|
|
334
|
+
assets,
|
|
335
|
+
provenance: provenanceRecords,
|
|
336
|
+
sync: syncRecords,
|
|
337
|
+
};
|
|
338
|
+
try {
|
|
339
|
+
mkdirSync(dirname(opts.exportPath), { recursive: true });
|
|
340
|
+
writeFileSync(opts.exportPath, `${JSON.stringify(pkg, null, 2)}\n`, 'utf8');
|
|
341
|
+
}
|
|
342
|
+
catch {
|
|
343
|
+
throw new SyncAbortError('export_failed', 'could not write .gepx file');
|
|
344
|
+
}
|
|
345
|
+
return {
|
|
346
|
+
ok: true,
|
|
347
|
+
group: GROUP,
|
|
348
|
+
mode: 'export',
|
|
349
|
+
counts: {
|
|
350
|
+
exported: assets.length,
|
|
351
|
+
provenance: provenanceRecords.length,
|
|
352
|
+
sync: syncRecords.length,
|
|
353
|
+
},
|
|
354
|
+
assets: assets.map((asset) => ({
|
|
355
|
+
assetId: asset.asset_id,
|
|
356
|
+
type: asset.type,
|
|
357
|
+
...(stringField(asset, 'id') ? { logicalId: stringField(asset, 'id') } : {}),
|
|
358
|
+
trusted: provenanceSnapshot.get(asset.asset_id)?.trusted ?? true,
|
|
359
|
+
synced: Boolean(syncLedger.get(asset.asset_id)),
|
|
360
|
+
})),
|
|
361
|
+
};
|
|
362
|
+
}
|
|
363
|
+
async function buildGepxImportPreview(opts, deps) {
|
|
364
|
+
const pkg = readGepxPackage(opts.importPath);
|
|
365
|
+
const store = deps.store ?? new assetstore.LocalJsonlProvider(deps.assetsDir ?? events.assetsDir());
|
|
366
|
+
const local = await localIndex(store);
|
|
367
|
+
const candidates = classifyGepxAssets(pkg, opts, local);
|
|
368
|
+
return { ok: true, group: GROUP, mode: 'import_preview', counts: countsFromCandidates(emptyCounts(candidates.length), candidates), candidates };
|
|
369
|
+
}
|
|
370
|
+
async function executeGepxImportWrite(opts, deps) {
|
|
371
|
+
const pkg = readGepxPackage(opts.importPath);
|
|
372
|
+
assertGepxPackageIntegrity(pkg);
|
|
373
|
+
const store = deps.store ?? new assetstore.LocalJsonlProvider(deps.assetsDir ?? events.assetsDir());
|
|
374
|
+
const local = await localIndex(store);
|
|
375
|
+
const finalCandidates = classifyGepxAssets(pkg, opts, local);
|
|
376
|
+
const assetsById = gepxImportAssetsById(pkg);
|
|
377
|
+
const syncById = new Map((pkg.sync ?? []).map((record) => [record.assetId, record]));
|
|
378
|
+
const prepared = [];
|
|
379
|
+
const pendingLogical = new Map(local.logical);
|
|
380
|
+
for (const candidate of finalCandidates) {
|
|
381
|
+
if (candidate.action !== 'would_import' && !(opts.force && candidate.action === 'id_collision'))
|
|
382
|
+
continue;
|
|
383
|
+
const asset = assetsById.get(candidate.assetId);
|
|
384
|
+
if (!asset)
|
|
385
|
+
throw new SyncAbortError('integrity_error', '.gepx package asset is missing');
|
|
386
|
+
const preparedAsset = preparePackagedAsset(candidate, asset, local.byAssetId, pendingLogical, opts.force);
|
|
387
|
+
if ('blocked' in preparedAsset) {
|
|
388
|
+
updateFinalCandidate(finalCandidates, candidate, preparedAsset.blocked);
|
|
389
|
+
continue;
|
|
390
|
+
}
|
|
391
|
+
const logicalId = stringField(preparedAsset.asset, 'id');
|
|
392
|
+
const finalCandidate = preparedAsset.forced
|
|
393
|
+
? {
|
|
394
|
+
...candidate,
|
|
395
|
+
...(logicalId ? { logicalId } : {}),
|
|
396
|
+
action: 'force_import',
|
|
397
|
+
collisionWithAssetId: preparedAsset.collisionWithAssetId,
|
|
398
|
+
}
|
|
399
|
+
: {
|
|
400
|
+
assetId: candidate.assetId,
|
|
401
|
+
type: candidate.type,
|
|
402
|
+
source: 'gepx',
|
|
403
|
+
...(candidate.status ? { status: candidate.status } : {}),
|
|
404
|
+
...(logicalId ? { logicalId } : {}),
|
|
405
|
+
action: 'would_import',
|
|
406
|
+
};
|
|
407
|
+
updateFinalCandidate(finalCandidates, candidate, finalCandidate);
|
|
408
|
+
prepared.push({
|
|
409
|
+
candidate: finalCandidate,
|
|
410
|
+
asset: preparedAsset.asset,
|
|
411
|
+
...(preparedAsset.forced ? { forced: true, collisionWithAssetId: preparedAsset.collisionWithAssetId } : {}),
|
|
412
|
+
});
|
|
413
|
+
if (logicalId)
|
|
414
|
+
pendingLogical.set(`${preparedAsset.asset.type}:${logicalId}`, preparedAsset.asset.asset_id);
|
|
415
|
+
}
|
|
416
|
+
const baseDir = storeBaseDir(store, deps);
|
|
417
|
+
const provenance = deps.provenance ?? new assetstore.ProvenanceStore(baseDir, deps.now);
|
|
418
|
+
const syncLedger = deps.syncLedger ?? new assetstore.AssetSyncLedger(baseDir, deps.now);
|
|
419
|
+
const written = [];
|
|
420
|
+
for (const item of prepared) {
|
|
421
|
+
const stored = await assetstore.ingestUntrusted(store, provenance, item.asset, 'migrated');
|
|
422
|
+
const assetId = stored.asset_id;
|
|
423
|
+
if (!stored.stored) {
|
|
424
|
+
updateFinalCandidate(finalCandidates, item.candidate, { ...item.candidate, assetId, action: 'already_local' });
|
|
425
|
+
continue;
|
|
426
|
+
}
|
|
427
|
+
const syncRecord = syncById.get(assetId);
|
|
428
|
+
if (syncRecord)
|
|
429
|
+
syncLedger.append({
|
|
430
|
+
assetId,
|
|
431
|
+
type: item.asset.type,
|
|
432
|
+
source: 'hub',
|
|
433
|
+
scope: syncRecord.scope,
|
|
434
|
+
remoteAssetId: syncRecord.remoteAssetId,
|
|
435
|
+
...(syncRecord.logicalId ? { logicalId: syncRecord.logicalId } : {}),
|
|
436
|
+
...(syncRecord.status ? { status: syncRecord.status } : {}),
|
|
437
|
+
...(syncRecord.syncedAt ? { syncedAt: syncRecord.syncedAt } : {}),
|
|
438
|
+
...(syncRecord.forced ? { forced: true } : {}),
|
|
439
|
+
...(syncRecord.collisionWithAssetId ? { collisionWithAssetId: syncRecord.collisionWithAssetId } : {}),
|
|
440
|
+
});
|
|
441
|
+
written.push({
|
|
442
|
+
assetId,
|
|
443
|
+
type: item.asset.type,
|
|
444
|
+
source: 'gepx',
|
|
445
|
+
stored: stored.stored,
|
|
446
|
+
trusted: false,
|
|
447
|
+
...(item.candidate.logicalId ? { logicalId: item.candidate.logicalId } : {}),
|
|
448
|
+
...(item.candidate.status ? { status: item.candidate.status } : {}),
|
|
449
|
+
...(item.forced ? { forced: true } : {}),
|
|
450
|
+
...(item.collisionWithAssetId ? { collisionWithAssetId: item.collisionWithAssetId } : {}),
|
|
451
|
+
});
|
|
452
|
+
}
|
|
453
|
+
const counts = countsFromCandidates(emptyCounts(finalCandidates.length), finalCandidates);
|
|
454
|
+
return {
|
|
455
|
+
ok: true,
|
|
456
|
+
group: GROUP,
|
|
457
|
+
mode: 'import',
|
|
458
|
+
counts,
|
|
459
|
+
candidates: finalCandidates,
|
|
460
|
+
written,
|
|
461
|
+
blocked: finalCandidates.filter(isBlockedCandidate),
|
|
462
|
+
};
|
|
463
|
+
}
|
|
464
|
+
function emptyPreview(scope) {
|
|
465
|
+
return {
|
|
466
|
+
ok: true,
|
|
467
|
+
group: GROUP,
|
|
468
|
+
mode: 'preview',
|
|
469
|
+
scope,
|
|
470
|
+
counts: {
|
|
471
|
+
remotePurchased: 0,
|
|
472
|
+
remotePublished: 0,
|
|
473
|
+
uniqueRemote: 0,
|
|
474
|
+
alreadyLocal: 0,
|
|
475
|
+
idCollision: 0,
|
|
476
|
+
unsupported: 0,
|
|
477
|
+
integrityError: 0,
|
|
478
|
+
wouldImport: 0,
|
|
479
|
+
forcedImport: 0,
|
|
480
|
+
},
|
|
481
|
+
candidates: [],
|
|
482
|
+
};
|
|
483
|
+
}
|
|
484
|
+
function emptyCounts(uniqueRemote = 0) {
|
|
485
|
+
return {
|
|
486
|
+
remotePurchased: 0,
|
|
487
|
+
remotePublished: 0,
|
|
488
|
+
uniqueRemote,
|
|
489
|
+
alreadyLocal: 0,
|
|
490
|
+
idCollision: 0,
|
|
491
|
+
unsupported: 0,
|
|
492
|
+
integrityError: 0,
|
|
493
|
+
wouldImport: 0,
|
|
494
|
+
forcedImport: 0,
|
|
495
|
+
};
|
|
496
|
+
}
|
|
497
|
+
function emptyWrite(scope, mode = 'write') {
|
|
498
|
+
return {
|
|
499
|
+
...emptyPreview(scope),
|
|
500
|
+
mode,
|
|
501
|
+
written: [],
|
|
502
|
+
blocked: [],
|
|
503
|
+
};
|
|
504
|
+
}
|
|
505
|
+
function createDefaultHub(deps) {
|
|
506
|
+
const hub = createRecipeHubFromEnv(deps.env ?? process.env, deps.connectHub ?? connectPublicHub);
|
|
507
|
+
return hub;
|
|
508
|
+
}
|
|
509
|
+
async function listRemoteRows(hub, opts) {
|
|
510
|
+
const purchased = opts.scope === 'all' || opts.scope === 'purchased'
|
|
511
|
+
? await listAll(hub, { scope: 'purchased', ...(opts.type ? { type: opts.type } : {}), limit: opts.limit })
|
|
512
|
+
: [];
|
|
513
|
+
const remaining = Math.max(0, opts.limit - purchased.length);
|
|
514
|
+
const publishedLimit = opts.scope === 'all' ? remaining : opts.limit;
|
|
515
|
+
const published = (opts.scope === 'all' || opts.scope === 'published') && publishedLimit > 0
|
|
516
|
+
? await listAll(hub, {
|
|
517
|
+
scope: 'published',
|
|
518
|
+
...(opts.type ? { type: opts.type } : {}),
|
|
519
|
+
status: opts.status,
|
|
520
|
+
limit: publishedLimit,
|
|
521
|
+
})
|
|
522
|
+
: [];
|
|
523
|
+
return { purchased, published };
|
|
524
|
+
}
|
|
525
|
+
async function listAll(hub, opts) {
|
|
526
|
+
const rows = [];
|
|
527
|
+
let cursor = opts.cursor;
|
|
528
|
+
const seenCursors = new Set();
|
|
529
|
+
while (rows.length < opts.limit) {
|
|
530
|
+
const remaining = opts.limit - rows.length;
|
|
531
|
+
const result = await hub.listAccountAssets({ ...opts, limit: remaining, ...(cursor ? { cursor } : {}) });
|
|
532
|
+
const pageRows = result.assets;
|
|
533
|
+
rows.push(...pageRows);
|
|
534
|
+
if (!result.hasMore || !result.nextCursor)
|
|
535
|
+
break;
|
|
536
|
+
if (pageRows.length === 0 || result.nextCursor === cursor || seenCursors.has(result.nextCursor))
|
|
537
|
+
break;
|
|
538
|
+
if (cursor)
|
|
539
|
+
seenCursors.add(cursor);
|
|
540
|
+
cursor = result.nextCursor;
|
|
541
|
+
}
|
|
542
|
+
return rows.slice(0, opts.limit);
|
|
543
|
+
}
|
|
544
|
+
function addUnique(target, missingAssetId, row, source) {
|
|
545
|
+
const assetId = stringField(row, 'asset_id');
|
|
546
|
+
if (!assetId) {
|
|
547
|
+
missingAssetId.push({ row, source });
|
|
548
|
+
return;
|
|
549
|
+
}
|
|
550
|
+
if (target.has(assetId))
|
|
551
|
+
return;
|
|
552
|
+
target.set(assetId, { row, source });
|
|
553
|
+
}
|
|
554
|
+
async function localIndex(store) {
|
|
555
|
+
const byAssetId = new Set();
|
|
556
|
+
const logical = new Map();
|
|
557
|
+
for (const kind of ['Gene', 'Capsule']) {
|
|
558
|
+
for (const row of await store.list(kind, Number.MAX_SAFE_INTEGER)) {
|
|
559
|
+
byAssetId.add(row.asset_id);
|
|
560
|
+
const logicalId = stringField(row, 'id');
|
|
561
|
+
if (logicalId)
|
|
562
|
+
logical.set(`${kind}:${logicalId}`, row.asset_id);
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
return { byAssetId, logical };
|
|
566
|
+
}
|
|
567
|
+
async function listLocalExportAssets(store, opts) {
|
|
568
|
+
const kinds = opts.type ? [opts.type] : ['Gene', 'Capsule'];
|
|
569
|
+
const assets = [];
|
|
570
|
+
for (const kind of kinds) {
|
|
571
|
+
const remaining = opts.limit - assets.length;
|
|
572
|
+
if (remaining <= 0)
|
|
573
|
+
break;
|
|
574
|
+
assets.push(...await store.list(kind, remaining));
|
|
575
|
+
}
|
|
576
|
+
return assets.slice(0, opts.limit);
|
|
577
|
+
}
|
|
578
|
+
function classifyRemote(row, source, local) {
|
|
579
|
+
const assetId = stringField(row, 'asset_id') ?? MISSING_ASSET_ID;
|
|
580
|
+
const type = remoteType(row);
|
|
581
|
+
const logicalId = remoteLogicalId(row);
|
|
582
|
+
const status = stringField(row, 'status');
|
|
583
|
+
const base = {
|
|
584
|
+
assetId,
|
|
585
|
+
type: type ?? 'unknown',
|
|
586
|
+
...(logicalId ? { logicalId } : {}),
|
|
587
|
+
source,
|
|
588
|
+
...(status ? { status } : {}),
|
|
589
|
+
};
|
|
590
|
+
if (type !== 'Gene' && type !== 'Capsule')
|
|
591
|
+
return { ...base, action: 'unsupported_type' };
|
|
592
|
+
if (assetId === MISSING_ASSET_ID)
|
|
593
|
+
return { ...base, action: 'integrity_error' };
|
|
594
|
+
if (remotePayloadIntegrityInvalid(row, type, assetId))
|
|
595
|
+
return { ...base, action: 'integrity_error' };
|
|
596
|
+
if (local.byAssetId.has(assetId))
|
|
597
|
+
return { ...base, action: 'already_local' };
|
|
598
|
+
if (logicalId) {
|
|
599
|
+
const localAssetId = local.logical.get(`${type}:${logicalId}`);
|
|
600
|
+
if (localAssetId && localAssetId !== assetId)
|
|
601
|
+
return { ...base, action: 'id_collision', collisionWithAssetId: localAssetId };
|
|
602
|
+
}
|
|
603
|
+
return { ...base, action: 'would_import' };
|
|
604
|
+
}
|
|
605
|
+
function classifyGepxAssets(pkg, opts, local) {
|
|
606
|
+
return uniqueGepxAssets(pkg)
|
|
607
|
+
.filter((entry) => !opts.type || entry.type === opts.type)
|
|
608
|
+
.slice(0, opts.limit)
|
|
609
|
+
.map((entry) => classifyGepxAsset(entry, local));
|
|
610
|
+
}
|
|
611
|
+
function classifyGepxAsset(entry, local) {
|
|
612
|
+
const { assetId, type, logicalId } = entry;
|
|
613
|
+
const base = {
|
|
614
|
+
assetId,
|
|
615
|
+
type: type ?? String(entry.original.type ?? 'unknown'),
|
|
616
|
+
...(logicalId ? { logicalId } : {}),
|
|
617
|
+
source: 'gepx',
|
|
618
|
+
};
|
|
619
|
+
if (type !== 'Gene' && type !== 'Capsule')
|
|
620
|
+
return { ...base, action: 'unsupported_type' };
|
|
621
|
+
if (entry.integrityError)
|
|
622
|
+
return { ...base, action: 'integrity_error' };
|
|
623
|
+
if (local.byAssetId.has(assetId))
|
|
624
|
+
return { ...base, action: 'already_local' };
|
|
625
|
+
if (logicalId) {
|
|
626
|
+
const localAssetId = local.logical.get(`${type}:${logicalId}`);
|
|
627
|
+
if (localAssetId && localAssetId !== assetId)
|
|
628
|
+
return { ...base, action: 'id_collision', collisionWithAssetId: localAssetId };
|
|
629
|
+
}
|
|
630
|
+
return { ...base, action: 'would_import' };
|
|
631
|
+
}
|
|
632
|
+
function uniqueGepxAssets(pkg) {
|
|
633
|
+
const unique = new Map();
|
|
634
|
+
const missing = [];
|
|
635
|
+
for (const asset of pkg.assets) {
|
|
636
|
+
const normalized = normalizeGepxAsset(asset);
|
|
637
|
+
if (normalized.assetId === MISSING_ASSET_ID) {
|
|
638
|
+
missing.push(normalized);
|
|
639
|
+
continue;
|
|
640
|
+
}
|
|
641
|
+
if (!unique.has(normalized.assetId))
|
|
642
|
+
unique.set(normalized.assetId, normalized);
|
|
643
|
+
}
|
|
644
|
+
return [...unique.values(), ...missing];
|
|
645
|
+
}
|
|
646
|
+
function gepxImportAssetsById(pkg) {
|
|
647
|
+
const assets = new Map();
|
|
648
|
+
for (const entry of uniqueGepxAssets(pkg)) {
|
|
649
|
+
if (entry.type && !entry.integrityError && !assets.has(entry.assetId))
|
|
650
|
+
assets.set(entry.assetId, entry.asset);
|
|
651
|
+
}
|
|
652
|
+
return assets;
|
|
653
|
+
}
|
|
654
|
+
function assertGepxPackageIntegrity(pkg) {
|
|
655
|
+
for (const asset of pkg.assets) {
|
|
656
|
+
const normalized = normalizeGepxAsset(asset);
|
|
657
|
+
if (normalized.type && normalized.integrityError) {
|
|
658
|
+
throw new SyncAbortError('integrity_error', '.gepx package integrity verification failed before import');
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
function normalizeGepxAsset(asset) {
|
|
663
|
+
const cleaned = stripHubMetadata(asset);
|
|
664
|
+
const assetId = stringField(cleaned, 'asset_id') ?? stringField(asset, 'asset_id') ?? MISSING_ASSET_ID;
|
|
665
|
+
const type = cleaned.type === 'Gene' || cleaned.type === 'Capsule' ? cleaned.type : undefined;
|
|
666
|
+
const logicalId = stringField(cleaned, 'id');
|
|
667
|
+
let integrityError = false;
|
|
668
|
+
if (type) {
|
|
669
|
+
const claimed = stringField(cleaned, 'asset_id');
|
|
670
|
+
const fullAsset = looksLikeFullAsset(cleaned, type);
|
|
671
|
+
const computed = fullAsset ? wire.computeAssetId(cleaned) : undefined;
|
|
672
|
+
integrityError = assetId === MISSING_ASSET_ID || !claimed || !fullAsset || !computed || claimed !== assetId || computed !== claimed;
|
|
673
|
+
}
|
|
674
|
+
return {
|
|
675
|
+
original: asset,
|
|
676
|
+
asset: cleaned,
|
|
677
|
+
assetId,
|
|
678
|
+
...(type ? { type } : {}),
|
|
679
|
+
...(logicalId ? { logicalId } : {}),
|
|
680
|
+
integrityError,
|
|
681
|
+
};
|
|
682
|
+
}
|
|
683
|
+
function countsFromCandidates(base, candidates) {
|
|
684
|
+
const counts = {
|
|
685
|
+
remotePurchased: base.remotePurchased,
|
|
686
|
+
remotePublished: base.remotePublished,
|
|
687
|
+
uniqueRemote: candidates.length,
|
|
688
|
+
alreadyLocal: 0,
|
|
689
|
+
idCollision: 0,
|
|
690
|
+
unsupported: 0,
|
|
691
|
+
integrityError: 0,
|
|
692
|
+
wouldImport: 0,
|
|
693
|
+
forcedImport: 0,
|
|
694
|
+
};
|
|
695
|
+
for (const candidate of candidates) {
|
|
696
|
+
if (candidate.action === 'already_local')
|
|
697
|
+
counts.alreadyLocal += 1;
|
|
698
|
+
else if (candidate.action === 'id_collision')
|
|
699
|
+
counts.idCollision += 1;
|
|
700
|
+
else if (candidate.action === 'would_import')
|
|
701
|
+
counts.wouldImport += 1;
|
|
702
|
+
else if (candidate.action === 'force_import')
|
|
703
|
+
counts.forcedImport += 1;
|
|
704
|
+
else if (candidate.action === 'unsupported_type')
|
|
705
|
+
counts.unsupported += 1;
|
|
706
|
+
else
|
|
707
|
+
counts.integrityError += 1;
|
|
708
|
+
}
|
|
709
|
+
return counts;
|
|
710
|
+
}
|
|
711
|
+
function updateFinalCandidate(candidates, original, replacement) {
|
|
712
|
+
const index = candidates.findIndex((candidate) => candidate.assetId === original.assetId && candidate.source === original.source);
|
|
713
|
+
if (index >= 0)
|
|
714
|
+
candidates[index] = replacement;
|
|
715
|
+
}
|
|
716
|
+
function isBlockedCandidate(candidate) {
|
|
717
|
+
return candidate.action !== 'would_import' && candidate.action !== 'force_import' && candidate.action !== 'already_local';
|
|
718
|
+
}
|
|
719
|
+
function remotePayloadIntegrityInvalid(row, type, assetId) {
|
|
720
|
+
const payload = asRecord(row.payload);
|
|
721
|
+
const source = payload ?? row;
|
|
722
|
+
if (!looksLikeFullAsset(source, type))
|
|
723
|
+
return false;
|
|
724
|
+
const candidate = stripHubMetadata({ ...source, type, asset_id: stringField(source, 'asset_id') ?? assetId });
|
|
725
|
+
return Boolean(candidate.asset_id && wire.computeAssetId(candidate) !== candidate.asset_id);
|
|
726
|
+
}
|
|
727
|
+
function prepareFetchedAsset(candidate, fetched, localAssetIds, logical, force) {
|
|
728
|
+
const type = fetched.type === 'Gene' || fetched.type === 'Capsule' ? fetched.type : undefined;
|
|
729
|
+
if (!type)
|
|
730
|
+
return { blocked: { ...candidate, type: fetched.type ?? candidate.type, action: 'unsupported_type' } };
|
|
731
|
+
if (type !== candidate.type)
|
|
732
|
+
throw new SyncAbortError('integrity_error', 'Hub asset type changed before import');
|
|
733
|
+
const cleaned = stripHubMetadata(fetched);
|
|
734
|
+
const claimed = stringField(cleaned, 'asset_id');
|
|
735
|
+
const computed = wire.computeAssetId(cleaned);
|
|
736
|
+
if (!claimed || !computed || claimed !== computed || claimed !== candidate.assetId) {
|
|
737
|
+
throw new SyncAbortError('integrity_error', 'Hub asset integrity verification failed before import');
|
|
738
|
+
}
|
|
739
|
+
if (!looksLikeFullAsset(cleaned, type)) {
|
|
740
|
+
throw new SyncAbortError('integrity_error', 'Hub asset payload is incomplete');
|
|
741
|
+
}
|
|
742
|
+
if (localAssetIds.has(cleaned.asset_id))
|
|
743
|
+
return { blocked: { ...candidate, action: 'already_local' } };
|
|
744
|
+
const logicalId = stringField(cleaned, 'id');
|
|
745
|
+
if (logicalId) {
|
|
746
|
+
const localAssetId = logical.get(`${type}:${logicalId}`);
|
|
747
|
+
if (localAssetId && localAssetId !== cleaned.asset_id) {
|
|
748
|
+
if (force)
|
|
749
|
+
return { asset: cleaned, forced: true, collisionWithAssetId: localAssetId };
|
|
750
|
+
return { blocked: { ...candidate, logicalId, action: 'id_collision', collisionWithAssetId: localAssetId } };
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
return { asset: cleaned };
|
|
754
|
+
}
|
|
755
|
+
function preparePackagedAsset(candidate, asset, localAssetIds, logical, force) {
|
|
756
|
+
const cleaned = stripHubMetadata(asset);
|
|
757
|
+
const type = cleaned.type === 'Gene' || cleaned.type === 'Capsule' ? cleaned.type : undefined;
|
|
758
|
+
if (!type)
|
|
759
|
+
return { blocked: { ...candidate, type: cleaned.type ?? candidate.type, action: 'unsupported_type' } };
|
|
760
|
+
if (type !== candidate.type)
|
|
761
|
+
return { blocked: { ...candidate, type, action: 'unsupported_type' } };
|
|
762
|
+
const claimed = stringField(cleaned, 'asset_id');
|
|
763
|
+
const computed = wire.computeAssetId(cleaned);
|
|
764
|
+
if (!claimed || !computed || claimed !== computed || claimed !== candidate.assetId || !looksLikeFullAsset(cleaned, type)) {
|
|
765
|
+
throw new SyncAbortError('integrity_error', '.gepx package integrity verification failed before import');
|
|
766
|
+
}
|
|
767
|
+
if (localAssetIds.has(cleaned.asset_id))
|
|
768
|
+
return { blocked: { ...candidate, action: 'already_local' } };
|
|
769
|
+
const logicalId = stringField(cleaned, 'id');
|
|
770
|
+
if (logicalId) {
|
|
771
|
+
const localAssetId = logical.get(`${type}:${logicalId}`);
|
|
772
|
+
if (localAssetId && localAssetId !== cleaned.asset_id) {
|
|
773
|
+
if (force)
|
|
774
|
+
return { asset: cleaned, forced: true, collisionWithAssetId: localAssetId };
|
|
775
|
+
return { blocked: { ...candidate, logicalId, action: 'id_collision', collisionWithAssetId: localAssetId } };
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
return { asset: cleaned };
|
|
779
|
+
}
|
|
780
|
+
function looksLikeFullAsset(value, type) {
|
|
781
|
+
if (!stringField(value, 'schema_version'))
|
|
782
|
+
return false;
|
|
783
|
+
if (type === 'Gene') {
|
|
784
|
+
return Boolean(stringField(value, 'id') &&
|
|
785
|
+
stringField(value, 'category') &&
|
|
786
|
+
Array.isArray(value['signals_match']) &&
|
|
787
|
+
Array.isArray(value['strategy']) &&
|
|
788
|
+
asRecord(value['constraints']) &&
|
|
789
|
+
Array.isArray(value['validation']));
|
|
790
|
+
}
|
|
791
|
+
return Boolean(stringField(value, 'id') &&
|
|
792
|
+
stringField(value, 'gene') &&
|
|
793
|
+
stringField(value, 'summary') &&
|
|
794
|
+
asRecord(value['outcome']));
|
|
795
|
+
}
|
|
796
|
+
function stripHubMetadata(asset) {
|
|
797
|
+
const out = {};
|
|
798
|
+
for (const [key, value] of Object.entries(asset))
|
|
799
|
+
if (!HUB_METADATA_KEYS.has(key))
|
|
800
|
+
out[key] = value;
|
|
801
|
+
return out;
|
|
802
|
+
}
|
|
803
|
+
function readGepxPackage(path) {
|
|
804
|
+
if (!path)
|
|
805
|
+
throw new SyncAbortError('invalid_arg', '--import requires a file');
|
|
806
|
+
if (!existsSync(path))
|
|
807
|
+
throw new SyncAbortError('gepx_read_failed', 'could not read .gepx file');
|
|
808
|
+
let parsed;
|
|
809
|
+
try {
|
|
810
|
+
parsed = JSON.parse(readFileSync(path, 'utf8'));
|
|
811
|
+
}
|
|
812
|
+
catch {
|
|
813
|
+
throw new SyncAbortError('invalid_gepx', 'invalid .gepx package');
|
|
814
|
+
}
|
|
815
|
+
const obj = asRecord(parsed);
|
|
816
|
+
if (!obj || obj['type'] !== GEPX_TYPE || obj['version'] !== GEPX_VERSION || !Array.isArray(obj['assets'])) {
|
|
817
|
+
throw new SyncAbortError('invalid_gepx', 'invalid .gepx package');
|
|
818
|
+
}
|
|
819
|
+
const assets = obj['assets']
|
|
820
|
+
.map((asset) => asRecord(asset))
|
|
821
|
+
.filter((asset) => Boolean(asset))
|
|
822
|
+
.map((asset) => asset);
|
|
823
|
+
const provenance = Array.isArray(obj['provenance'])
|
|
824
|
+
? obj['provenance'].map((record) => parseGepxProvenanceRecord(asRecord(record))).filter((record) => Boolean(record))
|
|
825
|
+
: [];
|
|
826
|
+
const sync = Array.isArray(obj['sync'])
|
|
827
|
+
? obj['sync'].map((record) => parseGepxSyncRecord(asRecord(record))).filter((record) => Boolean(record))
|
|
828
|
+
: [];
|
|
829
|
+
return {
|
|
830
|
+
type: GEPX_TYPE,
|
|
831
|
+
version: GEPX_VERSION,
|
|
832
|
+
...(stringField(obj, 'exportedAt') ? { exportedAt: stringField(obj, 'exportedAt') } : {}),
|
|
833
|
+
assets,
|
|
834
|
+
provenance,
|
|
835
|
+
sync,
|
|
836
|
+
};
|
|
837
|
+
}
|
|
838
|
+
function parseGepxProvenanceRecord(value) {
|
|
839
|
+
if (!value)
|
|
840
|
+
return null;
|
|
841
|
+
const assetId = stringField(value, 'assetId');
|
|
842
|
+
const source = stringField(value, 'source');
|
|
843
|
+
const at = stringField(value, 'at');
|
|
844
|
+
if (!assetId || !at || (source !== 'local' && source !== 'migrated' && source !== 'hub'))
|
|
845
|
+
return null;
|
|
846
|
+
return {
|
|
847
|
+
assetId,
|
|
848
|
+
source,
|
|
849
|
+
trusted: value['trusted'] === true,
|
|
850
|
+
at,
|
|
851
|
+
...(stringField(value, 'promotedBy') ? { promotedBy: stringField(value, 'promotedBy') } : {}),
|
|
852
|
+
...(stringField(value, 'reason') ? { reason: stringField(value, 'reason') } : {}),
|
|
853
|
+
};
|
|
854
|
+
}
|
|
855
|
+
function parseGepxSyncRecord(value) {
|
|
856
|
+
if (!value)
|
|
857
|
+
return null;
|
|
858
|
+
const assetId = stringField(value, 'assetId');
|
|
859
|
+
const type = stringField(value, 'type');
|
|
860
|
+
const source = stringField(value, 'source');
|
|
861
|
+
const scope = stringField(value, 'scope');
|
|
862
|
+
const syncedAt = stringField(value, 'syncedAt');
|
|
863
|
+
const remoteAssetId = stringField(value, 'remoteAssetId');
|
|
864
|
+
if (!assetId || (type !== 'Gene' && type !== 'Capsule') || source !== 'hub' || (scope !== 'purchased' && scope !== 'published') || !syncedAt || !remoteAssetId) {
|
|
865
|
+
return null;
|
|
866
|
+
}
|
|
867
|
+
return {
|
|
868
|
+
assetId,
|
|
869
|
+
type,
|
|
870
|
+
source: 'hub',
|
|
871
|
+
scope,
|
|
872
|
+
syncedAt,
|
|
873
|
+
remoteAssetId,
|
|
874
|
+
...(stringField(value, 'logicalId') ? { logicalId: stringField(value, 'logicalId') } : {}),
|
|
875
|
+
...(stringField(value, 'status') ? { status: stringField(value, 'status') } : {}),
|
|
876
|
+
...(value['forced'] === true ? { forced: true } : {}),
|
|
877
|
+
...(stringField(value, 'collisionWithAssetId') ? { collisionWithAssetId: stringField(value, 'collisionWithAssetId') } : {}),
|
|
878
|
+
};
|
|
879
|
+
}
|
|
880
|
+
function remoteType(row) {
|
|
881
|
+
const payload = asRecord(row.payload);
|
|
882
|
+
const raw = stringField(row, 'type') ?? stringField(row, 'asset_type') ?? (payload ? stringField(payload, 'type') : undefined);
|
|
883
|
+
return raw === 'Gene' || raw === 'Capsule' ? raw : undefined;
|
|
884
|
+
}
|
|
885
|
+
function remoteLogicalId(row) {
|
|
886
|
+
const payload = asRecord(row.payload);
|
|
887
|
+
return stringField(row, 'id') ?? stringField(row, 'local_id') ?? (payload ? stringField(payload, 'id') : undefined);
|
|
888
|
+
}
|
|
889
|
+
function emitTextPreview(preview, out) {
|
|
890
|
+
const c = preview.counts;
|
|
891
|
+
out(`sync preview: scope=${preview.scope} purchased=${c.remotePurchased} published=${c.remotePublished} unique=${c.uniqueRemote}`);
|
|
892
|
+
out(` would_import=${c.wouldImport} forced_import=${c.forcedImport} already_local=${c.alreadyLocal} id_collision=${c.idCollision} unsupported=${c.unsupported} integrity_error=${c.integrityError}`);
|
|
893
|
+
for (const candidate of preview.candidates.slice(0, 10)) {
|
|
894
|
+
out(` ${candidate.action}: ${candidate.type} ${candidate.assetId}${candidate.logicalId ? ` (${candidate.logicalId})` : ''}`);
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
function emitTextWrite(result, out) {
|
|
898
|
+
const c = result.counts;
|
|
899
|
+
out(`sync ${result.mode}: scope=${result.scope} purchased=${c.remotePurchased} published=${c.remotePublished} unique=${c.uniqueRemote}`);
|
|
900
|
+
out(` written=${result.written.length} blocked=${result.blocked.length} would_import=${c.wouldImport} forced_import=${c.forcedImport} already_local=${c.alreadyLocal} id_collision=${c.idCollision} unsupported=${c.unsupported} integrity_error=${c.integrityError}`);
|
|
901
|
+
for (const asset of result.written.slice(0, 10)) {
|
|
902
|
+
out(` imported: ${asset.type} ${asset.assetId}${asset.logicalId ? ` (${asset.logicalId})` : ''}`);
|
|
903
|
+
}
|
|
904
|
+
for (const candidate of result.blocked.slice(0, 10)) {
|
|
905
|
+
out(` blocked/${candidate.action}: ${candidate.type} ${candidate.assetId}${candidate.logicalId ? ` (${candidate.logicalId})` : ''}`);
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
function emitTextExport(result, out) {
|
|
909
|
+
out(`sync export: exported=${result.counts.exported} provenance=${result.counts.provenance} sync=${result.counts.sync}`);
|
|
910
|
+
for (const asset of result.assets.slice(0, 10)) {
|
|
911
|
+
out(` exported: ${asset.type} ${asset.assetId}${asset.logicalId ? ` (${asset.logicalId})` : ''}`);
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
function emitTextImportPreview(result, out) {
|
|
915
|
+
const c = result.counts;
|
|
916
|
+
out(`sync import preview: unique=${c.uniqueRemote}`);
|
|
917
|
+
out(` would_import=${c.wouldImport} forced_import=${c.forcedImport} already_local=${c.alreadyLocal} id_collision=${c.idCollision} unsupported=${c.unsupported} integrity_error=${c.integrityError}`);
|
|
918
|
+
for (const candidate of result.candidates.slice(0, 10)) {
|
|
919
|
+
out(` ${candidate.action}: ${candidate.type} ${candidate.assetId}${candidate.logicalId ? ` (${candidate.logicalId})` : ''}`);
|
|
920
|
+
}
|
|
921
|
+
}
|
|
922
|
+
function emitTextImport(result, out) {
|
|
923
|
+
const c = result.counts;
|
|
924
|
+
out(`sync import: written=${result.written.length} blocked=${result.blocked.length} unique=${c.uniqueRemote}`);
|
|
925
|
+
out(` would_import=${c.wouldImport} forced_import=${c.forcedImport} already_local=${c.alreadyLocal} id_collision=${c.idCollision} unsupported=${c.unsupported} integrity_error=${c.integrityError}`);
|
|
926
|
+
for (const asset of result.written.slice(0, 10)) {
|
|
927
|
+
out(` imported: ${asset.type} ${asset.assetId}${asset.logicalId ? ` (${asset.logicalId})` : ''}`);
|
|
928
|
+
}
|
|
929
|
+
for (const candidate of result.blocked.slice(0, 10)) {
|
|
930
|
+
out(` blocked/${candidate.action}: ${candidate.type} ${candidate.assetId}${candidate.logicalId ? ` (${candidate.logicalId})` : ''}`);
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
class SyncAbortError extends Error {
|
|
934
|
+
reason;
|
|
935
|
+
constructor(reason, message) {
|
|
936
|
+
super(message);
|
|
937
|
+
this.reason = reason;
|
|
938
|
+
this.name = 'SyncAbortError';
|
|
939
|
+
}
|
|
940
|
+
}
|
|
941
|
+
function emitFailure(reason, message, jsonOut, out, err) {
|
|
942
|
+
const payload = { ok: false, group: GROUP, reason, message: redact(message) };
|
|
943
|
+
if (jsonOut)
|
|
944
|
+
out(JSON.stringify(payload));
|
|
945
|
+
else
|
|
946
|
+
err(`sync failed (${reason}): ${payload.message}`);
|
|
947
|
+
return 1;
|
|
948
|
+
}
|
|
949
|
+
function mapSyncError(error) {
|
|
950
|
+
if (error instanceof SyncAbortError)
|
|
951
|
+
return { reason: error.reason, message: error.message };
|
|
952
|
+
if (error instanceof AuthError)
|
|
953
|
+
return { reason: 'auth_required', message: 'Hub authentication required' };
|
|
954
|
+
if (error instanceof HubClientError) {
|
|
955
|
+
if (error.status === 401 || error.status === 403)
|
|
956
|
+
return { reason: 'auth_required', message: 'Hub authentication required' };
|
|
957
|
+
if (error.status === 429 || error.status >= 500)
|
|
958
|
+
return { reason: 'network_error', message: 'Hub temporarily unavailable' };
|
|
959
|
+
return { reason: 'hub_rejected', message: 'Hub rejected the sync request' };
|
|
960
|
+
}
|
|
961
|
+
if (error instanceof HubUnreachableError)
|
|
962
|
+
return { reason: 'network_error', message: 'Hub unreachable' };
|
|
963
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
964
|
+
if (/credential|auth|login|node_secret|token/i.test(message))
|
|
965
|
+
return { reason: 'auth_required', message: redact(message) };
|
|
966
|
+
if (/network|fetch failed|ECONN|ENOTFOUND|ETIMEDOUT|hub 5\d\d/i.test(message))
|
|
967
|
+
return { reason: 'network_error', message: 'Hub unreachable' };
|
|
968
|
+
return { reason: 'internal_error', message: redact(message) };
|
|
969
|
+
}
|
|
970
|
+
function hasFetchAssetById(hub) {
|
|
971
|
+
return typeof hub.fetchAssetById === 'function';
|
|
972
|
+
}
|
|
973
|
+
function storeBaseDir(store, deps) {
|
|
974
|
+
return store instanceof assetstore.LocalJsonlProvider ? store.baseDir : deps.assetsDir ?? events.assetsDir();
|
|
975
|
+
}
|
|
976
|
+
function redact(value) {
|
|
977
|
+
return value
|
|
978
|
+
.replace(/\bBearer\s+[A-Za-z0-9._~+/=-]+/gi, 'Bearer [redacted]')
|
|
979
|
+
.replace(/\b([A-Z][A-Z0-9_]*(?:_SECRET|_TOKEN))\b\s*[:=]\s*["']?[^"',\s;}]+/g, '$1=[redacted]')
|
|
980
|
+
.replace(/\b(authorization|node_secret|nodeSecret|access_token|refresh_token|token|secret)\b\s*[:=]\s*["']?[^"',\s;}]+/gi, '$1=[redacted]');
|
|
981
|
+
}
|
|
982
|
+
function asRecord(value) {
|
|
983
|
+
return value && typeof value === 'object' && !Array.isArray(value) ? value : undefined;
|
|
984
|
+
}
|
|
985
|
+
function stringField(value, key) {
|
|
986
|
+
const raw = value[key];
|
|
987
|
+
return typeof raw === 'string' && raw.trim() ? raw.trim() : undefined;
|
|
988
|
+
}
|