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