@evomap/evolver-cli 2.0.0-beta.1 → 2.0.0-beta.12
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 +107 -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.d.ts +6 -0
- package/dist/autoDistillLlm.js +44 -7
- package/dist/autoexec.d.ts +14 -12
- package/dist/autoexec.js +84 -34
- package/dist/autoexecConfig.d.ts +10 -0
- package/dist/autoexecConfig.js +68 -0
- package/dist/cli.js +12 -5
- package/dist/cliContracts.js +30 -3
- 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 +33 -0
- package/dist/dashboard.js +352 -0
- package/dist/dispatch.d.ts +10 -1
- package/dist/dispatch.js +40 -2
- package/dist/distillAdmission.d.ts +13 -0
- package/dist/distillAdmission.js +35 -0
- package/dist/distillObserver.js +6 -8
- package/dist/distillPrimitives.d.ts +9 -7
- package/dist/distillPrimitives.js +65 -12
- package/dist/doctor.d.ts +2 -0
- package/dist/doctor.js +49 -3
- package/dist/index.d.ts +8 -2
- package/dist/index.js +350 -42
- package/dist/issueReport.d.ts +7 -0
- package/dist/issueReport.js +291 -0
- package/dist/lifecycle.d.ts +22 -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 +401 -0
- package/dist/materialSnapshot.d.ts +54 -0
- package/dist/materialSnapshot.js +370 -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 +12 -2
- package/dist/recipe.js +381 -8
- package/dist/reuse.d.ts +5 -3
- package/dist/reuse.js +126 -15
- 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 +11 -1
- package/dist/setupHooks.js +235 -16
- 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 +38 -0
- package/dist/sync.js +1981 -0
- package/dist/trajectoryExport.js +23 -12
- package/dist/v1Compat.d.ts +24 -0
- package/dist/v1Compat.js +249 -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 +631 -0
- package/package.json +12 -6
package/dist/sync.js
ADDED
|
@@ -0,0 +1,1981 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
3
|
+
import { dirname, join } from 'node:path';
|
|
4
|
+
import { assetstore, events, hub as hubNs, wire } from '@evomap/evolver-core';
|
|
5
|
+
import { AuthError, connectPublicHub, HubClientError, HubUnreachableError, isHubDryRunEnabled, resolveHubUrl, } from '@evomap/evolver-adapter-public';
|
|
6
|
+
import { loadEnvFileFromEnv } from '@evomap/evolver-mcp';
|
|
7
|
+
import { createRecipeHubFromEnv, resolveRecipeHubResumeIdentityFingerprint } from './recipe.js';
|
|
8
|
+
import { getCliVersion } from './version.js';
|
|
9
|
+
const DEFAULT_LIMIT = 100;
|
|
10
|
+
const MAX_LIMIT = 10_000;
|
|
11
|
+
const DEFAULT_PAGE_SIZE = 100;
|
|
12
|
+
const MAX_PAGE_SIZE = 1000;
|
|
13
|
+
const MAX_CURSOR_LENGTH = 4096;
|
|
14
|
+
const MAX_CONSECUTIVE_EMPTY_PAGES = 10;
|
|
15
|
+
const MAX_CONSECUTIVE_PAGES_WITHOUT_UNIQUE_PROGRESS = 10;
|
|
16
|
+
const MAX_RAW_PAGES = 20_000;
|
|
17
|
+
const MAX_RAW_ROWS = 100_000;
|
|
18
|
+
const MAX_GEPX_BYTES = 64 * 1024 * 1024;
|
|
19
|
+
const MAX_GEPX_ASSETS = 10_000;
|
|
20
|
+
const GROUP = 'sync';
|
|
21
|
+
const USAGE = [
|
|
22
|
+
'usage: evolver sync [--write] [--force] [--resume] [--scope all|purchased|published] [--type Gene|Capsule] [--status draft|promoted|all] [--limit N] [--page-size N] [--purchased-cursor CURSOR] [--published-cursor CURSOR] [--json]',
|
|
23
|
+
' evolver sync --export <file.gepx> [--type Gene|Capsule] [--limit N] [--json]',
|
|
24
|
+
' evolver sync --import <file.gepx> [--write] [--force] [--type Gene|Capsule] [--limit N] [--json]',
|
|
25
|
+
' evolver sync --json',
|
|
26
|
+
].join('\n');
|
|
27
|
+
const VALUE_FLAGS = new Set(['--scope', '--type', '--status', '--limit', '--page-size', '--purchased-cursor', '--published-cursor', '--export', '--import']);
|
|
28
|
+
const GEPX_TYPE = 'evomap.gepx';
|
|
29
|
+
const GEPX_VERSION = 1;
|
|
30
|
+
const HUB_METADATA_KEYS = new Set([
|
|
31
|
+
'credit_cost',
|
|
32
|
+
'gdi_score',
|
|
33
|
+
'success_rate',
|
|
34
|
+
'reuse_count',
|
|
35
|
+
'ranking_score',
|
|
36
|
+
'source_node_id',
|
|
37
|
+
'fetched_at',
|
|
38
|
+
'receipt',
|
|
39
|
+
'hub_receipt',
|
|
40
|
+
'already_purchased',
|
|
41
|
+
'_semantic_similarity',
|
|
42
|
+
'semantic_similarity',
|
|
43
|
+
'_search_score',
|
|
44
|
+
'search_score',
|
|
45
|
+
'_match_score',
|
|
46
|
+
'match_score',
|
|
47
|
+
'_retrieval_rank',
|
|
48
|
+
'retrieval_rank',
|
|
49
|
+
'original_asset_id',
|
|
50
|
+
'asset_type',
|
|
51
|
+
'local_id',
|
|
52
|
+
'payload',
|
|
53
|
+
'source',
|
|
54
|
+
'status',
|
|
55
|
+
]);
|
|
56
|
+
const MISSING_ASSET_ID = '[missing]';
|
|
57
|
+
export async function runSyncCommand(argv, deps = {}) {
|
|
58
|
+
const out = deps.stdout ?? ((line) => { process.stdout.write(`${line}\n`); });
|
|
59
|
+
const err = deps.stderr ?? ((line) => { process.stderr.write(`${line}\n`); });
|
|
60
|
+
const parsed = parseSyncArgs(argv);
|
|
61
|
+
if (!parsed.ok)
|
|
62
|
+
return emitFailure(parsed.reason, parsed.message, parsed.jsonOut, out, err);
|
|
63
|
+
if ('help' in parsed) {
|
|
64
|
+
if (parsed.jsonOut)
|
|
65
|
+
out(JSON.stringify({ ok: true, group: GROUP, mode: 'help', usage: USAGE }));
|
|
66
|
+
else
|
|
67
|
+
out(USAGE);
|
|
68
|
+
return 0;
|
|
69
|
+
}
|
|
70
|
+
try {
|
|
71
|
+
const env = deps.env ?? process.env;
|
|
72
|
+
loadSyncEnv(env);
|
|
73
|
+
const runtimeDeps = {
|
|
74
|
+
...deps,
|
|
75
|
+
env,
|
|
76
|
+
assetsDir: deps.assetsDir ?? join(events.evomapHome(env), 'assets'),
|
|
77
|
+
};
|
|
78
|
+
const result = parsed.value.exportPath
|
|
79
|
+
? await executeSyncExport(parsed.value, runtimeDeps)
|
|
80
|
+
: parsed.value.importPath
|
|
81
|
+
? parsed.value.write
|
|
82
|
+
? await executeGepxImportWrite(parsed.value, runtimeDeps)
|
|
83
|
+
: await buildGepxImportPreview(parsed.value, runtimeDeps)
|
|
84
|
+
: parsed.value.write
|
|
85
|
+
? await executeSyncWrite(parsed.value, runtimeDeps)
|
|
86
|
+
: await executeSyncPreview(parsed.value, runtimeDeps);
|
|
87
|
+
if (parsed.value.jsonOut)
|
|
88
|
+
out(JSON.stringify(result));
|
|
89
|
+
else if (result.mode === 'preview')
|
|
90
|
+
emitTextPreview(result, out);
|
|
91
|
+
else if (result.mode === 'export')
|
|
92
|
+
emitTextExport(result, out);
|
|
93
|
+
else if (result.mode === 'import_preview')
|
|
94
|
+
emitTextImportPreview(result, out);
|
|
95
|
+
else if (result.mode === 'import')
|
|
96
|
+
emitTextImport(result, out);
|
|
97
|
+
else
|
|
98
|
+
emitTextWrite(result, out);
|
|
99
|
+
if ('failures' in result && result.failures.length > 0)
|
|
100
|
+
return 1;
|
|
101
|
+
if (result.mode === 'import' && result.blocked.length > 0)
|
|
102
|
+
return 1;
|
|
103
|
+
if (result.mode === 'write' && !result.reconciliation.consistent)
|
|
104
|
+
return 1;
|
|
105
|
+
return 0;
|
|
106
|
+
}
|
|
107
|
+
catch (error) {
|
|
108
|
+
const mapped = mapSyncError(error);
|
|
109
|
+
return emitFailure(mapped.reason, mapped.message, parsed.value.jsonOut, out, err);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
function parseSyncArgs(argv) {
|
|
113
|
+
let scope = 'all';
|
|
114
|
+
let type;
|
|
115
|
+
let status = 'all';
|
|
116
|
+
let limit = DEFAULT_LIMIT;
|
|
117
|
+
let pageSize = DEFAULT_PAGE_SIZE;
|
|
118
|
+
let purchasedCursor;
|
|
119
|
+
let publishedCursor;
|
|
120
|
+
let jsonOut = argv.includes('--json');
|
|
121
|
+
let write = false;
|
|
122
|
+
let force = false;
|
|
123
|
+
let resume = false;
|
|
124
|
+
let exportPath;
|
|
125
|
+
let importPath;
|
|
126
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
127
|
+
const token = argv[i];
|
|
128
|
+
if (!token)
|
|
129
|
+
continue;
|
|
130
|
+
if (token === '--help' || token === '-h')
|
|
131
|
+
return { ok: true, help: true, jsonOut };
|
|
132
|
+
if (token === '--json') {
|
|
133
|
+
jsonOut = true;
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
if (token === '--write') {
|
|
137
|
+
write = true;
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
140
|
+
if (token === '--force') {
|
|
141
|
+
force = true;
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
if (token === '--resume') {
|
|
145
|
+
resume = true;
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
148
|
+
if (token.startsWith('--')) {
|
|
149
|
+
const eq = token.indexOf('=');
|
|
150
|
+
const flag = eq >= 0 ? token.slice(0, eq) : token;
|
|
151
|
+
if (!VALUE_FLAGS.has(flag)) {
|
|
152
|
+
return { ok: false, reason: 'invalid_arg', message: `unsupported sync argument: ${flag}`, jsonOut };
|
|
153
|
+
}
|
|
154
|
+
const value = eq >= 0 ? token.slice(eq + 1) : argv[i + 1];
|
|
155
|
+
if (!value || value.startsWith('--'))
|
|
156
|
+
return { ok: false, reason: 'invalid_arg', message: `${flag} requires a value`, jsonOut };
|
|
157
|
+
if (eq < 0)
|
|
158
|
+
i += 1;
|
|
159
|
+
if (flag === '--scope') {
|
|
160
|
+
if (value !== 'all' && value !== 'purchased' && value !== 'published') {
|
|
161
|
+
return { ok: false, reason: 'invalid_arg', message: '--scope must be all|purchased|published', jsonOut };
|
|
162
|
+
}
|
|
163
|
+
scope = value;
|
|
164
|
+
}
|
|
165
|
+
else if (flag === '--type') {
|
|
166
|
+
if (value !== 'Gene' && value !== 'Capsule')
|
|
167
|
+
return { ok: false, reason: 'invalid_arg', message: '--type must be Gene|Capsule', jsonOut };
|
|
168
|
+
type = value;
|
|
169
|
+
}
|
|
170
|
+
else if (flag === '--status') {
|
|
171
|
+
if (value !== 'draft' && value !== 'promoted' && value !== 'all') {
|
|
172
|
+
return { ok: false, reason: 'invalid_arg', message: '--status must be draft|promoted|all', jsonOut };
|
|
173
|
+
}
|
|
174
|
+
status = value;
|
|
175
|
+
}
|
|
176
|
+
else if (flag === '--limit') {
|
|
177
|
+
const parsedLimit = Number(value);
|
|
178
|
+
if (!Number.isSafeInteger(parsedLimit) || parsedLimit <= 0)
|
|
179
|
+
return { ok: false, reason: 'invalid_arg', message: '--limit must be a positive integer', jsonOut };
|
|
180
|
+
limit = Math.min(parsedLimit, MAX_LIMIT);
|
|
181
|
+
}
|
|
182
|
+
else if (flag === '--page-size') {
|
|
183
|
+
const parsedPageSize = Number(value);
|
|
184
|
+
if (!Number.isSafeInteger(parsedPageSize) || parsedPageSize <= 0)
|
|
185
|
+
return { ok: false, reason: 'invalid_arg', message: '--page-size must be a positive integer', jsonOut };
|
|
186
|
+
pageSize = Math.min(parsedPageSize, MAX_PAGE_SIZE);
|
|
187
|
+
}
|
|
188
|
+
else if (flag === '--purchased-cursor' || flag === '--published-cursor') {
|
|
189
|
+
if (!isValidOpaqueCursor(value)) {
|
|
190
|
+
return { ok: false, reason: 'invalid_arg', message: `${flag} must be a non-empty cursor of at most ${MAX_CURSOR_LENGTH} characters`, jsonOut };
|
|
191
|
+
}
|
|
192
|
+
if (flag === '--purchased-cursor')
|
|
193
|
+
purchasedCursor = value;
|
|
194
|
+
else
|
|
195
|
+
publishedCursor = value;
|
|
196
|
+
}
|
|
197
|
+
else if (flag === '--export') {
|
|
198
|
+
exportPath = value;
|
|
199
|
+
}
|
|
200
|
+
else if (flag === '--import') {
|
|
201
|
+
importPath = value;
|
|
202
|
+
}
|
|
203
|
+
continue;
|
|
204
|
+
}
|
|
205
|
+
return { ok: false, reason: 'invalid_arg', message: `unsupported sync argument: ${token}`, jsonOut };
|
|
206
|
+
}
|
|
207
|
+
if (force && !write) {
|
|
208
|
+
return { ok: false, reason: 'force_requires_write', message: '--force requires --write', jsonOut };
|
|
209
|
+
}
|
|
210
|
+
if (resume && !write) {
|
|
211
|
+
return { ok: false, reason: 'resume_requires_write', message: '--resume requires --write', jsonOut };
|
|
212
|
+
}
|
|
213
|
+
if (exportPath && importPath) {
|
|
214
|
+
return { ok: false, reason: 'invalid_arg', message: '--export and --import cannot be used together', jsonOut };
|
|
215
|
+
}
|
|
216
|
+
if (exportPath && write) {
|
|
217
|
+
return { ok: false, reason: 'invalid_arg', message: '--export does not use --write', jsonOut };
|
|
218
|
+
}
|
|
219
|
+
if (purchasedCursor && scope === 'published') {
|
|
220
|
+
return { ok: false, reason: 'invalid_arg', message: '--purchased-cursor requires --scope all|purchased', jsonOut };
|
|
221
|
+
}
|
|
222
|
+
if (publishedCursor && scope === 'purchased') {
|
|
223
|
+
return { ok: false, reason: 'invalid_arg', message: '--published-cursor requires --scope all|published', jsonOut };
|
|
224
|
+
}
|
|
225
|
+
if ((purchasedCursor || publishedCursor) && (exportPath || importPath)) {
|
|
226
|
+
return { ok: false, reason: 'invalid_arg', message: 'Hub cursors cannot be used with --export or --import', jsonOut };
|
|
227
|
+
}
|
|
228
|
+
return { ok: true, value: { scope, ...(type ? { type } : {}), status, limit, pageSize, ...(purchasedCursor ? { purchasedCursor } : {}), ...(publishedCursor ? { publishedCursor } : {}), jsonOut, write, force, resume, ...(exportPath ? { exportPath } : {}), ...(importPath ? { importPath } : {}) } };
|
|
229
|
+
}
|
|
230
|
+
async function buildSyncPreview(opts, deps, listing = {
|
|
231
|
+
skipPurchased: false,
|
|
232
|
+
skipPublished: false,
|
|
233
|
+
}) {
|
|
234
|
+
const env = deps.env ?? process.env;
|
|
235
|
+
validatePrivateHubUrl(env);
|
|
236
|
+
if (isHubDryRunEnabled(env))
|
|
237
|
+
return emptyPreview(opts.scope);
|
|
238
|
+
const hub = deps.hub ?? await createDefaultHub(deps, env);
|
|
239
|
+
const store = deps.store ?? new assetstore.LocalJsonlProvider(deps.assetsDir ?? events.assetsDir());
|
|
240
|
+
const local = await localIndex(store);
|
|
241
|
+
const { purchased, published, failures, inventoryComplete, nextCursors } = await listRemoteRows(hub, opts, listing);
|
|
242
|
+
const counts = {
|
|
243
|
+
remotePurchased: purchased.length,
|
|
244
|
+
remotePublished: published.length,
|
|
245
|
+
uniqueRemote: 0,
|
|
246
|
+
alreadyLocal: 0,
|
|
247
|
+
tombstone: 0,
|
|
248
|
+
idCollision: 0,
|
|
249
|
+
unsupported: 0,
|
|
250
|
+
integrityError: 0,
|
|
251
|
+
wouldImport: 0,
|
|
252
|
+
forcedImport: 0,
|
|
253
|
+
skippedLimit: 0,
|
|
254
|
+
fetchFailed: 0,
|
|
255
|
+
writeFailed: 0,
|
|
256
|
+
};
|
|
257
|
+
const unique = new Map();
|
|
258
|
+
const missingAssetId = [];
|
|
259
|
+
for (const row of purchased)
|
|
260
|
+
addUnique(unique, missingAssetId, row, 'purchased');
|
|
261
|
+
for (const row of published)
|
|
262
|
+
addUnique(unique, missingAssetId, row, 'published');
|
|
263
|
+
counts.uniqueRemote = unique.size + missingAssetId.length;
|
|
264
|
+
const candidates = [];
|
|
265
|
+
const pendingLogical = new Map(local.logical);
|
|
266
|
+
for (const { row, source } of [...unique.values(), ...missingAssetId]) {
|
|
267
|
+
const candidate = classifyRemote(row, source, { byAssetId: local.byAssetId, logical: pendingLogical });
|
|
268
|
+
candidates.push(candidate);
|
|
269
|
+
if (candidate.action === 'already_local')
|
|
270
|
+
counts.alreadyLocal += 1;
|
|
271
|
+
else if (candidate.action === 'tombstone')
|
|
272
|
+
counts.tombstone += 1;
|
|
273
|
+
else if (candidate.action === 'id_collision')
|
|
274
|
+
counts.idCollision += 1;
|
|
275
|
+
else if (candidate.action === 'would_import') {
|
|
276
|
+
counts.wouldImport += 1;
|
|
277
|
+
if (candidate.logicalId && (candidate.type === 'Gene' || candidate.type === 'Capsule')) {
|
|
278
|
+
pendingLogical.set(`${candidate.type}:${candidate.logicalId}`, candidate.assetId);
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
else if (candidate.action === 'force_import')
|
|
282
|
+
counts.forcedImport += 1;
|
|
283
|
+
else if (candidate.action === 'unsupported_type')
|
|
284
|
+
counts.unsupported += 1;
|
|
285
|
+
else
|
|
286
|
+
counts.integrityError += 1;
|
|
287
|
+
}
|
|
288
|
+
return {
|
|
289
|
+
ok: true,
|
|
290
|
+
group: GROUP,
|
|
291
|
+
mode: 'preview',
|
|
292
|
+
scope: opts.scope,
|
|
293
|
+
counts,
|
|
294
|
+
candidates,
|
|
295
|
+
failures,
|
|
296
|
+
nextCursors,
|
|
297
|
+
reconciliation: reconcile(candidates, failures, 0, false, inventoryComplete, 0),
|
|
298
|
+
};
|
|
299
|
+
}
|
|
300
|
+
async function executeSyncPreview(opts, deps) {
|
|
301
|
+
const env = deps.env ?? process.env;
|
|
302
|
+
validatePrivateHubUrl(env);
|
|
303
|
+
if (isHubDryRunEnabled(env))
|
|
304
|
+
return emptyPreview(opts.scope);
|
|
305
|
+
const hub = deps.hub ?? await createDefaultHub(deps, env);
|
|
306
|
+
const store = deps.store ?? new assetstore.LocalJsonlProvider(deps.assetsDir ?? events.assetsDir());
|
|
307
|
+
if (!opts.purchasedCursor && !opts.publishedCursor) {
|
|
308
|
+
return buildSyncPreview(opts, { ...deps, env, hub, store });
|
|
309
|
+
}
|
|
310
|
+
const baseDir = storeBaseDir(store, deps);
|
|
311
|
+
const syncLedger = deps.syncLedger ?? new assetstore.AssetSyncLedger(baseDir, deps.now);
|
|
312
|
+
const inventoryKey = syncInventoryKey(opts, env, deps);
|
|
313
|
+
const inventoryScan = prepareInventoryScan(syncLedger, inventoryKey, opts);
|
|
314
|
+
return buildSyncPreview(opts, { ...deps, env, hub, store }, inventoryScan);
|
|
315
|
+
}
|
|
316
|
+
async function executeSyncWrite(opts, deps) {
|
|
317
|
+
const env = deps.env ?? process.env;
|
|
318
|
+
validatePrivateHubUrl(env);
|
|
319
|
+
if (isHubDryRunEnabled(env))
|
|
320
|
+
return emptyWrite(opts.scope, 'dry_run');
|
|
321
|
+
const hub = deps.hub ?? await createDefaultHub(deps, env);
|
|
322
|
+
if (!hasFetchAssetById(hub))
|
|
323
|
+
throw new Error('sync write requires fetchAssetById support');
|
|
324
|
+
const store = deps.store ?? new assetstore.LocalJsonlProvider(deps.assetsDir ?? events.assetsDir());
|
|
325
|
+
const baseDir = storeBaseDir(store, deps);
|
|
326
|
+
const provenance = deps.provenance ?? new assetstore.ProvenanceStore(baseDir, deps.now);
|
|
327
|
+
const syncLedger = deps.syncLedger ?? new assetstore.AssetSyncLedger(baseDir, deps.now);
|
|
328
|
+
const runKey = syncRunKey(opts, env, deps);
|
|
329
|
+
const inventoryKey = syncInventoryKey(opts, env, deps);
|
|
330
|
+
const inventoryScan = prepareInventoryScan(syncLedger, inventoryKey, opts);
|
|
331
|
+
const preview = await buildSyncPreview(opts, { ...deps, env, hub, store }, inventoryScan);
|
|
332
|
+
const local = await localIndex(store);
|
|
333
|
+
const checkpointEnabled = !preview.failures.some((failure) => failure.stage === 'list');
|
|
334
|
+
const previousRun = opts.resume && checkpointEnabled ? syncLedger.latestIncompleteRun(runKey) : null;
|
|
335
|
+
const runId = previousRun?.runId ?? randomUUID();
|
|
336
|
+
const appendRunCheckpoint = (record) => {
|
|
337
|
+
if (checkpointEnabled)
|
|
338
|
+
syncLedger.appendRun(record);
|
|
339
|
+
};
|
|
340
|
+
const resumeSelection = previousRun
|
|
341
|
+
? resumePlannedCandidates(preview.candidates, previousRun, preview.reconciliation.inventoryComplete)
|
|
342
|
+
: { candidates: preview.candidates.map((candidate) => ({ ...candidate })), remoteMissingAssetIds: [], newRemoteMissingAssetIds: [] };
|
|
343
|
+
const finalCandidates = resumeSelection.candidates;
|
|
344
|
+
const currentPlan = actionableCandidatePlanIds(finalCandidates, opts.force);
|
|
345
|
+
const runPlan = previousRun?.plan ? mergeCandidatePlan(previousRun.plan, currentPlan) : currentPlan;
|
|
346
|
+
const hasActionable = currentPlan.length > 0;
|
|
347
|
+
if (previousRun?.plan) {
|
|
348
|
+
if (runPlan.length > previousRun.plan.length) {
|
|
349
|
+
appendRunCheckpoint({ runId, runKey, state: 'started', plan: runPlan });
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
if (hasActionable && !previousRun) {
|
|
353
|
+
appendRunCheckpoint({
|
|
354
|
+
runId,
|
|
355
|
+
runKey,
|
|
356
|
+
state: 'started',
|
|
357
|
+
plan: runPlan,
|
|
358
|
+
});
|
|
359
|
+
}
|
|
360
|
+
for (const assetId of resumeSelection.newRemoteMissingAssetIds) {
|
|
361
|
+
appendRunCheckpoint({
|
|
362
|
+
runId,
|
|
363
|
+
runKey,
|
|
364
|
+
state: 'progress',
|
|
365
|
+
remoteAssetId: assetId,
|
|
366
|
+
outcome: 'remote_missing',
|
|
367
|
+
});
|
|
368
|
+
}
|
|
369
|
+
const failures = [...preview.failures];
|
|
370
|
+
const resumed = previousRun
|
|
371
|
+
? await reconcileResumeCandidates({
|
|
372
|
+
candidates: finalCandidates,
|
|
373
|
+
previousRun,
|
|
374
|
+
store,
|
|
375
|
+
provenance,
|
|
376
|
+
syncLedger,
|
|
377
|
+
appendRunCheckpoint,
|
|
378
|
+
runId,
|
|
379
|
+
runKey,
|
|
380
|
+
inventoryKey,
|
|
381
|
+
failures,
|
|
382
|
+
})
|
|
383
|
+
: 0;
|
|
384
|
+
await verifyAlreadyLocalCandidates(finalCandidates, store, failures);
|
|
385
|
+
const prepared = [];
|
|
386
|
+
const pendingLogical = new Map(local.logical);
|
|
387
|
+
for (const candidate of finalCandidates) {
|
|
388
|
+
if (candidate.action !== 'would_import' && !(opts.force && candidate.action === 'id_collision'))
|
|
389
|
+
continue;
|
|
390
|
+
const checkpoint = previousRun?.processed.get(candidate.assetId);
|
|
391
|
+
if (checkpoint && checkpoint.outcome !== 'failed' && local.byAssetId.has(candidate.assetId))
|
|
392
|
+
continue;
|
|
393
|
+
let preparedAsset;
|
|
394
|
+
try {
|
|
395
|
+
const fetched = await hub.fetchAssetById(candidate.assetId);
|
|
396
|
+
if (!fetched)
|
|
397
|
+
throw new SyncAbortError('not_found', 'Hub asset disappeared before import');
|
|
398
|
+
preparedAsset = prepareFetchedAsset(candidate, fetched, local.byAssetId, pendingLogical, opts.force);
|
|
399
|
+
}
|
|
400
|
+
catch (error) {
|
|
401
|
+
const mapped = mapSyncError(error);
|
|
402
|
+
failures.push({ stage: 'fetch', assetId: candidate.assetId, reason: mapped.reason });
|
|
403
|
+
appendRunCheckpoint({ runId, runKey, state: 'progress', remoteAssetId: candidate.assetId, outcome: 'failed', reason: mapped.reason });
|
|
404
|
+
updateFinalCandidate(finalCandidates, candidate, mapped.reason === 'integrity_error'
|
|
405
|
+
? { ...candidate, action: 'integrity_error' }
|
|
406
|
+
: { ...candidate, action: 'fetch_failed', failureReason: mapped.reason });
|
|
407
|
+
continue;
|
|
408
|
+
}
|
|
409
|
+
if ('blocked' in preparedAsset) {
|
|
410
|
+
updateFinalCandidate(finalCandidates, candidate, preparedAsset.blocked);
|
|
411
|
+
continue;
|
|
412
|
+
}
|
|
413
|
+
const logicalId = stringField(preparedAsset.asset, 'id');
|
|
414
|
+
const finalCandidate = preparedAsset.forced
|
|
415
|
+
? {
|
|
416
|
+
...candidate,
|
|
417
|
+
...(logicalId ? { logicalId } : {}),
|
|
418
|
+
action: 'force_import',
|
|
419
|
+
collisionWithAssetId: preparedAsset.collisionWithAssetId,
|
|
420
|
+
}
|
|
421
|
+
: {
|
|
422
|
+
assetId: candidate.assetId,
|
|
423
|
+
type: candidate.type,
|
|
424
|
+
source: candidate.source,
|
|
425
|
+
...(candidate.status ? { status: candidate.status } : {}),
|
|
426
|
+
...(logicalId ? { logicalId } : {}),
|
|
427
|
+
action: 'would_import',
|
|
428
|
+
};
|
|
429
|
+
updateFinalCandidate(finalCandidates, candidate, finalCandidate);
|
|
430
|
+
prepared.push({
|
|
431
|
+
candidate: finalCandidate,
|
|
432
|
+
asset: preparedAsset.asset,
|
|
433
|
+
...(preparedAsset.forced ? { forced: true, collisionWithAssetId: preparedAsset.collisionWithAssetId } : {}),
|
|
434
|
+
});
|
|
435
|
+
if (logicalId)
|
|
436
|
+
pendingLogical.set(`${preparedAsset.asset.type}:${logicalId}`, preparedAsset.asset.asset_id);
|
|
437
|
+
}
|
|
438
|
+
const written = [];
|
|
439
|
+
for (const item of prepared) {
|
|
440
|
+
try {
|
|
441
|
+
const stored = await assetstore.ingestUntrustedConditional(store, provenance, item.asset, { allowLogicalCollision: opts.force }, 'hub');
|
|
442
|
+
const assetId = stored.asset_id;
|
|
443
|
+
if (stored.status === 'logical_collision') {
|
|
444
|
+
updateFinalCandidate(finalCandidates, item.candidate, {
|
|
445
|
+
...item.candidate,
|
|
446
|
+
assetId,
|
|
447
|
+
action: 'id_collision',
|
|
448
|
+
collisionWithAssetId: stored.collisionWithAssetId,
|
|
449
|
+
});
|
|
450
|
+
continue;
|
|
451
|
+
}
|
|
452
|
+
await readBackStoredAsset(store, assetId, item.asset);
|
|
453
|
+
if (stored.status === 'already_exists') {
|
|
454
|
+
updateFinalCandidate(finalCandidates, item.candidate, { ...item.candidate, assetId, action: 'already_local' });
|
|
455
|
+
appendRunCheckpoint({ runId, runKey, state: 'progress', remoteAssetId: item.candidate.assetId, outcome: 'already_local' });
|
|
456
|
+
continue;
|
|
457
|
+
}
|
|
458
|
+
const collisionWithAssetId = stored.collisionWithAssetId ?? item.collisionWithAssetId;
|
|
459
|
+
const forced = item.forced === true || collisionWithAssetId !== undefined;
|
|
460
|
+
const writtenCandidate = forced
|
|
461
|
+
? { ...item.candidate, action: 'force_import', collisionWithAssetId }
|
|
462
|
+
: item.candidate;
|
|
463
|
+
updateFinalCandidate(finalCandidates, item.candidate, writtenCandidate);
|
|
464
|
+
appendSyncRecord(syncLedger, writtenCandidate, item.asset, runKey, inventoryKey, {
|
|
465
|
+
...(forced ? { forced: true } : {}),
|
|
466
|
+
...(collisionWithAssetId ? { collisionWithAssetId } : {}),
|
|
467
|
+
});
|
|
468
|
+
appendRunCheckpoint({ runId, runKey, state: 'progress', remoteAssetId: item.candidate.assetId, outcome: 'imported' });
|
|
469
|
+
written.push({
|
|
470
|
+
assetId,
|
|
471
|
+
type: item.asset.type,
|
|
472
|
+
source: writtenCandidate.source,
|
|
473
|
+
stored: true,
|
|
474
|
+
trusted: false,
|
|
475
|
+
...(writtenCandidate.logicalId ? { logicalId: writtenCandidate.logicalId } : {}),
|
|
476
|
+
...(writtenCandidate.status ? { status: writtenCandidate.status } : {}),
|
|
477
|
+
...(forced ? { forced: true } : {}),
|
|
478
|
+
...(collisionWithAssetId ? { collisionWithAssetId } : {}),
|
|
479
|
+
});
|
|
480
|
+
}
|
|
481
|
+
catch (error) {
|
|
482
|
+
const mapped = mapSyncError(error);
|
|
483
|
+
failures.push({ stage: 'write', assetId: item.candidate.assetId, reason: mapped.reason });
|
|
484
|
+
appendRunCheckpoint({ runId, runKey, state: 'progress', remoteAssetId: item.candidate.assetId, outcome: 'failed', reason: mapped.reason });
|
|
485
|
+
updateFinalCandidate(finalCandidates, item.candidate, {
|
|
486
|
+
...item.candidate,
|
|
487
|
+
action: 'write_failed',
|
|
488
|
+
failureReason: mapped.reason,
|
|
489
|
+
});
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
const retryableInventoryFailure = failures.some(isRetryableAssetFailure);
|
|
493
|
+
let inventoryComplete = preview.reconciliation.inventoryComplete;
|
|
494
|
+
if (retryableInventoryFailure)
|
|
495
|
+
inventoryComplete = false;
|
|
496
|
+
let remoteAssetIds = new Set(finalCandidates.flatMap((candidate) => (candidate.assetId === MISSING_ASSET_ID ? [] : [candidate.assetId])));
|
|
497
|
+
let missingRemote = inventoryComplete
|
|
498
|
+
? countMissingRemote(syncLedger, inventoryKey, runKey, local.byAssetId, remoteAssetIds)
|
|
499
|
+
: 0;
|
|
500
|
+
let reconciliation;
|
|
501
|
+
let inventoryCheckpointFailed = false;
|
|
502
|
+
if (inventoryScan.trackable
|
|
503
|
+
&& inventoryScan.index === 0
|
|
504
|
+
&& !inventoryScan.retry
|
|
505
|
+
&& inventoryComplete
|
|
506
|
+
&& !failures.some((failure) => failure.stage === 'list')) {
|
|
507
|
+
try {
|
|
508
|
+
syncLedger.clearInventoryScan(inventoryKey);
|
|
509
|
+
}
|
|
510
|
+
catch {
|
|
511
|
+
failures.push({ stage: 'list', reason: 'inventory_scan_checkpoint_failed' });
|
|
512
|
+
inventoryComplete = false;
|
|
513
|
+
missingRemote = 0;
|
|
514
|
+
inventoryCheckpointFailed = true;
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
const shouldCheckpointInventory = inventoryScan.trackable
|
|
518
|
+
&& !inventoryCheckpointFailed
|
|
519
|
+
&& !failures.some((failure) => failure.stage === 'list')
|
|
520
|
+
&& (!inventoryComplete || inventoryScan.index > 0 || inventoryScan.retry);
|
|
521
|
+
if (shouldCheckpointInventory) {
|
|
522
|
+
const segment = inventorySegmentOutcome(finalCandidates, failures, written);
|
|
523
|
+
const inventoryBatch = {
|
|
524
|
+
scanId: inventoryScan.scanId,
|
|
525
|
+
inventoryKey,
|
|
526
|
+
scope: opts.scope,
|
|
527
|
+
index: inventoryScan.index,
|
|
528
|
+
inputCursorFingerprints: inventoryScan.inputCursorFingerprints,
|
|
529
|
+
nextCursorFingerprints: retryableInventoryFailure
|
|
530
|
+
? inventoryScan.inputCursorFingerprints
|
|
531
|
+
: fingerprintCursors(preview.nextCursors),
|
|
532
|
+
items: segment.items,
|
|
533
|
+
anonymousBlocked: segment.anonymousBlocked,
|
|
534
|
+
...(retryableInventoryFailure ? { cursorHeld: true } : {}),
|
|
535
|
+
};
|
|
536
|
+
const appended = inventoryScan.retry
|
|
537
|
+
? syncLedger.replaceInventoryRetryBatch(inventoryBatch)
|
|
538
|
+
: syncLedger.appendInventoryBatch(inventoryBatch);
|
|
539
|
+
const snapshot = appended ? syncLedger.latestInventoryScan(inventoryKey) : undefined;
|
|
540
|
+
if (!snapshot || snapshot.scanId !== inventoryScan.scanId) {
|
|
541
|
+
failures.push({ stage: 'list', reason: 'inventory_scan_checkpoint_failed' });
|
|
542
|
+
inventoryComplete = false;
|
|
543
|
+
missingRemote = 0;
|
|
544
|
+
inventoryCheckpointFailed = true;
|
|
545
|
+
}
|
|
546
|
+
else if (snapshot.complete) {
|
|
547
|
+
inventoryComplete = true;
|
|
548
|
+
remoteAssetIds = new Set(snapshot.outcomes.keys());
|
|
549
|
+
missingRemote = countMissingRemote(syncLedger, inventoryKey, runKey, local.byAssetId, remoteAssetIds);
|
|
550
|
+
reconciliation = reconcileInventorySnapshot(snapshot, missingRemote);
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
reconciliation ??= reconcile(finalCandidates, failures, written.length, true, inventoryComplete, missingRemote);
|
|
554
|
+
const counts = countsFromCandidates(preview.counts, finalCandidates);
|
|
555
|
+
const blocked = finalCandidates.filter(isBlockedCandidate);
|
|
556
|
+
const failedAssetIds = new Set(failures.flatMap((failure) => failure.assetId ? [failure.assetId] : []));
|
|
557
|
+
const finalCandidatesByAssetId = new Map(finalCandidates.map((candidate) => [candidate.assetId, candidate]));
|
|
558
|
+
const writtenAssetIds = new Set(written.map((asset) => asset.assetId));
|
|
559
|
+
const remoteMissingAssetIds = new Set(resumeSelection.remoteMissingAssetIds);
|
|
560
|
+
const actionComplete = runPlan.every((assetId) => {
|
|
561
|
+
if (remoteMissingAssetIds.has(assetId))
|
|
562
|
+
return true;
|
|
563
|
+
if (failedAssetIds.has(assetId))
|
|
564
|
+
return false;
|
|
565
|
+
if (local.byAssetId.has(assetId) || writtenAssetIds.has(assetId))
|
|
566
|
+
return true;
|
|
567
|
+
const candidate = finalCandidatesByAssetId.get(assetId);
|
|
568
|
+
return candidate?.action === 'already_local' || (candidate !== undefined && isBlockedCandidate(candidate));
|
|
569
|
+
});
|
|
570
|
+
if ((hasActionable || previousRun) && actionComplete && !inventoryCheckpointFailed) {
|
|
571
|
+
appendRunCheckpoint({ runId, runKey, state: 'completed' });
|
|
572
|
+
}
|
|
573
|
+
return {
|
|
574
|
+
ok: true,
|
|
575
|
+
group: GROUP,
|
|
576
|
+
mode: 'write',
|
|
577
|
+
scope: opts.scope,
|
|
578
|
+
counts,
|
|
579
|
+
candidates: finalCandidates,
|
|
580
|
+
written,
|
|
581
|
+
blocked,
|
|
582
|
+
failures,
|
|
583
|
+
nextCursors: preview.nextCursors,
|
|
584
|
+
resumed,
|
|
585
|
+
reconciliation,
|
|
586
|
+
};
|
|
587
|
+
}
|
|
588
|
+
async function executeSyncExport(opts, deps) {
|
|
589
|
+
if (!opts.exportPath)
|
|
590
|
+
throw new SyncAbortError('invalid_arg', '--export requires a file');
|
|
591
|
+
const store = deps.store ?? new assetstore.LocalJsonlProvider(deps.assetsDir ?? events.assetsDir());
|
|
592
|
+
const baseDir = storeBaseDir(store, deps);
|
|
593
|
+
const provenance = deps.provenance ?? new assetstore.ProvenanceStore(baseDir, deps.now);
|
|
594
|
+
const syncLedger = deps.syncLedger ?? new assetstore.AssetSyncLedger(baseDir, deps.now);
|
|
595
|
+
const provenanceSnapshot = provenance.snapshot();
|
|
596
|
+
const assets = await listLocalExportAssets(store, opts);
|
|
597
|
+
const provenanceRecords = assets
|
|
598
|
+
.map((asset) => provenanceSnapshot.get(asset.asset_id) ?? null)
|
|
599
|
+
.filter((record) => Boolean(record));
|
|
600
|
+
const syncRecords = assets
|
|
601
|
+
.map((asset) => syncLedger.get(asset.asset_id))
|
|
602
|
+
.filter((record) => Boolean(record));
|
|
603
|
+
const pkg = {
|
|
604
|
+
type: GEPX_TYPE,
|
|
605
|
+
version: GEPX_VERSION,
|
|
606
|
+
exportedAt: new Date(deps.now ? deps.now() : Date.now()).toISOString(),
|
|
607
|
+
assets,
|
|
608
|
+
malformedAssets: [],
|
|
609
|
+
provenance: provenanceRecords,
|
|
610
|
+
sync: syncRecords,
|
|
611
|
+
};
|
|
612
|
+
try {
|
|
613
|
+
mkdirSync(dirname(opts.exportPath), { recursive: true });
|
|
614
|
+
writeFileSync(opts.exportPath, `${JSON.stringify(pkg, null, 2)}\n`, 'utf8');
|
|
615
|
+
}
|
|
616
|
+
catch {
|
|
617
|
+
throw new SyncAbortError('export_failed', 'could not write .gepx file');
|
|
618
|
+
}
|
|
619
|
+
return {
|
|
620
|
+
ok: true,
|
|
621
|
+
group: GROUP,
|
|
622
|
+
mode: 'export',
|
|
623
|
+
counts: {
|
|
624
|
+
exported: assets.length,
|
|
625
|
+
provenance: provenanceRecords.length,
|
|
626
|
+
sync: syncRecords.length,
|
|
627
|
+
},
|
|
628
|
+
assets: assets.map((asset) => ({
|
|
629
|
+
assetId: asset.asset_id,
|
|
630
|
+
type: asset.type,
|
|
631
|
+
...(stringField(asset, 'id') ? { logicalId: stringField(asset, 'id') } : {}),
|
|
632
|
+
trusted: provenanceSnapshot.get(asset.asset_id)?.trusted ?? true,
|
|
633
|
+
synced: Boolean(syncLedger.get(asset.asset_id)),
|
|
634
|
+
})),
|
|
635
|
+
};
|
|
636
|
+
}
|
|
637
|
+
async function buildGepxImportPreview(opts, deps) {
|
|
638
|
+
const pkg = readGepxPackage(opts.importPath);
|
|
639
|
+
const store = deps.store ?? new assetstore.LocalJsonlProvider(deps.assetsDir ?? events.assetsDir());
|
|
640
|
+
const local = await localIndex(store);
|
|
641
|
+
const candidates = classifyGepxAssets(pkg, opts, local);
|
|
642
|
+
return { ok: true, group: GROUP, mode: 'import_preview', counts: countsFromCandidates(emptyCounts(candidates.length), candidates), candidates };
|
|
643
|
+
}
|
|
644
|
+
async function executeGepxImportWrite(opts, deps) {
|
|
645
|
+
const pkg = readGepxPackage(opts.importPath);
|
|
646
|
+
assertNoConflictingGepxDuplicates(pkg);
|
|
647
|
+
const store = deps.store ?? new assetstore.LocalJsonlProvider(deps.assetsDir ?? events.assetsDir());
|
|
648
|
+
const local = await localIndex(store);
|
|
649
|
+
const finalCandidates = classifyGepxAssets(pkg, opts, local);
|
|
650
|
+
const failures = finalCandidates
|
|
651
|
+
.filter((candidate) => candidate.action === 'integrity_error')
|
|
652
|
+
.map((candidate) => ({
|
|
653
|
+
stage: 'write',
|
|
654
|
+
...(candidate.assetId.startsWith(MISSING_ASSET_ID) ? {} : { assetId: candidate.assetId }),
|
|
655
|
+
reason: candidate.failureReason ?? 'integrity_error',
|
|
656
|
+
}));
|
|
657
|
+
const assetsById = gepxImportAssetsById(pkg);
|
|
658
|
+
const syncById = new Map((pkg.sync ?? []).map((record) => [record.assetId, record]));
|
|
659
|
+
const prepared = [];
|
|
660
|
+
const pendingLogical = new Map(local.logical);
|
|
661
|
+
for (const candidate of finalCandidates) {
|
|
662
|
+
if (candidate.action !== 'would_import' && !(opts.force && candidate.action === 'id_collision'))
|
|
663
|
+
continue;
|
|
664
|
+
const asset = assetsById.get(candidate.assetId);
|
|
665
|
+
if (!asset)
|
|
666
|
+
throw new SyncAbortError('integrity_error', '.gepx package asset is missing');
|
|
667
|
+
const preparedAsset = preparePackagedAsset(candidate, asset, local.byAssetId, pendingLogical, opts.force);
|
|
668
|
+
if ('blocked' in preparedAsset) {
|
|
669
|
+
updateFinalCandidate(finalCandidates, candidate, preparedAsset.blocked);
|
|
670
|
+
continue;
|
|
671
|
+
}
|
|
672
|
+
const logicalId = stringField(preparedAsset.asset, 'id');
|
|
673
|
+
const finalCandidate = preparedAsset.forced
|
|
674
|
+
? {
|
|
675
|
+
...candidate,
|
|
676
|
+
...(logicalId ? { logicalId } : {}),
|
|
677
|
+
action: 'force_import',
|
|
678
|
+
collisionWithAssetId: preparedAsset.collisionWithAssetId,
|
|
679
|
+
}
|
|
680
|
+
: {
|
|
681
|
+
assetId: candidate.assetId,
|
|
682
|
+
type: candidate.type,
|
|
683
|
+
source: 'gepx',
|
|
684
|
+
...(candidate.status ? { status: candidate.status } : {}),
|
|
685
|
+
...(logicalId ? { logicalId } : {}),
|
|
686
|
+
action: 'would_import',
|
|
687
|
+
};
|
|
688
|
+
updateFinalCandidate(finalCandidates, candidate, finalCandidate);
|
|
689
|
+
prepared.push({
|
|
690
|
+
candidate: finalCandidate,
|
|
691
|
+
asset: preparedAsset.asset,
|
|
692
|
+
...(preparedAsset.forced ? { forced: true, collisionWithAssetId: preparedAsset.collisionWithAssetId } : {}),
|
|
693
|
+
});
|
|
694
|
+
if (logicalId)
|
|
695
|
+
pendingLogical.set(`${preparedAsset.asset.type}:${logicalId}`, preparedAsset.asset.asset_id);
|
|
696
|
+
}
|
|
697
|
+
const baseDir = storeBaseDir(store, deps);
|
|
698
|
+
const provenance = deps.provenance ?? new assetstore.ProvenanceStore(baseDir, deps.now);
|
|
699
|
+
const syncLedger = deps.syncLedger ?? new assetstore.AssetSyncLedger(baseDir, deps.now);
|
|
700
|
+
const written = [];
|
|
701
|
+
for (const item of prepared) {
|
|
702
|
+
try {
|
|
703
|
+
const stored = await assetstore.ingestUntrustedConditional(store, provenance, item.asset, { allowLogicalCollision: opts.force }, 'migrated');
|
|
704
|
+
const assetId = stored.asset_id;
|
|
705
|
+
if (stored.status === 'logical_collision') {
|
|
706
|
+
updateFinalCandidate(finalCandidates, item.candidate, {
|
|
707
|
+
...item.candidate,
|
|
708
|
+
assetId,
|
|
709
|
+
action: 'id_collision',
|
|
710
|
+
collisionWithAssetId: stored.collisionWithAssetId,
|
|
711
|
+
});
|
|
712
|
+
continue;
|
|
713
|
+
}
|
|
714
|
+
await readBackStoredAsset(store, assetId, item.asset);
|
|
715
|
+
if (stored.status === 'already_exists') {
|
|
716
|
+
updateFinalCandidate(finalCandidates, item.candidate, { ...item.candidate, assetId, action: 'already_local' });
|
|
717
|
+
continue;
|
|
718
|
+
}
|
|
719
|
+
const collisionWithAssetId = stored.collisionWithAssetId ?? item.collisionWithAssetId;
|
|
720
|
+
const forced = item.forced === true || collisionWithAssetId !== undefined;
|
|
721
|
+
const writtenCandidate = forced
|
|
722
|
+
? { ...item.candidate, action: 'force_import', collisionWithAssetId }
|
|
723
|
+
: item.candidate;
|
|
724
|
+
updateFinalCandidate(finalCandidates, item.candidate, writtenCandidate);
|
|
725
|
+
const syncRecord = syncById.get(assetId);
|
|
726
|
+
if (syncRecord)
|
|
727
|
+
syncLedger.append({
|
|
728
|
+
assetId,
|
|
729
|
+
type: item.asset.type,
|
|
730
|
+
source: 'hub',
|
|
731
|
+
scope: syncRecord.scope,
|
|
732
|
+
remoteAssetId: syncRecord.remoteAssetId,
|
|
733
|
+
...(syncRecord.logicalId ? { logicalId: syncRecord.logicalId } : {}),
|
|
734
|
+
...(syncRecord.status ? { status: syncRecord.status } : {}),
|
|
735
|
+
...(syncRecord.syncedAt ? { syncedAt: syncRecord.syncedAt } : {}),
|
|
736
|
+
...(syncRecord.forced ? { forced: true } : {}),
|
|
737
|
+
...(syncRecord.collisionWithAssetId ? { collisionWithAssetId: syncRecord.collisionWithAssetId } : {}),
|
|
738
|
+
});
|
|
739
|
+
written.push({
|
|
740
|
+
assetId,
|
|
741
|
+
type: item.asset.type,
|
|
742
|
+
source: 'gepx',
|
|
743
|
+
stored: stored.stored,
|
|
744
|
+
trusted: false,
|
|
745
|
+
...(writtenCandidate.logicalId ? { logicalId: writtenCandidate.logicalId } : {}),
|
|
746
|
+
...(writtenCandidate.status ? { status: writtenCandidate.status } : {}),
|
|
747
|
+
...(forced ? { forced: true } : {}),
|
|
748
|
+
...(collisionWithAssetId ? { collisionWithAssetId } : {}),
|
|
749
|
+
});
|
|
750
|
+
}
|
|
751
|
+
catch (error) {
|
|
752
|
+
const mapped = mapSyncError(error);
|
|
753
|
+
failures.push({ stage: 'write', assetId: item.candidate.assetId, reason: mapped.reason });
|
|
754
|
+
updateFinalCandidate(finalCandidates, item.candidate, {
|
|
755
|
+
...item.candidate,
|
|
756
|
+
action: 'write_failed',
|
|
757
|
+
failureReason: mapped.reason,
|
|
758
|
+
});
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
const counts = countsFromCandidates(emptyCounts(finalCandidates.length), finalCandidates);
|
|
762
|
+
return {
|
|
763
|
+
ok: true,
|
|
764
|
+
group: GROUP,
|
|
765
|
+
mode: 'import',
|
|
766
|
+
counts,
|
|
767
|
+
candidates: finalCandidates,
|
|
768
|
+
written,
|
|
769
|
+
blocked: finalCandidates.filter(isBlockedCandidate),
|
|
770
|
+
failures,
|
|
771
|
+
};
|
|
772
|
+
}
|
|
773
|
+
function emptyPreview(scope) {
|
|
774
|
+
return {
|
|
775
|
+
ok: true,
|
|
776
|
+
group: GROUP,
|
|
777
|
+
mode: 'preview',
|
|
778
|
+
scope,
|
|
779
|
+
counts: {
|
|
780
|
+
remotePurchased: 0,
|
|
781
|
+
remotePublished: 0,
|
|
782
|
+
uniqueRemote: 0,
|
|
783
|
+
alreadyLocal: 0,
|
|
784
|
+
tombstone: 0,
|
|
785
|
+
idCollision: 0,
|
|
786
|
+
unsupported: 0,
|
|
787
|
+
integrityError: 0,
|
|
788
|
+
wouldImport: 0,
|
|
789
|
+
forcedImport: 0,
|
|
790
|
+
skippedLimit: 0,
|
|
791
|
+
fetchFailed: 0,
|
|
792
|
+
writeFailed: 0,
|
|
793
|
+
},
|
|
794
|
+
candidates: [],
|
|
795
|
+
failures: [],
|
|
796
|
+
nextCursors: { purchased: null, published: null },
|
|
797
|
+
reconciliation: {
|
|
798
|
+
remoteUnique: 0,
|
|
799
|
+
accounted: 0,
|
|
800
|
+
imported: 0,
|
|
801
|
+
alreadyLocal: 0,
|
|
802
|
+
blocked: 0,
|
|
803
|
+
failed: 0,
|
|
804
|
+
pending: 0,
|
|
805
|
+
inventoryComplete: true,
|
|
806
|
+
missingRemote: 0,
|
|
807
|
+
consistent: false,
|
|
808
|
+
},
|
|
809
|
+
};
|
|
810
|
+
}
|
|
811
|
+
function emptyCounts(uniqueRemote = 0) {
|
|
812
|
+
return {
|
|
813
|
+
remotePurchased: 0,
|
|
814
|
+
remotePublished: 0,
|
|
815
|
+
uniqueRemote,
|
|
816
|
+
alreadyLocal: 0,
|
|
817
|
+
tombstone: 0,
|
|
818
|
+
idCollision: 0,
|
|
819
|
+
unsupported: 0,
|
|
820
|
+
integrityError: 0,
|
|
821
|
+
wouldImport: 0,
|
|
822
|
+
forcedImport: 0,
|
|
823
|
+
skippedLimit: 0,
|
|
824
|
+
fetchFailed: 0,
|
|
825
|
+
writeFailed: 0,
|
|
826
|
+
};
|
|
827
|
+
}
|
|
828
|
+
function emptyWrite(scope, mode = 'write') {
|
|
829
|
+
return {
|
|
830
|
+
...emptyPreview(scope),
|
|
831
|
+
mode,
|
|
832
|
+
written: [],
|
|
833
|
+
blocked: [],
|
|
834
|
+
resumed: 0,
|
|
835
|
+
};
|
|
836
|
+
}
|
|
837
|
+
async function createDefaultHub(deps, env) {
|
|
838
|
+
if (isPrivateHubMode(env)) {
|
|
839
|
+
try {
|
|
840
|
+
const hubUrl = requirePrivateHubUrl(env);
|
|
841
|
+
if (deps.connectPrivateHub)
|
|
842
|
+
return await deps.connectPrivateHub(env);
|
|
843
|
+
const { connectPrivateProxyHub } = await import('@evomap/evolver-proxy');
|
|
844
|
+
const runtime = await connectPrivateProxyHub({
|
|
845
|
+
hubUrl,
|
|
846
|
+
senderId: () => env['EVOMAP_NODE_ID'] ?? env['A2A_NODE_ID'],
|
|
847
|
+
env,
|
|
848
|
+
...(deps.now ? { now: deps.now } : {}),
|
|
849
|
+
});
|
|
850
|
+
return await preparePrivateSyncHub(runtime);
|
|
851
|
+
}
|
|
852
|
+
catch {
|
|
853
|
+
// Adapter diagnostics may contain local paths or credentials; never expose them through the CLI.
|
|
854
|
+
throw new SyncAbortError('private_adapter_unavailable', 'private Hub adapter is unavailable');
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
const hub = createRecipeHubFromEnv(env, deps.connectHub ?? connectPublicHub);
|
|
858
|
+
if (!isSyncAccountAssetHub(hub))
|
|
859
|
+
throw new Error('Hub adapter does not support account asset sync');
|
|
860
|
+
return hub;
|
|
861
|
+
}
|
|
862
|
+
export async function preparePrivateSyncHub(runtime) {
|
|
863
|
+
const hello = await runtime.hello({ rotate: false, evolverVersion: getCliVersion() });
|
|
864
|
+
if (!hello.ok)
|
|
865
|
+
throw new Error('private Hub enrollment failed');
|
|
866
|
+
if (!isSyncAccountAssetHub(runtime.hub))
|
|
867
|
+
throw new Error('private Hub adapter does not support account asset sync');
|
|
868
|
+
return runtime.hub;
|
|
869
|
+
}
|
|
870
|
+
async function listRemoteRows(hub, opts, listing) {
|
|
871
|
+
const failures = [];
|
|
872
|
+
const purchasedBudget = { uniqueAssetIds: new Set(), rawPages: 0, rawRows: 0 };
|
|
873
|
+
const publishedBudget = { uniqueAssetIds: new Set(), rawPages: 0, rawRows: 0 };
|
|
874
|
+
const purchasedResult = (opts.scope === 'all' || opts.scope === 'purchased') && !listing.skipPurchased
|
|
875
|
+
? await listAll(hub, {
|
|
876
|
+
scope: 'purchased',
|
|
877
|
+
...(opts.type ? { type: opts.type } : {}),
|
|
878
|
+
limit: opts.limit,
|
|
879
|
+
...(opts.purchasedCursor ? { cursor: opts.purchasedCursor } : {}),
|
|
880
|
+
}, opts.pageSize, failures, purchasedBudget)
|
|
881
|
+
: { rows: [], complete: true, nextCursor: undefined };
|
|
882
|
+
const shouldListPublished = (opts.scope === 'all' || opts.scope === 'published') && !listing.skipPublished;
|
|
883
|
+
const publishedResult = shouldListPublished
|
|
884
|
+
? await listAll(hub, {
|
|
885
|
+
scope: 'published',
|
|
886
|
+
...(opts.type ? { type: opts.type } : {}),
|
|
887
|
+
status: opts.status,
|
|
888
|
+
limit: opts.limit,
|
|
889
|
+
...(opts.publishedCursor ? { cursor: opts.publishedCursor } : {}),
|
|
890
|
+
}, opts.pageSize, failures, publishedBudget)
|
|
891
|
+
: { rows: [], complete: true, nextCursor: undefined };
|
|
892
|
+
const startsAtInventoryBeginning = !opts.purchasedCursor && !opts.publishedCursor;
|
|
893
|
+
return {
|
|
894
|
+
purchased: purchasedResult.rows,
|
|
895
|
+
published: publishedResult.rows,
|
|
896
|
+
failures,
|
|
897
|
+
inventoryComplete: startsAtInventoryBeginning && purchasedResult.complete && publishedResult.complete && failures.length === 0,
|
|
898
|
+
nextCursors: {
|
|
899
|
+
purchased: purchasedResult.nextCursor ?? null,
|
|
900
|
+
published: publishedResult.nextCursor ?? null,
|
|
901
|
+
},
|
|
902
|
+
};
|
|
903
|
+
}
|
|
904
|
+
async function listAll(hub, opts, pageSize, failures, budget) {
|
|
905
|
+
const rows = [];
|
|
906
|
+
let cursor = opts.cursor;
|
|
907
|
+
const seenCursors = new Set();
|
|
908
|
+
let consecutiveEmptyPages = 0;
|
|
909
|
+
let consecutivePagesWithoutUniqueProgress = 0;
|
|
910
|
+
while (budget.uniqueAssetIds.size < opts.limit) {
|
|
911
|
+
if (budget.rawPages >= MAX_RAW_PAGES) {
|
|
912
|
+
failures.push({ stage: 'list', scope: opts.scope, reason: 'raw_page_limit' });
|
|
913
|
+
break;
|
|
914
|
+
}
|
|
915
|
+
if (budget.rawRows >= MAX_RAW_ROWS) {
|
|
916
|
+
failures.push({ stage: 'list', scope: opts.scope, reason: 'raw_row_limit' });
|
|
917
|
+
break;
|
|
918
|
+
}
|
|
919
|
+
const remaining = opts.limit - budget.uniqueAssetIds.size;
|
|
920
|
+
const requestedPageLimit = Math.min(remaining, pageSize);
|
|
921
|
+
let rawResult;
|
|
922
|
+
try {
|
|
923
|
+
rawResult = await hub.listAccountAssets({ ...opts, limit: requestedPageLimit, ...(cursor ? { cursor } : {}) });
|
|
924
|
+
budget.rawPages += 1;
|
|
925
|
+
}
|
|
926
|
+
catch (error) {
|
|
927
|
+
failures.push({ stage: 'list', scope: opts.scope, reason: mapSyncError(error).reason });
|
|
928
|
+
break;
|
|
929
|
+
}
|
|
930
|
+
const result = asRecord(rawResult);
|
|
931
|
+
if (!result || !Array.isArray(result['assets']) || typeof result['hasMore'] !== 'boolean') {
|
|
932
|
+
failures.push({ stage: 'list', scope: opts.scope, reason: 'malformed_page' });
|
|
933
|
+
break;
|
|
934
|
+
}
|
|
935
|
+
const pageRows = result['assets'];
|
|
936
|
+
if (pageRows.length > requestedPageLimit) {
|
|
937
|
+
failures.push({ stage: 'list', scope: opts.scope, reason: 'oversized_page' });
|
|
938
|
+
break;
|
|
939
|
+
}
|
|
940
|
+
const availableRawRows = MAX_RAW_ROWS - budget.rawRows;
|
|
941
|
+
const boundedPageRows = pageRows.slice(0, availableRawRows);
|
|
942
|
+
budget.rawRows += boundedPageRows.length;
|
|
943
|
+
const uniqueBefore = budget.uniqueAssetIds.size;
|
|
944
|
+
let consumedPageRows = 0;
|
|
945
|
+
// The page is bounded by the remaining unique budget, so consuming it fully cannot exceed the limit.
|
|
946
|
+
for (const raw of boundedPageRows) {
|
|
947
|
+
consumedPageRows += 1;
|
|
948
|
+
const row = asRecord(raw);
|
|
949
|
+
if (!row) {
|
|
950
|
+
failures.push({ stage: 'list', scope: opts.scope, reason: 'invalid_remote_asset' });
|
|
951
|
+
continue;
|
|
952
|
+
}
|
|
953
|
+
rows.push(row);
|
|
954
|
+
const assetId = stringField(row, 'asset_id');
|
|
955
|
+
if (assetId)
|
|
956
|
+
budget.uniqueAssetIds.add(assetId);
|
|
957
|
+
}
|
|
958
|
+
const uniqueProgress = budget.uniqueAssetIds.size - uniqueBefore;
|
|
959
|
+
if (!result['hasMore']) {
|
|
960
|
+
return { rows, complete: consumedPageRows === pageRows.length, nextCursor: undefined };
|
|
961
|
+
}
|
|
962
|
+
const nextCursor = result['nextCursor'];
|
|
963
|
+
if (typeof nextCursor !== 'string' || !nextCursor.trim()) {
|
|
964
|
+
failures.push({ stage: 'list', scope: opts.scope, reason: 'invalid_remote_pagination' });
|
|
965
|
+
break;
|
|
966
|
+
}
|
|
967
|
+
if (boundedPageRows.length < pageRows.length || budget.rawRows >= MAX_RAW_ROWS) {
|
|
968
|
+
failures.push({ stage: 'list', scope: opts.scope, reason: 'raw_row_limit' });
|
|
969
|
+
break;
|
|
970
|
+
}
|
|
971
|
+
consecutiveEmptyPages = pageRows.length === 0 ? consecutiveEmptyPages + 1 : 0;
|
|
972
|
+
if (consecutiveEmptyPages > MAX_CONSECUTIVE_EMPTY_PAGES) {
|
|
973
|
+
failures.push({ stage: 'list', scope: opts.scope, reason: 'empty_page_limit' });
|
|
974
|
+
break;
|
|
975
|
+
}
|
|
976
|
+
consecutivePagesWithoutUniqueProgress = uniqueProgress === 0 ? consecutivePagesWithoutUniqueProgress + 1 : 0;
|
|
977
|
+
if (consecutivePagesWithoutUniqueProgress > MAX_CONSECUTIVE_PAGES_WITHOUT_UNIQUE_PROGRESS) {
|
|
978
|
+
failures.push({ stage: 'list', scope: opts.scope, reason: 'no_unique_progress_limit' });
|
|
979
|
+
break;
|
|
980
|
+
}
|
|
981
|
+
if (!isValidOpaqueCursor(nextCursor)) {
|
|
982
|
+
failures.push({ stage: 'list', scope: opts.scope, reason: 'malformed_cursor' });
|
|
983
|
+
break;
|
|
984
|
+
}
|
|
985
|
+
if (nextCursor === cursor || seenCursors.has(nextCursor)) {
|
|
986
|
+
failures.push({ stage: 'list', scope: opts.scope, reason: 'invalid_remote_pagination' });
|
|
987
|
+
break;
|
|
988
|
+
}
|
|
989
|
+
if (budget.uniqueAssetIds.size >= opts.limit)
|
|
990
|
+
return { rows, complete: false, nextCursor };
|
|
991
|
+
if (cursor)
|
|
992
|
+
seenCursors.add(cursor);
|
|
993
|
+
cursor = nextCursor;
|
|
994
|
+
}
|
|
995
|
+
return { rows, complete: false, nextCursor: cursor };
|
|
996
|
+
}
|
|
997
|
+
function isValidOpaqueCursor(cursor) {
|
|
998
|
+
if (cursor.length > MAX_CURSOR_LENGTH || !cursor.trim())
|
|
999
|
+
return false;
|
|
1000
|
+
for (const character of cursor) {
|
|
1001
|
+
const codePoint = character.codePointAt(0);
|
|
1002
|
+
if (codePoint !== undefined && (codePoint <= 0x1f || codePoint === 0x7f))
|
|
1003
|
+
return false;
|
|
1004
|
+
}
|
|
1005
|
+
return true;
|
|
1006
|
+
}
|
|
1007
|
+
function addUnique(target, missingAssetId, row, source) {
|
|
1008
|
+
const assetId = stringField(row, 'asset_id');
|
|
1009
|
+
if (!assetId) {
|
|
1010
|
+
missingAssetId.push({ row, source });
|
|
1011
|
+
return;
|
|
1012
|
+
}
|
|
1013
|
+
if (target.has(assetId))
|
|
1014
|
+
return;
|
|
1015
|
+
target.set(assetId, { row, source });
|
|
1016
|
+
}
|
|
1017
|
+
async function localIndex(store) {
|
|
1018
|
+
const byAssetId = new Set();
|
|
1019
|
+
const logical = new Map();
|
|
1020
|
+
for (const kind of ['Gene', 'Capsule']) {
|
|
1021
|
+
for (const row of await store.list(kind, Number.MAX_SAFE_INTEGER)) {
|
|
1022
|
+
byAssetId.add(row.asset_id);
|
|
1023
|
+
const logicalId = stringField(row, 'id');
|
|
1024
|
+
if (logicalId)
|
|
1025
|
+
logical.set(`${kind}:${logicalId}`, row.asset_id);
|
|
1026
|
+
}
|
|
1027
|
+
}
|
|
1028
|
+
return { byAssetId, logical };
|
|
1029
|
+
}
|
|
1030
|
+
async function listLocalExportAssets(store, opts) {
|
|
1031
|
+
const kinds = opts.type ? [opts.type] : ['Gene', 'Capsule'];
|
|
1032
|
+
const assets = [];
|
|
1033
|
+
for (const kind of kinds) {
|
|
1034
|
+
const remaining = opts.limit - assets.length;
|
|
1035
|
+
if (remaining <= 0)
|
|
1036
|
+
break;
|
|
1037
|
+
assets.push(...await store.list(kind, remaining));
|
|
1038
|
+
}
|
|
1039
|
+
return assets.slice(0, opts.limit);
|
|
1040
|
+
}
|
|
1041
|
+
function classifyRemote(row, source, local) {
|
|
1042
|
+
const assetId = stringField(row, 'asset_id') ?? MISSING_ASSET_ID;
|
|
1043
|
+
const type = remoteType(row);
|
|
1044
|
+
const logicalId = remoteLogicalId(row);
|
|
1045
|
+
const status = stringField(row, 'status');
|
|
1046
|
+
const base = {
|
|
1047
|
+
assetId,
|
|
1048
|
+
type: type ?? 'unknown',
|
|
1049
|
+
...(logicalId ? { logicalId } : {}),
|
|
1050
|
+
source,
|
|
1051
|
+
...(status ? { status } : {}),
|
|
1052
|
+
};
|
|
1053
|
+
if (assetId === MISSING_ASSET_ID)
|
|
1054
|
+
return { ...base, action: 'integrity_error' };
|
|
1055
|
+
if (isRemoteTombstone(row))
|
|
1056
|
+
return { ...base, action: 'tombstone' };
|
|
1057
|
+
if (type !== 'Gene' && type !== 'Capsule')
|
|
1058
|
+
return { ...base, action: 'unsupported_type' };
|
|
1059
|
+
if (remotePayloadIntegrityInvalid(row, type, assetId))
|
|
1060
|
+
return { ...base, action: 'integrity_error' };
|
|
1061
|
+
if (local.byAssetId.has(assetId))
|
|
1062
|
+
return { ...base, action: 'already_local' };
|
|
1063
|
+
if (logicalId) {
|
|
1064
|
+
const localAssetId = local.logical.get(`${type}:${logicalId}`);
|
|
1065
|
+
if (localAssetId && localAssetId !== assetId)
|
|
1066
|
+
return { ...base, action: 'id_collision', collisionWithAssetId: localAssetId };
|
|
1067
|
+
}
|
|
1068
|
+
return { ...base, action: 'would_import' };
|
|
1069
|
+
}
|
|
1070
|
+
function classifyGepxAssets(pkg, opts, local) {
|
|
1071
|
+
const classified = uniqueGepxAssets(pkg)
|
|
1072
|
+
.filter((entry) => !opts.type || entry.type === opts.type)
|
|
1073
|
+
.map((entry) => classifyGepxAsset(entry, local));
|
|
1074
|
+
let remaining = opts.limit;
|
|
1075
|
+
const candidates = classified.map((candidate) => {
|
|
1076
|
+
if (candidate.action === 'integrity_error')
|
|
1077
|
+
return candidate;
|
|
1078
|
+
if (remaining > 0) {
|
|
1079
|
+
remaining -= 1;
|
|
1080
|
+
return candidate;
|
|
1081
|
+
}
|
|
1082
|
+
return { ...candidate, action: 'skipped_limit', failureReason: 'limit_reached' };
|
|
1083
|
+
});
|
|
1084
|
+
const malformed = pkg.malformedAssets.map((entry) => ({
|
|
1085
|
+
assetId: entry.assetId ?? `${MISSING_ASSET_ID}-${entry.index}`,
|
|
1086
|
+
type: 'unknown',
|
|
1087
|
+
source: 'gepx',
|
|
1088
|
+
action: 'integrity_error',
|
|
1089
|
+
failureReason: 'invalid_package_asset',
|
|
1090
|
+
}));
|
|
1091
|
+
return [...candidates, ...malformed];
|
|
1092
|
+
}
|
|
1093
|
+
function classifyGepxAsset(entry, local) {
|
|
1094
|
+
const { assetId, type, logicalId } = entry;
|
|
1095
|
+
const base = {
|
|
1096
|
+
assetId,
|
|
1097
|
+
type: type ?? String(entry.original.type ?? 'unknown'),
|
|
1098
|
+
...(logicalId ? { logicalId } : {}),
|
|
1099
|
+
source: 'gepx',
|
|
1100
|
+
};
|
|
1101
|
+
if (type !== 'Gene' && type !== 'Capsule')
|
|
1102
|
+
return { ...base, action: 'unsupported_type' };
|
|
1103
|
+
if (entry.integrityError)
|
|
1104
|
+
return { ...base, action: 'integrity_error' };
|
|
1105
|
+
if (local.byAssetId.has(assetId))
|
|
1106
|
+
return { ...base, action: 'already_local' };
|
|
1107
|
+
if (logicalId) {
|
|
1108
|
+
const localAssetId = local.logical.get(`${type}:${logicalId}`);
|
|
1109
|
+
if (localAssetId && localAssetId !== assetId)
|
|
1110
|
+
return { ...base, action: 'id_collision', collisionWithAssetId: localAssetId };
|
|
1111
|
+
}
|
|
1112
|
+
return { ...base, action: 'would_import' };
|
|
1113
|
+
}
|
|
1114
|
+
function uniqueGepxAssets(pkg) {
|
|
1115
|
+
const unique = new Map();
|
|
1116
|
+
const missing = [];
|
|
1117
|
+
for (const asset of pkg.assets) {
|
|
1118
|
+
const normalized = normalizeGepxAsset(asset);
|
|
1119
|
+
if (normalized.assetId === MISSING_ASSET_ID) {
|
|
1120
|
+
missing.push(normalized);
|
|
1121
|
+
continue;
|
|
1122
|
+
}
|
|
1123
|
+
if (!unique.has(normalized.assetId))
|
|
1124
|
+
unique.set(normalized.assetId, normalized);
|
|
1125
|
+
}
|
|
1126
|
+
return [...unique.values(), ...missing];
|
|
1127
|
+
}
|
|
1128
|
+
function gepxImportAssetsById(pkg) {
|
|
1129
|
+
const assets = new Map();
|
|
1130
|
+
for (const entry of uniqueGepxAssets(pkg)) {
|
|
1131
|
+
if (entry.type && !entry.integrityError && !assets.has(entry.assetId))
|
|
1132
|
+
assets.set(entry.assetId, entry.asset);
|
|
1133
|
+
}
|
|
1134
|
+
return assets;
|
|
1135
|
+
}
|
|
1136
|
+
function normalizeGepxAsset(asset) {
|
|
1137
|
+
const cleaned = stripHubMetadata(asset);
|
|
1138
|
+
const assetId = stringField(cleaned, 'asset_id') ?? stringField(asset, 'asset_id') ?? MISSING_ASSET_ID;
|
|
1139
|
+
const type = cleaned.type === 'Gene' || cleaned.type === 'Capsule' ? cleaned.type : undefined;
|
|
1140
|
+
const logicalId = stringField(cleaned, 'id');
|
|
1141
|
+
let integrityError = false;
|
|
1142
|
+
if (type) {
|
|
1143
|
+
const claimed = stringField(cleaned, 'asset_id');
|
|
1144
|
+
const fullAsset = looksLikeFullAsset(cleaned, type);
|
|
1145
|
+
const computed = fullAsset ? wire.computeAssetId(cleaned) : undefined;
|
|
1146
|
+
integrityError = assetId === MISSING_ASSET_ID || !claimed || !fullAsset || !computed || claimed !== assetId || computed !== claimed;
|
|
1147
|
+
}
|
|
1148
|
+
return {
|
|
1149
|
+
original: asset,
|
|
1150
|
+
asset: cleaned,
|
|
1151
|
+
assetId,
|
|
1152
|
+
...(type ? { type } : {}),
|
|
1153
|
+
...(logicalId ? { logicalId } : {}),
|
|
1154
|
+
integrityError,
|
|
1155
|
+
};
|
|
1156
|
+
}
|
|
1157
|
+
function countsFromCandidates(base, candidates) {
|
|
1158
|
+
const counts = {
|
|
1159
|
+
remotePurchased: base.remotePurchased,
|
|
1160
|
+
remotePublished: base.remotePublished,
|
|
1161
|
+
uniqueRemote: candidates.length,
|
|
1162
|
+
alreadyLocal: 0,
|
|
1163
|
+
tombstone: 0,
|
|
1164
|
+
idCollision: 0,
|
|
1165
|
+
unsupported: 0,
|
|
1166
|
+
integrityError: 0,
|
|
1167
|
+
wouldImport: 0,
|
|
1168
|
+
forcedImport: 0,
|
|
1169
|
+
skippedLimit: 0,
|
|
1170
|
+
fetchFailed: 0,
|
|
1171
|
+
writeFailed: 0,
|
|
1172
|
+
};
|
|
1173
|
+
for (const candidate of candidates) {
|
|
1174
|
+
if (candidate.action === 'already_local')
|
|
1175
|
+
counts.alreadyLocal += 1;
|
|
1176
|
+
else if (candidate.action === 'tombstone')
|
|
1177
|
+
counts.tombstone += 1;
|
|
1178
|
+
else if (candidate.action === 'id_collision')
|
|
1179
|
+
counts.idCollision += 1;
|
|
1180
|
+
else if (candidate.action === 'would_import')
|
|
1181
|
+
counts.wouldImport += 1;
|
|
1182
|
+
else if (candidate.action === 'force_import')
|
|
1183
|
+
counts.forcedImport += 1;
|
|
1184
|
+
else if (candidate.action === 'skipped_limit')
|
|
1185
|
+
counts.skippedLimit += 1;
|
|
1186
|
+
else if (candidate.action === 'fetch_failed')
|
|
1187
|
+
counts.fetchFailed += 1;
|
|
1188
|
+
else if (candidate.action === 'write_failed')
|
|
1189
|
+
counts.writeFailed += 1;
|
|
1190
|
+
else if (candidate.action === 'unsupported_type')
|
|
1191
|
+
counts.unsupported += 1;
|
|
1192
|
+
else if (candidate.action === 'integrity_error')
|
|
1193
|
+
counts.integrityError += 1;
|
|
1194
|
+
}
|
|
1195
|
+
return counts;
|
|
1196
|
+
}
|
|
1197
|
+
function updateFinalCandidate(candidates, original, replacement) {
|
|
1198
|
+
const index = candidates.findIndex((candidate) => candidate.assetId === original.assetId && candidate.source === original.source);
|
|
1199
|
+
if (index >= 0)
|
|
1200
|
+
candidates[index] = replacement;
|
|
1201
|
+
}
|
|
1202
|
+
function isBlockedCandidate(candidate) {
|
|
1203
|
+
return candidate.action !== 'would_import'
|
|
1204
|
+
&& candidate.action !== 'force_import'
|
|
1205
|
+
&& candidate.action !== 'already_local'
|
|
1206
|
+
&& candidate.action !== 'skipped_limit';
|
|
1207
|
+
}
|
|
1208
|
+
function remotePayloadIntegrityInvalid(row, type, assetId) {
|
|
1209
|
+
const payload = asRecord(row.payload);
|
|
1210
|
+
const source = payload ?? row;
|
|
1211
|
+
if (!looksLikeFullAsset(source, type))
|
|
1212
|
+
return false;
|
|
1213
|
+
const candidate = stripHubMetadata({ ...source, type, asset_id: stringField(source, 'asset_id') ?? assetId });
|
|
1214
|
+
return Boolean(candidate.asset_id && wire.computeAssetId(candidate) !== candidate.asset_id);
|
|
1215
|
+
}
|
|
1216
|
+
function prepareFetchedAsset(candidate, fetched, localAssetIds, logical, force) {
|
|
1217
|
+
const type = fetched.type === 'Gene' || fetched.type === 'Capsule' ? fetched.type : undefined;
|
|
1218
|
+
if (!type)
|
|
1219
|
+
return { blocked: { ...candidate, type: fetched.type ?? candidate.type, action: 'unsupported_type' } };
|
|
1220
|
+
if (type !== candidate.type)
|
|
1221
|
+
throw new SyncAbortError('integrity_error', 'Hub asset type changed before import');
|
|
1222
|
+
const cleaned = stripHubMetadata(fetched);
|
|
1223
|
+
const claimed = stringField(cleaned, 'asset_id');
|
|
1224
|
+
const computed = wire.computeAssetId(cleaned);
|
|
1225
|
+
if (!claimed || !computed || claimed !== computed || claimed !== candidate.assetId) {
|
|
1226
|
+
throw new SyncAbortError('integrity_error', 'Hub asset integrity verification failed before import');
|
|
1227
|
+
}
|
|
1228
|
+
if (!looksLikeFullAsset(cleaned, type)) {
|
|
1229
|
+
throw new SyncAbortError('integrity_error', 'Hub asset payload is incomplete');
|
|
1230
|
+
}
|
|
1231
|
+
if (localAssetIds.has(cleaned.asset_id))
|
|
1232
|
+
return { blocked: { ...candidate, action: 'already_local' } };
|
|
1233
|
+
const logicalId = stringField(cleaned, 'id');
|
|
1234
|
+
if (logicalId) {
|
|
1235
|
+
const localAssetId = logical.get(`${type}:${logicalId}`);
|
|
1236
|
+
if (localAssetId && localAssetId !== cleaned.asset_id) {
|
|
1237
|
+
if (force)
|
|
1238
|
+
return { asset: cleaned, forced: true, collisionWithAssetId: localAssetId };
|
|
1239
|
+
return { blocked: { ...candidate, logicalId, action: 'id_collision', collisionWithAssetId: localAssetId } };
|
|
1240
|
+
}
|
|
1241
|
+
}
|
|
1242
|
+
return { asset: cleaned };
|
|
1243
|
+
}
|
|
1244
|
+
function resumePlannedCandidates(candidates, previousRun, inventoryComplete) {
|
|
1245
|
+
const plan = previousRun.plan;
|
|
1246
|
+
if (!plan) {
|
|
1247
|
+
throw new SyncAbortError('resume_plan_drift', 'cannot resume a run without its original candidate plan');
|
|
1248
|
+
}
|
|
1249
|
+
const byPlanId = new Map(candidates.flatMap((candidate) => candidate.assetId === MISSING_ASSET_ID
|
|
1250
|
+
? []
|
|
1251
|
+
: [[candidate.assetId, candidate]]));
|
|
1252
|
+
const knownRemoteMissing = plan.filter((assetId) => (previousRun.processed.get(assetId)?.outcome === 'remote_missing'
|
|
1253
|
+
&& !byPlanId.has(assetId)));
|
|
1254
|
+
const unresolvedMissing = plan.filter((assetId) => {
|
|
1255
|
+
const processed = previousRun.processed.get(assetId);
|
|
1256
|
+
return (!processed || processed.outcome === 'failed') && !byPlanId.has(assetId);
|
|
1257
|
+
});
|
|
1258
|
+
const newRemoteMissingAssetIds = inventoryComplete ? unresolvedMissing : [];
|
|
1259
|
+
const remoteMissingAssetIds = [...knownRemoteMissing, ...newRemoteMissingAssetIds];
|
|
1260
|
+
const remoteMissing = new Set(remoteMissingAssetIds);
|
|
1261
|
+
const plannedCandidates = plan.flatMap((assetId) => {
|
|
1262
|
+
const candidate = byPlanId.get(assetId);
|
|
1263
|
+
if (candidate)
|
|
1264
|
+
return [{ ...candidate }];
|
|
1265
|
+
return remoteMissing.has(assetId) ? [{
|
|
1266
|
+
assetId,
|
|
1267
|
+
type: 'unknown',
|
|
1268
|
+
source: 'reconciliation',
|
|
1269
|
+
action: 'tombstone',
|
|
1270
|
+
failureReason: 'remote_missing',
|
|
1271
|
+
}] : [];
|
|
1272
|
+
});
|
|
1273
|
+
const plannedIds = new Set(plan);
|
|
1274
|
+
const newCandidates = candidates
|
|
1275
|
+
.filter((candidate) => candidate.assetId === MISSING_ASSET_ID || !plannedIds.has(candidate.assetId))
|
|
1276
|
+
.map((candidate) => ({ ...candidate }));
|
|
1277
|
+
return {
|
|
1278
|
+
candidates: [...plannedCandidates, ...newCandidates],
|
|
1279
|
+
remoteMissingAssetIds,
|
|
1280
|
+
newRemoteMissingAssetIds,
|
|
1281
|
+
};
|
|
1282
|
+
}
|
|
1283
|
+
function actionableCandidatePlanIds(candidates, force) {
|
|
1284
|
+
return candidates.flatMap((candidate) => (candidate.assetId !== MISSING_ASSET_ID
|
|
1285
|
+
&& (candidate.action === 'would_import' || (force && candidate.action === 'id_collision'))
|
|
1286
|
+
? [candidate.assetId]
|
|
1287
|
+
: []));
|
|
1288
|
+
}
|
|
1289
|
+
function mergeCandidatePlan(previous, current) {
|
|
1290
|
+
const merged = [...previous];
|
|
1291
|
+
const seen = new Set(previous);
|
|
1292
|
+
for (const assetId of current) {
|
|
1293
|
+
if (seen.has(assetId))
|
|
1294
|
+
continue;
|
|
1295
|
+
seen.add(assetId);
|
|
1296
|
+
merged.push(assetId);
|
|
1297
|
+
}
|
|
1298
|
+
return merged;
|
|
1299
|
+
}
|
|
1300
|
+
function assertNoConflictingGepxDuplicates(pkg) {
|
|
1301
|
+
const seen = new Map();
|
|
1302
|
+
for (const asset of pkg.assets) {
|
|
1303
|
+
const assetId = stringField(asset, 'asset_id');
|
|
1304
|
+
if (!assetId)
|
|
1305
|
+
continue;
|
|
1306
|
+
const serialized = JSON.stringify(asset);
|
|
1307
|
+
const previous = seen.get(assetId);
|
|
1308
|
+
if (previous !== undefined && previous !== serialized) {
|
|
1309
|
+
throw new SyncAbortError('integrity_error', '.gepx package contains conflicting duplicate asset IDs');
|
|
1310
|
+
}
|
|
1311
|
+
seen.set(assetId, serialized);
|
|
1312
|
+
}
|
|
1313
|
+
}
|
|
1314
|
+
async function reconcileResumeCandidates(input) {
|
|
1315
|
+
let resumed = 0;
|
|
1316
|
+
for (const candidate of input.candidates) {
|
|
1317
|
+
if (candidate.action !== 'already_local')
|
|
1318
|
+
continue;
|
|
1319
|
+
const checkpoint = input.previousRun.processed.get(candidate.assetId);
|
|
1320
|
+
const provenanceRecord = input.provenance.get(candidate.assetId);
|
|
1321
|
+
const syncRecord = input.syncLedger.getForRunKey(input.runKey, candidate.assetId);
|
|
1322
|
+
const checkpointedAlreadyLocal = checkpoint?.outcome === 'already_local';
|
|
1323
|
+
const hubImportProvenance = provenanceRecord?.assetId === candidate.assetId
|
|
1324
|
+
&& provenanceRecord.source === 'hub'
|
|
1325
|
+
&& !provenanceRecord.trusted;
|
|
1326
|
+
const importedEvidence = Boolean(hubImportProvenance || syncRecord || (checkpoint && checkpoint.outcome !== 'already_local'));
|
|
1327
|
+
if (!checkpointedAlreadyLocal && !importedEvidence)
|
|
1328
|
+
continue;
|
|
1329
|
+
try {
|
|
1330
|
+
const storedAsset = await readBackStoredAsset(input.store, candidate.assetId);
|
|
1331
|
+
if (checkpointedAlreadyLocal) {
|
|
1332
|
+
resumed += 1;
|
|
1333
|
+
continue;
|
|
1334
|
+
}
|
|
1335
|
+
if (!provenanceRecord || provenanceRecord.assetId !== candidate.assetId || provenanceRecord.source !== 'hub' || provenanceRecord.trusted) {
|
|
1336
|
+
throw new SyncAbortError('resume_verification_failed', 'Resume provenance verification failed');
|
|
1337
|
+
}
|
|
1338
|
+
if (syncRecord && !syncRecordMatches(syncRecord, candidate, storedAsset)) {
|
|
1339
|
+
throw new SyncAbortError('resume_verification_failed', 'Resume sync ledger verification failed');
|
|
1340
|
+
}
|
|
1341
|
+
if (!syncRecord)
|
|
1342
|
+
appendSyncRecord(input.syncLedger, candidate, storedAsset, input.runKey, input.inventoryKey);
|
|
1343
|
+
if (checkpoint?.outcome !== 'imported') {
|
|
1344
|
+
input.appendRunCheckpoint({
|
|
1345
|
+
runId: input.runId,
|
|
1346
|
+
runKey: input.runKey,
|
|
1347
|
+
state: 'progress',
|
|
1348
|
+
remoteAssetId: candidate.assetId,
|
|
1349
|
+
outcome: 'imported',
|
|
1350
|
+
});
|
|
1351
|
+
}
|
|
1352
|
+
resumed += 1;
|
|
1353
|
+
}
|
|
1354
|
+
catch (error) {
|
|
1355
|
+
const mapped = mapSyncError(error);
|
|
1356
|
+
input.failures.push({ stage: 'write', assetId: candidate.assetId, reason: mapped.reason });
|
|
1357
|
+
input.appendRunCheckpoint({
|
|
1358
|
+
runId: input.runId,
|
|
1359
|
+
runKey: input.runKey,
|
|
1360
|
+
state: 'progress',
|
|
1361
|
+
remoteAssetId: candidate.assetId,
|
|
1362
|
+
outcome: 'failed',
|
|
1363
|
+
reason: mapped.reason,
|
|
1364
|
+
});
|
|
1365
|
+
}
|
|
1366
|
+
}
|
|
1367
|
+
return resumed;
|
|
1368
|
+
}
|
|
1369
|
+
async function verifyAlreadyLocalCandidates(candidates, store, failures) {
|
|
1370
|
+
const failedAssetIds = new Set(failures.flatMap((failure) => failure.assetId ? [failure.assetId] : []));
|
|
1371
|
+
for (const candidate of candidates) {
|
|
1372
|
+
if (candidate.action !== 'already_local' || failedAssetIds.has(candidate.assetId))
|
|
1373
|
+
continue;
|
|
1374
|
+
try {
|
|
1375
|
+
await readBackStoredAsset(store, candidate.assetId);
|
|
1376
|
+
}
|
|
1377
|
+
catch (error) {
|
|
1378
|
+
const mapped = mapSyncError(error);
|
|
1379
|
+
failures.push({ stage: 'write', assetId: candidate.assetId, reason: mapped.reason });
|
|
1380
|
+
failedAssetIds.add(candidate.assetId);
|
|
1381
|
+
}
|
|
1382
|
+
}
|
|
1383
|
+
}
|
|
1384
|
+
async function readBackStoredAsset(store, assetId, expected) {
|
|
1385
|
+
let stored;
|
|
1386
|
+
try {
|
|
1387
|
+
stored = await store.get(assetId);
|
|
1388
|
+
}
|
|
1389
|
+
catch {
|
|
1390
|
+
throw new SyncAbortError('store_read_back_failed', 'Stored asset could not be read back');
|
|
1391
|
+
}
|
|
1392
|
+
const computed = stored ? wire.computeAssetId(stored) : null;
|
|
1393
|
+
const expectedComputed = expected ? wire.computeAssetId(expected) : assetId;
|
|
1394
|
+
if (!stored ||
|
|
1395
|
+
stored.asset_id !== assetId ||
|
|
1396
|
+
computed !== assetId ||
|
|
1397
|
+
expectedComputed !== assetId ||
|
|
1398
|
+
(expected && stored.type !== expected.type)) {
|
|
1399
|
+
throw new SyncAbortError('store_read_back_failed', 'Stored asset failed read-back verification');
|
|
1400
|
+
}
|
|
1401
|
+
return stored;
|
|
1402
|
+
}
|
|
1403
|
+
function appendSyncRecord(syncLedger, candidate, asset, runKey, inventoryKey, extra = {}) {
|
|
1404
|
+
return syncLedger.append({
|
|
1405
|
+
assetId: asset.asset_id,
|
|
1406
|
+
type: asset.type,
|
|
1407
|
+
source: 'hub',
|
|
1408
|
+
scope: candidate.source === 'published' ? 'published' : 'purchased',
|
|
1409
|
+
remoteAssetId: candidate.assetId,
|
|
1410
|
+
runKey,
|
|
1411
|
+
inventoryKey,
|
|
1412
|
+
...(stringField(asset, 'id') ? { logicalId: stringField(asset, 'id') } : {}),
|
|
1413
|
+
...(candidate.status ? { status: candidate.status } : {}),
|
|
1414
|
+
...extra,
|
|
1415
|
+
});
|
|
1416
|
+
}
|
|
1417
|
+
function syncRecordMatches(record, candidate, asset) {
|
|
1418
|
+
const scope = candidate.source === 'published' ? 'published' : 'purchased';
|
|
1419
|
+
const logicalId = stringField(asset, 'id');
|
|
1420
|
+
return record.assetId === candidate.assetId &&
|
|
1421
|
+
record.remoteAssetId === candidate.assetId &&
|
|
1422
|
+
record.type === asset.type &&
|
|
1423
|
+
record.source === 'hub' &&
|
|
1424
|
+
record.scope === scope &&
|
|
1425
|
+
(!logicalId || record.logicalId === logicalId);
|
|
1426
|
+
}
|
|
1427
|
+
function preparePackagedAsset(candidate, asset, localAssetIds, logical, force) {
|
|
1428
|
+
const cleaned = stripHubMetadata(asset);
|
|
1429
|
+
const type = cleaned.type === 'Gene' || cleaned.type === 'Capsule' ? cleaned.type : undefined;
|
|
1430
|
+
if (!type)
|
|
1431
|
+
return { blocked: { ...candidate, type: cleaned.type ?? candidate.type, action: 'unsupported_type' } };
|
|
1432
|
+
if (type !== candidate.type)
|
|
1433
|
+
return { blocked: { ...candidate, type, action: 'unsupported_type' } };
|
|
1434
|
+
const claimed = stringField(cleaned, 'asset_id');
|
|
1435
|
+
const computed = wire.computeAssetId(cleaned);
|
|
1436
|
+
if (!claimed || !computed || claimed !== computed || claimed !== candidate.assetId || !looksLikeFullAsset(cleaned, type)) {
|
|
1437
|
+
throw new SyncAbortError('integrity_error', '.gepx package integrity verification failed before import');
|
|
1438
|
+
}
|
|
1439
|
+
if (localAssetIds.has(cleaned.asset_id))
|
|
1440
|
+
return { blocked: { ...candidate, action: 'already_local' } };
|
|
1441
|
+
const logicalId = stringField(cleaned, 'id');
|
|
1442
|
+
if (logicalId) {
|
|
1443
|
+
const localAssetId = logical.get(`${type}:${logicalId}`);
|
|
1444
|
+
if (localAssetId && localAssetId !== cleaned.asset_id) {
|
|
1445
|
+
if (force)
|
|
1446
|
+
return { asset: cleaned, forced: true, collisionWithAssetId: localAssetId };
|
|
1447
|
+
return { blocked: { ...candidate, logicalId, action: 'id_collision', collisionWithAssetId: localAssetId } };
|
|
1448
|
+
}
|
|
1449
|
+
}
|
|
1450
|
+
return { asset: cleaned };
|
|
1451
|
+
}
|
|
1452
|
+
function looksLikeFullAsset(value, type) {
|
|
1453
|
+
if (!stringField(value, 'schema_version'))
|
|
1454
|
+
return false;
|
|
1455
|
+
if (type === 'Gene') {
|
|
1456
|
+
return Boolean(stringField(value, 'id') &&
|
|
1457
|
+
stringField(value, 'category') &&
|
|
1458
|
+
Array.isArray(value['signals_match']) &&
|
|
1459
|
+
Array.isArray(value['strategy']) &&
|
|
1460
|
+
asRecord(value['constraints']) &&
|
|
1461
|
+
Array.isArray(value['validation']));
|
|
1462
|
+
}
|
|
1463
|
+
return Boolean(stringField(value, 'id') &&
|
|
1464
|
+
stringField(value, 'gene') &&
|
|
1465
|
+
stringField(value, 'summary') &&
|
|
1466
|
+
asRecord(value['outcome']));
|
|
1467
|
+
}
|
|
1468
|
+
function stripHubMetadata(asset) {
|
|
1469
|
+
const out = {};
|
|
1470
|
+
for (const [key, value] of Object.entries(asset))
|
|
1471
|
+
if (!HUB_METADATA_KEYS.has(key))
|
|
1472
|
+
out[key] = value;
|
|
1473
|
+
return out;
|
|
1474
|
+
}
|
|
1475
|
+
function readGepxPackage(path) {
|
|
1476
|
+
if (!path)
|
|
1477
|
+
throw new SyncAbortError('invalid_arg', '--import requires a file');
|
|
1478
|
+
if (!existsSync(path))
|
|
1479
|
+
throw new SyncAbortError('gepx_read_failed', 'could not read .gepx file');
|
|
1480
|
+
try {
|
|
1481
|
+
const stat = statSync(path);
|
|
1482
|
+
if (!stat.isFile() || stat.size > MAX_GEPX_BYTES)
|
|
1483
|
+
throw new SyncAbortError('invalid_gepx', 'invalid .gepx package');
|
|
1484
|
+
}
|
|
1485
|
+
catch (error) {
|
|
1486
|
+
if (error instanceof SyncAbortError)
|
|
1487
|
+
throw error;
|
|
1488
|
+
throw new SyncAbortError('gepx_read_failed', 'could not read .gepx file');
|
|
1489
|
+
}
|
|
1490
|
+
let parsed;
|
|
1491
|
+
try {
|
|
1492
|
+
parsed = JSON.parse(readFileSync(path, 'utf8'));
|
|
1493
|
+
}
|
|
1494
|
+
catch {
|
|
1495
|
+
throw new SyncAbortError('invalid_gepx', 'invalid .gepx package');
|
|
1496
|
+
}
|
|
1497
|
+
const obj = asRecord(parsed);
|
|
1498
|
+
if (!obj || obj['type'] !== GEPX_TYPE || obj['version'] !== GEPX_VERSION || !Array.isArray(obj['assets'])) {
|
|
1499
|
+
throw new SyncAbortError('invalid_gepx', 'invalid .gepx package');
|
|
1500
|
+
}
|
|
1501
|
+
if (obj['assets'].length > MAX_GEPX_ASSETS)
|
|
1502
|
+
throw new SyncAbortError('invalid_gepx', 'invalid .gepx package');
|
|
1503
|
+
const assets = [];
|
|
1504
|
+
const malformedAssets = [];
|
|
1505
|
+
obj['assets'].forEach((rawAsset, index) => {
|
|
1506
|
+
const asset = asRecord(rawAsset);
|
|
1507
|
+
const assetId = asset && typeof asset['asset_id'] === 'string' && asset['asset_id'].trim()
|
|
1508
|
+
? asset['asset_id']
|
|
1509
|
+
: undefined;
|
|
1510
|
+
if (!asset || !assetId) {
|
|
1511
|
+
malformedAssets.push({ index, ...(assetId ? { assetId } : {}) });
|
|
1512
|
+
return;
|
|
1513
|
+
}
|
|
1514
|
+
assets.push(asset);
|
|
1515
|
+
});
|
|
1516
|
+
const provenance = Array.isArray(obj['provenance'])
|
|
1517
|
+
? obj['provenance'].map((record) => parseGepxProvenanceRecord(asRecord(record))).filter((record) => Boolean(record))
|
|
1518
|
+
: [];
|
|
1519
|
+
const sync = Array.isArray(obj['sync'])
|
|
1520
|
+
? obj['sync'].map((record) => parseGepxSyncRecord(asRecord(record))).filter((record) => Boolean(record))
|
|
1521
|
+
: [];
|
|
1522
|
+
return {
|
|
1523
|
+
type: GEPX_TYPE,
|
|
1524
|
+
version: GEPX_VERSION,
|
|
1525
|
+
...(stringField(obj, 'exportedAt') ? { exportedAt: stringField(obj, 'exportedAt') } : {}),
|
|
1526
|
+
assets,
|
|
1527
|
+
malformedAssets,
|
|
1528
|
+
provenance,
|
|
1529
|
+
sync,
|
|
1530
|
+
};
|
|
1531
|
+
}
|
|
1532
|
+
function parseGepxProvenanceRecord(value) {
|
|
1533
|
+
if (!value)
|
|
1534
|
+
return null;
|
|
1535
|
+
const assetId = stringField(value, 'assetId');
|
|
1536
|
+
const source = stringField(value, 'source');
|
|
1537
|
+
const at = stringField(value, 'at');
|
|
1538
|
+
if (!assetId || !at || (source !== 'local' && source !== 'migrated' && source !== 'hub'))
|
|
1539
|
+
return null;
|
|
1540
|
+
return {
|
|
1541
|
+
assetId,
|
|
1542
|
+
source,
|
|
1543
|
+
trusted: value['trusted'] === true,
|
|
1544
|
+
at,
|
|
1545
|
+
...(stringField(value, 'promotedBy') ? { promotedBy: stringField(value, 'promotedBy') } : {}),
|
|
1546
|
+
...(stringField(value, 'reason') ? { reason: stringField(value, 'reason') } : {}),
|
|
1547
|
+
};
|
|
1548
|
+
}
|
|
1549
|
+
function parseGepxSyncRecord(value) {
|
|
1550
|
+
if (!value)
|
|
1551
|
+
return null;
|
|
1552
|
+
const assetId = stringField(value, 'assetId');
|
|
1553
|
+
const type = stringField(value, 'type');
|
|
1554
|
+
const source = stringField(value, 'source');
|
|
1555
|
+
const scope = stringField(value, 'scope');
|
|
1556
|
+
const syncedAt = stringField(value, 'syncedAt');
|
|
1557
|
+
const remoteAssetId = stringField(value, 'remoteAssetId');
|
|
1558
|
+
if (!assetId || (type !== 'Gene' && type !== 'Capsule') || source !== 'hub' || (scope !== 'purchased' && scope !== 'published') || !syncedAt || !remoteAssetId) {
|
|
1559
|
+
return null;
|
|
1560
|
+
}
|
|
1561
|
+
return {
|
|
1562
|
+
assetId,
|
|
1563
|
+
type,
|
|
1564
|
+
source: 'hub',
|
|
1565
|
+
scope,
|
|
1566
|
+
syncedAt,
|
|
1567
|
+
remoteAssetId,
|
|
1568
|
+
...(stringField(value, 'logicalId') ? { logicalId: stringField(value, 'logicalId') } : {}),
|
|
1569
|
+
...(stringField(value, 'status') ? { status: stringField(value, 'status') } : {}),
|
|
1570
|
+
...(value['forced'] === true ? { forced: true } : {}),
|
|
1571
|
+
...(stringField(value, 'collisionWithAssetId') ? { collisionWithAssetId: stringField(value, 'collisionWithAssetId') } : {}),
|
|
1572
|
+
};
|
|
1573
|
+
}
|
|
1574
|
+
function remoteType(row) {
|
|
1575
|
+
const payload = asRecord(row.payload);
|
|
1576
|
+
const raw = stringField(row, 'type') ?? stringField(row, 'asset_type') ?? (payload ? stringField(payload, 'type') : undefined);
|
|
1577
|
+
return raw === 'Gene' || raw === 'Capsule' ? raw : undefined;
|
|
1578
|
+
}
|
|
1579
|
+
function remoteLogicalId(row) {
|
|
1580
|
+
const payload = asRecord(row.payload);
|
|
1581
|
+
return stringField(row, 'id') ?? stringField(row, 'local_id') ?? (payload ? stringField(payload, 'id') : undefined);
|
|
1582
|
+
}
|
|
1583
|
+
function isRemoteTombstone(row) {
|
|
1584
|
+
return stringField(row, 'status')?.toLowerCase() === 'revoked'
|
|
1585
|
+
|| stringField(row, 'trust_state')?.toLowerCase() === 'revoked';
|
|
1586
|
+
}
|
|
1587
|
+
function emitTextPreview(preview, out) {
|
|
1588
|
+
const c = preview.counts;
|
|
1589
|
+
out(`sync preview: scope=${preview.scope} purchased=${c.remotePurchased} published=${c.remotePublished} unique=${c.uniqueRemote}`);
|
|
1590
|
+
out(` would_import=${c.wouldImport} forced_import=${c.forcedImport} skipped_limit=${c.skippedLimit} fetch_failed=${c.fetchFailed} write_failed=${c.writeFailed} already_local=${c.alreadyLocal} tombstone=${c.tombstone} id_collision=${c.idCollision} unsupported=${c.unsupported} integrity_error=${c.integrityError}`);
|
|
1591
|
+
out(` reconciliation: accounted=${preview.reconciliation.accounted}/${preview.reconciliation.remoteUnique} failed=${preview.reconciliation.failed} inventory_complete=${preview.reconciliation.inventoryComplete} missing_remote=${preview.reconciliation.missingRemote} consistent=${preview.reconciliation.consistent}`);
|
|
1592
|
+
emitTextNextCursors(preview.nextCursors, out);
|
|
1593
|
+
for (const candidate of preview.candidates.slice(0, 10)) {
|
|
1594
|
+
out(` ${candidate.action}: ${candidate.type} ${candidate.assetId}${candidate.logicalId ? ` (${candidate.logicalId})` : ''}`);
|
|
1595
|
+
}
|
|
1596
|
+
}
|
|
1597
|
+
function emitTextWrite(result, out) {
|
|
1598
|
+
const c = result.counts;
|
|
1599
|
+
out(`sync ${result.mode}: scope=${result.scope} purchased=${c.remotePurchased} published=${c.remotePublished} unique=${c.uniqueRemote}`);
|
|
1600
|
+
out(` written=${result.written.length} blocked=${result.blocked.length} would_import=${c.wouldImport} forced_import=${c.forcedImport} skipped_limit=${c.skippedLimit} fetch_failed=${c.fetchFailed} write_failed=${c.writeFailed} already_local=${c.alreadyLocal} tombstone=${c.tombstone} id_collision=${c.idCollision} unsupported=${c.unsupported} integrity_error=${c.integrityError}`);
|
|
1601
|
+
out(` reconciliation: accounted=${result.reconciliation.accounted}/${result.reconciliation.remoteUnique} imported=${result.reconciliation.imported} resumed=${result.resumed} failed=${result.reconciliation.failed} inventory_complete=${result.reconciliation.inventoryComplete} missing_remote=${result.reconciliation.missingRemote} consistent=${result.reconciliation.consistent}`);
|
|
1602
|
+
emitTextNextCursors(result.nextCursors, out);
|
|
1603
|
+
for (const asset of result.written.slice(0, 10)) {
|
|
1604
|
+
out(` imported: ${asset.type} ${asset.assetId}${asset.logicalId ? ` (${asset.logicalId})` : ''}`);
|
|
1605
|
+
}
|
|
1606
|
+
for (const candidate of result.blocked.slice(0, 10)) {
|
|
1607
|
+
out(` blocked/${candidate.action}: ${candidate.type} ${candidate.assetId}${candidate.logicalId ? ` (${candidate.logicalId})` : ''}`);
|
|
1608
|
+
}
|
|
1609
|
+
}
|
|
1610
|
+
function emitTextNextCursors(nextCursors, out) {
|
|
1611
|
+
if (nextCursors.purchased)
|
|
1612
|
+
out(` next_purchased_cursor=${nextCursors.purchased}`);
|
|
1613
|
+
if (nextCursors.published)
|
|
1614
|
+
out(` next_published_cursor=${nextCursors.published}`);
|
|
1615
|
+
}
|
|
1616
|
+
function emitTextExport(result, out) {
|
|
1617
|
+
out(`sync export: exported=${result.counts.exported} provenance=${result.counts.provenance} sync=${result.counts.sync}`);
|
|
1618
|
+
for (const asset of result.assets.slice(0, 10)) {
|
|
1619
|
+
out(` exported: ${asset.type} ${asset.assetId}${asset.logicalId ? ` (${asset.logicalId})` : ''}`);
|
|
1620
|
+
}
|
|
1621
|
+
}
|
|
1622
|
+
function emitTextImportPreview(result, out) {
|
|
1623
|
+
const c = result.counts;
|
|
1624
|
+
out(`sync import preview: unique=${c.uniqueRemote}`);
|
|
1625
|
+
out(` would_import=${c.wouldImport} forced_import=${c.forcedImport} skipped_limit=${c.skippedLimit} fetch_failed=${c.fetchFailed} write_failed=${c.writeFailed} already_local=${c.alreadyLocal} id_collision=${c.idCollision} unsupported=${c.unsupported} integrity_error=${c.integrityError}`);
|
|
1626
|
+
for (const candidate of result.candidates.slice(0, 10)) {
|
|
1627
|
+
out(` ${candidate.action}: ${candidate.type} ${candidate.assetId}${candidate.logicalId ? ` (${candidate.logicalId})` : ''}`);
|
|
1628
|
+
}
|
|
1629
|
+
}
|
|
1630
|
+
function emitTextImport(result, out) {
|
|
1631
|
+
const c = result.counts;
|
|
1632
|
+
out(`sync import: written=${result.written.length} blocked=${result.blocked.length} failed=${result.failures.length} unique=${c.uniqueRemote}`);
|
|
1633
|
+
out(` would_import=${c.wouldImport} forced_import=${c.forcedImport} skipped_limit=${c.skippedLimit} fetch_failed=${c.fetchFailed} write_failed=${c.writeFailed} already_local=${c.alreadyLocal} id_collision=${c.idCollision} unsupported=${c.unsupported} integrity_error=${c.integrityError}`);
|
|
1634
|
+
for (const asset of result.written.slice(0, 10)) {
|
|
1635
|
+
out(` imported: ${asset.type} ${asset.assetId}${asset.logicalId ? ` (${asset.logicalId})` : ''}`);
|
|
1636
|
+
}
|
|
1637
|
+
for (const candidate of result.blocked.slice(0, 10)) {
|
|
1638
|
+
out(` blocked/${candidate.action}: ${candidate.type} ${candidate.assetId}${candidate.logicalId ? ` (${candidate.logicalId})` : ''}`);
|
|
1639
|
+
}
|
|
1640
|
+
for (const failure of result.failures.slice(0, 10)) {
|
|
1641
|
+
out(` failed/${failure.reason}: ${failure.assetId ?? 'unknown'}`);
|
|
1642
|
+
}
|
|
1643
|
+
}
|
|
1644
|
+
class SyncAbortError extends Error {
|
|
1645
|
+
reason;
|
|
1646
|
+
constructor(reason, message) {
|
|
1647
|
+
super(message);
|
|
1648
|
+
this.reason = reason;
|
|
1649
|
+
this.name = 'SyncAbortError';
|
|
1650
|
+
}
|
|
1651
|
+
}
|
|
1652
|
+
function loadSyncEnv(env) {
|
|
1653
|
+
const envFile = loadEnvFileFromEnv(env);
|
|
1654
|
+
if (envFile.error)
|
|
1655
|
+
throw new SyncAbortError('env_file_unavailable', 'Configured environment file is unavailable');
|
|
1656
|
+
}
|
|
1657
|
+
function emitFailure(reason, message, jsonOut, out, err) {
|
|
1658
|
+
const payload = { ok: false, group: GROUP, reason, message: redact(message) };
|
|
1659
|
+
if (jsonOut)
|
|
1660
|
+
out(JSON.stringify(payload));
|
|
1661
|
+
else
|
|
1662
|
+
err(`sync failed (${reason}): ${payload.message}`);
|
|
1663
|
+
return 1;
|
|
1664
|
+
}
|
|
1665
|
+
function mapSyncError(error) {
|
|
1666
|
+
if (error instanceof SyncAbortError)
|
|
1667
|
+
return { reason: error.reason, message: error.message };
|
|
1668
|
+
if (error instanceof assetstore.InvalidConditionalPutResultError) {
|
|
1669
|
+
return { reason: 'conditional_write_invalid', message: 'Conditional asset write returned an invalid result' };
|
|
1670
|
+
}
|
|
1671
|
+
if (error instanceof AuthError)
|
|
1672
|
+
return { reason: 'auth_required', message: 'Hub authentication required' };
|
|
1673
|
+
if (error instanceof HubClientError) {
|
|
1674
|
+
if (error.status === 401 || error.status === 403)
|
|
1675
|
+
return { reason: 'auth_required', message: 'Hub authentication required' };
|
|
1676
|
+
if (error.status === 429 || error.status >= 500)
|
|
1677
|
+
return { reason: 'network_error', message: 'Hub temporarily unavailable' };
|
|
1678
|
+
return { reason: 'hub_rejected', message: 'Hub rejected the sync request' };
|
|
1679
|
+
}
|
|
1680
|
+
if (error instanceof HubUnreachableError)
|
|
1681
|
+
return { reason: 'network_error', message: 'Hub unreachable' };
|
|
1682
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1683
|
+
if (/credential|auth|login|node_secret|token/i.test(message))
|
|
1684
|
+
return { reason: 'auth_required', message: redact(message) };
|
|
1685
|
+
if (/network|fetch failed|ECONN|ENOTFOUND|ETIMEDOUT|hub 5\d\d/i.test(message))
|
|
1686
|
+
return { reason: 'network_error', message: 'Hub unreachable' };
|
|
1687
|
+
return { reason: 'internal_error', message: 'Sync operation failed' };
|
|
1688
|
+
}
|
|
1689
|
+
function hasFetchAssetById(hub) {
|
|
1690
|
+
return typeof hub.fetchAssetById === 'function';
|
|
1691
|
+
}
|
|
1692
|
+
function isSyncAccountAssetHub(value) {
|
|
1693
|
+
const candidate = value;
|
|
1694
|
+
return typeof candidate?.listAccountAssets === 'function' && typeof candidate.fetchAssetById === 'function';
|
|
1695
|
+
}
|
|
1696
|
+
function syncRunKey(opts, env, deps) {
|
|
1697
|
+
const material = {
|
|
1698
|
+
...syncInventoryIdentity(opts, env, deps),
|
|
1699
|
+
limit: opts.limit,
|
|
1700
|
+
pageSize: opts.pageSize,
|
|
1701
|
+
force: opts.force,
|
|
1702
|
+
purchasedCursor: opts.purchasedCursor ?? '',
|
|
1703
|
+
publishedCursor: opts.publishedCursor ?? '',
|
|
1704
|
+
};
|
|
1705
|
+
return createHash('sha256').update(JSON.stringify(material)).digest('hex');
|
|
1706
|
+
}
|
|
1707
|
+
function syncInventoryKey(opts, env, deps) {
|
|
1708
|
+
return createHash('sha256').update(JSON.stringify(syncInventoryIdentity(opts, env, deps))).digest('hex');
|
|
1709
|
+
}
|
|
1710
|
+
function prepareInventoryScan(syncLedger, inventoryKey, opts) {
|
|
1711
|
+
const inputCursors = {
|
|
1712
|
+
purchased: opts.purchasedCursor ?? null,
|
|
1713
|
+
published: opts.publishedCursor ?? null,
|
|
1714
|
+
};
|
|
1715
|
+
const inputCursorFingerprints = fingerprintCursors(inputCursors);
|
|
1716
|
+
const previous = syncLedger.latestInventoryScan(inventoryKey);
|
|
1717
|
+
if (opts.resume
|
|
1718
|
+
&& previous
|
|
1719
|
+
&& !previous.complete
|
|
1720
|
+
&& previous.retryIndex !== undefined
|
|
1721
|
+
&& previous.scope === opts.scope
|
|
1722
|
+
&& cursorFingerprintsMatch(previous.nextCursorFingerprints, inputCursorFingerprints)) {
|
|
1723
|
+
return {
|
|
1724
|
+
trackable: true,
|
|
1725
|
+
scanId: previous.scanId,
|
|
1726
|
+
index: previous.retryIndex,
|
|
1727
|
+
retry: true,
|
|
1728
|
+
inputCursorFingerprints,
|
|
1729
|
+
skipPurchased: opts.scope === 'all'
|
|
1730
|
+
&& previous.nextCursorFingerprints.purchased === null
|
|
1731
|
+
&& previous.nextCursorFingerprints.published !== null,
|
|
1732
|
+
skipPublished: opts.scope === 'all'
|
|
1733
|
+
&& previous.nextCursorFingerprints.published === null
|
|
1734
|
+
&& previous.nextCursorFingerprints.purchased !== null,
|
|
1735
|
+
};
|
|
1736
|
+
}
|
|
1737
|
+
if (inputCursors.purchased === null && inputCursors.published === null) {
|
|
1738
|
+
return {
|
|
1739
|
+
trackable: true,
|
|
1740
|
+
scanId: randomUUID(),
|
|
1741
|
+
index: 0,
|
|
1742
|
+
retry: false,
|
|
1743
|
+
inputCursorFingerprints,
|
|
1744
|
+
skipPurchased: false,
|
|
1745
|
+
skipPublished: false,
|
|
1746
|
+
};
|
|
1747
|
+
}
|
|
1748
|
+
if (previous
|
|
1749
|
+
&& !previous.complete
|
|
1750
|
+
&& previous.retryIndex === undefined
|
|
1751
|
+
&& previous.scope === opts.scope
|
|
1752
|
+
&& cursorFingerprintsMatch(previous.nextCursorFingerprints, inputCursorFingerprints)) {
|
|
1753
|
+
return {
|
|
1754
|
+
trackable: true,
|
|
1755
|
+
scanId: previous.scanId,
|
|
1756
|
+
index: previous.segmentCount,
|
|
1757
|
+
retry: false,
|
|
1758
|
+
inputCursorFingerprints,
|
|
1759
|
+
skipPurchased: opts.scope === 'all' && previous.nextCursorFingerprints.purchased === null,
|
|
1760
|
+
skipPublished: opts.scope === 'all' && previous.nextCursorFingerprints.published === null,
|
|
1761
|
+
};
|
|
1762
|
+
}
|
|
1763
|
+
return {
|
|
1764
|
+
trackable: false,
|
|
1765
|
+
scanId: randomUUID(),
|
|
1766
|
+
index: 0,
|
|
1767
|
+
retry: false,
|
|
1768
|
+
inputCursorFingerprints,
|
|
1769
|
+
skipPurchased: false,
|
|
1770
|
+
skipPublished: false,
|
|
1771
|
+
};
|
|
1772
|
+
}
|
|
1773
|
+
function isRetryableAssetFailure(failure) {
|
|
1774
|
+
return (failure.stage === 'fetch' || failure.stage === 'write')
|
|
1775
|
+
&& (failure.reason === 'network_error' || failure.reason === 'internal_error');
|
|
1776
|
+
}
|
|
1777
|
+
function fingerprintCursors(cursors) {
|
|
1778
|
+
return {
|
|
1779
|
+
purchased: cursors.purchased === null ? null : createHash('sha256').update(cursors.purchased).digest('hex'),
|
|
1780
|
+
published: cursors.published === null ? null : createHash('sha256').update(cursors.published).digest('hex'),
|
|
1781
|
+
};
|
|
1782
|
+
}
|
|
1783
|
+
function cursorFingerprintsMatch(left, right) {
|
|
1784
|
+
return left.purchased === right.purchased && left.published === right.published;
|
|
1785
|
+
}
|
|
1786
|
+
function syncInventoryIdentity(opts, env, deps) {
|
|
1787
|
+
const privateMode = isPrivateHubMode(env);
|
|
1788
|
+
return {
|
|
1789
|
+
mode: String(env['EVOMAP_HUB_MODE'] ?? 'public').trim().toLowerCase(),
|
|
1790
|
+
hubUrl: privateMode ? requirePrivateHubUrl(env) : resolveHubUrl(env),
|
|
1791
|
+
account: privateMode
|
|
1792
|
+
? firstNonEmptyEnv(env, ['EVOMAP_ENTERPRISE_SUBJECT', 'EVOMAP_PRIVATE_SUBJECT', 'PHUB_ENTERPRISE_SUBJECT', 'USER']) ?? 'evolver-proxy'
|
|
1793
|
+
: '',
|
|
1794
|
+
credentialFingerprint: privateMode
|
|
1795
|
+
? syncCredentialFingerprint(env)
|
|
1796
|
+
: publicResumeIdentityFingerprint(env, deps),
|
|
1797
|
+
scope: opts.scope,
|
|
1798
|
+
type: opts.type ?? '',
|
|
1799
|
+
status: opts.status,
|
|
1800
|
+
};
|
|
1801
|
+
}
|
|
1802
|
+
function reconciliationRecords(syncLedger, inventoryKey, legacyRunKey) {
|
|
1803
|
+
const records = new Map();
|
|
1804
|
+
for (const record of syncLedger.listForInventoryKey(inventoryKey))
|
|
1805
|
+
records.set(record.assetId, record);
|
|
1806
|
+
// Records written before inventoryKey existed retain same-parameter reconciliation behavior.
|
|
1807
|
+
for (const record of syncLedger.listForRunKey(legacyRunKey))
|
|
1808
|
+
records.set(record.assetId, record);
|
|
1809
|
+
return [...records.values()];
|
|
1810
|
+
}
|
|
1811
|
+
function countMissingRemote(syncLedger, inventoryKey, legacyRunKey, localAssetIds, remoteAssetIds) {
|
|
1812
|
+
return reconciliationRecords(syncLedger, inventoryKey, legacyRunKey)
|
|
1813
|
+
.filter((record) => localAssetIds.has(record.assetId) && !remoteAssetIds.has(record.remoteAssetId))
|
|
1814
|
+
.length;
|
|
1815
|
+
}
|
|
1816
|
+
function inventorySegmentOutcome(candidates, failures, written) {
|
|
1817
|
+
const failedAssetIds = new Set(failures.flatMap((failure) => failure.assetId ? [failure.assetId] : []));
|
|
1818
|
+
const writtenAssetIds = new Set(written.map((asset) => asset.assetId));
|
|
1819
|
+
const items = [];
|
|
1820
|
+
let anonymousBlocked = 0;
|
|
1821
|
+
for (const candidate of candidates) {
|
|
1822
|
+
if (candidate.assetId === MISSING_ASSET_ID) {
|
|
1823
|
+
anonymousBlocked += 1;
|
|
1824
|
+
continue;
|
|
1825
|
+
}
|
|
1826
|
+
let outcome;
|
|
1827
|
+
if (failedAssetIds.has(candidate.assetId))
|
|
1828
|
+
outcome = 'failed';
|
|
1829
|
+
else if (candidate.action === 'already_local')
|
|
1830
|
+
outcome = 'already_local';
|
|
1831
|
+
else if (isBlockedCandidate(candidate))
|
|
1832
|
+
outcome = 'blocked';
|
|
1833
|
+
else if (writtenAssetIds.has(candidate.assetId))
|
|
1834
|
+
outcome = 'imported';
|
|
1835
|
+
else
|
|
1836
|
+
outcome = 'pending';
|
|
1837
|
+
items.push({ remoteAssetId: candidate.assetId, outcome });
|
|
1838
|
+
}
|
|
1839
|
+
return { items, anonymousBlocked };
|
|
1840
|
+
}
|
|
1841
|
+
function reconcileInventorySnapshot(snapshot, missingRemote) {
|
|
1842
|
+
let imported = 0;
|
|
1843
|
+
let alreadyLocal = 0;
|
|
1844
|
+
let blocked = snapshot.anonymousBlocked;
|
|
1845
|
+
let failed = 0;
|
|
1846
|
+
let pending = 0;
|
|
1847
|
+
for (const outcome of snapshot.outcomes.values()) {
|
|
1848
|
+
if (outcome === 'imported')
|
|
1849
|
+
imported += 1;
|
|
1850
|
+
else if (outcome === 'already_local')
|
|
1851
|
+
alreadyLocal += 1;
|
|
1852
|
+
else if (outcome === 'blocked')
|
|
1853
|
+
blocked += 1;
|
|
1854
|
+
else if (outcome === 'failed')
|
|
1855
|
+
failed += 1;
|
|
1856
|
+
else
|
|
1857
|
+
pending += 1;
|
|
1858
|
+
}
|
|
1859
|
+
const remoteUnique = snapshot.outcomes.size + snapshot.anonymousBlocked;
|
|
1860
|
+
const accounted = imported + alreadyLocal + blocked + failed + pending;
|
|
1861
|
+
return {
|
|
1862
|
+
remoteUnique,
|
|
1863
|
+
accounted,
|
|
1864
|
+
imported,
|
|
1865
|
+
alreadyLocal,
|
|
1866
|
+
blocked,
|
|
1867
|
+
failed,
|
|
1868
|
+
pending,
|
|
1869
|
+
inventoryComplete: snapshot.complete,
|
|
1870
|
+
missingRemote,
|
|
1871
|
+
consistent: snapshot.complete
|
|
1872
|
+
&& missingRemote === 0
|
|
1873
|
+
&& blocked === 0
|
|
1874
|
+
&& failed === 0
|
|
1875
|
+
&& pending === 0
|
|
1876
|
+
&& accounted === remoteUnique,
|
|
1877
|
+
};
|
|
1878
|
+
}
|
|
1879
|
+
function publicResumeIdentityFingerprint(env, deps) {
|
|
1880
|
+
const supplied = deps.resumeIdentityFingerprint?.trim();
|
|
1881
|
+
if (supplied)
|
|
1882
|
+
return createHash('sha256').update(supplied).digest('hex');
|
|
1883
|
+
if (!deps.hub)
|
|
1884
|
+
return resolveRecipeHubResumeIdentityFingerprint(env);
|
|
1885
|
+
return createHash('sha256').update(JSON.stringify({
|
|
1886
|
+
account: firstNonEmptyEnv(env, ['EVOMAP_NODE_ID', 'A2A_NODE_ID']) ?? '',
|
|
1887
|
+
credentialFingerprint: syncCredentialFingerprint(env),
|
|
1888
|
+
})).digest('hex');
|
|
1889
|
+
}
|
|
1890
|
+
function syncCredentialFingerprint(env) {
|
|
1891
|
+
const credentials = [
|
|
1892
|
+
['A2A_INVITATION_TOKEN', firstNonEmptyEnv(env, ['A2A_INVITATION_TOKEN'])],
|
|
1893
|
+
['enterprise', firstNonEmptyEnv(env, [
|
|
1894
|
+
'EVOMAP_ENTERPRISE_TOKEN',
|
|
1895
|
+
'EVOMAP_PRIVATE_HUB_TOKEN',
|
|
1896
|
+
'PHUB_ENTERPRISE_TOKEN',
|
|
1897
|
+
'PRIVATE_HUB_ENTERPRISE_TOKEN',
|
|
1898
|
+
])],
|
|
1899
|
+
['node', firstNonEmptyEnv(env, ['EVOMAP_NODE_SECRET', 'A2A_NODE_SECRET'])],
|
|
1900
|
+
].filter((entry) => entry[1] !== undefined);
|
|
1901
|
+
if (credentials.length === 0)
|
|
1902
|
+
return '';
|
|
1903
|
+
return createHash('sha256').update(JSON.stringify(credentials)).digest('hex');
|
|
1904
|
+
}
|
|
1905
|
+
function isPrivateHubMode(env) {
|
|
1906
|
+
return String(env['EVOMAP_HUB_MODE'] ?? 'public').trim().toLowerCase() === 'private';
|
|
1907
|
+
}
|
|
1908
|
+
function configuredPrivateHubUrl(env) {
|
|
1909
|
+
return firstNonEmptyEnv(env, ['EVOMAP_HUB_URL', 'A2A_HUB_URL', 'EVOLVER_DEFAULT_HUB_URL']);
|
|
1910
|
+
}
|
|
1911
|
+
function requirePrivateHubUrl(env) {
|
|
1912
|
+
const hubUrl = configuredPrivateHubUrl(env);
|
|
1913
|
+
if (!hubUrl)
|
|
1914
|
+
throw new SyncAbortError('private_hub_url_required', 'Private Hub URL must be configured explicitly');
|
|
1915
|
+
return hubUrl;
|
|
1916
|
+
}
|
|
1917
|
+
function validatePrivateHubUrl(env) {
|
|
1918
|
+
if (isPrivateHubMode(env))
|
|
1919
|
+
requirePrivateHubUrl(env);
|
|
1920
|
+
}
|
|
1921
|
+
function firstNonEmptyEnv(env, keys) {
|
|
1922
|
+
for (const key of keys) {
|
|
1923
|
+
const value = env[key]?.trim();
|
|
1924
|
+
if (value)
|
|
1925
|
+
return value;
|
|
1926
|
+
}
|
|
1927
|
+
return undefined;
|
|
1928
|
+
}
|
|
1929
|
+
function reconcile(candidates, failures, imported, final, inventoryComplete, missingRemote) {
|
|
1930
|
+
const failedAssetIds = new Set(failures.flatMap((failure) => failure.assetId ? [failure.assetId] : []));
|
|
1931
|
+
let alreadyLocal = 0;
|
|
1932
|
+
let blocked = 0;
|
|
1933
|
+
let actionable = 0;
|
|
1934
|
+
for (const candidate of candidates) {
|
|
1935
|
+
if (failedAssetIds.has(candidate.assetId))
|
|
1936
|
+
continue;
|
|
1937
|
+
if (candidate.action === 'already_local')
|
|
1938
|
+
alreadyLocal += 1;
|
|
1939
|
+
else if (isBlockedCandidate(candidate))
|
|
1940
|
+
blocked += 1;
|
|
1941
|
+
else
|
|
1942
|
+
actionable += 1;
|
|
1943
|
+
}
|
|
1944
|
+
const failed = failedAssetIds.size;
|
|
1945
|
+
const pending = Math.max(0, actionable - imported);
|
|
1946
|
+
const accounted = imported + alreadyLocal + blocked + failed + pending;
|
|
1947
|
+
return {
|
|
1948
|
+
remoteUnique: candidates.length,
|
|
1949
|
+
accounted,
|
|
1950
|
+
imported,
|
|
1951
|
+
alreadyLocal,
|
|
1952
|
+
blocked,
|
|
1953
|
+
failed,
|
|
1954
|
+
pending,
|
|
1955
|
+
inventoryComplete,
|
|
1956
|
+
missingRemote,
|
|
1957
|
+
consistent: final
|
|
1958
|
+
&& inventoryComplete
|
|
1959
|
+
&& missingRemote === 0
|
|
1960
|
+
&& failures.length === 0
|
|
1961
|
+
&& blocked === 0
|
|
1962
|
+
&& pending === 0
|
|
1963
|
+
&& accounted === candidates.length,
|
|
1964
|
+
};
|
|
1965
|
+
}
|
|
1966
|
+
function storeBaseDir(store, deps) {
|
|
1967
|
+
return store instanceof assetstore.LocalJsonlProvider ? store.baseDir : deps.assetsDir ?? events.assetsDir();
|
|
1968
|
+
}
|
|
1969
|
+
function redact(value) {
|
|
1970
|
+
return value
|
|
1971
|
+
.replace(/\bBearer\s+[A-Za-z0-9._~+/=-]+/gi, 'Bearer [redacted]')
|
|
1972
|
+
.replace(/\b([A-Z][A-Z0-9_]*(?:_SECRET|_TOKEN))\b\s*[:=]\s*["']?[^"',\s;}]+/g, '$1=[redacted]')
|
|
1973
|
+
.replace(/\b(authorization|node_secret|nodeSecret|access_token|refresh_token|token|secret)\b\s*[:=]\s*["']?[^"',\s;}]+/gi, '$1=[redacted]');
|
|
1974
|
+
}
|
|
1975
|
+
function asRecord(value) {
|
|
1976
|
+
return value && typeof value === 'object' && !Array.isArray(value) ? value : undefined;
|
|
1977
|
+
}
|
|
1978
|
+
function stringField(value, key) {
|
|
1979
|
+
const raw = value[key];
|
|
1980
|
+
return typeof raw === 'string' && raw.trim() ? raw.trim() : undefined;
|
|
1981
|
+
}
|