@evomap/evolver-cli 2.0.0-beta.2 → 2.0.0-beta.22
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/antiGeneBenchmark.js +2 -0
- package/dist/antiGeneRollout.js +9 -3
- package/dist/assetHealth.d.ts +6 -0
- package/dist/assetHealth.js +107 -0
- package/dist/assetRepair.d.ts +24 -0
- package/dist/assetRepair.js +172 -0
- package/dist/assetSidecarRecovery.d.ts +14 -0
- package/dist/assetSidecarRecovery.js +171 -0
- package/dist/assetTrust.d.ts +24 -0
- package/dist/assetTrust.js +231 -0
- package/dist/atp.d.ts +10 -5
- package/dist/atp.js +119 -26
- package/dist/atpAutoBuyer.d.ts +120 -0
- package/dist/atpAutoBuyer.js +814 -0
- package/dist/atpAutoDeliver.js +2 -2
- package/dist/autoDistillAntiGene.js +7 -5
- package/dist/autoDistillLlm.d.ts +26 -0
- package/dist/autoDistillLlm.js +119 -22
- package/dist/autoDistillTranscript.js +3 -2
- package/dist/autoexec.d.ts +111 -24
- package/dist/autoexec.js +887 -120
- package/dist/autoexecConfig.d.ts +10 -0
- package/dist/autoexecConfig.js +69 -0
- package/dist/cli.js +13 -0
- package/dist/cliContracts.d.ts +33 -2
- package/dist/cliContracts.js +818 -78
- package/dist/commandCatalog.d.ts +72 -0
- package/dist/commandCatalog.js +120 -0
- package/dist/commands.d.ts +1 -0
- package/dist/commands.js +1 -0
- package/dist/curriculumCapabilityGaps.d.ts +6 -0
- package/dist/curriculumCapabilityGaps.js +24 -0
- package/dist/cycleConsumer.d.ts +17 -2
- package/dist/cycleConsumer.js +374 -50
- package/dist/dashboard.d.ts +13 -1
- package/dist/dashboard.js +235 -18
- package/dist/dispatch.d.ts +9 -2
- package/dist/dispatch.js +29 -6
- package/dist/distillAdmission.d.ts +13 -0
- package/dist/distillAdmission.js +35 -0
- package/dist/distillObserver.js +27 -12
- package/dist/distillPrimitives.d.ts +11 -8
- package/dist/distillPrimitives.js +116 -22
- package/dist/doctor.d.ts +13 -0
- package/dist/doctor.js +177 -10
- package/dist/identityHome.d.ts +9 -0
- package/dist/identityHome.js +47 -0
- package/dist/index.d.ts +73 -40
- package/dist/index.js +745 -207
- package/dist/issueReport.d.ts +7 -0
- package/dist/issueReport.js +291 -0
- package/dist/learningTrace.d.ts +15 -0
- package/dist/learningTrace.js +73 -0
- package/dist/lifecycle.d.ts +199 -2
- package/dist/lifecycle.js +4999 -152
- package/dist/lifecycleBootstrapTransaction.d.ts +235 -0
- package/dist/lifecycleBootstrapTransaction.js +2182 -0
- package/dist/localMemoryGraph.d.ts +184 -0
- package/dist/localMemoryGraph.js +2689 -0
- package/dist/login.d.ts +1 -1
- package/dist/login.js +3 -3
- package/dist/materialPackage.js +3 -6
- package/dist/materialSnapshot.d.ts +35 -1
- package/dist/materialSnapshot.js +265 -18
- package/dist/memoryGraphOps.d.ts +8 -0
- package/dist/memoryGraphOps.js +140 -0
- package/dist/migrate/assetFormatMap.d.ts +61 -0
- package/dist/migrate/assetFormatMap.js +53 -0
- package/dist/migrate/envTranslate.d.ts +26 -0
- package/dist/migrate/envTranslate.js +147 -0
- package/dist/migrate/fieldMap.d.ts +7 -5
- package/dist/migrate/fieldMap.js +20 -14
- package/dist/migrate/oauthImport.d.ts +66 -0
- package/dist/migrate/oauthImport.js +667 -0
- package/dist/migrate/v1Import.d.ts +98 -1
- package/dist/migrate/v1Import.js +1532 -71
- package/dist/modelCompatibility.d.ts +10 -0
- package/dist/modelCompatibility.js +296 -0
- package/dist/promptRecallHook.d.ts +24 -0
- package/dist/promptRecallHook.js +425 -0
- package/dist/recallVerifyReport.d.ts +37 -0
- package/dist/recallVerifyReport.js +244 -0
- package/dist/recipe.d.ts +14 -2
- package/dist/recipe.js +543 -65
- package/dist/repairedAssetStore.d.ts +2 -0
- package/dist/repairedAssetStore.js +12 -0
- package/dist/requiredSandboxValidation.d.ts +5 -0
- package/dist/requiredSandboxValidation.js +4 -0
- package/dist/reuse.d.ts +18 -4
- package/dist/reuse.js +375 -107
- package/dist/reviewFilter.d.ts +3 -1
- package/dist/reviewFilter.js +3 -1
- package/dist/runtimeCapabilities.d.ts +18 -0
- package/dist/runtimeCapabilities.js +81 -0
- package/dist/runtimeSessionSource.d.ts +8 -2
- package/dist/runtimeSessionSource.js +63 -11
- package/dist/selectionPolicyConfig.d.ts +8 -0
- package/dist/selectionPolicyConfig.js +18 -0
- package/dist/semanticIdfConfig.d.ts +2 -0
- package/dist/semanticIdfConfig.js +4 -0
- package/dist/sessionIngest.d.ts +43 -0
- package/dist/sessionIngest.js +180 -0
- package/dist/setupHooks.d.ts +5 -0
- package/dist/setupHooks.js +330 -14
- package/dist/skill2gep.d.ts +13 -9
- package/dist/skill2gep.js +99 -36
- package/dist/skillDistill.d.ts +8 -4
- package/dist/skillDistill.js +39 -9
- package/dist/solo/mode.js +1 -0
- package/dist/sync.d.ts +13 -1
- package/dist/sync.js +1947 -265
- package/dist/thesis.d.ts +1 -1
- package/dist/thesis.js +20 -3
- package/dist/trajectoryExport.js +21 -3
- package/dist/v1Compat.d.ts +1 -0
- package/dist/v1Compat.js +9 -0
- package/dist/valueDigest.js +8 -1
- package/dist/windowsLegacyTaskCleanup.d.ts +228 -0
- package/dist/windowsLegacyTaskCleanup.js +1475 -0
- package/dist/workflow.d.ts +39 -0
- package/dist/workflow.js +386 -0
- package/dist/workflowRuntime.d.ts +66 -0
- package/dist/workflowRuntime.js +638 -0
- package/package.json +14 -7
package/dist/sync.js
CHANGED
|
@@ -1,83 +1,85 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, readSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { Buffer } from 'node:buffer';
|
|
3
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
4
|
+
import { dirname, join } from 'node:path';
|
|
3
5
|
import { assetstore, events, hub as hubNs, wire } from '@evomap/evolver-core';
|
|
4
|
-
import { AuthError, connectPublicHub, HubClientError, HubUnreachableError, isHubDryRunEnabled, } from '@evomap/evolver-adapter-public';
|
|
6
|
+
import { AuthError, connectPublicHub, HubClientError, HubUnreachableError, isHubDryRunEnabled, MalformedAccountAssetPageError, resolveHubUrl, stripHubDeliveryMetadataForIntegrity, } from '@evomap/evolver-adapter-public';
|
|
5
7
|
import { loadEnvFileFromEnv } from '@evomap/evolver-mcp';
|
|
6
|
-
import { createRecipeHubFromEnv } from './recipe.js';
|
|
8
|
+
import { createRecipeHubFromEnv, resolveRecipeHubResumeIdentityFingerprint } from './recipe.js';
|
|
9
|
+
import { getCliVersion } from './version.js';
|
|
7
10
|
const DEFAULT_LIMIT = 100;
|
|
8
|
-
const MAX_LIMIT =
|
|
11
|
+
const MAX_LIMIT = 10_000;
|
|
12
|
+
const DEFAULT_PAGE_SIZE = 100;
|
|
13
|
+
const MAX_PAGE_SIZE = 1000;
|
|
14
|
+
const MAX_CURSOR_LENGTH = 4096;
|
|
15
|
+
const MAX_CONSECUTIVE_EMPTY_PAGES = 10;
|
|
16
|
+
const MAX_CONSECUTIVE_PAGES_WITHOUT_UNIQUE_PROGRESS = 10;
|
|
17
|
+
const MAX_RAW_PAGES = 20_000;
|
|
18
|
+
const MAX_RAW_ROWS = 100_000;
|
|
19
|
+
const MAX_GEPX_BYTES = 64 * 1024 * 1024;
|
|
20
|
+
const MAX_GEPX_ASSETS = 10_000;
|
|
21
|
+
const MAX_GEPX_SIDECAR_RECORDS = MAX_GEPX_ASSETS;
|
|
9
22
|
const GROUP = 'sync';
|
|
10
23
|
const USAGE = [
|
|
11
|
-
'usage: evolver sync [--write] [--force] [--scope all|purchased|published] [--type Gene|Capsule] [--status draft|promoted|all] [--limit N] [--json]',
|
|
24
|
+
'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
25
|
' evolver sync --export <file.gepx> [--type Gene|Capsule] [--limit N] [--json]',
|
|
13
26
|
' evolver sync --import <file.gepx> [--write] [--force] [--type Gene|Capsule] [--limit N] [--json]',
|
|
14
27
|
' evolver sync --json',
|
|
15
28
|
].join('\n');
|
|
16
|
-
const VALUE_FLAGS = new Set(['--scope', '--type', '--status', '--limit', '--export', '--import']);
|
|
29
|
+
const VALUE_FLAGS = new Set(['--scope', '--type', '--status', '--limit', '--page-size', '--purchased-cursor', '--published-cursor', '--export', '--import']);
|
|
17
30
|
const GEPX_TYPE = 'evomap.gepx';
|
|
18
31
|
const GEPX_VERSION = 1;
|
|
19
|
-
const HUB_METADATA_KEYS = new Set([
|
|
20
|
-
'credit_cost',
|
|
21
|
-
'gdi_score',
|
|
22
|
-
'success_rate',
|
|
23
|
-
'reuse_count',
|
|
24
|
-
'ranking_score',
|
|
25
|
-
'source_node_id',
|
|
26
|
-
'fetched_at',
|
|
27
|
-
'receipt',
|
|
28
|
-
'hub_receipt',
|
|
29
|
-
'already_purchased',
|
|
30
|
-
'_semantic_similarity',
|
|
31
|
-
'semantic_similarity',
|
|
32
|
-
'_search_score',
|
|
33
|
-
'search_score',
|
|
34
|
-
'_match_score',
|
|
35
|
-
'match_score',
|
|
36
|
-
'_retrieval_rank',
|
|
37
|
-
'retrieval_rank',
|
|
38
|
-
'original_asset_id',
|
|
39
|
-
'asset_type',
|
|
40
|
-
'local_id',
|
|
41
|
-
'payload',
|
|
42
|
-
'source',
|
|
43
|
-
'status',
|
|
44
|
-
]);
|
|
45
32
|
const MISSING_ASSET_ID = '[missing]';
|
|
33
|
+
const UNVERIFIED_HUB_WRITE_PENDING_REASON = 'unverified_hub_write_pending';
|
|
46
34
|
export async function runSyncCommand(argv, deps = {}) {
|
|
47
35
|
const out = deps.stdout ?? ((line) => { process.stdout.write(`${line}\n`); });
|
|
48
36
|
const err = deps.stderr ?? ((line) => { process.stderr.write(`${line}\n`); });
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
37
|
+
const textOut = (line) => { out(formatTerminalText(line)); };
|
|
38
|
+
const parsed = parseSyncArgs(argv);
|
|
39
|
+
if (!parsed.ok)
|
|
40
|
+
return emitFailure(parsed.reason, parsed.message, parsed.jsonOut, out, err);
|
|
41
|
+
if ('help' in parsed) {
|
|
42
|
+
if (parsed.jsonOut)
|
|
43
|
+
out(stringifyJsonOutput({ ok: true, group: GROUP, mode: 'help', usage: USAGE }));
|
|
52
44
|
else
|
|
53
45
|
out(USAGE);
|
|
54
46
|
return 0;
|
|
55
47
|
}
|
|
56
|
-
const parsed = parseSyncArgs(argv);
|
|
57
|
-
if (!parsed.ok)
|
|
58
|
-
return emitFailure(parsed.reason, parsed.message, parsed.jsonOut, out, err);
|
|
59
48
|
try {
|
|
49
|
+
const env = deps.env ?? process.env;
|
|
50
|
+
loadSyncEnv(env);
|
|
51
|
+
const runtimeDeps = {
|
|
52
|
+
...deps,
|
|
53
|
+
env,
|
|
54
|
+
assetsDir: deps.assetsDir ?? join(events.evomapHome(env), 'assets'),
|
|
55
|
+
};
|
|
60
56
|
const result = parsed.value.exportPath
|
|
61
|
-
? await executeSyncExport(parsed.value,
|
|
57
|
+
? await executeSyncExport(parsed.value, runtimeDeps)
|
|
62
58
|
: parsed.value.importPath
|
|
63
59
|
? parsed.value.write
|
|
64
|
-
? await executeGepxImportWrite(parsed.value,
|
|
65
|
-
: await buildGepxImportPreview(parsed.value,
|
|
60
|
+
? await executeGepxImportWrite(parsed.value, runtimeDeps)
|
|
61
|
+
: await buildGepxImportPreview(parsed.value, runtimeDeps)
|
|
66
62
|
: parsed.value.write
|
|
67
|
-
? await executeSyncWrite(parsed.value,
|
|
68
|
-
: await
|
|
63
|
+
? await executeSyncWrite(parsed.value, runtimeDeps)
|
|
64
|
+
: await executeSyncPreview(parsed.value, runtimeDeps);
|
|
69
65
|
if (parsed.value.jsonOut)
|
|
70
|
-
out(
|
|
66
|
+
out(stringifyJsonOutput(result));
|
|
71
67
|
else if (result.mode === 'preview')
|
|
72
|
-
emitTextPreview(result,
|
|
68
|
+
emitTextPreview(result, textOut);
|
|
73
69
|
else if (result.mode === 'export')
|
|
74
|
-
emitTextExport(result,
|
|
70
|
+
emitTextExport(result, textOut);
|
|
75
71
|
else if (result.mode === 'import_preview')
|
|
76
|
-
emitTextImportPreview(result,
|
|
72
|
+
emitTextImportPreview(result, textOut);
|
|
77
73
|
else if (result.mode === 'import')
|
|
78
|
-
emitTextImport(result,
|
|
74
|
+
emitTextImport(result, textOut);
|
|
79
75
|
else
|
|
80
|
-
emitTextWrite(result,
|
|
76
|
+
emitTextWrite(result, textOut);
|
|
77
|
+
if ('failures' in result && result.failures.length > 0)
|
|
78
|
+
return 1;
|
|
79
|
+
if (result.mode === 'import' && result.blocked.length > 0)
|
|
80
|
+
return 1;
|
|
81
|
+
if (result.mode === 'write' && !result.reconciliation.consistent)
|
|
82
|
+
return 1;
|
|
81
83
|
return 0;
|
|
82
84
|
}
|
|
83
85
|
catch (error) {
|
|
@@ -90,15 +92,21 @@ function parseSyncArgs(argv) {
|
|
|
90
92
|
let type;
|
|
91
93
|
let status = 'all';
|
|
92
94
|
let limit = DEFAULT_LIMIT;
|
|
95
|
+
let pageSize = DEFAULT_PAGE_SIZE;
|
|
96
|
+
let purchasedCursor;
|
|
97
|
+
let publishedCursor;
|
|
93
98
|
let jsonOut = argv.includes('--json');
|
|
94
99
|
let write = false;
|
|
95
100
|
let force = false;
|
|
101
|
+
let resume = false;
|
|
96
102
|
let exportPath;
|
|
97
103
|
let importPath;
|
|
98
104
|
for (let i = 0; i < argv.length; i += 1) {
|
|
99
105
|
const token = argv[i];
|
|
100
106
|
if (!token)
|
|
101
107
|
continue;
|
|
108
|
+
if (token === '--help' || token === '-h')
|
|
109
|
+
return { ok: true, help: true, jsonOut };
|
|
102
110
|
if (token === '--json') {
|
|
103
111
|
jsonOut = true;
|
|
104
112
|
continue;
|
|
@@ -111,6 +119,10 @@ function parseSyncArgs(argv) {
|
|
|
111
119
|
force = true;
|
|
112
120
|
continue;
|
|
113
121
|
}
|
|
122
|
+
if (token === '--resume') {
|
|
123
|
+
resume = true;
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
114
126
|
if (token.startsWith('--')) {
|
|
115
127
|
const eq = token.indexOf('=');
|
|
116
128
|
const flag = eq >= 0 ? token.slice(0, eq) : token;
|
|
@@ -145,6 +157,21 @@ function parseSyncArgs(argv) {
|
|
|
145
157
|
return { ok: false, reason: 'invalid_arg', message: '--limit must be a positive integer', jsonOut };
|
|
146
158
|
limit = Math.min(parsedLimit, MAX_LIMIT);
|
|
147
159
|
}
|
|
160
|
+
else if (flag === '--page-size') {
|
|
161
|
+
const parsedPageSize = Number(value);
|
|
162
|
+
if (!Number.isSafeInteger(parsedPageSize) || parsedPageSize <= 0)
|
|
163
|
+
return { ok: false, reason: 'invalid_arg', message: '--page-size must be a positive integer', jsonOut };
|
|
164
|
+
pageSize = Math.min(parsedPageSize, MAX_PAGE_SIZE);
|
|
165
|
+
}
|
|
166
|
+
else if (flag === '--purchased-cursor' || flag === '--published-cursor') {
|
|
167
|
+
if (!isValidOpaqueCursor(value)) {
|
|
168
|
+
return { ok: false, reason: 'invalid_arg', message: `${flag} must be a non-empty cursor of at most ${MAX_CURSOR_LENGTH} characters`, jsonOut };
|
|
169
|
+
}
|
|
170
|
+
if (flag === '--purchased-cursor')
|
|
171
|
+
purchasedCursor = value;
|
|
172
|
+
else
|
|
173
|
+
publishedCursor = value;
|
|
174
|
+
}
|
|
148
175
|
else if (flag === '--export') {
|
|
149
176
|
exportPath = value;
|
|
150
177
|
}
|
|
@@ -158,51 +185,85 @@ function parseSyncArgs(argv) {
|
|
|
158
185
|
if (force && !write) {
|
|
159
186
|
return { ok: false, reason: 'force_requires_write', message: '--force requires --write', jsonOut };
|
|
160
187
|
}
|
|
188
|
+
if (resume && !write) {
|
|
189
|
+
return { ok: false, reason: 'resume_requires_write', message: '--resume requires --write', jsonOut };
|
|
190
|
+
}
|
|
161
191
|
if (exportPath && importPath) {
|
|
162
192
|
return { ok: false, reason: 'invalid_arg', message: '--export and --import cannot be used together', jsonOut };
|
|
163
193
|
}
|
|
164
194
|
if (exportPath && write) {
|
|
165
195
|
return { ok: false, reason: 'invalid_arg', message: '--export does not use --write', jsonOut };
|
|
166
196
|
}
|
|
167
|
-
|
|
197
|
+
if (purchasedCursor && scope === 'published') {
|
|
198
|
+
return { ok: false, reason: 'invalid_arg', message: '--purchased-cursor requires --scope all|purchased', jsonOut };
|
|
199
|
+
}
|
|
200
|
+
if (publishedCursor && scope === 'purchased') {
|
|
201
|
+
return { ok: false, reason: 'invalid_arg', message: '--published-cursor requires --scope all|published', jsonOut };
|
|
202
|
+
}
|
|
203
|
+
if ((purchasedCursor || publishedCursor) && (exportPath || importPath)) {
|
|
204
|
+
return { ok: false, reason: 'invalid_arg', message: 'Hub cursors cannot be used with --export or --import', jsonOut };
|
|
205
|
+
}
|
|
206
|
+
return { ok: true, value: { scope, ...(type ? { type } : {}), status, limit, pageSize, ...(purchasedCursor ? { purchasedCursor } : {}), ...(publishedCursor ? { publishedCursor } : {}), jsonOut, write, force, resume, ...(exportPath ? { exportPath } : {}), ...(importPath ? { importPath } : {}) } };
|
|
168
207
|
}
|
|
169
|
-
async function buildSyncPreview(opts, deps
|
|
208
|
+
async function buildSyncPreview(opts, deps, listing = {
|
|
209
|
+
skipPurchased: false,
|
|
210
|
+
skipPublished: false,
|
|
211
|
+
}) {
|
|
170
212
|
const env = deps.env ?? process.env;
|
|
171
|
-
|
|
213
|
+
validatePrivateHubUrl(env);
|
|
172
214
|
if (isHubDryRunEnabled(env))
|
|
173
215
|
return emptyPreview(opts.scope);
|
|
174
|
-
const hub = deps.hub ?? createDefaultHub(deps);
|
|
216
|
+
const hub = deps.hub ?? await createDefaultHub(deps, env);
|
|
175
217
|
const store = deps.store ?? new assetstore.LocalJsonlProvider(deps.assetsDir ?? events.assetsDir());
|
|
176
218
|
const local = await localIndex(store);
|
|
177
|
-
const { purchased, published } = await listRemoteRows(hub, opts);
|
|
219
|
+
const { purchased, published, failures, inventoryComplete, nextCursors } = await listRemoteRows(hub, opts, listing);
|
|
220
|
+
const provenanceSnapshot = previewProvenanceSnapshot(store, deps);
|
|
178
221
|
const counts = {
|
|
179
222
|
remotePurchased: purchased.length,
|
|
180
223
|
remotePublished: published.length,
|
|
181
224
|
uniqueRemote: 0,
|
|
182
225
|
alreadyLocal: 0,
|
|
226
|
+
tombstone: 0,
|
|
183
227
|
idCollision: 0,
|
|
184
228
|
unsupported: 0,
|
|
185
229
|
integrityError: 0,
|
|
186
230
|
wouldImport: 0,
|
|
231
|
+
unverifiedWouldImport: 0,
|
|
187
232
|
forcedImport: 0,
|
|
233
|
+
skippedLimit: 0,
|
|
234
|
+
fetchFailed: 0,
|
|
235
|
+
writeFailed: 0,
|
|
188
236
|
};
|
|
189
237
|
const unique = new Map();
|
|
238
|
+
const conflictingDuplicateAssetIds = new Set();
|
|
190
239
|
const missingAssetId = [];
|
|
191
240
|
for (const row of purchased)
|
|
192
|
-
addUnique(unique, missingAssetId, row, 'purchased');
|
|
241
|
+
addUnique(unique, missingAssetId, conflictingDuplicateAssetIds, row, 'purchased');
|
|
193
242
|
for (const row of published)
|
|
194
|
-
addUnique(unique, missingAssetId, row, 'published');
|
|
243
|
+
addUnique(unique, missingAssetId, conflictingDuplicateAssetIds, row, 'published');
|
|
195
244
|
counts.uniqueRemote = unique.size + missingAssetId.length;
|
|
196
245
|
const candidates = [];
|
|
246
|
+
const pendingLogical = new Map(local.logical);
|
|
197
247
|
for (const { row, source } of [...unique.values(), ...missingAssetId]) {
|
|
198
|
-
const
|
|
248
|
+
const assetId = rawStringField(row, 'asset_id');
|
|
249
|
+
const candidate = assetId && conflictingDuplicateAssetIds.has(assetId)
|
|
250
|
+
? classifyConflictingRemoteDuplicate(row, source)
|
|
251
|
+
: classifyRemote(row, source, { ...local, logical: pendingLogical }, provenanceSnapshot);
|
|
199
252
|
candidates.push(candidate);
|
|
200
253
|
if (candidate.action === 'already_local')
|
|
201
254
|
counts.alreadyLocal += 1;
|
|
255
|
+
else if (candidate.action === 'tombstone')
|
|
256
|
+
counts.tombstone += 1;
|
|
202
257
|
else if (candidate.action === 'id_collision')
|
|
203
258
|
counts.idCollision += 1;
|
|
204
|
-
else if (candidate.action === 'would_import')
|
|
259
|
+
else if (candidate.action === 'would_import') {
|
|
205
260
|
counts.wouldImport += 1;
|
|
261
|
+
if (candidate.verification === 'unverified')
|
|
262
|
+
counts.unverifiedWouldImport += 1;
|
|
263
|
+
if (candidate.logicalId && (candidate.type === 'Gene' || candidate.type === 'Capsule')) {
|
|
264
|
+
pendingLogical.set(`${candidate.type}:${candidate.logicalId}`, candidate.assetId);
|
|
265
|
+
}
|
|
266
|
+
}
|
|
206
267
|
else if (candidate.action === 'force_import')
|
|
207
268
|
counts.forcedImport += 1;
|
|
208
269
|
else if (candidate.action === 'unsupported_type')
|
|
@@ -210,97 +271,364 @@ async function buildSyncPreview(opts, deps) {
|
|
|
210
271
|
else
|
|
211
272
|
counts.integrityError += 1;
|
|
212
273
|
}
|
|
213
|
-
return {
|
|
274
|
+
return {
|
|
275
|
+
ok: true,
|
|
276
|
+
group: GROUP,
|
|
277
|
+
mode: 'preview',
|
|
278
|
+
scope: opts.scope,
|
|
279
|
+
counts,
|
|
280
|
+
candidates,
|
|
281
|
+
failures,
|
|
282
|
+
nextCursors,
|
|
283
|
+
reconciliation: reconcile(candidates, failures, 0, false, inventoryComplete, 0),
|
|
284
|
+
};
|
|
285
|
+
}
|
|
286
|
+
async function executeSyncPreview(opts, deps) {
|
|
287
|
+
const env = deps.env ?? process.env;
|
|
288
|
+
validatePrivateHubUrl(env);
|
|
289
|
+
if (isHubDryRunEnabled(env))
|
|
290
|
+
return emptyPreview(opts.scope);
|
|
291
|
+
const hub = deps.hub ?? await createDefaultHub(deps, env);
|
|
292
|
+
const store = deps.store ?? new assetstore.LocalJsonlProvider(deps.assetsDir ?? events.assetsDir());
|
|
293
|
+
if (!opts.purchasedCursor && !opts.publishedCursor) {
|
|
294
|
+
return buildSyncPreview(opts, { ...deps, env, hub, store });
|
|
295
|
+
}
|
|
296
|
+
const baseDir = storeBaseDir(store, deps);
|
|
297
|
+
const syncLedger = deps.syncLedger ?? new assetstore.AssetSyncLedger(baseDir, deps.now);
|
|
298
|
+
const inventoryKey = syncInventoryKey(opts, env, deps);
|
|
299
|
+
const inventoryScan = prepareInventoryScan(syncLedger, inventoryKey, opts);
|
|
300
|
+
return buildSyncPreview(opts, { ...deps, env, hub, store }, inventoryScan);
|
|
214
301
|
}
|
|
215
302
|
async function executeSyncWrite(opts, deps) {
|
|
216
303
|
const env = deps.env ?? process.env;
|
|
217
|
-
|
|
304
|
+
validatePrivateHubUrl(env);
|
|
218
305
|
if (isHubDryRunEnabled(env))
|
|
219
306
|
return emptyWrite(opts.scope, 'dry_run');
|
|
220
|
-
const hub = deps.hub ?? createDefaultHub(deps);
|
|
307
|
+
const hub = deps.hub ?? await createDefaultHub(deps, env);
|
|
221
308
|
if (!hasFetchAssetById(hub))
|
|
222
309
|
throw new Error('sync write requires fetchAssetById support');
|
|
223
310
|
const store = deps.store ?? new assetstore.LocalJsonlProvider(deps.assetsDir ?? events.assetsDir());
|
|
224
|
-
const
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
311
|
+
const baseDir = storeBaseDir(store, deps);
|
|
312
|
+
const provenance = deps.provenance ?? new assetstore.ProvenanceStore(baseDir, deps.now);
|
|
313
|
+
const syncLedger = deps.syncLedger ?? new assetstore.AssetSyncLedger(baseDir, deps.now);
|
|
314
|
+
const runKey = syncRunKey(opts, env, deps);
|
|
315
|
+
const inventoryKey = syncInventoryKey(opts, env, deps);
|
|
316
|
+
const inventoryScan = prepareInventoryScan(syncLedger, inventoryKey, opts);
|
|
317
|
+
const preview = await buildSyncPreview(opts, { ...deps, env, hub, store, provenance }, inventoryScan);
|
|
228
318
|
const local = await localIndex(store);
|
|
229
|
-
const
|
|
319
|
+
const provenanceSnapshot = provenance.snapshot();
|
|
320
|
+
const pendingUnverifiedRecoveryIds = await reactivatePendingUnverifiedCandidates(preview.candidates, store, provenanceSnapshot);
|
|
321
|
+
const thinFrozenRevalidationIds = reactivateThinFrozenCandidates(preview.candidates, local, provenanceSnapshot);
|
|
322
|
+
const checkpointEnabled = !preview.failures.some((failure) => failure.stage === 'list');
|
|
323
|
+
const previousRun = opts.resume && checkpointEnabled ? syncLedger.latestIncompleteRun(runKey) : null;
|
|
324
|
+
const runId = previousRun?.runId ?? randomUUID();
|
|
325
|
+
const appendRunCheckpoint = (record) => {
|
|
326
|
+
if (checkpointEnabled)
|
|
327
|
+
syncLedger.appendRun(record);
|
|
328
|
+
};
|
|
329
|
+
const resumeSelection = previousRun
|
|
330
|
+
? resumePlannedCandidates(preview.candidates, previousRun, preview.reconciliation.inventoryComplete)
|
|
331
|
+
: { candidates: preview.candidates.map((candidate) => ({ ...candidate })), remoteMissingAssetIds: [], newRemoteMissingAssetIds: [] };
|
|
332
|
+
const finalCandidates = resumeSelection.candidates;
|
|
333
|
+
const currentPlan = actionableCandidatePlanIds(finalCandidates, opts.force);
|
|
334
|
+
const runPlan = previousRun?.plan ? mergeCandidatePlan(previousRun.plan, currentPlan) : currentPlan;
|
|
335
|
+
const hasActionable = currentPlan.length > 0;
|
|
336
|
+
if (previousRun?.plan) {
|
|
337
|
+
if (runPlan.length > previousRun.plan.length) {
|
|
338
|
+
appendRunCheckpoint({ runId, runKey, state: 'started', plan: runPlan });
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
if (hasActionable && !previousRun) {
|
|
342
|
+
appendRunCheckpoint({
|
|
343
|
+
runId,
|
|
344
|
+
runKey,
|
|
345
|
+
state: 'started',
|
|
346
|
+
plan: runPlan,
|
|
347
|
+
});
|
|
348
|
+
}
|
|
349
|
+
for (const assetId of resumeSelection.newRemoteMissingAssetIds) {
|
|
350
|
+
appendRunCheckpoint({
|
|
351
|
+
runId,
|
|
352
|
+
runKey,
|
|
353
|
+
state: 'progress',
|
|
354
|
+
remoteAssetId: assetId,
|
|
355
|
+
outcome: 'remote_missing',
|
|
356
|
+
});
|
|
357
|
+
}
|
|
358
|
+
const failures = [...preview.failures];
|
|
359
|
+
const resumed = previousRun
|
|
360
|
+
? await reconcileResumeCandidates({
|
|
361
|
+
candidates: finalCandidates,
|
|
362
|
+
previousRun,
|
|
363
|
+
store,
|
|
364
|
+
provenanceSnapshot,
|
|
365
|
+
syncLedger,
|
|
366
|
+
appendRunCheckpoint,
|
|
367
|
+
runId,
|
|
368
|
+
runKey,
|
|
369
|
+
inventoryKey,
|
|
370
|
+
failures,
|
|
371
|
+
})
|
|
372
|
+
: 0;
|
|
373
|
+
await verifyAlreadyLocalCandidates(finalCandidates, store, provenanceSnapshot, failures);
|
|
230
374
|
const prepared = [];
|
|
231
375
|
const pendingLogical = new Map(local.logical);
|
|
232
376
|
for (const candidate of finalCandidates) {
|
|
233
377
|
if (candidate.action !== 'would_import' && !(opts.force && candidate.action === 'id_collision'))
|
|
234
378
|
continue;
|
|
235
|
-
const
|
|
236
|
-
if (
|
|
237
|
-
|
|
238
|
-
|
|
379
|
+
const checkpoint = previousRun?.processed.get(candidate.assetId);
|
|
380
|
+
if (checkpoint
|
|
381
|
+
&& checkpoint.outcome !== 'failed'
|
|
382
|
+
&& local.byAssetId.has(candidate.assetId)
|
|
383
|
+
&& !pendingUnverifiedRecoveryIds.has(candidate.assetId)
|
|
384
|
+
&& !thinFrozenRevalidationIds.has(candidate.assetId))
|
|
385
|
+
continue;
|
|
386
|
+
let preparedAsset;
|
|
387
|
+
try {
|
|
388
|
+
const fetched = await hub.fetchAssetById(candidate.assetId, { allowUnverifiedExactIdentity: true });
|
|
389
|
+
if (!fetched)
|
|
390
|
+
throw new SyncAbortError('not_found', 'Hub asset disappeared before import');
|
|
391
|
+
preparedAsset = prepareFetchedAsset(candidate, fetched, local.byAssetId, pendingLogical, opts.force, pendingUnverifiedRecoveryIds.has(candidate.assetId)
|
|
392
|
+
|| thinFrozenRevalidationIds.has(candidate.assetId));
|
|
393
|
+
}
|
|
394
|
+
catch (error) {
|
|
395
|
+
const mapped = mapSyncError(error);
|
|
396
|
+
failures.push({ stage: 'fetch', assetId: candidate.assetId, reason: mapped.reason });
|
|
397
|
+
appendRunCheckpoint({ runId, runKey, state: 'progress', remoteAssetId: candidate.assetId, outcome: 'failed', reason: mapped.reason });
|
|
398
|
+
updateFinalCandidate(finalCandidates, candidate, mapped.reason === 'integrity_error'
|
|
399
|
+
? { ...candidate, action: 'integrity_error' }
|
|
400
|
+
: mapped.reason === 'remote_revoked'
|
|
401
|
+
? { ...candidate, action: 'tombstone', failureReason: mapped.reason }
|
|
402
|
+
: { ...candidate, action: 'fetch_failed', failureReason: mapped.reason });
|
|
403
|
+
continue;
|
|
404
|
+
}
|
|
239
405
|
if ('blocked' in preparedAsset) {
|
|
240
406
|
updateFinalCandidate(finalCandidates, candidate, preparedAsset.blocked);
|
|
241
407
|
continue;
|
|
242
408
|
}
|
|
243
|
-
|
|
409
|
+
if (thinFrozenRevalidationIds.has(candidate.assetId)) {
|
|
410
|
+
try {
|
|
411
|
+
const persistedProvenance = provenance.get(candidate.assetId);
|
|
412
|
+
const stored = await readBackStoredAsset(store, candidate.assetId, preparedAsset.asset, false, persistedProvenance, preparedAsset.asset.type);
|
|
413
|
+
if (!preparedAsset.frozenUnverified
|
|
414
|
+
|| !preparedAsset.verificationReason
|
|
415
|
+
|| !preparedAsset.frozenContentId
|
|
416
|
+
|| !isActiveFrozenWaiver(persistedProvenance, candidate.assetId, preparedAsset.frozenContentId)
|
|
417
|
+
|| !assetstore.frozenAssetRecordsEqual(stored, preparedAsset.asset)) {
|
|
418
|
+
throw new SyncAbortError('integrity_error', 'Fetched Hub body differs from frozen local content');
|
|
419
|
+
}
|
|
420
|
+
updateFinalCandidate(finalCandidates, candidate, {
|
|
421
|
+
...candidate,
|
|
422
|
+
action: 'already_local',
|
|
423
|
+
verification: 'unverified',
|
|
424
|
+
verificationReason: preparedAsset.verificationReason,
|
|
425
|
+
});
|
|
426
|
+
appendRunCheckpoint({
|
|
427
|
+
runId,
|
|
428
|
+
runKey,
|
|
429
|
+
state: 'progress',
|
|
430
|
+
remoteAssetId: candidate.assetId,
|
|
431
|
+
outcome: 'already_local',
|
|
432
|
+
});
|
|
433
|
+
}
|
|
434
|
+
catch (error) {
|
|
435
|
+
const mapped = mapSyncError(error);
|
|
436
|
+
failures.push({ stage: 'fetch', assetId: candidate.assetId, reason: mapped.reason });
|
|
437
|
+
appendRunCheckpoint({
|
|
438
|
+
runId,
|
|
439
|
+
runKey,
|
|
440
|
+
state: 'progress',
|
|
441
|
+
remoteAssetId: candidate.assetId,
|
|
442
|
+
outcome: 'failed',
|
|
443
|
+
reason: mapped.reason,
|
|
444
|
+
});
|
|
445
|
+
updateFinalCandidate(finalCandidates, candidate, mapped.reason === 'integrity_error'
|
|
446
|
+
? { ...candidate, action: 'integrity_error', failureReason: mapped.reason }
|
|
447
|
+
: { ...candidate, action: 'fetch_failed', failureReason: mapped.reason });
|
|
448
|
+
}
|
|
449
|
+
continue;
|
|
450
|
+
}
|
|
451
|
+
const logicalId = rawStringField(preparedAsset.asset, 'id');
|
|
452
|
+
const finalCandidateBase = {
|
|
453
|
+
assetId: candidate.assetId,
|
|
454
|
+
type: candidate.type,
|
|
455
|
+
source: candidate.source,
|
|
456
|
+
...(candidate.status ? { status: candidate.status } : {}),
|
|
457
|
+
...(logicalId ? { logicalId } : {}),
|
|
458
|
+
...(preparedAsset.frozenUnverified && preparedAsset.verificationReason
|
|
459
|
+
? { verification: 'unverified', verificationReason: preparedAsset.verificationReason }
|
|
460
|
+
: {}),
|
|
461
|
+
};
|
|
244
462
|
const finalCandidate = preparedAsset.forced
|
|
245
463
|
? {
|
|
246
|
-
...
|
|
247
|
-
...(logicalId ? { logicalId } : {}),
|
|
464
|
+
...finalCandidateBase,
|
|
248
465
|
action: 'force_import',
|
|
249
466
|
collisionWithAssetId: preparedAsset.collisionWithAssetId,
|
|
250
467
|
}
|
|
251
|
-
: {
|
|
252
|
-
assetId: candidate.assetId,
|
|
253
|
-
type: candidate.type,
|
|
254
|
-
source: candidate.source,
|
|
255
|
-
...(candidate.status ? { status: candidate.status } : {}),
|
|
256
|
-
...(logicalId ? { logicalId } : {}),
|
|
257
|
-
action: 'would_import',
|
|
258
|
-
};
|
|
468
|
+
: { ...finalCandidateBase, action: 'would_import' };
|
|
259
469
|
updateFinalCandidate(finalCandidates, candidate, finalCandidate);
|
|
260
470
|
prepared.push({
|
|
261
471
|
candidate: finalCandidate,
|
|
262
472
|
asset: preparedAsset.asset,
|
|
473
|
+
...(preparedAsset.frozenUnverified ? { frozenUnverified: true } : {}),
|
|
474
|
+
...(preparedAsset.verificationReason ? { verificationReason: preparedAsset.verificationReason } : {}),
|
|
475
|
+
...(preparedAsset.frozenContentId ? { frozenContentId: preparedAsset.frozenContentId } : {}),
|
|
263
476
|
...(preparedAsset.forced ? { forced: true, collisionWithAssetId: preparedAsset.collisionWithAssetId } : {}),
|
|
264
477
|
});
|
|
265
478
|
if (logicalId)
|
|
266
479
|
pendingLogical.set(`${preparedAsset.asset.type}:${logicalId}`, preparedAsset.asset.asset_id);
|
|
267
480
|
}
|
|
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
481
|
const written = [];
|
|
272
482
|
for (const item of prepared) {
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
483
|
+
try {
|
|
484
|
+
const stored = item.frozenUnverified && item.verificationReason
|
|
485
|
+
? await assetstore.ingestUnverifiedConditional(store, provenance, item.asset, item.verificationReason, { allowLogicalCollision: opts.force }, 'hub')
|
|
486
|
+
: await assetstore.ingestUntrustedConditional(store, provenance, item.asset, { allowLogicalCollision: opts.force }, 'hub');
|
|
487
|
+
const assetId = stored.asset_id;
|
|
488
|
+
if (stored.status === 'logical_collision') {
|
|
489
|
+
updateFinalCandidate(finalCandidates, item.candidate, {
|
|
490
|
+
...item.candidate,
|
|
491
|
+
assetId,
|
|
492
|
+
action: 'id_collision',
|
|
493
|
+
collisionWithAssetId: stored.collisionWithAssetId,
|
|
494
|
+
});
|
|
495
|
+
continue;
|
|
496
|
+
}
|
|
497
|
+
const persistedProvenance = provenance.get(assetId);
|
|
498
|
+
await readBackStoredAsset(store, assetId, item.asset, false, persistedProvenance, item.asset.type);
|
|
499
|
+
if (stored.status === 'already_exists') {
|
|
500
|
+
updateFinalCandidate(finalCandidates, item.candidate, { ...item.candidate, assetId, action: 'already_local' });
|
|
501
|
+
if (item.frozenUnverified && !syncLedger.getForRunKey(runKey, assetId)) {
|
|
502
|
+
appendSyncRecord(syncLedger, item.candidate, item.asset, runKey, inventoryKey, {
|
|
503
|
+
...(item.forced ? { forced: true } : {}),
|
|
504
|
+
...(item.collisionWithAssetId ? { collisionWithAssetId: item.collisionWithAssetId } : {}),
|
|
505
|
+
});
|
|
506
|
+
}
|
|
507
|
+
appendRunCheckpoint({
|
|
508
|
+
runId,
|
|
509
|
+
runKey,
|
|
510
|
+
state: 'progress',
|
|
511
|
+
remoteAssetId: item.candidate.assetId,
|
|
512
|
+
outcome: item.frozenUnverified ? 'imported' : 'already_local',
|
|
513
|
+
});
|
|
514
|
+
continue;
|
|
515
|
+
}
|
|
516
|
+
const collisionWithAssetId = stored.collisionWithAssetId ?? item.collisionWithAssetId;
|
|
517
|
+
const forced = item.forced === true || collisionWithAssetId !== undefined;
|
|
518
|
+
const writtenCandidate = forced
|
|
519
|
+
? { ...item.candidate, action: 'force_import', collisionWithAssetId }
|
|
520
|
+
: item.candidate;
|
|
521
|
+
updateFinalCandidate(finalCandidates, item.candidate, writtenCandidate);
|
|
522
|
+
appendSyncRecord(syncLedger, writtenCandidate, item.asset, runKey, inventoryKey, {
|
|
523
|
+
...(forced ? { forced: true } : {}),
|
|
524
|
+
...(collisionWithAssetId ? { collisionWithAssetId } : {}),
|
|
525
|
+
});
|
|
526
|
+
appendRunCheckpoint({ runId, runKey, state: 'progress', remoteAssetId: item.candidate.assetId, outcome: 'imported' });
|
|
527
|
+
written.push({
|
|
528
|
+
assetId,
|
|
529
|
+
type: item.asset.type,
|
|
530
|
+
source: writtenCandidate.source,
|
|
531
|
+
stored: true,
|
|
532
|
+
trusted: false,
|
|
533
|
+
verification: item.frozenUnverified ? 'unverified' : 'verified',
|
|
534
|
+
...(item.verificationReason ? { verificationReason: item.verificationReason } : {}),
|
|
535
|
+
...(item.frozenContentId ? { frozenContentId: item.frozenContentId } : {}),
|
|
536
|
+
...(writtenCandidate.logicalId ? { logicalId: writtenCandidate.logicalId } : {}),
|
|
537
|
+
...(writtenCandidate.status ? { status: writtenCandidate.status } : {}),
|
|
538
|
+
...(forced ? { forced: true } : {}),
|
|
539
|
+
...(collisionWithAssetId ? { collisionWithAssetId } : {}),
|
|
540
|
+
});
|
|
541
|
+
}
|
|
542
|
+
catch (error) {
|
|
543
|
+
const mapped = mapSyncError(error);
|
|
544
|
+
failures.push({ stage: 'write', assetId: item.candidate.assetId, reason: mapped.reason });
|
|
545
|
+
appendRunCheckpoint({ runId, runKey, state: 'progress', remoteAssetId: item.candidate.assetId, outcome: 'failed', reason: mapped.reason });
|
|
546
|
+
updateFinalCandidate(finalCandidates, item.candidate, mapped.reason === 'integrity_error'
|
|
547
|
+
? { ...item.candidate, action: 'integrity_error', failureReason: mapped.reason }
|
|
548
|
+
: { ...item.candidate, action: 'write_failed', failureReason: mapped.reason });
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
const retryableInventoryFailure = failures.some(isRetryableAssetFailure);
|
|
552
|
+
let inventoryComplete = preview.reconciliation.inventoryComplete;
|
|
553
|
+
if (retryableInventoryFailure)
|
|
554
|
+
inventoryComplete = false;
|
|
555
|
+
let remoteAssetIds = new Set(finalCandidates.flatMap((candidate) => (candidate.assetId === MISSING_ASSET_ID ? [] : [candidate.assetId])));
|
|
556
|
+
let missingRemote = inventoryComplete
|
|
557
|
+
? countMissingRemote(syncLedger, inventoryKey, runKey, local.byAssetId, remoteAssetIds)
|
|
558
|
+
: 0;
|
|
559
|
+
let reconciliation;
|
|
560
|
+
let inventoryCheckpointFailed = false;
|
|
561
|
+
if (inventoryScan.trackable
|
|
562
|
+
&& inventoryScan.index === 0
|
|
563
|
+
&& !inventoryScan.retry
|
|
564
|
+
&& inventoryComplete
|
|
565
|
+
&& !failures.some((failure) => failure.stage === 'list')) {
|
|
566
|
+
try {
|
|
567
|
+
syncLedger.clearInventoryScan(inventoryKey);
|
|
568
|
+
}
|
|
569
|
+
catch {
|
|
570
|
+
failures.push({ stage: 'list', reason: 'inventory_scan_checkpoint_failed' });
|
|
571
|
+
inventoryComplete = false;
|
|
572
|
+
missingRemote = 0;
|
|
573
|
+
inventoryCheckpointFailed = true;
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
const shouldCheckpointInventory = inventoryScan.trackable
|
|
577
|
+
&& !inventoryCheckpointFailed
|
|
578
|
+
&& !failures.some((failure) => failure.stage === 'list')
|
|
579
|
+
&& (!inventoryComplete || inventoryScan.index > 0 || inventoryScan.retry);
|
|
580
|
+
if (shouldCheckpointInventory) {
|
|
581
|
+
const segment = inventorySegmentOutcome(finalCandidates, failures, written);
|
|
582
|
+
const inventoryBatch = {
|
|
583
|
+
scanId: inventoryScan.scanId,
|
|
584
|
+
inventoryKey,
|
|
585
|
+
scope: opts.scope,
|
|
586
|
+
index: inventoryScan.index,
|
|
587
|
+
inputCursorFingerprints: inventoryScan.inputCursorFingerprints,
|
|
588
|
+
nextCursorFingerprints: retryableInventoryFailure
|
|
589
|
+
? inventoryScan.inputCursorFingerprints
|
|
590
|
+
: fingerprintCursors(preview.nextCursors),
|
|
591
|
+
items: segment.items,
|
|
592
|
+
anonymousBlocked: segment.anonymousBlocked,
|
|
593
|
+
...(retryableInventoryFailure ? { cursorHeld: true } : {}),
|
|
594
|
+
};
|
|
595
|
+
const appended = inventoryScan.retry
|
|
596
|
+
? syncLedger.replaceInventoryRetryBatch(inventoryBatch)
|
|
597
|
+
: syncLedger.appendInventoryBatch(inventoryBatch);
|
|
598
|
+
const snapshot = appended ? syncLedger.latestInventoryScan(inventoryKey) : undefined;
|
|
599
|
+
if (!snapshot || snapshot.scanId !== inventoryScan.scanId) {
|
|
600
|
+
failures.push({ stage: 'list', reason: 'inventory_scan_checkpoint_failed' });
|
|
601
|
+
inventoryComplete = false;
|
|
602
|
+
missingRemote = 0;
|
|
603
|
+
inventoryCheckpointFailed = true;
|
|
604
|
+
}
|
|
605
|
+
else if (snapshot.complete) {
|
|
606
|
+
inventoryComplete = true;
|
|
607
|
+
remoteAssetIds = new Set(snapshot.outcomes.keys());
|
|
608
|
+
missingRemote = countMissingRemote(syncLedger, inventoryKey, runKey, local.byAssetId, remoteAssetIds);
|
|
609
|
+
reconciliation = reconcileInventorySnapshot(snapshot, missingRemote);
|
|
278
610
|
}
|
|
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
611
|
}
|
|
612
|
+
reconciliation ??= reconcile(finalCandidates, failures, written.length, true, inventoryComplete, missingRemote);
|
|
302
613
|
const counts = countsFromCandidates(preview.counts, finalCandidates);
|
|
303
614
|
const blocked = finalCandidates.filter(isBlockedCandidate);
|
|
615
|
+
const failedAssetIds = new Set(failures.flatMap((failure) => failure.assetId ? [failure.assetId] : []));
|
|
616
|
+
const finalCandidatesByAssetId = new Map(finalCandidates.map((candidate) => [candidate.assetId, candidate]));
|
|
617
|
+
const writtenAssetIds = new Set(written.map((asset) => asset.assetId));
|
|
618
|
+
const remoteMissingAssetIds = new Set(resumeSelection.remoteMissingAssetIds);
|
|
619
|
+
const actionComplete = runPlan.every((assetId) => {
|
|
620
|
+
if (remoteMissingAssetIds.has(assetId))
|
|
621
|
+
return true;
|
|
622
|
+
if (failedAssetIds.has(assetId))
|
|
623
|
+
return false;
|
|
624
|
+
if (local.byAssetId.has(assetId) || writtenAssetIds.has(assetId))
|
|
625
|
+
return true;
|
|
626
|
+
const candidate = finalCandidatesByAssetId.get(assetId);
|
|
627
|
+
return candidate?.action === 'already_local' || (candidate !== undefined && isBlockedCandidate(candidate));
|
|
628
|
+
});
|
|
629
|
+
if ((hasActionable || previousRun) && actionComplete && !inventoryCheckpointFailed) {
|
|
630
|
+
appendRunCheckpoint({ runId, runKey, state: 'completed' });
|
|
631
|
+
}
|
|
304
632
|
return {
|
|
305
633
|
ok: true,
|
|
306
634
|
group: GROUP,
|
|
@@ -310,6 +638,10 @@ async function executeSyncWrite(opts, deps) {
|
|
|
310
638
|
candidates: finalCandidates,
|
|
311
639
|
written,
|
|
312
640
|
blocked,
|
|
641
|
+
failures,
|
|
642
|
+
nextCursors: preview.nextCursors,
|
|
643
|
+
resumed,
|
|
644
|
+
reconciliation,
|
|
313
645
|
};
|
|
314
646
|
}
|
|
315
647
|
async function executeSyncExport(opts, deps) {
|
|
@@ -332,12 +664,23 @@ async function executeSyncExport(opts, deps) {
|
|
|
332
664
|
version: GEPX_VERSION,
|
|
333
665
|
exportedAt: new Date(deps.now ? deps.now() : Date.now()).toISOString(),
|
|
334
666
|
assets,
|
|
667
|
+
malformedAssets: [],
|
|
335
668
|
provenance: provenanceRecords,
|
|
336
669
|
sync: syncRecords,
|
|
337
670
|
};
|
|
671
|
+
let serialized;
|
|
672
|
+
try {
|
|
673
|
+
serialized = `${JSON.stringify(pkg, null, 2)}\n`;
|
|
674
|
+
}
|
|
675
|
+
catch {
|
|
676
|
+
throw new SyncAbortError('export_failed', 'could not serialize .gepx package');
|
|
677
|
+
}
|
|
678
|
+
if (Buffer.byteLength(serialized, 'utf8') > MAX_GEPX_BYTES) {
|
|
679
|
+
throw new SyncAbortError('gepx_too_large', '.gepx package exceeds the 64 MiB limit');
|
|
680
|
+
}
|
|
338
681
|
try {
|
|
339
682
|
mkdirSync(dirname(opts.exportPath), { recursive: true });
|
|
340
|
-
writeFileSync(opts.exportPath,
|
|
683
|
+
writeFileSync(opts.exportPath, serialized, 'utf8');
|
|
341
684
|
}
|
|
342
685
|
catch {
|
|
343
686
|
throw new SyncAbortError('export_failed', 'could not write .gepx file');
|
|
@@ -354,7 +697,7 @@ async function executeSyncExport(opts, deps) {
|
|
|
354
697
|
assets: assets.map((asset) => ({
|
|
355
698
|
assetId: asset.asset_id,
|
|
356
699
|
type: asset.type,
|
|
357
|
-
...(
|
|
700
|
+
...(rawStringField(asset, 'id') ? { logicalId: rawStringField(asset, 'id') } : {}),
|
|
358
701
|
trusted: provenanceSnapshot.get(asset.asset_id)?.trusted ?? true,
|
|
359
702
|
synced: Boolean(syncLedger.get(asset.asset_id)),
|
|
360
703
|
})),
|
|
@@ -369,10 +712,17 @@ async function buildGepxImportPreview(opts, deps) {
|
|
|
369
712
|
}
|
|
370
713
|
async function executeGepxImportWrite(opts, deps) {
|
|
371
714
|
const pkg = readGepxPackage(opts.importPath);
|
|
372
|
-
|
|
715
|
+
assertNoConflictingGepxDuplicates(pkg);
|
|
373
716
|
const store = deps.store ?? new assetstore.LocalJsonlProvider(deps.assetsDir ?? events.assetsDir());
|
|
374
717
|
const local = await localIndex(store);
|
|
375
718
|
const finalCandidates = classifyGepxAssets(pkg, opts, local);
|
|
719
|
+
const failures = finalCandidates
|
|
720
|
+
.filter((candidate) => candidate.action === 'integrity_error')
|
|
721
|
+
.map((candidate) => ({
|
|
722
|
+
stage: 'write',
|
|
723
|
+
...(candidate.assetId.startsWith(MISSING_ASSET_ID) ? {} : { assetId: candidate.assetId }),
|
|
724
|
+
reason: candidate.failureReason ?? 'integrity_error',
|
|
725
|
+
}));
|
|
376
726
|
const assetsById = gepxImportAssetsById(pkg);
|
|
377
727
|
const syncById = new Map((pkg.sync ?? []).map((record) => [record.assetId, record]));
|
|
378
728
|
const prepared = [];
|
|
@@ -380,15 +730,15 @@ async function executeGepxImportWrite(opts, deps) {
|
|
|
380
730
|
for (const candidate of finalCandidates) {
|
|
381
731
|
if (candidate.action !== 'would_import' && !(opts.force && candidate.action === 'id_collision'))
|
|
382
732
|
continue;
|
|
383
|
-
const
|
|
384
|
-
if (!
|
|
733
|
+
const entry = assetsById.get(candidate.assetId);
|
|
734
|
+
if (!entry)
|
|
385
735
|
throw new SyncAbortError('integrity_error', '.gepx package asset is missing');
|
|
386
|
-
const preparedAsset = preparePackagedAsset(candidate, asset, local.byAssetId, pendingLogical, opts.force);
|
|
736
|
+
const preparedAsset = preparePackagedAsset(candidate, entry.asset, local.byAssetId, pendingLogical, opts.force, entry.frozenUnverified);
|
|
387
737
|
if ('blocked' in preparedAsset) {
|
|
388
738
|
updateFinalCandidate(finalCandidates, candidate, preparedAsset.blocked);
|
|
389
739
|
continue;
|
|
390
740
|
}
|
|
391
|
-
const logicalId =
|
|
741
|
+
const logicalId = rawStringField(preparedAsset.asset, 'id');
|
|
392
742
|
const finalCandidate = preparedAsset.forced
|
|
393
743
|
? {
|
|
394
744
|
...candidate,
|
|
@@ -408,6 +758,7 @@ async function executeGepxImportWrite(opts, deps) {
|
|
|
408
758
|
prepared.push({
|
|
409
759
|
candidate: finalCandidate,
|
|
410
760
|
asset: preparedAsset.asset,
|
|
761
|
+
...(entry.frozenUnverified ? { frozenUnverified: true } : {}),
|
|
411
762
|
...(preparedAsset.forced ? { forced: true, collisionWithAssetId: preparedAsset.collisionWithAssetId } : {}),
|
|
412
763
|
});
|
|
413
764
|
if (logicalId)
|
|
@@ -416,39 +767,69 @@ async function executeGepxImportWrite(opts, deps) {
|
|
|
416
767
|
const baseDir = storeBaseDir(store, deps);
|
|
417
768
|
const provenance = deps.provenance ?? new assetstore.ProvenanceStore(baseDir, deps.now);
|
|
418
769
|
const syncLedger = deps.syncLedger ?? new assetstore.AssetSyncLedger(baseDir, deps.now);
|
|
770
|
+
await verifyAlreadyLocalGepxCandidates(finalCandidates, assetsById, store, provenance.snapshot(), failures);
|
|
419
771
|
const written = [];
|
|
420
772
|
for (const item of prepared) {
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
773
|
+
try {
|
|
774
|
+
const stored = item.frozenUnverified
|
|
775
|
+
? await assetstore.ingestUnverifiedConditional(store, provenance, item.asset, 'unverified_gepx_import', { allowLogicalCollision: opts.force }, 'migrated')
|
|
776
|
+
: await assetstore.ingestUntrustedConditional(store, provenance, item.asset, { allowLogicalCollision: opts.force }, 'migrated');
|
|
777
|
+
const assetId = stored.asset_id;
|
|
778
|
+
if (stored.status === 'logical_collision') {
|
|
779
|
+
updateFinalCandidate(finalCandidates, item.candidate, {
|
|
780
|
+
...item.candidate,
|
|
781
|
+
assetId,
|
|
782
|
+
action: 'id_collision',
|
|
783
|
+
collisionWithAssetId: stored.collisionWithAssetId,
|
|
784
|
+
});
|
|
785
|
+
continue;
|
|
786
|
+
}
|
|
787
|
+
await readBackStoredAsset(store, assetId, item.asset, item.frozenUnverified === true);
|
|
788
|
+
if (stored.status === 'already_exists') {
|
|
789
|
+
updateFinalCandidate(finalCandidates, item.candidate, { ...item.candidate, assetId, action: 'already_local' });
|
|
790
|
+
continue;
|
|
791
|
+
}
|
|
792
|
+
const collisionWithAssetId = stored.collisionWithAssetId ?? item.collisionWithAssetId;
|
|
793
|
+
const forced = item.forced === true || collisionWithAssetId !== undefined;
|
|
794
|
+
const writtenCandidate = forced
|
|
795
|
+
? { ...item.candidate, action: 'force_import', collisionWithAssetId }
|
|
796
|
+
: item.candidate;
|
|
797
|
+
updateFinalCandidate(finalCandidates, item.candidate, writtenCandidate);
|
|
798
|
+
const syncRecord = syncById.get(assetId);
|
|
799
|
+
if (syncRecord)
|
|
800
|
+
syncLedger.append({
|
|
801
|
+
assetId,
|
|
802
|
+
type: item.asset.type,
|
|
803
|
+
source: 'hub',
|
|
804
|
+
scope: syncRecord.scope,
|
|
805
|
+
remoteAssetId: syncRecord.remoteAssetId,
|
|
806
|
+
...(syncRecord.logicalId ? { logicalId: syncRecord.logicalId } : {}),
|
|
807
|
+
...(syncRecord.status ? { status: syncRecord.status } : {}),
|
|
808
|
+
...(syncRecord.syncedAt ? { syncedAt: syncRecord.syncedAt } : {}),
|
|
809
|
+
...(syncRecord.forced ? { forced: true } : {}),
|
|
810
|
+
...(syncRecord.collisionWithAssetId ? { collisionWithAssetId: syncRecord.collisionWithAssetId } : {}),
|
|
811
|
+
});
|
|
812
|
+
written.push({
|
|
430
813
|
assetId,
|
|
431
814
|
type: item.asset.type,
|
|
432
|
-
source: '
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
...(
|
|
436
|
-
...(
|
|
437
|
-
...(
|
|
438
|
-
...(
|
|
439
|
-
...(syncRecord.collisionWithAssetId ? { collisionWithAssetId: syncRecord.collisionWithAssetId } : {}),
|
|
815
|
+
source: 'gepx',
|
|
816
|
+
stored: stored.stored,
|
|
817
|
+
trusted: false,
|
|
818
|
+
...(writtenCandidate.logicalId ? { logicalId: writtenCandidate.logicalId } : {}),
|
|
819
|
+
...(writtenCandidate.status ? { status: writtenCandidate.status } : {}),
|
|
820
|
+
...(forced ? { forced: true } : {}),
|
|
821
|
+
...(collisionWithAssetId ? { collisionWithAssetId } : {}),
|
|
440
822
|
});
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
});
|
|
823
|
+
}
|
|
824
|
+
catch (error) {
|
|
825
|
+
const mapped = mapSyncError(error);
|
|
826
|
+
failures.push({ stage: 'write', assetId: item.candidate.assetId, reason: mapped.reason });
|
|
827
|
+
updateFinalCandidate(finalCandidates, item.candidate, {
|
|
828
|
+
...item.candidate,
|
|
829
|
+
action: 'write_failed',
|
|
830
|
+
failureReason: mapped.reason,
|
|
831
|
+
});
|
|
832
|
+
}
|
|
452
833
|
}
|
|
453
834
|
const counts = countsFromCandidates(emptyCounts(finalCandidates.length), finalCandidates);
|
|
454
835
|
return {
|
|
@@ -459,6 +840,7 @@ async function executeGepxImportWrite(opts, deps) {
|
|
|
459
840
|
candidates: finalCandidates,
|
|
460
841
|
written,
|
|
461
842
|
blocked: finalCandidates.filter(isBlockedCandidate),
|
|
843
|
+
failures,
|
|
462
844
|
};
|
|
463
845
|
}
|
|
464
846
|
function emptyPreview(scope) {
|
|
@@ -472,13 +854,32 @@ function emptyPreview(scope) {
|
|
|
472
854
|
remotePublished: 0,
|
|
473
855
|
uniqueRemote: 0,
|
|
474
856
|
alreadyLocal: 0,
|
|
857
|
+
tombstone: 0,
|
|
475
858
|
idCollision: 0,
|
|
476
859
|
unsupported: 0,
|
|
477
860
|
integrityError: 0,
|
|
478
861
|
wouldImport: 0,
|
|
862
|
+
unverifiedWouldImport: 0,
|
|
479
863
|
forcedImport: 0,
|
|
864
|
+
skippedLimit: 0,
|
|
865
|
+
fetchFailed: 0,
|
|
866
|
+
writeFailed: 0,
|
|
480
867
|
},
|
|
481
868
|
candidates: [],
|
|
869
|
+
failures: [],
|
|
870
|
+
nextCursors: { purchased: null, published: null },
|
|
871
|
+
reconciliation: {
|
|
872
|
+
remoteUnique: 0,
|
|
873
|
+
accounted: 0,
|
|
874
|
+
imported: 0,
|
|
875
|
+
alreadyLocal: 0,
|
|
876
|
+
blocked: 0,
|
|
877
|
+
failed: 0,
|
|
878
|
+
pending: 0,
|
|
879
|
+
inventoryComplete: true,
|
|
880
|
+
missingRemote: 0,
|
|
881
|
+
consistent: false,
|
|
882
|
+
},
|
|
482
883
|
};
|
|
483
884
|
}
|
|
484
885
|
function emptyCounts(uniqueRemote = 0) {
|
|
@@ -487,11 +888,16 @@ function emptyCounts(uniqueRemote = 0) {
|
|
|
487
888
|
remotePublished: 0,
|
|
488
889
|
uniqueRemote,
|
|
489
890
|
alreadyLocal: 0,
|
|
891
|
+
tombstone: 0,
|
|
490
892
|
idCollision: 0,
|
|
491
893
|
unsupported: 0,
|
|
492
894
|
integrityError: 0,
|
|
493
895
|
wouldImport: 0,
|
|
896
|
+
unverifiedWouldImport: 0,
|
|
494
897
|
forcedImport: 0,
|
|
898
|
+
skippedLimit: 0,
|
|
899
|
+
fetchFailed: 0,
|
|
900
|
+
writeFailed: 0,
|
|
495
901
|
};
|
|
496
902
|
}
|
|
497
903
|
function emptyWrite(scope, mode = 'write') {
|
|
@@ -500,69 +906,290 @@ function emptyWrite(scope, mode = 'write') {
|
|
|
500
906
|
mode,
|
|
501
907
|
written: [],
|
|
502
908
|
blocked: [],
|
|
909
|
+
resumed: 0,
|
|
503
910
|
};
|
|
504
911
|
}
|
|
505
|
-
function createDefaultHub(deps) {
|
|
506
|
-
|
|
912
|
+
async function createDefaultHub(deps, env) {
|
|
913
|
+
if (isPrivateHubMode(env)) {
|
|
914
|
+
try {
|
|
915
|
+
const hubUrl = requirePrivateHubUrl(env);
|
|
916
|
+
if (deps.connectPrivateHub)
|
|
917
|
+
return await deps.connectPrivateHub(env);
|
|
918
|
+
const { connectPrivateProxyHub } = await import('@evomap/evolver-proxy');
|
|
919
|
+
const runtime = await connectPrivateProxyHub({
|
|
920
|
+
hubUrl,
|
|
921
|
+
senderId: () => env['EVOMAP_NODE_ID'] ?? env['A2A_NODE_ID'],
|
|
922
|
+
env,
|
|
923
|
+
...(deps.now ? { now: deps.now } : {}),
|
|
924
|
+
});
|
|
925
|
+
return await preparePrivateSyncHub(runtime);
|
|
926
|
+
}
|
|
927
|
+
catch {
|
|
928
|
+
// Adapter diagnostics may contain local paths or credentials; never expose them through the CLI.
|
|
929
|
+
throw new SyncAbortError('private_adapter_unavailable', 'private Hub adapter is unavailable');
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
const hub = createRecipeHubFromEnv(env, deps.connectHub ?? connectPublicHub);
|
|
933
|
+
if (!isSyncAccountAssetHub(hub))
|
|
934
|
+
throw new Error('Hub adapter does not support account asset sync');
|
|
507
935
|
return hub;
|
|
508
936
|
}
|
|
509
|
-
async function
|
|
510
|
-
const
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
937
|
+
export async function preparePrivateSyncHub(runtime) {
|
|
938
|
+
const hello = await runtime.hello({ rotate: false, evolverVersion: getCliVersion() });
|
|
939
|
+
if (!hello.ok)
|
|
940
|
+
throw new Error('private Hub enrollment failed');
|
|
941
|
+
if (!isSyncAccountAssetHub(runtime.hub))
|
|
942
|
+
throw new Error('private Hub adapter does not support account asset sync');
|
|
943
|
+
return runtime.hub;
|
|
944
|
+
}
|
|
945
|
+
async function listRemoteRows(hub, opts, listing) {
|
|
946
|
+
const failures = [];
|
|
947
|
+
const purchasedBudget = { uniqueAssetIds: new Set(), rawPages: 0, rawRows: 0 };
|
|
948
|
+
const publishedBudget = { uniqueAssetIds: new Set(), rawPages: 0, rawRows: 0 };
|
|
949
|
+
const purchasedResult = (opts.scope === 'all' || opts.scope === 'purchased') && !listing.skipPurchased
|
|
950
|
+
? await listAll(hub, {
|
|
951
|
+
scope: 'purchased',
|
|
952
|
+
...(opts.type ? { type: opts.type } : {}),
|
|
953
|
+
limit: opts.limit,
|
|
954
|
+
...(opts.purchasedCursor ? { cursor: opts.purchasedCursor } : {}),
|
|
955
|
+
}, opts.pageSize, failures, purchasedBudget)
|
|
956
|
+
: { rows: [], complete: true, nextCursor: undefined };
|
|
957
|
+
const shouldListPublished = (opts.scope === 'all' || opts.scope === 'published') && !listing.skipPublished;
|
|
958
|
+
const publishedResult = shouldListPublished
|
|
516
959
|
? await listAll(hub, {
|
|
517
960
|
scope: 'published',
|
|
518
961
|
...(opts.type ? { type: opts.type } : {}),
|
|
519
962
|
status: opts.status,
|
|
520
|
-
limit:
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
963
|
+
limit: opts.limit,
|
|
964
|
+
...(opts.publishedCursor ? { cursor: opts.publishedCursor } : {}),
|
|
965
|
+
}, opts.pageSize, failures, publishedBudget)
|
|
966
|
+
: { rows: [], complete: true, nextCursor: undefined };
|
|
967
|
+
const startsAtInventoryBeginning = !opts.purchasedCursor && !opts.publishedCursor;
|
|
968
|
+
return {
|
|
969
|
+
purchased: purchasedResult.rows,
|
|
970
|
+
published: publishedResult.rows,
|
|
971
|
+
failures,
|
|
972
|
+
inventoryComplete: startsAtInventoryBeginning && purchasedResult.complete && publishedResult.complete && failures.length === 0,
|
|
973
|
+
nextCursors: {
|
|
974
|
+
purchased: purchasedResult.nextCursor ?? null,
|
|
975
|
+
published: publishedResult.nextCursor ?? null,
|
|
976
|
+
},
|
|
977
|
+
};
|
|
524
978
|
}
|
|
525
|
-
async function listAll(hub, opts) {
|
|
979
|
+
async function listAll(hub, opts, pageSize, failures, budget) {
|
|
526
980
|
const rows = [];
|
|
527
981
|
let cursor = opts.cursor;
|
|
528
982
|
const seenCursors = new Set();
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
983
|
+
let consecutiveEmptyPages = 0;
|
|
984
|
+
let consecutivePagesWithoutUniqueProgress = 0;
|
|
985
|
+
while (budget.uniqueAssetIds.size < opts.limit) {
|
|
986
|
+
if (budget.rawPages >= MAX_RAW_PAGES) {
|
|
987
|
+
failures.push({ stage: 'list', scope: opts.scope, reason: 'raw_page_limit' });
|
|
988
|
+
break;
|
|
989
|
+
}
|
|
990
|
+
if (budget.rawRows >= MAX_RAW_ROWS) {
|
|
991
|
+
failures.push({ stage: 'list', scope: opts.scope, reason: 'raw_row_limit' });
|
|
992
|
+
break;
|
|
993
|
+
}
|
|
994
|
+
const remaining = opts.limit - budget.uniqueAssetIds.size;
|
|
995
|
+
const requestedPageLimit = Math.min(remaining, pageSize);
|
|
996
|
+
let rawResult;
|
|
997
|
+
try {
|
|
998
|
+
rawResult = await hub.listAccountAssets({ ...opts, limit: requestedPageLimit, ...(cursor ? { cursor } : {}) });
|
|
999
|
+
budget.rawPages += 1;
|
|
1000
|
+
}
|
|
1001
|
+
catch (error) {
|
|
1002
|
+
failures.push({ stage: 'list', scope: opts.scope, reason: mapSyncError(error).reason });
|
|
535
1003
|
break;
|
|
536
|
-
|
|
1004
|
+
}
|
|
1005
|
+
const result = asRecord(rawResult);
|
|
1006
|
+
if (!result || !Array.isArray(result['assets']) || typeof result['hasMore'] !== 'boolean') {
|
|
1007
|
+
failures.push({ stage: 'list', scope: opts.scope, reason: 'malformed_page' });
|
|
1008
|
+
break;
|
|
1009
|
+
}
|
|
1010
|
+
const hasMore = result['hasMore'];
|
|
1011
|
+
const nextCursor = result['nextCursor'];
|
|
1012
|
+
const pageRows = result['assets'];
|
|
1013
|
+
if (pageRows.length > requestedPageLimit) {
|
|
1014
|
+
failures.push({ stage: 'list', scope: opts.scope, reason: 'oversized_page' });
|
|
1015
|
+
break;
|
|
1016
|
+
}
|
|
1017
|
+
const availableRawRows = MAX_RAW_ROWS - budget.rawRows;
|
|
1018
|
+
const boundedPageRows = pageRows.slice(0, availableRawRows);
|
|
1019
|
+
budget.rawRows += boundedPageRows.length;
|
|
1020
|
+
const uniqueBefore = budget.uniqueAssetIds.size;
|
|
1021
|
+
let consumedPageRows = 0;
|
|
1022
|
+
// The page is bounded by the remaining unique budget, so consuming it fully cannot exceed the limit.
|
|
1023
|
+
for (const raw of boundedPageRows) {
|
|
1024
|
+
consumedPageRows += 1;
|
|
1025
|
+
const row = asRecord(raw);
|
|
1026
|
+
if (!row) {
|
|
1027
|
+
failures.push({ stage: 'list', scope: opts.scope, reason: 'invalid_remote_asset' });
|
|
1028
|
+
continue;
|
|
1029
|
+
}
|
|
1030
|
+
rows.push(row);
|
|
1031
|
+
const assetId = rawStringField(row, 'asset_id');
|
|
1032
|
+
if (assetId)
|
|
1033
|
+
budget.uniqueAssetIds.add(assetId);
|
|
1034
|
+
}
|
|
1035
|
+
const uniqueProgress = budget.uniqueAssetIds.size - uniqueBefore;
|
|
1036
|
+
if ((!hasMore && nextCursor !== undefined) || (hasMore && (typeof nextCursor !== 'string' || !nextCursor.trim()))) {
|
|
1037
|
+
failures.push({ stage: 'list', scope: opts.scope, reason: 'invalid_remote_pagination' });
|
|
1038
|
+
break;
|
|
1039
|
+
}
|
|
1040
|
+
if (hasMore && typeof nextCursor === 'string' && !isValidOpaqueCursor(nextCursor)) {
|
|
1041
|
+
failures.push({ stage: 'list', scope: opts.scope, reason: 'malformed_cursor' });
|
|
537
1042
|
break;
|
|
1043
|
+
}
|
|
1044
|
+
if (!hasMore) {
|
|
1045
|
+
return { rows, complete: consumedPageRows === pageRows.length, nextCursor: undefined };
|
|
1046
|
+
}
|
|
1047
|
+
if (typeof nextCursor !== 'string' || !nextCursor.trim()) {
|
|
1048
|
+
failures.push({ stage: 'list', scope: opts.scope, reason: 'invalid_remote_pagination' });
|
|
1049
|
+
break;
|
|
1050
|
+
}
|
|
1051
|
+
if (boundedPageRows.length < pageRows.length || budget.rawRows >= MAX_RAW_ROWS) {
|
|
1052
|
+
failures.push({ stage: 'list', scope: opts.scope, reason: 'raw_row_limit' });
|
|
1053
|
+
break;
|
|
1054
|
+
}
|
|
1055
|
+
consecutiveEmptyPages = pageRows.length === 0 ? consecutiveEmptyPages + 1 : 0;
|
|
1056
|
+
if (consecutiveEmptyPages > MAX_CONSECUTIVE_EMPTY_PAGES) {
|
|
1057
|
+
failures.push({ stage: 'list', scope: opts.scope, reason: 'empty_page_limit' });
|
|
1058
|
+
break;
|
|
1059
|
+
}
|
|
1060
|
+
consecutivePagesWithoutUniqueProgress = uniqueProgress === 0 ? consecutivePagesWithoutUniqueProgress + 1 : 0;
|
|
1061
|
+
if (consecutivePagesWithoutUniqueProgress > MAX_CONSECUTIVE_PAGES_WITHOUT_UNIQUE_PROGRESS) {
|
|
1062
|
+
failures.push({ stage: 'list', scope: opts.scope, reason: 'no_unique_progress_limit' });
|
|
1063
|
+
break;
|
|
1064
|
+
}
|
|
1065
|
+
if (nextCursor === cursor || seenCursors.has(nextCursor)) {
|
|
1066
|
+
failures.push({ stage: 'list', scope: opts.scope, reason: 'invalid_remote_pagination' });
|
|
1067
|
+
break;
|
|
1068
|
+
}
|
|
1069
|
+
if (budget.uniqueAssetIds.size >= opts.limit)
|
|
1070
|
+
return { rows, complete: false, nextCursor };
|
|
538
1071
|
if (cursor)
|
|
539
1072
|
seenCursors.add(cursor);
|
|
540
|
-
cursor =
|
|
1073
|
+
cursor = nextCursor;
|
|
541
1074
|
}
|
|
542
|
-
return rows
|
|
1075
|
+
return { rows, complete: false, nextCursor: cursor };
|
|
543
1076
|
}
|
|
544
|
-
function
|
|
545
|
-
|
|
1077
|
+
function isValidOpaqueCursor(cursor) {
|
|
1078
|
+
if (cursor.length > MAX_CURSOR_LENGTH || !cursor.trim())
|
|
1079
|
+
return false;
|
|
1080
|
+
for (const character of cursor) {
|
|
1081
|
+
const codePoint = character.codePointAt(0);
|
|
1082
|
+
if (codePoint !== undefined && (codePoint <= 0x1f || codePoint === 0x7f))
|
|
1083
|
+
return false;
|
|
1084
|
+
}
|
|
1085
|
+
return true;
|
|
1086
|
+
}
|
|
1087
|
+
function addUnique(target, missingAssetId, conflictingDuplicateAssetIds, row, source) {
|
|
1088
|
+
const assetId = rawStringField(row, 'asset_id');
|
|
546
1089
|
if (!assetId) {
|
|
547
1090
|
missingAssetId.push({ row, source });
|
|
548
1091
|
return;
|
|
549
1092
|
}
|
|
550
|
-
|
|
1093
|
+
const existing = target.get(assetId);
|
|
1094
|
+
if (!existing) {
|
|
1095
|
+
target.set(assetId, { row, source });
|
|
551
1096
|
return;
|
|
552
|
-
|
|
1097
|
+
}
|
|
1098
|
+
const merged = mergeDuplicateRemoteRows(existing.row, row, assetId);
|
|
1099
|
+
if (!merged)
|
|
1100
|
+
conflictingDuplicateAssetIds.add(assetId);
|
|
1101
|
+
else
|
|
1102
|
+
target.set(assetId, {
|
|
1103
|
+
row: merged,
|
|
1104
|
+
source: existing.source === 'purchased' || source === 'purchased' ? 'purchased' : existing.source,
|
|
1105
|
+
});
|
|
1106
|
+
}
|
|
1107
|
+
function classifyConflictingRemoteDuplicate(row, source) {
|
|
1108
|
+
return {
|
|
1109
|
+
assetId: rawStringField(row, 'asset_id') ?? MISSING_ASSET_ID,
|
|
1110
|
+
type: 'unknown',
|
|
1111
|
+
source,
|
|
1112
|
+
action: 'integrity_error',
|
|
1113
|
+
failureReason: 'conflicting_remote_duplicate',
|
|
1114
|
+
};
|
|
1115
|
+
}
|
|
1116
|
+
function mergeDuplicateRemoteRows(left, right, assetId) {
|
|
1117
|
+
const leftIdentity = remoteDuplicateIdentity(left, assetId);
|
|
1118
|
+
const rightIdentity = remoteDuplicateIdentity(right, assetId);
|
|
1119
|
+
if (leftIdentity.invalid || rightIdentity.invalid)
|
|
1120
|
+
return null;
|
|
1121
|
+
if (leftIdentity.declaredType
|
|
1122
|
+
&& rightIdentity.declaredType
|
|
1123
|
+
&& leftIdentity.declaredType !== rightIdentity.declaredType)
|
|
1124
|
+
return null;
|
|
1125
|
+
if (leftIdentity.logicalId && rightIdentity.logicalId && leftIdentity.logicalId !== rightIdentity.logicalId)
|
|
1126
|
+
return null;
|
|
1127
|
+
if (leftIdentity.tombstone !== rightIdentity.tombstone)
|
|
1128
|
+
return null;
|
|
1129
|
+
if (leftIdentity.canonicalBody && rightIdentity.canonicalBody && leftIdentity.canonicalBody !== rightIdentity.canonicalBody) {
|
|
1130
|
+
return null;
|
|
1131
|
+
}
|
|
1132
|
+
if (leftIdentity.canonicalBody && !rightIdentity.canonicalBody)
|
|
1133
|
+
return left;
|
|
1134
|
+
if (rightIdentity.canonicalBody && !leftIdentity.canonicalBody)
|
|
1135
|
+
return right;
|
|
1136
|
+
if (leftIdentity.synthesized !== rightIdentity.synthesized)
|
|
1137
|
+
return leftIdentity.synthesized ? left : right;
|
|
1138
|
+
return stableRemoteRowKey(left) <= stableRemoteRowKey(right) ? left : right;
|
|
1139
|
+
}
|
|
1140
|
+
function remoteDuplicateIdentity(row, assetId) {
|
|
1141
|
+
const type = remoteType(row);
|
|
1142
|
+
const declaredType = remoteDeclaredType(row);
|
|
1143
|
+
const logicalId = remoteLogicalId(row);
|
|
1144
|
+
const delivery = unwrapLiveHubDelivery(row, assetId);
|
|
1145
|
+
let canonicalBody;
|
|
1146
|
+
let invalid = delivery.invalid;
|
|
1147
|
+
if (!invalid && type && declaresFullAssetPayload(delivery.content, type)) {
|
|
1148
|
+
const cleaned = stripHubDeliveryMetadataForIntegrity(delivery.content);
|
|
1149
|
+
if (!looksLikeFullAsset(cleaned, type) || !wire.validateWireDeep(cleaned).ok) {
|
|
1150
|
+
invalid = true;
|
|
1151
|
+
}
|
|
1152
|
+
else {
|
|
1153
|
+
try {
|
|
1154
|
+
canonicalBody = wire.canonicalize(cleaned);
|
|
1155
|
+
}
|
|
1156
|
+
catch {
|
|
1157
|
+
invalid = true;
|
|
1158
|
+
}
|
|
1159
|
+
}
|
|
1160
|
+
}
|
|
1161
|
+
return {
|
|
1162
|
+
...(declaredType ? { declaredType } : {}),
|
|
1163
|
+
...(logicalId ? { logicalId } : {}),
|
|
1164
|
+
tombstone: isRemoteTombstoneDelivery(row),
|
|
1165
|
+
...(canonicalBody ? { canonicalBody } : {}),
|
|
1166
|
+
synthesized: Boolean(stringField(delivery.content, 'payload_backfill_reason')
|
|
1167
|
+
?? stringField(row, 'payload_backfill_reason')),
|
|
1168
|
+
invalid,
|
|
1169
|
+
};
|
|
1170
|
+
}
|
|
1171
|
+
function stableRemoteRowKey(row) {
|
|
1172
|
+
try {
|
|
1173
|
+
return wire.canonicalize(row);
|
|
1174
|
+
}
|
|
1175
|
+
catch {
|
|
1176
|
+
return JSON.stringify(row) ?? '';
|
|
1177
|
+
}
|
|
553
1178
|
}
|
|
554
1179
|
async function localIndex(store) {
|
|
555
1180
|
const byAssetId = new Set();
|
|
556
1181
|
const logical = new Map();
|
|
1182
|
+
const recordsByAssetId = new Map();
|
|
557
1183
|
for (const kind of ['Gene', 'Capsule']) {
|
|
558
1184
|
for (const row of await store.list(kind, Number.MAX_SAFE_INTEGER)) {
|
|
559
1185
|
byAssetId.add(row.asset_id);
|
|
560
|
-
|
|
1186
|
+
recordsByAssetId.set(row.asset_id, row);
|
|
1187
|
+
const logicalId = rawStringField(row, 'id');
|
|
561
1188
|
if (logicalId)
|
|
562
1189
|
logical.set(`${kind}:${logicalId}`, row.asset_id);
|
|
563
1190
|
}
|
|
564
1191
|
}
|
|
565
|
-
return { byAssetId, logical };
|
|
1192
|
+
return { byAssetId, logical, recordsByAssetId };
|
|
566
1193
|
}
|
|
567
1194
|
async function listLocalExportAssets(store, opts) {
|
|
568
1195
|
const kinds = opts.type ? [opts.type] : ['Gene', 'Capsule'];
|
|
@@ -575,8 +1202,8 @@ async function listLocalExportAssets(store, opts) {
|
|
|
575
1202
|
}
|
|
576
1203
|
return assets.slice(0, opts.limit);
|
|
577
1204
|
}
|
|
578
|
-
function classifyRemote(row, source, local) {
|
|
579
|
-
const assetId =
|
|
1205
|
+
function classifyRemote(row, source, local, provenanceSnapshot) {
|
|
1206
|
+
const assetId = rawStringField(row, 'asset_id') ?? MISSING_ASSET_ID;
|
|
580
1207
|
const type = remoteType(row);
|
|
581
1208
|
const logicalId = remoteLogicalId(row);
|
|
582
1209
|
const status = stringField(row, 'status');
|
|
@@ -587,26 +1214,92 @@ function classifyRemote(row, source, local) {
|
|
|
587
1214
|
source,
|
|
588
1215
|
...(status ? { status } : {}),
|
|
589
1216
|
};
|
|
590
|
-
if (type !== 'Gene' && type !== 'Capsule')
|
|
591
|
-
return { ...base, action: 'unsupported_type' };
|
|
592
1217
|
if (assetId === MISSING_ASSET_ID)
|
|
593
1218
|
return { ...base, action: 'integrity_error' };
|
|
594
|
-
if (
|
|
1219
|
+
if (!isContentAssetId(assetId))
|
|
595
1220
|
return { ...base, action: 'integrity_error' };
|
|
596
|
-
if (
|
|
597
|
-
return { ...base, action: '
|
|
1221
|
+
if (unwrapLiveHubDelivery(row, assetId).invalid)
|
|
1222
|
+
return { ...base, action: 'integrity_error' };
|
|
1223
|
+
if (isRemoteTombstoneDelivery(row))
|
|
1224
|
+
return { ...base, action: 'tombstone' };
|
|
1225
|
+
if (type !== 'Gene' && type !== 'Capsule')
|
|
1226
|
+
return { ...base, action: 'unsupported_type' };
|
|
1227
|
+
const payloadVerification = inspectRemotePayload(row, type, assetId);
|
|
1228
|
+
if (payloadVerification === 'invalid')
|
|
1229
|
+
return { ...base, action: 'integrity_error' };
|
|
1230
|
+
const isUnverified = payloadVerification === 'unverified_hub_rewrite'
|
|
1231
|
+
|| payloadVerification === 'unverified_hub_synthesized';
|
|
1232
|
+
const verifiedBase = isUnverified
|
|
1233
|
+
? { ...base, verification: 'unverified', verificationReason: payloadVerification }
|
|
1234
|
+
: base;
|
|
1235
|
+
if (local.byAssetId.has(assetId)) {
|
|
1236
|
+
if (payloadVerification === 'unavailable') {
|
|
1237
|
+
const stored = local.recordsByAssetId.get(assetId);
|
|
1238
|
+
const localComputed = stored ? wire.computeAssetId(stored) : null;
|
|
1239
|
+
if (!stored
|
|
1240
|
+
|| stored.asset_id !== assetId
|
|
1241
|
+
|| stored.type !== type
|
|
1242
|
+
|| !localComputed) {
|
|
1243
|
+
return {
|
|
1244
|
+
...base,
|
|
1245
|
+
action: 'integrity_error',
|
|
1246
|
+
failureReason: 'local_content_integrity_mismatch',
|
|
1247
|
+
};
|
|
1248
|
+
}
|
|
1249
|
+
if (localComputed !== assetId) {
|
|
1250
|
+
if (!isActiveFrozenWaiver(provenanceSnapshot.get(assetId), assetId, localComputed, true)) {
|
|
1251
|
+
return {
|
|
1252
|
+
...base,
|
|
1253
|
+
action: 'integrity_error',
|
|
1254
|
+
failureReason: 'local_frozen_waiver_mismatch',
|
|
1255
|
+
};
|
|
1256
|
+
}
|
|
1257
|
+
return {
|
|
1258
|
+
...base,
|
|
1259
|
+
action: 'already_local',
|
|
1260
|
+
verification: 'unverified',
|
|
1261
|
+
};
|
|
1262
|
+
}
|
|
1263
|
+
}
|
|
1264
|
+
if (payloadVerification !== 'unavailable'
|
|
1265
|
+
&& !inlineContentMatchesLocal(row, type, assetId, local.recordsByAssetId.get(assetId), provenanceSnapshot.get(assetId))) {
|
|
1266
|
+
return {
|
|
1267
|
+
...base,
|
|
1268
|
+
action: 'integrity_error',
|
|
1269
|
+
failureReason: 'frozen_remote_content_changed',
|
|
1270
|
+
};
|
|
1271
|
+
}
|
|
1272
|
+
return { ...verifiedBase, action: 'already_local' };
|
|
1273
|
+
}
|
|
598
1274
|
if (logicalId) {
|
|
599
1275
|
const localAssetId = local.logical.get(`${type}:${logicalId}`);
|
|
600
1276
|
if (localAssetId && localAssetId !== assetId)
|
|
601
|
-
return { ...
|
|
1277
|
+
return { ...verifiedBase, action: 'id_collision', collisionWithAssetId: localAssetId };
|
|
602
1278
|
}
|
|
603
|
-
return { ...
|
|
1279
|
+
return { ...verifiedBase, action: 'would_import' };
|
|
604
1280
|
}
|
|
605
1281
|
function classifyGepxAssets(pkg, opts, local) {
|
|
606
|
-
|
|
1282
|
+
const classified = uniqueGepxAssets(pkg)
|
|
607
1283
|
.filter((entry) => !opts.type || entry.type === opts.type)
|
|
608
|
-
.slice(0, opts.limit)
|
|
609
1284
|
.map((entry) => classifyGepxAsset(entry, local));
|
|
1285
|
+
let remaining = opts.limit;
|
|
1286
|
+
const candidates = classified.map((candidate) => {
|
|
1287
|
+
if (candidate.action === 'integrity_error')
|
|
1288
|
+
return candidate;
|
|
1289
|
+
if (remaining > 0) {
|
|
1290
|
+
remaining -= 1;
|
|
1291
|
+
return candidate;
|
|
1292
|
+
}
|
|
1293
|
+
return { ...candidate, action: 'skipped_limit', failureReason: 'limit_reached' };
|
|
1294
|
+
});
|
|
1295
|
+
const malformed = pkg.malformedAssets.map((entry) => ({
|
|
1296
|
+
assetId: entry.assetId ?? `${MISSING_ASSET_ID}-${entry.index}`,
|
|
1297
|
+
type: 'unknown',
|
|
1298
|
+
source: 'gepx',
|
|
1299
|
+
action: 'integrity_error',
|
|
1300
|
+
failureReason: 'invalid_package_asset',
|
|
1301
|
+
}));
|
|
1302
|
+
return [...candidates, ...malformed];
|
|
610
1303
|
}
|
|
611
1304
|
function classifyGepxAsset(entry, local) {
|
|
612
1305
|
const { assetId, type, logicalId } = entry;
|
|
@@ -632,8 +1325,9 @@ function classifyGepxAsset(entry, local) {
|
|
|
632
1325
|
function uniqueGepxAssets(pkg) {
|
|
633
1326
|
const unique = new Map();
|
|
634
1327
|
const missing = [];
|
|
1328
|
+
const provenanceByAssetId = indexUniqueGepxProvenance(pkg);
|
|
635
1329
|
for (const asset of pkg.assets) {
|
|
636
|
-
const normalized = normalizeGepxAsset(asset);
|
|
1330
|
+
const normalized = normalizeGepxAsset(asset, provenanceByAssetId.get(asset.asset_id) ?? undefined);
|
|
637
1331
|
if (normalized.assetId === MISSING_ASSET_ID) {
|
|
638
1332
|
missing.push(normalized);
|
|
639
1333
|
continue;
|
|
@@ -647,29 +1341,50 @@ function gepxImportAssetsById(pkg) {
|
|
|
647
1341
|
const assets = new Map();
|
|
648
1342
|
for (const entry of uniqueGepxAssets(pkg)) {
|
|
649
1343
|
if (entry.type && !entry.integrityError && !assets.has(entry.assetId))
|
|
650
|
-
assets.set(entry.assetId, entry
|
|
1344
|
+
assets.set(entry.assetId, entry);
|
|
651
1345
|
}
|
|
652
1346
|
return assets;
|
|
653
1347
|
}
|
|
654
|
-
function
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
throw new SyncAbortError('integrity_error', '.gepx package integrity verification failed before import');
|
|
659
|
-
}
|
|
1348
|
+
function indexUniqueGepxProvenance(pkg) {
|
|
1349
|
+
const indexed = new Map();
|
|
1350
|
+
for (const record of pkg.provenance ?? []) {
|
|
1351
|
+
indexed.set(record.assetId, indexed.has(record.assetId) ? null : record);
|
|
660
1352
|
}
|
|
1353
|
+
return indexed;
|
|
661
1354
|
}
|
|
662
|
-
function normalizeGepxAsset(asset) {
|
|
663
|
-
const cleaned =
|
|
664
|
-
const assetId =
|
|
1355
|
+
function normalizeGepxAsset(asset, provenance) {
|
|
1356
|
+
const cleaned = { ...asset };
|
|
1357
|
+
const assetId = rawStringField(cleaned, 'asset_id') ?? MISSING_ASSET_ID;
|
|
665
1358
|
const type = cleaned.type === 'Gene' || cleaned.type === 'Capsule' ? cleaned.type : undefined;
|
|
666
|
-
const logicalId =
|
|
1359
|
+
const logicalId = rawStringField(cleaned, 'id');
|
|
667
1360
|
let integrityError = false;
|
|
1361
|
+
let frozenUnverified = false;
|
|
668
1362
|
if (type) {
|
|
669
|
-
const claimed =
|
|
1363
|
+
const claimed = rawStringField(cleaned, 'asset_id');
|
|
670
1364
|
const fullAsset = looksLikeFullAsset(cleaned, type);
|
|
671
1365
|
const computed = fullAsset ? wire.computeAssetId(cleaned) : undefined;
|
|
672
|
-
|
|
1366
|
+
const supportedFrozenProvenance = provenance
|
|
1367
|
+
&& ((provenance.source === 'hub'
|
|
1368
|
+
&& (provenance.reason === 'unverified_hub_rewrite' || provenance.reason === 'unverified_hub_synthesized'))
|
|
1369
|
+
|| (provenance.source === 'migrated' && provenance.reason === 'unverified_gepx_import'));
|
|
1370
|
+
frozenUnverified = Boolean(claimed
|
|
1371
|
+
&& computed
|
|
1372
|
+
&& claimed === assetId
|
|
1373
|
+
&& computed !== claimed
|
|
1374
|
+
&& provenance?.assetId === assetId
|
|
1375
|
+
&& supportedFrozenProvenance
|
|
1376
|
+
&& provenance.trusted === false
|
|
1377
|
+
&& provenance.decision === undefined
|
|
1378
|
+
&& provenance.decidedBy === undefined
|
|
1379
|
+
&& provenance.promotedBy === undefined
|
|
1380
|
+
&& provenance.frozenContentId === computed);
|
|
1381
|
+
integrityError = assetId === MISSING_ASSET_ID
|
|
1382
|
+
|| !claimed
|
|
1383
|
+
|| !isContentAssetId(assetId)
|
|
1384
|
+
|| !fullAsset
|
|
1385
|
+
|| !computed
|
|
1386
|
+
|| claimed !== assetId
|
|
1387
|
+
|| (computed !== claimed && !frozenUnverified);
|
|
673
1388
|
}
|
|
674
1389
|
return {
|
|
675
1390
|
original: asset,
|
|
@@ -678,6 +1393,7 @@ function normalizeGepxAsset(asset) {
|
|
|
678
1393
|
...(type ? { type } : {}),
|
|
679
1394
|
...(logicalId ? { logicalId } : {}),
|
|
680
1395
|
integrityError,
|
|
1396
|
+
frozenUnverified,
|
|
681
1397
|
};
|
|
682
1398
|
}
|
|
683
1399
|
function countsFromCandidates(base, candidates) {
|
|
@@ -686,25 +1402,41 @@ function countsFromCandidates(base, candidates) {
|
|
|
686
1402
|
remotePublished: base.remotePublished,
|
|
687
1403
|
uniqueRemote: candidates.length,
|
|
688
1404
|
alreadyLocal: 0,
|
|
1405
|
+
tombstone: 0,
|
|
689
1406
|
idCollision: 0,
|
|
690
1407
|
unsupported: 0,
|
|
691
1408
|
integrityError: 0,
|
|
692
1409
|
wouldImport: 0,
|
|
1410
|
+
unverifiedWouldImport: 0,
|
|
693
1411
|
forcedImport: 0,
|
|
1412
|
+
skippedLimit: 0,
|
|
1413
|
+
fetchFailed: 0,
|
|
1414
|
+
writeFailed: 0,
|
|
694
1415
|
};
|
|
695
1416
|
for (const candidate of candidates) {
|
|
696
1417
|
if (candidate.action === 'already_local')
|
|
697
1418
|
counts.alreadyLocal += 1;
|
|
1419
|
+
else if (candidate.action === 'tombstone')
|
|
1420
|
+
counts.tombstone += 1;
|
|
698
1421
|
else if (candidate.action === 'id_collision')
|
|
699
1422
|
counts.idCollision += 1;
|
|
700
1423
|
else if (candidate.action === 'would_import')
|
|
701
1424
|
counts.wouldImport += 1;
|
|
702
1425
|
else if (candidate.action === 'force_import')
|
|
703
1426
|
counts.forcedImport += 1;
|
|
1427
|
+
else if (candidate.action === 'skipped_limit')
|
|
1428
|
+
counts.skippedLimit += 1;
|
|
1429
|
+
else if (candidate.action === 'fetch_failed')
|
|
1430
|
+
counts.fetchFailed += 1;
|
|
1431
|
+
else if (candidate.action === 'write_failed')
|
|
1432
|
+
counts.writeFailed += 1;
|
|
704
1433
|
else if (candidate.action === 'unsupported_type')
|
|
705
1434
|
counts.unsupported += 1;
|
|
706
|
-
else
|
|
1435
|
+
else if (candidate.action === 'integrity_error')
|
|
707
1436
|
counts.integrityError += 1;
|
|
1437
|
+
if (candidate.action === 'would_import' && candidate.verification === 'unverified') {
|
|
1438
|
+
counts.unverifiedWouldImport += 1;
|
|
1439
|
+
}
|
|
708
1440
|
}
|
|
709
1441
|
return counts;
|
|
710
1442
|
}
|
|
@@ -714,59 +1446,462 @@ function updateFinalCandidate(candidates, original, replacement) {
|
|
|
714
1446
|
candidates[index] = replacement;
|
|
715
1447
|
}
|
|
716
1448
|
function isBlockedCandidate(candidate) {
|
|
717
|
-
return candidate.action !== 'would_import'
|
|
1449
|
+
return candidate.action !== 'would_import'
|
|
1450
|
+
&& candidate.action !== 'force_import'
|
|
1451
|
+
&& candidate.action !== 'already_local'
|
|
1452
|
+
&& candidate.action !== 'skipped_limit';
|
|
718
1453
|
}
|
|
719
|
-
function
|
|
720
|
-
const
|
|
721
|
-
|
|
722
|
-
|
|
1454
|
+
function inspectRemotePayload(row, type, assetId) {
|
|
1455
|
+
const delivery = unwrapLiveHubDelivery(row, assetId);
|
|
1456
|
+
if (delivery.invalid)
|
|
1457
|
+
return 'invalid';
|
|
1458
|
+
const source = delivery.content;
|
|
1459
|
+
if (!looksLikeFullAsset(source, type)) {
|
|
1460
|
+
return declaresFullAssetPayload(source, type) ? 'invalid' : 'unavailable';
|
|
1461
|
+
}
|
|
1462
|
+
const candidate = stripHubDeliveryMetadataForIntegrity(source);
|
|
1463
|
+
if (!wire.validateWireDeep(candidate).ok)
|
|
1464
|
+
return 'invalid';
|
|
1465
|
+
const claimed = rawStringField(candidate, 'asset_id');
|
|
1466
|
+
if (!claimed || !isContentAssetId(claimed) || claimed !== assetId)
|
|
1467
|
+
return 'invalid';
|
|
1468
|
+
const computed = wire.computeAssetId(candidate);
|
|
1469
|
+
if (!computed)
|
|
1470
|
+
return 'invalid';
|
|
1471
|
+
if (computed === claimed)
|
|
1472
|
+
return 'verified';
|
|
1473
|
+
return stringField(source, 'payload_backfill_reason') ?? stringField(row, 'payload_backfill_reason')
|
|
1474
|
+
? 'unverified_hub_synthesized'
|
|
1475
|
+
: 'unverified_hub_rewrite';
|
|
1476
|
+
}
|
|
1477
|
+
function inlineContentMatchesLocal(row, type, assetId, local, provenance) {
|
|
1478
|
+
const delivery = unwrapLiveHubDelivery(row, assetId);
|
|
1479
|
+
if (delivery.invalid || !local)
|
|
1480
|
+
return false;
|
|
1481
|
+
const remote = stripHubDeliveryMetadataForIntegrity(delivery.content);
|
|
1482
|
+
const remoteComputed = wire.computeAssetId(remote);
|
|
1483
|
+
const localComputed = wire.computeAssetId(local);
|
|
1484
|
+
if (!remoteComputed
|
|
1485
|
+
|| !localComputed
|
|
1486
|
+
|| local.asset_id !== assetId
|
|
1487
|
+
|| local.type !== type
|
|
1488
|
+
|| remoteComputed !== localComputed
|
|
1489
|
+
|| !assetstore.frozenAssetRecordsEqual(local, remote))
|
|
723
1490
|
return false;
|
|
724
|
-
|
|
725
|
-
|
|
1491
|
+
if (remoteComputed === assetId)
|
|
1492
|
+
return true;
|
|
1493
|
+
return isActiveFrozenWaiver(provenance, assetId, remoteComputed, true);
|
|
1494
|
+
}
|
|
1495
|
+
function isActiveFrozenWaiver(provenance, assetId, frozenContentId, allowPending = false) {
|
|
1496
|
+
return Boolean(provenance?.assetId === assetId
|
|
1497
|
+
&& provenance.trusted === false
|
|
1498
|
+
&& provenance.frozenContentId === frozenContentId
|
|
1499
|
+
&& provenance.decision === undefined
|
|
1500
|
+
&& provenance.decidedBy === undefined
|
|
1501
|
+
&& provenance.promotedBy === undefined
|
|
1502
|
+
&& ((provenance.source === 'hub'
|
|
1503
|
+
&& (provenance.reason === 'unverified_hub_rewrite' || provenance.reason === 'unverified_hub_synthesized'))
|
|
1504
|
+
|| (provenance.source === 'migrated' && provenance.reason === 'unverified_gepx_import')
|
|
1505
|
+
|| (allowPending && provenance.source === 'hub' && provenance.reason === UNVERIFIED_HUB_WRITE_PENDING_REASON)));
|
|
726
1506
|
}
|
|
727
|
-
function
|
|
728
|
-
const
|
|
1507
|
+
function unwrapLiveHubDelivery(row, expectedAssetId) {
|
|
1508
|
+
const nested = asRecord(row.payload);
|
|
1509
|
+
if (Object.prototype.hasOwnProperty.call(row, 'type') || !nested) {
|
|
1510
|
+
const directType = rawStringField(row, 'type');
|
|
1511
|
+
const directLogicalId = rawStringField(row, 'id');
|
|
1512
|
+
const aliasType = rawStringField(row, 'asset_type');
|
|
1513
|
+
const aliasLogicalId = rawStringField(row, 'local_id');
|
|
1514
|
+
return {
|
|
1515
|
+
content: row,
|
|
1516
|
+
invalid: Boolean(hasInvalidLiveIdentityField(row, ['asset_id', 'type', 'asset_type', 'id', 'local_id'])
|
|
1517
|
+
|| (aliasType !== undefined && directType !== undefined && aliasType !== directType)
|
|
1518
|
+
|| (aliasLogicalId !== undefined && directLogicalId !== undefined && aliasLogicalId !== directLogicalId)),
|
|
1519
|
+
};
|
|
1520
|
+
}
|
|
1521
|
+
const outerAssetId = rawStringField(row, 'asset_id');
|
|
1522
|
+
const outerType = rawStringField(row, 'asset_type');
|
|
1523
|
+
const outerLogicalIds = [rawStringField(row, 'id'), rawStringField(row, 'local_id')]
|
|
1524
|
+
.filter((value) => value !== undefined);
|
|
1525
|
+
const innerAssetId = rawStringField(nested, 'asset_id');
|
|
1526
|
+
const innerType = rawStringField(nested, 'type');
|
|
1527
|
+
const innerAliasType = rawStringField(nested, 'asset_type');
|
|
1528
|
+
const innerLogicalId = rawStringField(nested, 'id');
|
|
1529
|
+
const innerAliasLogicalId = rawStringField(nested, 'local_id');
|
|
1530
|
+
const invalid = Boolean(hasInvalidLiveIdentityField(row, ['asset_id', 'asset_type', 'id', 'local_id'])
|
|
1531
|
+
|| hasInvalidLiveIdentityField(nested, ['asset_id', 'type', 'asset_type', 'id', 'local_id'])
|
|
1532
|
+
|| outerAssetId === undefined
|
|
1533
|
+
|| outerAssetId !== expectedAssetId
|
|
1534
|
+
|| innerAssetId === undefined
|
|
1535
|
+
|| innerAssetId !== expectedAssetId
|
|
1536
|
+
|| innerType === undefined
|
|
1537
|
+
|| (outerType !== undefined && innerType !== undefined && outerType !== innerType)
|
|
1538
|
+
|| (innerAliasType !== undefined && innerAliasType !== innerType)
|
|
1539
|
+
|| (outerLogicalIds.length > 0 && innerLogicalId === undefined)
|
|
1540
|
+
|| (innerLogicalId !== undefined && outerLogicalIds.some((outerLogicalId) => outerLogicalId !== innerLogicalId))
|
|
1541
|
+
|| (innerAliasLogicalId !== undefined && innerAliasLogicalId !== innerLogicalId));
|
|
1542
|
+
const backfillReason = stringField(row, 'payload_backfill_reason');
|
|
1543
|
+
return {
|
|
1544
|
+
content: backfillReason && stringField(nested, 'payload_backfill_reason') === undefined
|
|
1545
|
+
? { ...nested, payload_backfill_reason: backfillReason }
|
|
1546
|
+
: nested,
|
|
1547
|
+
invalid,
|
|
1548
|
+
};
|
|
1549
|
+
}
|
|
1550
|
+
function prepareFetchedAsset(candidate, fetched, localAssetIds, logical, force, allowExistingFrozenFinalize = false) {
|
|
1551
|
+
if (isRemoteTombstoneDelivery(fetched)) {
|
|
1552
|
+
throw new SyncAbortError('remote_revoked', 'Hub asset was revoked before import');
|
|
1553
|
+
}
|
|
1554
|
+
const delivery = unwrapLiveHubDelivery(fetched, candidate.assetId);
|
|
1555
|
+
if (delivery.invalid)
|
|
1556
|
+
throw new SyncAbortError('integrity_error', 'Hub delivery identity changed before import');
|
|
1557
|
+
const delivered = delivery.content;
|
|
1558
|
+
const type = delivered.type === 'Gene' || delivered.type === 'Capsule' ? delivered.type : undefined;
|
|
729
1559
|
if (!type)
|
|
730
|
-
return { blocked: { ...candidate, type:
|
|
1560
|
+
return { blocked: { ...candidate, type: delivered.type ?? candidate.type, action: 'unsupported_type' } };
|
|
731
1561
|
if (type !== candidate.type)
|
|
732
1562
|
throw new SyncAbortError('integrity_error', 'Hub asset type changed before import');
|
|
733
|
-
const cleaned =
|
|
734
|
-
const claimed =
|
|
735
|
-
const computed = wire.computeAssetId(cleaned);
|
|
736
|
-
if (!claimed || !computed || claimed !== computed || claimed !== candidate.assetId) {
|
|
737
|
-
throw new SyncAbortError('integrity_error', 'Hub asset integrity verification failed before import');
|
|
738
|
-
}
|
|
1563
|
+
const cleaned = stripHubDeliveryMetadataForIntegrity(delivered);
|
|
1564
|
+
const claimed = rawStringField(cleaned, 'asset_id');
|
|
739
1565
|
if (!looksLikeFullAsset(cleaned, type)) {
|
|
740
1566
|
throw new SyncAbortError('integrity_error', 'Hub asset payload is incomplete');
|
|
741
1567
|
}
|
|
742
|
-
if (
|
|
1568
|
+
if (!wire.validateWireDeep(cleaned).ok) {
|
|
1569
|
+
throw new SyncAbortError('integrity_error', 'Hub asset failed wire schema validation before import');
|
|
1570
|
+
}
|
|
1571
|
+
const computed = wire.computeAssetId(cleaned);
|
|
1572
|
+
if (!claimed || !computed || !isContentAssetId(claimed) || claimed !== candidate.assetId) {
|
|
1573
|
+
throw new SyncAbortError('integrity_error', 'Hub asset identity verification failed before import');
|
|
1574
|
+
}
|
|
1575
|
+
const logicalId = rawStringField(cleaned, 'id');
|
|
1576
|
+
if (candidate.logicalId && logicalId !== candidate.logicalId) {
|
|
1577
|
+
throw new SyncAbortError('integrity_error', 'Hub asset logical id changed before import');
|
|
1578
|
+
}
|
|
1579
|
+
const frozenUnverified = computed !== claimed;
|
|
1580
|
+
const verificationReason = frozenUnverified
|
|
1581
|
+
? stringField(delivered, 'payload_backfill_reason')
|
|
1582
|
+
? 'unverified_hub_synthesized'
|
|
1583
|
+
: 'unverified_hub_rewrite'
|
|
1584
|
+
: undefined;
|
|
1585
|
+
const verification = frozenUnverified
|
|
1586
|
+
? { frozenUnverified: true, verificationReason, frozenContentId: computed }
|
|
1587
|
+
: {};
|
|
1588
|
+
if (localAssetIds.has(cleaned.asset_id) && !allowExistingFrozenFinalize) {
|
|
743
1589
|
return { blocked: { ...candidate, action: 'already_local' } };
|
|
744
|
-
|
|
1590
|
+
}
|
|
745
1591
|
if (logicalId) {
|
|
746
1592
|
const localAssetId = logical.get(`${type}:${logicalId}`);
|
|
747
1593
|
if (localAssetId && localAssetId !== cleaned.asset_id) {
|
|
748
1594
|
if (force)
|
|
749
|
-
return { asset: cleaned, forced: true, collisionWithAssetId: localAssetId };
|
|
1595
|
+
return { asset: cleaned, ...verification, forced: true, collisionWithAssetId: localAssetId };
|
|
750
1596
|
return { blocked: { ...candidate, logicalId, action: 'id_collision', collisionWithAssetId: localAssetId } };
|
|
751
1597
|
}
|
|
752
1598
|
}
|
|
753
|
-
return { asset: cleaned };
|
|
1599
|
+
return { asset: cleaned, ...verification };
|
|
1600
|
+
}
|
|
1601
|
+
async function reactivatePendingUnverifiedCandidates(candidates, store, provenanceSnapshot) {
|
|
1602
|
+
const recoveryIds = new Set();
|
|
1603
|
+
for (const candidate of [...candidates]) {
|
|
1604
|
+
if (candidate.action !== 'already_local' || (candidate.type !== 'Gene' && candidate.type !== 'Capsule'))
|
|
1605
|
+
continue;
|
|
1606
|
+
const record = provenanceSnapshot.get(candidate.assetId);
|
|
1607
|
+
if (record?.assetId !== candidate.assetId
|
|
1608
|
+
|| record.source !== 'hub'
|
|
1609
|
+
|| record.trusted !== false
|
|
1610
|
+
|| record.reason !== UNVERIFIED_HUB_WRITE_PENDING_REASON
|
|
1611
|
+
|| !record.frozenContentId
|
|
1612
|
+
|| record.decision !== undefined
|
|
1613
|
+
|| record.decidedBy !== undefined
|
|
1614
|
+
|| record.promotedBy !== undefined)
|
|
1615
|
+
continue;
|
|
1616
|
+
let stored;
|
|
1617
|
+
try {
|
|
1618
|
+
stored = await store.get(candidate.assetId);
|
|
1619
|
+
}
|
|
1620
|
+
catch {
|
|
1621
|
+
continue;
|
|
1622
|
+
}
|
|
1623
|
+
const computed = stored ? wire.computeAssetId(stored) : null;
|
|
1624
|
+
const storedLogicalId = stored ? rawStringField(stored, 'id') : undefined;
|
|
1625
|
+
if (!stored
|
|
1626
|
+
|| stored.asset_id !== candidate.assetId
|
|
1627
|
+
|| stored.type !== candidate.type
|
|
1628
|
+
|| !looksLikeFullAsset(stored, candidate.type)
|
|
1629
|
+
|| !wire.validateWireDeep(stored).ok
|
|
1630
|
+
|| !computed
|
|
1631
|
+
|| computed === candidate.assetId
|
|
1632
|
+
|| computed !== record.frozenContentId
|
|
1633
|
+
|| (candidate.logicalId !== undefined && storedLogicalId !== candidate.logicalId))
|
|
1634
|
+
continue;
|
|
1635
|
+
recoveryIds.add(candidate.assetId);
|
|
1636
|
+
updateFinalCandidate(candidates, candidate, {
|
|
1637
|
+
...candidate,
|
|
1638
|
+
action: 'would_import',
|
|
1639
|
+
verification: 'unverified',
|
|
1640
|
+
});
|
|
1641
|
+
}
|
|
1642
|
+
return recoveryIds;
|
|
1643
|
+
}
|
|
1644
|
+
function reactivateThinFrozenCandidates(candidates, local, provenanceSnapshot) {
|
|
1645
|
+
const revalidationIds = new Set();
|
|
1646
|
+
for (const candidate of [...candidates]) {
|
|
1647
|
+
if (candidate.action !== 'already_local'
|
|
1648
|
+
|| candidate.verification !== 'unverified'
|
|
1649
|
+
|| candidate.verificationReason !== undefined
|
|
1650
|
+
|| (candidate.type !== 'Gene' && candidate.type !== 'Capsule'))
|
|
1651
|
+
continue;
|
|
1652
|
+
const stored = local.recordsByAssetId.get(candidate.assetId);
|
|
1653
|
+
const frozenContentId = stored ? wire.computeAssetId(stored) : null;
|
|
1654
|
+
if (!stored
|
|
1655
|
+
|| stored.asset_id !== candidate.assetId
|
|
1656
|
+
|| stored.type !== candidate.type
|
|
1657
|
+
|| !frozenContentId
|
|
1658
|
+
|| frozenContentId === candidate.assetId
|
|
1659
|
+
|| !isActiveFrozenWaiver(provenanceSnapshot.get(candidate.assetId), candidate.assetId, frozenContentId))
|
|
1660
|
+
continue;
|
|
1661
|
+
revalidationIds.add(candidate.assetId);
|
|
1662
|
+
updateFinalCandidate(candidates, candidate, {
|
|
1663
|
+
...candidate,
|
|
1664
|
+
action: 'would_import',
|
|
1665
|
+
verification: 'unverified',
|
|
1666
|
+
});
|
|
1667
|
+
}
|
|
1668
|
+
return revalidationIds;
|
|
1669
|
+
}
|
|
1670
|
+
function resumePlannedCandidates(candidates, previousRun, inventoryComplete) {
|
|
1671
|
+
const plan = previousRun.plan;
|
|
1672
|
+
if (!plan) {
|
|
1673
|
+
throw new SyncAbortError('resume_plan_drift', 'cannot resume a run without its original candidate plan');
|
|
1674
|
+
}
|
|
1675
|
+
const byPlanId = new Map(candidates.flatMap((candidate) => candidate.assetId === MISSING_ASSET_ID
|
|
1676
|
+
? []
|
|
1677
|
+
: [[candidate.assetId, candidate]]));
|
|
1678
|
+
const knownRemoteMissing = plan.filter((assetId) => (previousRun.processed.get(assetId)?.outcome === 'remote_missing'
|
|
1679
|
+
&& !byPlanId.has(assetId)));
|
|
1680
|
+
const unresolvedMissing = plan.filter((assetId) => {
|
|
1681
|
+
const processed = previousRun.processed.get(assetId);
|
|
1682
|
+
return (!processed || processed.outcome === 'failed') && !byPlanId.has(assetId);
|
|
1683
|
+
});
|
|
1684
|
+
const newRemoteMissingAssetIds = inventoryComplete ? unresolvedMissing : [];
|
|
1685
|
+
const remoteMissingAssetIds = [...knownRemoteMissing, ...newRemoteMissingAssetIds];
|
|
1686
|
+
const remoteMissing = new Set(remoteMissingAssetIds);
|
|
1687
|
+
const plannedCandidates = plan.flatMap((assetId) => {
|
|
1688
|
+
const candidate = byPlanId.get(assetId);
|
|
1689
|
+
if (candidate)
|
|
1690
|
+
return [{ ...candidate }];
|
|
1691
|
+
return remoteMissing.has(assetId) ? [{
|
|
1692
|
+
assetId,
|
|
1693
|
+
type: 'unknown',
|
|
1694
|
+
source: 'reconciliation',
|
|
1695
|
+
action: 'tombstone',
|
|
1696
|
+
failureReason: 'remote_missing',
|
|
1697
|
+
}] : [];
|
|
1698
|
+
});
|
|
1699
|
+
const plannedIds = new Set(plan);
|
|
1700
|
+
const newCandidates = candidates
|
|
1701
|
+
.filter((candidate) => candidate.assetId === MISSING_ASSET_ID || !plannedIds.has(candidate.assetId))
|
|
1702
|
+
.map((candidate) => ({ ...candidate }));
|
|
1703
|
+
return {
|
|
1704
|
+
candidates: [...plannedCandidates, ...newCandidates],
|
|
1705
|
+
remoteMissingAssetIds,
|
|
1706
|
+
newRemoteMissingAssetIds,
|
|
1707
|
+
};
|
|
1708
|
+
}
|
|
1709
|
+
function actionableCandidatePlanIds(candidates, force) {
|
|
1710
|
+
return candidates.flatMap((candidate) => (candidate.assetId !== MISSING_ASSET_ID
|
|
1711
|
+
&& (candidate.action === 'would_import' || (force && candidate.action === 'id_collision'))
|
|
1712
|
+
? [candidate.assetId]
|
|
1713
|
+
: []));
|
|
1714
|
+
}
|
|
1715
|
+
function mergeCandidatePlan(previous, current) {
|
|
1716
|
+
const merged = [...previous];
|
|
1717
|
+
const seen = new Set(previous);
|
|
1718
|
+
for (const assetId of current) {
|
|
1719
|
+
if (seen.has(assetId))
|
|
1720
|
+
continue;
|
|
1721
|
+
seen.add(assetId);
|
|
1722
|
+
merged.push(assetId);
|
|
1723
|
+
}
|
|
1724
|
+
return merged;
|
|
1725
|
+
}
|
|
1726
|
+
function assertNoConflictingGepxDuplicates(pkg) {
|
|
1727
|
+
const seen = new Map();
|
|
1728
|
+
for (const asset of pkg.assets) {
|
|
1729
|
+
const assetId = rawStringField(asset, 'asset_id');
|
|
1730
|
+
if (!assetId)
|
|
1731
|
+
continue;
|
|
1732
|
+
const serialized = JSON.stringify(asset);
|
|
1733
|
+
const previous = seen.get(assetId);
|
|
1734
|
+
if (previous !== undefined && previous !== serialized) {
|
|
1735
|
+
throw new SyncAbortError('integrity_error', '.gepx package contains conflicting duplicate asset IDs');
|
|
1736
|
+
}
|
|
1737
|
+
seen.set(assetId, serialized);
|
|
1738
|
+
}
|
|
1739
|
+
}
|
|
1740
|
+
async function reconcileResumeCandidates(input) {
|
|
1741
|
+
let resumed = 0;
|
|
1742
|
+
for (const candidate of input.candidates) {
|
|
1743
|
+
if (candidate.action !== 'already_local')
|
|
1744
|
+
continue;
|
|
1745
|
+
const checkpoint = input.previousRun.processed.get(candidate.assetId);
|
|
1746
|
+
const provenanceRecord = input.provenanceSnapshot.get(candidate.assetId);
|
|
1747
|
+
const syncRecord = input.syncLedger.getForRunKey(input.runKey, candidate.assetId);
|
|
1748
|
+
const checkpointedAlreadyLocal = checkpoint?.outcome === 'already_local';
|
|
1749
|
+
const hubImportProvenance = provenanceRecord?.assetId === candidate.assetId
|
|
1750
|
+
&& provenanceRecord.source === 'hub'
|
|
1751
|
+
&& !provenanceRecord.trusted;
|
|
1752
|
+
const importedEvidence = Boolean(hubImportProvenance || syncRecord || (checkpoint && checkpoint.outcome !== 'already_local'));
|
|
1753
|
+
if (!checkpointedAlreadyLocal && !importedEvidence)
|
|
1754
|
+
continue;
|
|
1755
|
+
try {
|
|
1756
|
+
const storedAsset = await readBackStoredAsset(input.store, candidate.assetId, undefined, false, provenanceRecord, candidate.type);
|
|
1757
|
+
if (checkpointedAlreadyLocal) {
|
|
1758
|
+
resumed += 1;
|
|
1759
|
+
continue;
|
|
1760
|
+
}
|
|
1761
|
+
if (!provenanceRecord || provenanceRecord.assetId !== candidate.assetId || provenanceRecord.source !== 'hub' || provenanceRecord.trusted) {
|
|
1762
|
+
throw new SyncAbortError('resume_verification_failed', 'Resume provenance verification failed');
|
|
1763
|
+
}
|
|
1764
|
+
if (syncRecord && !syncRecordMatches(syncRecord, candidate, storedAsset)) {
|
|
1765
|
+
throw new SyncAbortError('resume_verification_failed', 'Resume sync ledger verification failed');
|
|
1766
|
+
}
|
|
1767
|
+
if (!syncRecord)
|
|
1768
|
+
appendSyncRecord(input.syncLedger, candidate, storedAsset, input.runKey, input.inventoryKey);
|
|
1769
|
+
if (checkpoint?.outcome !== 'imported') {
|
|
1770
|
+
input.appendRunCheckpoint({
|
|
1771
|
+
runId: input.runId,
|
|
1772
|
+
runKey: input.runKey,
|
|
1773
|
+
state: 'progress',
|
|
1774
|
+
remoteAssetId: candidate.assetId,
|
|
1775
|
+
outcome: 'imported',
|
|
1776
|
+
});
|
|
1777
|
+
}
|
|
1778
|
+
resumed += 1;
|
|
1779
|
+
}
|
|
1780
|
+
catch (error) {
|
|
1781
|
+
const mapped = mapSyncError(error);
|
|
1782
|
+
input.failures.push({ stage: 'write', assetId: candidate.assetId, reason: mapped.reason });
|
|
1783
|
+
input.appendRunCheckpoint({
|
|
1784
|
+
runId: input.runId,
|
|
1785
|
+
runKey: input.runKey,
|
|
1786
|
+
state: 'progress',
|
|
1787
|
+
remoteAssetId: candidate.assetId,
|
|
1788
|
+
outcome: 'failed',
|
|
1789
|
+
reason: mapped.reason,
|
|
1790
|
+
});
|
|
1791
|
+
}
|
|
1792
|
+
}
|
|
1793
|
+
return resumed;
|
|
754
1794
|
}
|
|
755
|
-
function
|
|
756
|
-
const
|
|
1795
|
+
async function verifyAlreadyLocalCandidates(candidates, store, provenanceSnapshot, failures) {
|
|
1796
|
+
const failedAssetIds = new Set(failures.flatMap((failure) => failure.assetId ? [failure.assetId] : []));
|
|
1797
|
+
for (const candidate of candidates) {
|
|
1798
|
+
if (candidate.action !== 'already_local' || failedAssetIds.has(candidate.assetId))
|
|
1799
|
+
continue;
|
|
1800
|
+
try {
|
|
1801
|
+
await readBackStoredAsset(store, candidate.assetId, undefined, false, provenanceSnapshot.get(candidate.assetId), candidate.type);
|
|
1802
|
+
}
|
|
1803
|
+
catch (error) {
|
|
1804
|
+
const mapped = mapSyncError(error);
|
|
1805
|
+
failures.push({ stage: 'write', assetId: candidate.assetId, reason: mapped.reason });
|
|
1806
|
+
failedAssetIds.add(candidate.assetId);
|
|
1807
|
+
}
|
|
1808
|
+
}
|
|
1809
|
+
}
|
|
1810
|
+
async function verifyAlreadyLocalGepxCandidates(candidates, assetsById, store, provenanceSnapshot, failures) {
|
|
1811
|
+
for (const candidate of [...candidates]) {
|
|
1812
|
+
if (candidate.action !== 'already_local')
|
|
1813
|
+
continue;
|
|
1814
|
+
const entry = assetsById.get(candidate.assetId);
|
|
1815
|
+
if (!entry)
|
|
1816
|
+
throw new SyncAbortError('integrity_error', '.gepx package asset is missing');
|
|
1817
|
+
try {
|
|
1818
|
+
const stored = await readBackStoredAsset(store, candidate.assetId, entry.asset, false, provenanceSnapshot.get(candidate.assetId), candidate.type);
|
|
1819
|
+
if (!assetstore.frozenAssetRecordsEqual(stored, entry.asset)) {
|
|
1820
|
+
throw new SyncAbortError('store_read_back_failed', 'Stored asset differs from packaged asset');
|
|
1821
|
+
}
|
|
1822
|
+
}
|
|
1823
|
+
catch (error) {
|
|
1824
|
+
const mapped = mapSyncError(error);
|
|
1825
|
+
failures.push({ stage: 'write', assetId: candidate.assetId, reason: mapped.reason });
|
|
1826
|
+
updateFinalCandidate(candidates, candidate, {
|
|
1827
|
+
...candidate,
|
|
1828
|
+
action: 'write_failed',
|
|
1829
|
+
failureReason: mapped.reason,
|
|
1830
|
+
});
|
|
1831
|
+
}
|
|
1832
|
+
}
|
|
1833
|
+
}
|
|
1834
|
+
async function readBackStoredAsset(store, assetId, expected, allowFrozenUnverified = false, provenance, expectedType = expected?.type) {
|
|
1835
|
+
let stored;
|
|
1836
|
+
try {
|
|
1837
|
+
stored = await store.get(assetId);
|
|
1838
|
+
}
|
|
1839
|
+
catch {
|
|
1840
|
+
throw new SyncAbortError('store_read_back_failed', 'Stored asset could not be read back');
|
|
1841
|
+
}
|
|
1842
|
+
const computed = stored ? wire.computeAssetId(stored) : null;
|
|
1843
|
+
const expectedComputed = expected ? wire.computeAssetId(expected) : assetId;
|
|
1844
|
+
const exactFrozenBody = Boolean(allowFrozenUnverified
|
|
1845
|
+
&& stored
|
|
1846
|
+
&& expected
|
|
1847
|
+
&& assetstore.frozenAssetRecordsEqual(stored, expected)
|
|
1848
|
+
&& computed === expectedComputed);
|
|
1849
|
+
const provenanceBoundFrozenBody = Boolean(stored
|
|
1850
|
+
&& computed
|
|
1851
|
+
&& isActiveFrozenWaiver(provenance, assetId, computed));
|
|
1852
|
+
if (!stored ||
|
|
1853
|
+
stored.asset_id !== assetId ||
|
|
1854
|
+
(!exactFrozenBody && !provenanceBoundFrozenBody && computed !== assetId) ||
|
|
1855
|
+
(!exactFrozenBody && !provenanceBoundFrozenBody && expectedComputed !== assetId) ||
|
|
1856
|
+
(expectedType !== undefined && stored.type !== expectedType)) {
|
|
1857
|
+
throw new SyncAbortError('store_read_back_failed', 'Stored asset failed read-back verification');
|
|
1858
|
+
}
|
|
1859
|
+
return stored;
|
|
1860
|
+
}
|
|
1861
|
+
function appendSyncRecord(syncLedger, candidate, asset, runKey, inventoryKey, extra = {}) {
|
|
1862
|
+
return syncLedger.append({
|
|
1863
|
+
assetId: asset.asset_id,
|
|
1864
|
+
type: asset.type,
|
|
1865
|
+
source: 'hub',
|
|
1866
|
+
scope: candidate.source === 'published' ? 'published' : 'purchased',
|
|
1867
|
+
remoteAssetId: candidate.assetId,
|
|
1868
|
+
runKey,
|
|
1869
|
+
inventoryKey,
|
|
1870
|
+
...(rawStringField(asset, 'id') ? { logicalId: rawStringField(asset, 'id') } : {}),
|
|
1871
|
+
...(candidate.status ? { status: candidate.status } : {}),
|
|
1872
|
+
...extra,
|
|
1873
|
+
});
|
|
1874
|
+
}
|
|
1875
|
+
function syncRecordMatches(record, candidate, asset) {
|
|
1876
|
+
const scope = candidate.source === 'published' ? 'published' : 'purchased';
|
|
1877
|
+
const logicalId = rawStringField(asset, 'id');
|
|
1878
|
+
return record.assetId === candidate.assetId &&
|
|
1879
|
+
record.remoteAssetId === candidate.assetId &&
|
|
1880
|
+
record.type === asset.type &&
|
|
1881
|
+
record.source === 'hub' &&
|
|
1882
|
+
record.scope === scope &&
|
|
1883
|
+
(!logicalId || record.logicalId === logicalId);
|
|
1884
|
+
}
|
|
1885
|
+
function preparePackagedAsset(candidate, asset, localAssetIds, logical, force, frozenUnverified = false) {
|
|
1886
|
+
const cleaned = { ...asset };
|
|
757
1887
|
const type = cleaned.type === 'Gene' || cleaned.type === 'Capsule' ? cleaned.type : undefined;
|
|
758
1888
|
if (!type)
|
|
759
1889
|
return { blocked: { ...candidate, type: cleaned.type ?? candidate.type, action: 'unsupported_type' } };
|
|
760
1890
|
if (type !== candidate.type)
|
|
761
1891
|
return { blocked: { ...candidate, type, action: 'unsupported_type' } };
|
|
762
|
-
const claimed =
|
|
1892
|
+
const claimed = rawStringField(cleaned, 'asset_id');
|
|
763
1893
|
const computed = wire.computeAssetId(cleaned);
|
|
764
|
-
if (!claimed
|
|
1894
|
+
if (!claimed
|
|
1895
|
+
|| !computed
|
|
1896
|
+
|| (claimed !== computed && !frozenUnverified)
|
|
1897
|
+
|| claimed !== candidate.assetId
|
|
1898
|
+
|| !isContentAssetId(claimed)
|
|
1899
|
+
|| !looksLikeFullAsset(cleaned, type)) {
|
|
765
1900
|
throw new SyncAbortError('integrity_error', '.gepx package integrity verification failed before import');
|
|
766
1901
|
}
|
|
767
1902
|
if (localAssetIds.has(cleaned.asset_id))
|
|
768
1903
|
return { blocked: { ...candidate, action: 'already_local' } };
|
|
769
|
-
const logicalId =
|
|
1904
|
+
const logicalId = rawStringField(cleaned, 'id');
|
|
770
1905
|
if (logicalId) {
|
|
771
1906
|
const localAssetId = logical.get(`${type}:${logicalId}`);
|
|
772
1907
|
if (localAssetId && localAssetId !== cleaned.asset_id) {
|
|
@@ -793,33 +1928,55 @@ function looksLikeFullAsset(value, type) {
|
|
|
793
1928
|
stringField(value, 'summary') &&
|
|
794
1929
|
asRecord(value['outcome']));
|
|
795
1930
|
}
|
|
796
|
-
function
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
1931
|
+
function declaresFullAssetPayload(value, type) {
|
|
1932
|
+
if (Object.prototype.hasOwnProperty.call(value, 'schema_version'))
|
|
1933
|
+
return true;
|
|
1934
|
+
if (type === 'Gene') {
|
|
1935
|
+
return Boolean(stringField(value, 'id')
|
|
1936
|
+
&& stringField(value, 'category')
|
|
1937
|
+
&& Array.isArray(value['signals_match'])
|
|
1938
|
+
&& Array.isArray(value['strategy'])
|
|
1939
|
+
&& asRecord(value['constraints'])
|
|
1940
|
+
&& Array.isArray(value['validation']));
|
|
1941
|
+
}
|
|
1942
|
+
return Boolean(stringField(value, 'id')
|
|
1943
|
+
&& stringField(value, 'gene')
|
|
1944
|
+
&& stringField(value, 'summary')
|
|
1945
|
+
&& asRecord(value['outcome']));
|
|
802
1946
|
}
|
|
803
1947
|
function readGepxPackage(path) {
|
|
804
1948
|
if (!path)
|
|
805
1949
|
throw new SyncAbortError('invalid_arg', '--import requires a file');
|
|
806
|
-
if (!existsSync(path))
|
|
807
|
-
throw new SyncAbortError('gepx_read_failed', 'could not read .gepx file');
|
|
808
1950
|
let parsed;
|
|
809
1951
|
try {
|
|
810
|
-
parsed = JSON.parse(
|
|
1952
|
+
parsed = JSON.parse(readBoundedGepxText(path));
|
|
811
1953
|
}
|
|
812
|
-
catch {
|
|
1954
|
+
catch (error) {
|
|
1955
|
+
if (error instanceof SyncAbortError)
|
|
1956
|
+
throw error;
|
|
813
1957
|
throw new SyncAbortError('invalid_gepx', 'invalid .gepx package');
|
|
814
1958
|
}
|
|
815
1959
|
const obj = asRecord(parsed);
|
|
816
1960
|
if (!obj || obj['type'] !== GEPX_TYPE || obj['version'] !== GEPX_VERSION || !Array.isArray(obj['assets'])) {
|
|
817
1961
|
throw new SyncAbortError('invalid_gepx', 'invalid .gepx package');
|
|
818
1962
|
}
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
.
|
|
1963
|
+
if (obj['assets'].length > MAX_GEPX_ASSETS)
|
|
1964
|
+
throw new SyncAbortError('invalid_gepx', 'invalid .gepx package');
|
|
1965
|
+
if ((Array.isArray(obj['provenance']) && obj['provenance'].length > MAX_GEPX_SIDECAR_RECORDS)
|
|
1966
|
+
|| (Array.isArray(obj['sync']) && obj['sync'].length > MAX_GEPX_SIDECAR_RECORDS)) {
|
|
1967
|
+
throw new SyncAbortError('invalid_gepx', 'invalid .gepx package');
|
|
1968
|
+
}
|
|
1969
|
+
const assets = [];
|
|
1970
|
+
const malformedAssets = [];
|
|
1971
|
+
obj['assets'].forEach((rawAsset, index) => {
|
|
1972
|
+
const asset = asRecord(rawAsset);
|
|
1973
|
+
const assetId = asset ? rawStringField(asset, 'asset_id') : undefined;
|
|
1974
|
+
if (!asset || !assetId) {
|
|
1975
|
+
malformedAssets.push({ index, ...(assetId ? { assetId } : {}) });
|
|
1976
|
+
return;
|
|
1977
|
+
}
|
|
1978
|
+
assets.push(asset);
|
|
1979
|
+
});
|
|
823
1980
|
const provenance = Array.isArray(obj['provenance'])
|
|
824
1981
|
? obj['provenance'].map((record) => parseGepxProvenanceRecord(asRecord(record))).filter((record) => Boolean(record))
|
|
825
1982
|
: [];
|
|
@@ -831,36 +1988,132 @@ function readGepxPackage(path) {
|
|
|
831
1988
|
version: GEPX_VERSION,
|
|
832
1989
|
...(stringField(obj, 'exportedAt') ? { exportedAt: stringField(obj, 'exportedAt') } : {}),
|
|
833
1990
|
assets,
|
|
1991
|
+
malformedAssets,
|
|
834
1992
|
provenance,
|
|
835
1993
|
sync,
|
|
836
1994
|
};
|
|
837
1995
|
}
|
|
1996
|
+
function readBoundedGepxText(path) {
|
|
1997
|
+
let before;
|
|
1998
|
+
try {
|
|
1999
|
+
before = lstatSync(path, { bigint: true });
|
|
2000
|
+
}
|
|
2001
|
+
catch {
|
|
2002
|
+
throw new SyncAbortError('gepx_read_failed', 'could not read .gepx file');
|
|
2003
|
+
}
|
|
2004
|
+
if (!before.isFile() || before.isSymbolicLink() || before.size > BigInt(MAX_GEPX_BYTES)) {
|
|
2005
|
+
throw new SyncAbortError('invalid_gepx', 'invalid .gepx package');
|
|
2006
|
+
}
|
|
2007
|
+
let descriptor;
|
|
2008
|
+
try {
|
|
2009
|
+
descriptor = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
|
|
2010
|
+
}
|
|
2011
|
+
catch {
|
|
2012
|
+
throw new SyncAbortError('gepx_read_failed', 'could not read .gepx file');
|
|
2013
|
+
}
|
|
2014
|
+
let opened;
|
|
2015
|
+
let text;
|
|
2016
|
+
try {
|
|
2017
|
+
opened = fstatSync(descriptor, { bigint: true });
|
|
2018
|
+
if (!opened.isFile()
|
|
2019
|
+
|| opened.size > BigInt(MAX_GEPX_BYTES)
|
|
2020
|
+
|| opened.dev !== before.dev
|
|
2021
|
+
|| opened.ino !== before.ino
|
|
2022
|
+
|| opened.size !== before.size) {
|
|
2023
|
+
throw new SyncAbortError('invalid_gepx', 'invalid .gepx package');
|
|
2024
|
+
}
|
|
2025
|
+
const chunks = [];
|
|
2026
|
+
let total = 0;
|
|
2027
|
+
while (total <= MAX_GEPX_BYTES) {
|
|
2028
|
+
const remaining = MAX_GEPX_BYTES + 1 - total;
|
|
2029
|
+
if (remaining <= 0)
|
|
2030
|
+
break;
|
|
2031
|
+
const chunk = Buffer.allocUnsafe(Math.min(64 * 1024, remaining));
|
|
2032
|
+
const count = readSync(descriptor, chunk, 0, chunk.length, null);
|
|
2033
|
+
if (count === 0)
|
|
2034
|
+
break;
|
|
2035
|
+
chunks.push(chunk.subarray(0, count));
|
|
2036
|
+
total += count;
|
|
2037
|
+
}
|
|
2038
|
+
if (total > MAX_GEPX_BYTES)
|
|
2039
|
+
throw new SyncAbortError('invalid_gepx', 'invalid .gepx package');
|
|
2040
|
+
const settled = fstatSync(descriptor, { bigint: true });
|
|
2041
|
+
if (settled.dev !== opened.dev
|
|
2042
|
+
|| settled.ino !== opened.ino
|
|
2043
|
+
|| settled.size !== opened.size
|
|
2044
|
+
|| settled.mtimeNs !== opened.mtimeNs
|
|
2045
|
+
|| settled.ctimeNs !== opened.ctimeNs) {
|
|
2046
|
+
throw new SyncAbortError('invalid_gepx', 'invalid .gepx package');
|
|
2047
|
+
}
|
|
2048
|
+
text = Buffer.concat(chunks, total).toString('utf8');
|
|
2049
|
+
}
|
|
2050
|
+
catch (error) {
|
|
2051
|
+
if (error instanceof SyncAbortError)
|
|
2052
|
+
throw error;
|
|
2053
|
+
throw new SyncAbortError('gepx_read_failed', 'could not read .gepx file');
|
|
2054
|
+
}
|
|
2055
|
+
finally {
|
|
2056
|
+
closeSync(descriptor);
|
|
2057
|
+
}
|
|
2058
|
+
let after;
|
|
2059
|
+
try {
|
|
2060
|
+
after = lstatSync(path, { bigint: true });
|
|
2061
|
+
}
|
|
2062
|
+
catch {
|
|
2063
|
+
throw new SyncAbortError('invalid_gepx', 'invalid .gepx package');
|
|
2064
|
+
}
|
|
2065
|
+
if (!after.isFile()
|
|
2066
|
+
|| after.isSymbolicLink()
|
|
2067
|
+
|| after.dev !== before.dev
|
|
2068
|
+
|| after.ino !== before.ino
|
|
2069
|
+
|| after.size !== before.size
|
|
2070
|
+
|| after.mtimeNs !== before.mtimeNs
|
|
2071
|
+
|| after.ctimeNs !== before.ctimeNs) {
|
|
2072
|
+
throw new SyncAbortError('invalid_gepx', 'invalid .gepx package');
|
|
2073
|
+
}
|
|
2074
|
+
return text;
|
|
2075
|
+
}
|
|
838
2076
|
function parseGepxProvenanceRecord(value) {
|
|
839
2077
|
if (!value)
|
|
840
2078
|
return null;
|
|
841
|
-
const assetId =
|
|
2079
|
+
const assetId = rawStringField(value, 'assetId');
|
|
842
2080
|
const source = stringField(value, 'source');
|
|
843
2081
|
const at = stringField(value, 'at');
|
|
844
|
-
|
|
2082
|
+
const frozenContentId = rawStringField(value, 'frozenContentId');
|
|
2083
|
+
if (!assetId
|
|
2084
|
+
|| !at
|
|
2085
|
+
|| Number.isNaN(Date.parse(at))
|
|
2086
|
+
|| typeof value['trusted'] !== 'boolean'
|
|
2087
|
+
|| (source !== 'local' && source !== 'migrated' && source !== 'hub')
|
|
2088
|
+
|| (frozenContentId !== undefined && !/^sha256:[0-9a-f]{64}$/.test(frozenContentId)))
|
|
2089
|
+
return null;
|
|
2090
|
+
const rawDecision = value['decision'];
|
|
2091
|
+
if (rawDecision !== undefined && rawDecision !== 'promoted' && rawDecision !== 'revoked')
|
|
845
2092
|
return null;
|
|
2093
|
+
const decision = rawDecision === 'promoted' || rawDecision === 'revoked'
|
|
2094
|
+
? rawDecision
|
|
2095
|
+
: undefined;
|
|
846
2096
|
return {
|
|
847
2097
|
assetId,
|
|
848
2098
|
source,
|
|
849
|
-
trusted: value['trusted']
|
|
2099
|
+
trusted: value['trusted'],
|
|
850
2100
|
at,
|
|
2101
|
+
...(decision ? { decision } : {}),
|
|
2102
|
+
...(stringField(value, 'decidedBy') ? { decidedBy: stringField(value, 'decidedBy') } : {}),
|
|
851
2103
|
...(stringField(value, 'promotedBy') ? { promotedBy: stringField(value, 'promotedBy') } : {}),
|
|
852
2104
|
...(stringField(value, 'reason') ? { reason: stringField(value, 'reason') } : {}),
|
|
2105
|
+
...(frozenContentId ? { frozenContentId } : {}),
|
|
853
2106
|
};
|
|
854
2107
|
}
|
|
855
2108
|
function parseGepxSyncRecord(value) {
|
|
856
2109
|
if (!value)
|
|
857
2110
|
return null;
|
|
858
|
-
const assetId =
|
|
859
|
-
const type =
|
|
860
|
-
const source =
|
|
861
|
-
const scope =
|
|
2111
|
+
const assetId = rawStringField(value, 'assetId');
|
|
2112
|
+
const type = rawStringField(value, 'type');
|
|
2113
|
+
const source = rawStringField(value, 'source');
|
|
2114
|
+
const scope = rawStringField(value, 'scope');
|
|
862
2115
|
const syncedAt = stringField(value, 'syncedAt');
|
|
863
|
-
const remoteAssetId =
|
|
2116
|
+
const remoteAssetId = rawStringField(value, 'remoteAssetId');
|
|
864
2117
|
if (!assetId || (type !== 'Gene' && type !== 'Capsule') || source !== 'hub' || (scope !== 'purchased' && scope !== 'published') || !syncedAt || !remoteAssetId) {
|
|
865
2118
|
return null;
|
|
866
2119
|
}
|
|
@@ -871,40 +2124,78 @@ function parseGepxSyncRecord(value) {
|
|
|
871
2124
|
scope,
|
|
872
2125
|
syncedAt,
|
|
873
2126
|
remoteAssetId,
|
|
874
|
-
...(
|
|
2127
|
+
...(rawStringField(value, 'logicalId') ? { logicalId: rawStringField(value, 'logicalId') } : {}),
|
|
875
2128
|
...(stringField(value, 'status') ? { status: stringField(value, 'status') } : {}),
|
|
876
2129
|
...(value['forced'] === true ? { forced: true } : {}),
|
|
877
|
-
...(
|
|
2130
|
+
...(rawStringField(value, 'collisionWithAssetId') ? { collisionWithAssetId: rawStringField(value, 'collisionWithAssetId') } : {}),
|
|
878
2131
|
};
|
|
879
2132
|
}
|
|
880
2133
|
function remoteType(row) {
|
|
881
|
-
const
|
|
882
|
-
const raw = stringField(row, 'type') ?? stringField(row, 'asset_type') ?? (payload ? stringField(payload, 'type') : undefined);
|
|
2134
|
+
const raw = remoteDeclaredType(row);
|
|
883
2135
|
return raw === 'Gene' || raw === 'Capsule' ? raw : undefined;
|
|
884
2136
|
}
|
|
2137
|
+
function remoteDeclaredType(row) {
|
|
2138
|
+
const payload = asRecord(row.payload);
|
|
2139
|
+
return rawStringField(row, 'type')
|
|
2140
|
+
?? rawStringField(row, 'asset_type')
|
|
2141
|
+
?? (payload ? rawStringField(payload, 'type') : undefined);
|
|
2142
|
+
}
|
|
885
2143
|
function remoteLogicalId(row) {
|
|
886
2144
|
const payload = asRecord(row.payload);
|
|
887
|
-
|
|
2145
|
+
if (!Object.prototype.hasOwnProperty.call(row, 'type') && payload && rawStringField(payload, 'type') !== undefined) {
|
|
2146
|
+
return rawStringField(row, 'local_id') ?? rawStringField(payload, 'id');
|
|
2147
|
+
}
|
|
2148
|
+
return rawStringField(row, 'id')
|
|
2149
|
+
?? rawStringField(row, 'local_id')
|
|
2150
|
+
?? (payload ? rawStringField(payload, 'id') : undefined);
|
|
2151
|
+
}
|
|
2152
|
+
function isContentAssetId(value) {
|
|
2153
|
+
return /^sha256:[0-9a-f]{64}$/.test(value);
|
|
2154
|
+
}
|
|
2155
|
+
function isRemoteTombstone(row) {
|
|
2156
|
+
return stringField(row, 'status')?.toLowerCase() === 'revoked'
|
|
2157
|
+
|| stringField(row, 'trust_state')?.toLowerCase() === 'revoked';
|
|
2158
|
+
}
|
|
2159
|
+
function isRemoteTombstoneDelivery(row) {
|
|
2160
|
+
if (isRemoteTombstone(row))
|
|
2161
|
+
return true;
|
|
2162
|
+
const nested = asRecord(row.payload);
|
|
2163
|
+
return nested ? isRemoteTombstone(nested) : false;
|
|
888
2164
|
}
|
|
889
2165
|
function emitTextPreview(preview, out) {
|
|
890
2166
|
const c = preview.counts;
|
|
891
2167
|
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}`);
|
|
2168
|
+
out(` would_import=${c.wouldImport} unverified_would_import=${c.unverifiedWouldImport} 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}`);
|
|
2169
|
+
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}`);
|
|
2170
|
+
emitTextNextCursors(preview.nextCursors, out);
|
|
893
2171
|
for (const candidate of preview.candidates.slice(0, 10)) {
|
|
894
|
-
out(` ${candidate.action}: ${candidate.type} ${candidate.assetId}${candidate.logicalId ? ` (${candidate.logicalId})` : ''}`);
|
|
2172
|
+
out(` ${candidate.action}: ${candidate.type} ${candidate.assetId}${candidate.logicalId ? ` (${candidate.logicalId})` : ''}${formatHubVerification(candidate)}`);
|
|
895
2173
|
}
|
|
896
2174
|
}
|
|
897
2175
|
function emitTextWrite(result, out) {
|
|
898
2176
|
const c = result.counts;
|
|
899
2177
|
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}`);
|
|
2178
|
+
out(` written=${result.written.length} blocked=${result.blocked.length} would_import=${c.wouldImport} unverified_would_import=${c.unverifiedWouldImport} 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}`);
|
|
2179
|
+
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}`);
|
|
2180
|
+
emitTextNextCursors(result.nextCursors, out);
|
|
901
2181
|
for (const asset of result.written.slice(0, 10)) {
|
|
902
|
-
out(` imported: ${asset.type} ${asset.assetId}${asset.logicalId ? ` (${asset.logicalId})` : ''}`);
|
|
2182
|
+
out(` imported: ${asset.type} ${asset.assetId}${asset.logicalId ? ` (${asset.logicalId})` : ''}${formatHubVerification(asset)}`);
|
|
903
2183
|
}
|
|
904
2184
|
for (const candidate of result.blocked.slice(0, 10)) {
|
|
905
2185
|
out(` blocked/${candidate.action}: ${candidate.type} ${candidate.assetId}${candidate.logicalId ? ` (${candidate.logicalId})` : ''}`);
|
|
906
2186
|
}
|
|
907
2187
|
}
|
|
2188
|
+
function formatHubVerification(value) {
|
|
2189
|
+
if (value.verification !== 'unverified')
|
|
2190
|
+
return '';
|
|
2191
|
+
return ` [verification=unverified${value.verificationReason ? ` reason=${value.verificationReason}` : ''}]`;
|
|
2192
|
+
}
|
|
2193
|
+
function emitTextNextCursors(nextCursors, out) {
|
|
2194
|
+
if (nextCursors.purchased)
|
|
2195
|
+
out(` next_purchased_cursor=${nextCursors.purchased}`);
|
|
2196
|
+
if (nextCursors.published)
|
|
2197
|
+
out(` next_published_cursor=${nextCursors.published}`);
|
|
2198
|
+
}
|
|
908
2199
|
function emitTextExport(result, out) {
|
|
909
2200
|
out(`sync export: exported=${result.counts.exported} provenance=${result.counts.provenance} sync=${result.counts.sync}`);
|
|
910
2201
|
for (const asset of result.assets.slice(0, 10)) {
|
|
@@ -914,21 +2205,24 @@ function emitTextExport(result, out) {
|
|
|
914
2205
|
function emitTextImportPreview(result, out) {
|
|
915
2206
|
const c = result.counts;
|
|
916
2207
|
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}`);
|
|
2208
|
+
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
2209
|
for (const candidate of result.candidates.slice(0, 10)) {
|
|
919
2210
|
out(` ${candidate.action}: ${candidate.type} ${candidate.assetId}${candidate.logicalId ? ` (${candidate.logicalId})` : ''}`);
|
|
920
2211
|
}
|
|
921
2212
|
}
|
|
922
2213
|
function emitTextImport(result, out) {
|
|
923
2214
|
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}`);
|
|
2215
|
+
out(`sync import: written=${result.written.length} blocked=${result.blocked.length} failed=${result.failures.length} unique=${c.uniqueRemote}`);
|
|
2216
|
+
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
2217
|
for (const asset of result.written.slice(0, 10)) {
|
|
927
2218
|
out(` imported: ${asset.type} ${asset.assetId}${asset.logicalId ? ` (${asset.logicalId})` : ''}`);
|
|
928
2219
|
}
|
|
929
2220
|
for (const candidate of result.blocked.slice(0, 10)) {
|
|
930
2221
|
out(` blocked/${candidate.action}: ${candidate.type} ${candidate.assetId}${candidate.logicalId ? ` (${candidate.logicalId})` : ''}`);
|
|
931
2222
|
}
|
|
2223
|
+
for (const failure of result.failures.slice(0, 10)) {
|
|
2224
|
+
out(` failed/${failure.reason}: ${failure.assetId ?? 'unknown'}`);
|
|
2225
|
+
}
|
|
932
2226
|
}
|
|
933
2227
|
class SyncAbortError extends Error {
|
|
934
2228
|
reason;
|
|
@@ -938,17 +2232,31 @@ class SyncAbortError extends Error {
|
|
|
938
2232
|
this.name = 'SyncAbortError';
|
|
939
2233
|
}
|
|
940
2234
|
}
|
|
2235
|
+
function loadSyncEnv(env) {
|
|
2236
|
+
const envFile = loadEnvFileFromEnv(env);
|
|
2237
|
+
if (envFile.error)
|
|
2238
|
+
throw new SyncAbortError('env_file_unavailable', 'Configured environment file is unavailable');
|
|
2239
|
+
}
|
|
941
2240
|
function emitFailure(reason, message, jsonOut, out, err) {
|
|
942
|
-
const payload = { ok: false, group: GROUP, reason, message:
|
|
2241
|
+
const payload = { ok: false, group: GROUP, reason, message: formatTerminalText(message) };
|
|
943
2242
|
if (jsonOut)
|
|
944
|
-
out(
|
|
2243
|
+
out(stringifyJsonOutput(payload));
|
|
945
2244
|
else
|
|
946
|
-
err(`sync failed (${reason}): ${
|
|
2245
|
+
err(formatTerminalText(`sync failed (${reason}): ${message}`));
|
|
947
2246
|
return 1;
|
|
948
2247
|
}
|
|
949
2248
|
function mapSyncError(error) {
|
|
950
2249
|
if (error instanceof SyncAbortError)
|
|
951
2250
|
return { reason: error.reason, message: error.message };
|
|
2251
|
+
if (error instanceof MalformedAccountAssetPageError) {
|
|
2252
|
+
return { reason: 'malformed_page', message: 'Hub account asset page is malformed' };
|
|
2253
|
+
}
|
|
2254
|
+
if (error instanceof assetstore.FrozenAssetIdCollisionError) {
|
|
2255
|
+
return { reason: 'integrity_error', message: 'Frozen Hub asset conflicts with existing content or provenance' };
|
|
2256
|
+
}
|
|
2257
|
+
if (error instanceof assetstore.InvalidConditionalPutResultError) {
|
|
2258
|
+
return { reason: 'conditional_write_invalid', message: 'Conditional asset write returned an invalid result' };
|
|
2259
|
+
}
|
|
952
2260
|
if (error instanceof AuthError)
|
|
953
2261
|
return { reason: 'auth_required', message: 'Hub authentication required' };
|
|
954
2262
|
if (error instanceof HubClientError) {
|
|
@@ -965,24 +2273,398 @@ function mapSyncError(error) {
|
|
|
965
2273
|
return { reason: 'auth_required', message: redact(message) };
|
|
966
2274
|
if (/network|fetch failed|ECONN|ENOTFOUND|ETIMEDOUT|hub 5\d\d/i.test(message))
|
|
967
2275
|
return { reason: 'network_error', message: 'Hub unreachable' };
|
|
968
|
-
return { reason: 'internal_error', message:
|
|
2276
|
+
return { reason: 'internal_error', message: 'Sync operation failed' };
|
|
969
2277
|
}
|
|
970
2278
|
function hasFetchAssetById(hub) {
|
|
971
2279
|
return typeof hub.fetchAssetById === 'function';
|
|
972
2280
|
}
|
|
2281
|
+
function isSyncAccountAssetHub(value) {
|
|
2282
|
+
const candidate = value;
|
|
2283
|
+
return typeof candidate?.listAccountAssets === 'function' && typeof candidate.fetchAssetById === 'function';
|
|
2284
|
+
}
|
|
2285
|
+
function syncRunKey(opts, env, deps) {
|
|
2286
|
+
const material = {
|
|
2287
|
+
...syncInventoryIdentity(opts, env, deps),
|
|
2288
|
+
limit: opts.limit,
|
|
2289
|
+
pageSize: opts.pageSize,
|
|
2290
|
+
force: opts.force,
|
|
2291
|
+
purchasedCursor: opts.purchasedCursor ?? '',
|
|
2292
|
+
publishedCursor: opts.publishedCursor ?? '',
|
|
2293
|
+
};
|
|
2294
|
+
return createHash('sha256').update(JSON.stringify(material)).digest('hex');
|
|
2295
|
+
}
|
|
2296
|
+
function syncInventoryKey(opts, env, deps) {
|
|
2297
|
+
return createHash('sha256').update(JSON.stringify(syncInventoryIdentity(opts, env, deps))).digest('hex');
|
|
2298
|
+
}
|
|
2299
|
+
function prepareInventoryScan(syncLedger, inventoryKey, opts) {
|
|
2300
|
+
const inputCursors = {
|
|
2301
|
+
purchased: opts.purchasedCursor ?? null,
|
|
2302
|
+
published: opts.publishedCursor ?? null,
|
|
2303
|
+
};
|
|
2304
|
+
const inputCursorFingerprints = fingerprintCursors(inputCursors);
|
|
2305
|
+
const previous = syncLedger.latestInventoryScan(inventoryKey);
|
|
2306
|
+
if (opts.resume
|
|
2307
|
+
&& previous
|
|
2308
|
+
&& !previous.complete
|
|
2309
|
+
&& previous.retryIndex !== undefined
|
|
2310
|
+
&& previous.scope === opts.scope
|
|
2311
|
+
&& cursorFingerprintsMatch(previous.nextCursorFingerprints, inputCursorFingerprints)) {
|
|
2312
|
+
return {
|
|
2313
|
+
trackable: true,
|
|
2314
|
+
scanId: previous.scanId,
|
|
2315
|
+
index: previous.retryIndex,
|
|
2316
|
+
retry: true,
|
|
2317
|
+
inputCursorFingerprints,
|
|
2318
|
+
skipPurchased: opts.scope === 'all'
|
|
2319
|
+
&& previous.nextCursorFingerprints.purchased === null
|
|
2320
|
+
&& previous.nextCursorFingerprints.published !== null,
|
|
2321
|
+
skipPublished: opts.scope === 'all'
|
|
2322
|
+
&& previous.nextCursorFingerprints.published === null
|
|
2323
|
+
&& previous.nextCursorFingerprints.purchased !== null,
|
|
2324
|
+
};
|
|
2325
|
+
}
|
|
2326
|
+
if (inputCursors.purchased === null && inputCursors.published === null) {
|
|
2327
|
+
return {
|
|
2328
|
+
trackable: true,
|
|
2329
|
+
scanId: randomUUID(),
|
|
2330
|
+
index: 0,
|
|
2331
|
+
retry: false,
|
|
2332
|
+
inputCursorFingerprints,
|
|
2333
|
+
skipPurchased: false,
|
|
2334
|
+
skipPublished: false,
|
|
2335
|
+
};
|
|
2336
|
+
}
|
|
2337
|
+
if (previous
|
|
2338
|
+
&& !previous.complete
|
|
2339
|
+
&& previous.retryIndex === undefined
|
|
2340
|
+
&& previous.scope === opts.scope
|
|
2341
|
+
&& cursorFingerprintsMatch(previous.nextCursorFingerprints, inputCursorFingerprints)) {
|
|
2342
|
+
return {
|
|
2343
|
+
trackable: true,
|
|
2344
|
+
scanId: previous.scanId,
|
|
2345
|
+
index: previous.segmentCount,
|
|
2346
|
+
retry: false,
|
|
2347
|
+
inputCursorFingerprints,
|
|
2348
|
+
skipPurchased: opts.scope === 'all' && previous.nextCursorFingerprints.purchased === null,
|
|
2349
|
+
skipPublished: opts.scope === 'all' && previous.nextCursorFingerprints.published === null,
|
|
2350
|
+
};
|
|
2351
|
+
}
|
|
2352
|
+
return {
|
|
2353
|
+
trackable: false,
|
|
2354
|
+
scanId: randomUUID(),
|
|
2355
|
+
index: 0,
|
|
2356
|
+
retry: false,
|
|
2357
|
+
inputCursorFingerprints,
|
|
2358
|
+
skipPurchased: false,
|
|
2359
|
+
skipPublished: false,
|
|
2360
|
+
};
|
|
2361
|
+
}
|
|
2362
|
+
function isRetryableAssetFailure(failure) {
|
|
2363
|
+
return (failure.stage === 'fetch' || failure.stage === 'write')
|
|
2364
|
+
&& (failure.reason === 'network_error' || failure.reason === 'internal_error');
|
|
2365
|
+
}
|
|
2366
|
+
function fingerprintCursors(cursors) {
|
|
2367
|
+
return {
|
|
2368
|
+
purchased: cursors.purchased === null ? null : createHash('sha256').update(cursors.purchased).digest('hex'),
|
|
2369
|
+
published: cursors.published === null ? null : createHash('sha256').update(cursors.published).digest('hex'),
|
|
2370
|
+
};
|
|
2371
|
+
}
|
|
2372
|
+
function cursorFingerprintsMatch(left, right) {
|
|
2373
|
+
return left.purchased === right.purchased && left.published === right.published;
|
|
2374
|
+
}
|
|
2375
|
+
function syncInventoryIdentity(opts, env, deps) {
|
|
2376
|
+
const privateMode = isPrivateHubMode(env);
|
|
2377
|
+
const suppliedIdentityFingerprint = suppliedResumeIdentityFingerprint(deps);
|
|
2378
|
+
return {
|
|
2379
|
+
mode: String(env['EVOMAP_HUB_MODE'] ?? 'public').trim().toLowerCase(),
|
|
2380
|
+
hubUrl: privateMode ? requirePrivateHubUrl(env) : resolveHubUrl(env),
|
|
2381
|
+
account: privateMode
|
|
2382
|
+
? firstNonEmptyEnv(env, ['EVOMAP_ENTERPRISE_SUBJECT', 'EVOMAP_PRIVATE_SUBJECT', 'PHUB_ENTERPRISE_SUBJECT', 'USER']) ?? 'evolver-proxy'
|
|
2383
|
+
: '',
|
|
2384
|
+
credentialFingerprint: suppliedIdentityFingerprint
|
|
2385
|
+
?? (privateMode ? syncCredentialFingerprint(env) : publicResumeIdentityFingerprint(env, deps)),
|
|
2386
|
+
scope: opts.scope,
|
|
2387
|
+
type: opts.type ?? '',
|
|
2388
|
+
status: opts.status,
|
|
2389
|
+
};
|
|
2390
|
+
}
|
|
2391
|
+
function reconciliationRecords(syncLedger, inventoryKey, legacyRunKey) {
|
|
2392
|
+
const records = new Map();
|
|
2393
|
+
for (const record of syncLedger.listForInventoryKey(inventoryKey))
|
|
2394
|
+
records.set(record.assetId, record);
|
|
2395
|
+
// Records written before inventoryKey existed retain same-parameter reconciliation behavior.
|
|
2396
|
+
for (const record of syncLedger.listForRunKey(legacyRunKey))
|
|
2397
|
+
records.set(record.assetId, record);
|
|
2398
|
+
return [...records.values()];
|
|
2399
|
+
}
|
|
2400
|
+
function countMissingRemote(syncLedger, inventoryKey, legacyRunKey, localAssetIds, remoteAssetIds) {
|
|
2401
|
+
return reconciliationRecords(syncLedger, inventoryKey, legacyRunKey)
|
|
2402
|
+
.filter((record) => localAssetIds.has(record.assetId) && !remoteAssetIds.has(record.remoteAssetId))
|
|
2403
|
+
.length;
|
|
2404
|
+
}
|
|
2405
|
+
function inventorySegmentOutcome(candidates, failures, written) {
|
|
2406
|
+
const failedAssetIds = new Set(failures.flatMap((failure) => failure.assetId ? [failure.assetId] : []));
|
|
2407
|
+
const writtenAssetIds = new Set(written.map((asset) => asset.assetId));
|
|
2408
|
+
const items = [];
|
|
2409
|
+
let anonymousBlocked = 0;
|
|
2410
|
+
for (const candidate of candidates) {
|
|
2411
|
+
if (candidate.assetId === MISSING_ASSET_ID) {
|
|
2412
|
+
anonymousBlocked += 1;
|
|
2413
|
+
continue;
|
|
2414
|
+
}
|
|
2415
|
+
let outcome;
|
|
2416
|
+
if (failedAssetIds.has(candidate.assetId))
|
|
2417
|
+
outcome = 'failed';
|
|
2418
|
+
else if (candidate.action === 'already_local')
|
|
2419
|
+
outcome = 'already_local';
|
|
2420
|
+
else if (isBlockedCandidate(candidate))
|
|
2421
|
+
outcome = 'blocked';
|
|
2422
|
+
else if (writtenAssetIds.has(candidate.assetId))
|
|
2423
|
+
outcome = 'imported';
|
|
2424
|
+
else
|
|
2425
|
+
outcome = 'pending';
|
|
2426
|
+
items.push({ remoteAssetId: candidate.assetId, outcome });
|
|
2427
|
+
}
|
|
2428
|
+
return { items, anonymousBlocked };
|
|
2429
|
+
}
|
|
2430
|
+
function reconcileInventorySnapshot(snapshot, missingRemote) {
|
|
2431
|
+
let imported = 0;
|
|
2432
|
+
let alreadyLocal = 0;
|
|
2433
|
+
let blocked = snapshot.anonymousBlocked;
|
|
2434
|
+
let failed = 0;
|
|
2435
|
+
let pending = 0;
|
|
2436
|
+
for (const outcome of snapshot.outcomes.values()) {
|
|
2437
|
+
if (outcome === 'imported')
|
|
2438
|
+
imported += 1;
|
|
2439
|
+
else if (outcome === 'already_local')
|
|
2440
|
+
alreadyLocal += 1;
|
|
2441
|
+
else if (outcome === 'blocked')
|
|
2442
|
+
blocked += 1;
|
|
2443
|
+
else if (outcome === 'failed')
|
|
2444
|
+
failed += 1;
|
|
2445
|
+
else
|
|
2446
|
+
pending += 1;
|
|
2447
|
+
}
|
|
2448
|
+
const remoteUnique = snapshot.outcomes.size + snapshot.anonymousBlocked;
|
|
2449
|
+
const accounted = imported + alreadyLocal + blocked + failed + pending;
|
|
2450
|
+
return {
|
|
2451
|
+
remoteUnique,
|
|
2452
|
+
accounted,
|
|
2453
|
+
imported,
|
|
2454
|
+
alreadyLocal,
|
|
2455
|
+
blocked,
|
|
2456
|
+
failed,
|
|
2457
|
+
pending,
|
|
2458
|
+
inventoryComplete: snapshot.complete,
|
|
2459
|
+
missingRemote,
|
|
2460
|
+
consistent: snapshot.complete
|
|
2461
|
+
&& missingRemote === 0
|
|
2462
|
+
&& blocked === 0
|
|
2463
|
+
&& failed === 0
|
|
2464
|
+
&& pending === 0
|
|
2465
|
+
&& accounted === remoteUnique,
|
|
2466
|
+
};
|
|
2467
|
+
}
|
|
2468
|
+
function publicResumeIdentityFingerprint(env, deps) {
|
|
2469
|
+
if (!deps.hub)
|
|
2470
|
+
return resolveRecipeHubResumeIdentityFingerprint(env);
|
|
2471
|
+
return createHash('sha256').update(JSON.stringify({
|
|
2472
|
+
account: firstNonEmptyEnv(env, ['EVOMAP_NODE_ID', 'A2A_NODE_ID']) ?? '',
|
|
2473
|
+
credentialFingerprint: syncCredentialFingerprint(env),
|
|
2474
|
+
})).digest('hex');
|
|
2475
|
+
}
|
|
2476
|
+
function syncCredentialFingerprint(env) {
|
|
2477
|
+
const credentials = [
|
|
2478
|
+
['A2A_INVITATION_TOKEN', firstNonEmptyEnv(env, ['A2A_INVITATION_TOKEN'])],
|
|
2479
|
+
['enterprise', firstNonEmptyEnv(env, [
|
|
2480
|
+
'EVOMAP_ENTERPRISE_TOKEN',
|
|
2481
|
+
'EVOMAP_PRIVATE_HUB_TOKEN',
|
|
2482
|
+
'PHUB_ENTERPRISE_TOKEN',
|
|
2483
|
+
'PRIVATE_HUB_ENTERPRISE_TOKEN',
|
|
2484
|
+
])],
|
|
2485
|
+
['node', firstNonEmptyEnv(env, ['EVOMAP_NODE_SECRET', 'A2A_NODE_SECRET'])],
|
|
2486
|
+
].filter((entry) => entry[1] !== undefined);
|
|
2487
|
+
if (credentials.length === 0)
|
|
2488
|
+
return '';
|
|
2489
|
+
return createHash('sha256').update(JSON.stringify(credentials)).digest('hex');
|
|
2490
|
+
}
|
|
2491
|
+
function isPrivateHubMode(env) {
|
|
2492
|
+
return String(env['EVOMAP_HUB_MODE'] ?? 'public').trim().toLowerCase() === 'private';
|
|
2493
|
+
}
|
|
2494
|
+
function configuredPrivateHubUrl(env) {
|
|
2495
|
+
return firstNonEmptyEnv(env, ['EVOMAP_HUB_URL', 'A2A_HUB_URL', 'EVOLVER_DEFAULT_HUB_URL']);
|
|
2496
|
+
}
|
|
2497
|
+
function requirePrivateHubUrl(env) {
|
|
2498
|
+
const hubUrl = configuredPrivateHubUrl(env);
|
|
2499
|
+
if (!hubUrl)
|
|
2500
|
+
throw new SyncAbortError('private_hub_url_required', 'Private Hub URL must be configured explicitly');
|
|
2501
|
+
return hubUrl;
|
|
2502
|
+
}
|
|
2503
|
+
function validatePrivateHubUrl(env) {
|
|
2504
|
+
if (isPrivateHubMode(env))
|
|
2505
|
+
requirePrivateHubUrl(env);
|
|
2506
|
+
}
|
|
2507
|
+
function firstNonEmptyEnv(env, keys) {
|
|
2508
|
+
for (const key of keys) {
|
|
2509
|
+
const value = env[key]?.trim();
|
|
2510
|
+
if (value)
|
|
2511
|
+
return value;
|
|
2512
|
+
}
|
|
2513
|
+
return undefined;
|
|
2514
|
+
}
|
|
2515
|
+
function reconcile(candidates, failures, imported, final, inventoryComplete, missingRemote) {
|
|
2516
|
+
const failedAssetIds = new Set(failures.flatMap((failure) => failure.assetId ? [failure.assetId] : []));
|
|
2517
|
+
let alreadyLocal = 0;
|
|
2518
|
+
let blocked = 0;
|
|
2519
|
+
let actionable = 0;
|
|
2520
|
+
for (const candidate of candidates) {
|
|
2521
|
+
if (failedAssetIds.has(candidate.assetId))
|
|
2522
|
+
continue;
|
|
2523
|
+
if (candidate.action === 'already_local')
|
|
2524
|
+
alreadyLocal += 1;
|
|
2525
|
+
else if (isBlockedCandidate(candidate))
|
|
2526
|
+
blocked += 1;
|
|
2527
|
+
else
|
|
2528
|
+
actionable += 1;
|
|
2529
|
+
}
|
|
2530
|
+
const failed = failedAssetIds.size;
|
|
2531
|
+
const pending = Math.max(0, actionable - imported);
|
|
2532
|
+
const accounted = imported + alreadyLocal + blocked + failed + pending;
|
|
2533
|
+
return {
|
|
2534
|
+
remoteUnique: candidates.length,
|
|
2535
|
+
accounted,
|
|
2536
|
+
imported,
|
|
2537
|
+
alreadyLocal,
|
|
2538
|
+
blocked,
|
|
2539
|
+
failed,
|
|
2540
|
+
pending,
|
|
2541
|
+
inventoryComplete,
|
|
2542
|
+
missingRemote,
|
|
2543
|
+
consistent: final
|
|
2544
|
+
&& inventoryComplete
|
|
2545
|
+
&& missingRemote === 0
|
|
2546
|
+
&& failures.length === 0
|
|
2547
|
+
&& blocked === 0
|
|
2548
|
+
&& pending === 0
|
|
2549
|
+
&& accounted === candidates.length,
|
|
2550
|
+
};
|
|
2551
|
+
}
|
|
973
2552
|
function storeBaseDir(store, deps) {
|
|
974
2553
|
return store instanceof assetstore.LocalJsonlProvider ? store.baseDir : deps.assetsDir ?? events.assetsDir();
|
|
975
2554
|
}
|
|
2555
|
+
function suppliedResumeIdentityFingerprint(deps) {
|
|
2556
|
+
const supplied = deps.resumeIdentityFingerprint;
|
|
2557
|
+
return supplied === undefined ? undefined : createHash('sha256').update(supplied).digest('hex');
|
|
2558
|
+
}
|
|
2559
|
+
function previewProvenanceSnapshot(store, deps) {
|
|
2560
|
+
if (deps.provenance)
|
|
2561
|
+
return deps.provenance.snapshot();
|
|
2562
|
+
if (store instanceof assetstore.LocalJsonlProvider || deps.assetsDir) {
|
|
2563
|
+
return new assetstore.ProvenanceStore(storeBaseDir(store, deps), deps.now).snapshot();
|
|
2564
|
+
}
|
|
2565
|
+
return new Map();
|
|
2566
|
+
}
|
|
976
2567
|
function redact(value) {
|
|
977
2568
|
return value
|
|
978
2569
|
.replace(/\bBearer\s+[A-Za-z0-9._~+/=-]+/gi, 'Bearer [redacted]')
|
|
979
2570
|
.replace(/\b([A-Z][A-Z0-9_]*(?:_SECRET|_TOKEN))\b\s*[:=]\s*["']?[^"',\s;}]+/g, '$1=[redacted]')
|
|
980
2571
|
.replace(/\b(authorization|node_secret|nodeSecret|access_token|refresh_token|token|secret)\b\s*[:=]\s*["']?[^"',\s;}]+/gi, '$1=[redacted]');
|
|
981
2572
|
}
|
|
2573
|
+
function stringifyJsonOutput(value) {
|
|
2574
|
+
let output = '';
|
|
2575
|
+
for (const character of JSON.stringify(value)) {
|
|
2576
|
+
const codePoint = character.codePointAt(0);
|
|
2577
|
+
output += codePoint !== undefined && isTerminalControlCodePoint(codePoint)
|
|
2578
|
+
? `\\u${codePoint.toString(16).padStart(4, '0')}`
|
|
2579
|
+
: character;
|
|
2580
|
+
}
|
|
2581
|
+
return output;
|
|
2582
|
+
}
|
|
2583
|
+
function formatTerminalText(value) {
|
|
2584
|
+
const withoutAnsi = redactAnsiSequences(value);
|
|
2585
|
+
const withoutSecrets = redact(withoutAnsi)
|
|
2586
|
+
.replace(/\b[A-Za-z]:[\\/][^\s\x22'<>|\x5b\x5d]*/g, '[redacted-path]')
|
|
2587
|
+
.replace(/\\\\[^\s\x22'<>|\x5b\x5d]+\\[^\s\x22'<>|\x5b\x5d]*/g, '[redacted-path]')
|
|
2588
|
+
.replace(/(^|[\s(\x22'=])\/(?:[^/\s\x22'<>|\x5b\x5d]+\/?)+/g, '$1[redacted-path]');
|
|
2589
|
+
let output = '';
|
|
2590
|
+
for (const character of withoutSecrets) {
|
|
2591
|
+
const codePoint = character.codePointAt(0);
|
|
2592
|
+
output += codePoint !== undefined && isTerminalControlCodePoint(codePoint)
|
|
2593
|
+
? `\\u{${codePoint.toString(16).toUpperCase().padStart(4, '0')}}`
|
|
2594
|
+
: character;
|
|
2595
|
+
}
|
|
2596
|
+
return output;
|
|
2597
|
+
}
|
|
2598
|
+
function redactAnsiSequences(value) {
|
|
2599
|
+
let output = '';
|
|
2600
|
+
for (let index = 0; index < value.length;) {
|
|
2601
|
+
const code = value.charCodeAt(index);
|
|
2602
|
+
const next = value.charCodeAt(index + 1);
|
|
2603
|
+
const csi = code === 0x9b || (code === 0x1b && next === 0x5b);
|
|
2604
|
+
if (csi) {
|
|
2605
|
+
let end = index + (code === 0x1b ? 2 : 1);
|
|
2606
|
+
while (end < value.length) {
|
|
2607
|
+
const current = value.charCodeAt(end);
|
|
2608
|
+
end += 1;
|
|
2609
|
+
if (current >= 0x40 && current <= 0x7e)
|
|
2610
|
+
break;
|
|
2611
|
+
}
|
|
2612
|
+
output += ' [escaped-ansi] ';
|
|
2613
|
+
index = end;
|
|
2614
|
+
continue;
|
|
2615
|
+
}
|
|
2616
|
+
const osc = code === 0x9d || (code === 0x1b && next === 0x5d);
|
|
2617
|
+
if (osc) {
|
|
2618
|
+
let end = index + (code === 0x1b ? 2 : 1);
|
|
2619
|
+
while (end < value.length) {
|
|
2620
|
+
const current = value.charCodeAt(end);
|
|
2621
|
+
if (current === 0x07) {
|
|
2622
|
+
end += 1;
|
|
2623
|
+
break;
|
|
2624
|
+
}
|
|
2625
|
+
if (current === 0x1b && value.charCodeAt(end + 1) === 0x5c) {
|
|
2626
|
+
end += 2;
|
|
2627
|
+
break;
|
|
2628
|
+
}
|
|
2629
|
+
end += 1;
|
|
2630
|
+
}
|
|
2631
|
+
output += ' [escaped-ansi] ';
|
|
2632
|
+
index = end;
|
|
2633
|
+
continue;
|
|
2634
|
+
}
|
|
2635
|
+
output += value[index];
|
|
2636
|
+
index += 1;
|
|
2637
|
+
}
|
|
2638
|
+
return output;
|
|
2639
|
+
}
|
|
2640
|
+
function isTerminalControlCodePoint(codePoint) {
|
|
2641
|
+
return codePoint <= 0x1f
|
|
2642
|
+
|| (codePoint >= 0x7f && codePoint <= 0x9f)
|
|
2643
|
+
|| codePoint === 0x061c
|
|
2644
|
+
|| codePoint === 0x200e
|
|
2645
|
+
|| codePoint === 0x200f
|
|
2646
|
+
|| codePoint === 0x2028
|
|
2647
|
+
|| codePoint === 0x2029
|
|
2648
|
+
|| (codePoint >= 0x202a && codePoint <= 0x202e)
|
|
2649
|
+
|| (codePoint >= 0x2066 && codePoint <= 0x2069);
|
|
2650
|
+
}
|
|
982
2651
|
function asRecord(value) {
|
|
983
2652
|
return value && typeof value === 'object' && !Array.isArray(value) ? value : undefined;
|
|
984
2653
|
}
|
|
985
2654
|
function stringField(value, key) {
|
|
986
2655
|
const raw = value[key];
|
|
987
2656
|
return typeof raw === 'string' && raw.trim() ? raw.trim() : undefined;
|
|
2657
|
+
}
|
|
2658
|
+
function rawStringField(value, key) {
|
|
2659
|
+
const raw = value[key];
|
|
2660
|
+
return typeof raw === 'string' && raw.length > 0 ? raw : undefined;
|
|
2661
|
+
}
|
|
2662
|
+
function hasInvalidLiveIdentityField(value, keys) {
|
|
2663
|
+
const record = value;
|
|
2664
|
+
return keys.some((key) => {
|
|
2665
|
+
if (!Object.prototype.hasOwnProperty.call(record, key))
|
|
2666
|
+
return false;
|
|
2667
|
+
const raw = record[key];
|
|
2668
|
+
return typeof raw !== 'string' || raw.length === 0 || raw !== raw.trim();
|
|
2669
|
+
});
|
|
988
2670
|
}
|