@evomap/evolver-cli 2.0.2 → 2.0.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/sync.js CHANGED
@@ -1,8 +1,9 @@
1
- import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
1
+ import { closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, readSync, writeFileSync } from 'node:fs';
2
+ import { Buffer } from 'node:buffer';
2
3
  import { createHash, randomUUID } from 'node:crypto';
3
4
  import { dirname, join } from 'node:path';
4
5
  import { assetstore, events, hub as hubNs, wire } from '@evomap/evolver-core';
5
- import { AuthError, connectPublicHub, HubClientError, HubUnreachableError, isHubDryRunEnabled, resolveHubUrl, } from '@evomap/evolver-adapter-public';
6
+ import { AuthError, connectPublicHub, HubClientError, HubUnreachableError, isHubDryRunEnabled, MalformedAccountAssetPageError, resolveHubUrl, stripHubDeliveryMetadataForIntegrity, } from '@evomap/evolver-adapter-public';
6
7
  import { loadEnvFileFromEnv } from '@evomap/evolver-mcp';
7
8
  import { createRecipeHubFromEnv, resolveRecipeHubResumeIdentityFingerprint } from './recipe.js';
8
9
  import { getCliVersion } from './version.js';
@@ -28,44 +29,18 @@ const USAGE = [
28
29
  const VALUE_FLAGS = new Set(['--scope', '--type', '--status', '--limit', '--page-size', '--purchased-cursor', '--published-cursor', '--export', '--import']);
29
30
  const GEPX_TYPE = 'evomap.gepx';
30
31
  const GEPX_VERSION = 1;
31
- const HUB_METADATA_KEYS = new Set([
32
- 'credit_cost',
33
- 'gdi_score',
34
- 'success_rate',
35
- 'reuse_count',
36
- 'ranking_score',
37
- 'source_node_id',
38
- 'fetched_at',
39
- 'receipt',
40
- 'hub_receipt',
41
- 'already_purchased',
42
- '_semantic_similarity',
43
- 'semantic_similarity',
44
- '_search_score',
45
- 'search_score',
46
- '_match_score',
47
- 'match_score',
48
- '_retrieval_rank',
49
- 'retrieval_rank',
50
- 'original_asset_id',
51
- 'payload_backfill_reason',
52
- 'asset_type',
53
- 'local_id',
54
- 'payload',
55
- 'payload_backfill_reason',
56
- 'source',
57
- 'status',
58
- ]);
59
32
  const MISSING_ASSET_ID = '[missing]';
33
+ const UNVERIFIED_HUB_WRITE_PENDING_REASON = 'unverified_hub_write_pending';
60
34
  export async function runSyncCommand(argv, deps = {}) {
61
35
  const out = deps.stdout ?? ((line) => { process.stdout.write(`${line}\n`); });
62
36
  const err = deps.stderr ?? ((line) => { process.stderr.write(`${line}\n`); });
37
+ const textOut = (line) => { out(formatTerminalText(line)); };
63
38
  const parsed = parseSyncArgs(argv);
64
39
  if (!parsed.ok)
65
40
  return emitFailure(parsed.reason, parsed.message, parsed.jsonOut, out, err);
66
41
  if ('help' in parsed) {
67
42
  if (parsed.jsonOut)
68
- out(JSON.stringify({ ok: true, group: GROUP, mode: 'help', usage: USAGE }));
43
+ out(stringifyJsonOutput({ ok: true, group: GROUP, mode: 'help', usage: USAGE }));
69
44
  else
70
45
  out(USAGE);
71
46
  return 0;
@@ -88,17 +63,17 @@ export async function runSyncCommand(argv, deps = {}) {
88
63
  ? await executeSyncWrite(parsed.value, runtimeDeps)
89
64
  : await executeSyncPreview(parsed.value, runtimeDeps);
90
65
  if (parsed.value.jsonOut)
91
- out(JSON.stringify(result));
66
+ out(stringifyJsonOutput(result));
92
67
  else if (result.mode === 'preview')
93
- emitTextPreview(result, out);
68
+ emitTextPreview(result, textOut);
94
69
  else if (result.mode === 'export')
95
- emitTextExport(result, out);
70
+ emitTextExport(result, textOut);
96
71
  else if (result.mode === 'import_preview')
97
- emitTextImportPreview(result, out);
72
+ emitTextImportPreview(result, textOut);
98
73
  else if (result.mode === 'import')
99
- emitTextImport(result, out);
74
+ emitTextImport(result, textOut);
100
75
  else
101
- emitTextWrite(result, out);
76
+ emitTextWrite(result, textOut);
102
77
  if ('failures' in result && result.failures.length > 0)
103
78
  return 1;
104
79
  if (result.mode === 'import' && result.blocked.length > 0)
@@ -242,6 +217,7 @@ async function buildSyncPreview(opts, deps, listing = {
242
217
  const store = deps.store ?? new assetstore.LocalJsonlProvider(deps.assetsDir ?? events.assetsDir());
243
218
  const local = await localIndex(store);
244
219
  const { purchased, published, failures, inventoryComplete, nextCursors } = await listRemoteRows(hub, opts, listing);
220
+ const provenanceSnapshot = previewProvenanceSnapshot(store, deps);
245
221
  const counts = {
246
222
  remotePurchased: purchased.length,
247
223
  remotePublished: published.length,
@@ -252,22 +228,27 @@ async function buildSyncPreview(opts, deps, listing = {
252
228
  unsupported: 0,
253
229
  integrityError: 0,
254
230
  wouldImport: 0,
231
+ unverifiedWouldImport: 0,
255
232
  forcedImport: 0,
256
233
  skippedLimit: 0,
257
234
  fetchFailed: 0,
258
235
  writeFailed: 0,
259
236
  };
260
237
  const unique = new Map();
238
+ const conflictingDuplicateAssetIds = new Set();
261
239
  const missingAssetId = [];
262
240
  for (const row of purchased)
263
- addUnique(unique, missingAssetId, row, 'purchased');
241
+ addUnique(unique, missingAssetId, conflictingDuplicateAssetIds, row, 'purchased');
264
242
  for (const row of published)
265
- addUnique(unique, missingAssetId, row, 'published');
243
+ addUnique(unique, missingAssetId, conflictingDuplicateAssetIds, row, 'published');
266
244
  counts.uniqueRemote = unique.size + missingAssetId.length;
267
245
  const candidates = [];
268
246
  const pendingLogical = new Map(local.logical);
269
247
  for (const { row, source } of [...unique.values(), ...missingAssetId]) {
270
- const candidate = classifyRemote(row, source, { byAssetId: local.byAssetId, logical: pendingLogical });
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);
271
252
  candidates.push(candidate);
272
253
  if (candidate.action === 'already_local')
273
254
  counts.alreadyLocal += 1;
@@ -277,6 +258,8 @@ async function buildSyncPreview(opts, deps, listing = {
277
258
  counts.idCollision += 1;
278
259
  else if (candidate.action === 'would_import') {
279
260
  counts.wouldImport += 1;
261
+ if (candidate.verification === 'unverified')
262
+ counts.unverifiedWouldImport += 1;
280
263
  if (candidate.logicalId && (candidate.type === 'Gene' || candidate.type === 'Capsule')) {
281
264
  pendingLogical.set(`${candidate.type}:${candidate.logicalId}`, candidate.assetId);
282
265
  }
@@ -331,8 +314,11 @@ async function executeSyncWrite(opts, deps) {
331
314
  const runKey = syncRunKey(opts, env, deps);
332
315
  const inventoryKey = syncInventoryKey(opts, env, deps);
333
316
  const inventoryScan = prepareInventoryScan(syncLedger, inventoryKey, opts);
334
- const preview = await buildSyncPreview(opts, { ...deps, env, hub, store }, inventoryScan);
317
+ const preview = await buildSyncPreview(opts, { ...deps, env, hub, store, provenance }, inventoryScan);
335
318
  const local = await localIndex(store);
319
+ const provenanceSnapshot = provenance.snapshot();
320
+ const pendingUnverifiedRecoveryIds = await reactivatePendingUnverifiedCandidates(preview.candidates, store, provenanceSnapshot);
321
+ const thinFrozenRevalidationIds = reactivateThinFrozenCandidates(preview.candidates, local, provenanceSnapshot);
336
322
  const checkpointEnabled = !preview.failures.some((failure) => failure.stage === 'list');
337
323
  const previousRun = opts.resume && checkpointEnabled ? syncLedger.latestIncompleteRun(runKey) : null;
338
324
  const runId = previousRun?.runId ?? randomUUID();
@@ -370,7 +356,6 @@ async function executeSyncWrite(opts, deps) {
370
356
  });
371
357
  }
372
358
  const failures = [...preview.failures];
373
- const provenanceSnapshot = provenance.snapshot();
374
359
  const resumed = previousRun
375
360
  ? await reconcileResumeCandidates({
376
361
  candidates: finalCandidates,
@@ -392,14 +377,19 @@ async function executeSyncWrite(opts, deps) {
392
377
  if (candidate.action !== 'would_import' && !(opts.force && candidate.action === 'id_collision'))
393
378
  continue;
394
379
  const checkpoint = previousRun?.processed.get(candidate.assetId);
395
- if (checkpoint && checkpoint.outcome !== 'failed' && local.byAssetId.has(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))
396
385
  continue;
397
386
  let preparedAsset;
398
387
  try {
399
- const fetched = await hub.fetchAssetById(candidate.assetId);
388
+ const fetched = await hub.fetchAssetById(candidate.assetId, { allowUnverifiedExactIdentity: true });
400
389
  if (!fetched)
401
390
  throw new SyncAbortError('not_found', 'Hub asset disappeared before import');
402
- preparedAsset = prepareFetchedAsset(candidate, fetched, local.byAssetId, pendingLogical, opts.force);
391
+ preparedAsset = prepareFetchedAsset(candidate, fetched, local.byAssetId, pendingLogical, opts.force, pendingUnverifiedRecoveryIds.has(candidate.assetId)
392
+ || thinFrozenRevalidationIds.has(candidate.assetId));
403
393
  }
404
394
  catch (error) {
405
395
  const mapped = mapSyncError(error);
@@ -407,33 +397,82 @@ async function executeSyncWrite(opts, deps) {
407
397
  appendRunCheckpoint({ runId, runKey, state: 'progress', remoteAssetId: candidate.assetId, outcome: 'failed', reason: mapped.reason });
408
398
  updateFinalCandidate(finalCandidates, candidate, mapped.reason === 'integrity_error'
409
399
  ? { ...candidate, action: 'integrity_error' }
410
- : { ...candidate, action: 'fetch_failed', failureReason: mapped.reason });
400
+ : mapped.reason === 'remote_revoked'
401
+ ? { ...candidate, action: 'tombstone', failureReason: mapped.reason }
402
+ : { ...candidate, action: 'fetch_failed', failureReason: mapped.reason });
411
403
  continue;
412
404
  }
413
405
  if ('blocked' in preparedAsset) {
414
406
  updateFinalCandidate(finalCandidates, candidate, preparedAsset.blocked);
415
407
  continue;
416
408
  }
417
- const logicalId = stringField(preparedAsset.asset, 'id');
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
+ };
418
462
  const finalCandidate = preparedAsset.forced
419
463
  ? {
420
- ...candidate,
421
- ...(logicalId ? { logicalId } : {}),
464
+ ...finalCandidateBase,
422
465
  action: 'force_import',
423
466
  collisionWithAssetId: preparedAsset.collisionWithAssetId,
424
467
  }
425
- : {
426
- assetId: candidate.assetId,
427
- type: candidate.type,
428
- source: candidate.source,
429
- ...(candidate.status ? { status: candidate.status } : {}),
430
- ...(logicalId ? { logicalId } : {}),
431
- action: 'would_import',
432
- };
468
+ : { ...finalCandidateBase, action: 'would_import' };
433
469
  updateFinalCandidate(finalCandidates, candidate, finalCandidate);
434
470
  prepared.push({
435
471
  candidate: finalCandidate,
436
472
  asset: preparedAsset.asset,
473
+ ...(preparedAsset.frozenUnverified ? { frozenUnverified: true } : {}),
474
+ ...(preparedAsset.verificationReason ? { verificationReason: preparedAsset.verificationReason } : {}),
475
+ ...(preparedAsset.frozenContentId ? { frozenContentId: preparedAsset.frozenContentId } : {}),
437
476
  ...(preparedAsset.forced ? { forced: true, collisionWithAssetId: preparedAsset.collisionWithAssetId } : {}),
438
477
  });
439
478
  if (logicalId)
@@ -442,7 +481,9 @@ async function executeSyncWrite(opts, deps) {
442
481
  const written = [];
443
482
  for (const item of prepared) {
444
483
  try {
445
- const stored = await assetstore.ingestUntrustedConditional(store, provenance, item.asset, { allowLogicalCollision: opts.force }, 'hub');
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');
446
487
  const assetId = stored.asset_id;
447
488
  if (stored.status === 'logical_collision') {
448
489
  updateFinalCandidate(finalCandidates, item.candidate, {
@@ -453,10 +494,23 @@ async function executeSyncWrite(opts, deps) {
453
494
  });
454
495
  continue;
455
496
  }
456
- await readBackStoredAsset(store, assetId, item.asset);
497
+ const persistedProvenance = provenance.get(assetId);
498
+ await readBackStoredAsset(store, assetId, item.asset, false, persistedProvenance, item.asset.type);
457
499
  if (stored.status === 'already_exists') {
458
500
  updateFinalCandidate(finalCandidates, item.candidate, { ...item.candidate, assetId, action: 'already_local' });
459
- appendRunCheckpoint({ runId, runKey, state: 'progress', remoteAssetId: item.candidate.assetId, outcome: '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
+ });
460
514
  continue;
461
515
  }
462
516
  const collisionWithAssetId = stored.collisionWithAssetId ?? item.collisionWithAssetId;
@@ -476,6 +530,9 @@ async function executeSyncWrite(opts, deps) {
476
530
  source: writtenCandidate.source,
477
531
  stored: true,
478
532
  trusted: false,
533
+ verification: item.frozenUnverified ? 'unverified' : 'verified',
534
+ ...(item.verificationReason ? { verificationReason: item.verificationReason } : {}),
535
+ ...(item.frozenContentId ? { frozenContentId: item.frozenContentId } : {}),
479
536
  ...(writtenCandidate.logicalId ? { logicalId: writtenCandidate.logicalId } : {}),
480
537
  ...(writtenCandidate.status ? { status: writtenCandidate.status } : {}),
481
538
  ...(forced ? { forced: true } : {}),
@@ -486,11 +543,9 @@ async function executeSyncWrite(opts, deps) {
486
543
  const mapped = mapSyncError(error);
487
544
  failures.push({ stage: 'write', assetId: item.candidate.assetId, reason: mapped.reason });
488
545
  appendRunCheckpoint({ runId, runKey, state: 'progress', remoteAssetId: item.candidate.assetId, outcome: 'failed', reason: mapped.reason });
489
- updateFinalCandidate(finalCandidates, item.candidate, {
490
- ...item.candidate,
491
- action: 'write_failed',
492
- failureReason: mapped.reason,
493
- });
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 });
494
549
  }
495
550
  }
496
551
  const retryableInventoryFailure = failures.some(isRetryableAssetFailure);
@@ -613,9 +668,19 @@ async function executeSyncExport(opts, deps) {
613
668
  provenance: provenanceRecords,
614
669
  sync: syncRecords,
615
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
+ }
616
681
  try {
617
682
  mkdirSync(dirname(opts.exportPath), { recursive: true });
618
- writeFileSync(opts.exportPath, `${JSON.stringify(pkg, null, 2)}\n`, 'utf8');
683
+ writeFileSync(opts.exportPath, serialized, 'utf8');
619
684
  }
620
685
  catch {
621
686
  throw new SyncAbortError('export_failed', 'could not write .gepx file');
@@ -632,7 +697,7 @@ async function executeSyncExport(opts, deps) {
632
697
  assets: assets.map((asset) => ({
633
698
  assetId: asset.asset_id,
634
699
  type: asset.type,
635
- ...(stringField(asset, 'id') ? { logicalId: stringField(asset, 'id') } : {}),
700
+ ...(rawStringField(asset, 'id') ? { logicalId: rawStringField(asset, 'id') } : {}),
636
701
  trusted: provenanceSnapshot.get(asset.asset_id)?.trusted ?? true,
637
702
  synced: Boolean(syncLedger.get(asset.asset_id)),
638
703
  })),
@@ -673,7 +738,7 @@ async function executeGepxImportWrite(opts, deps) {
673
738
  updateFinalCandidate(finalCandidates, candidate, preparedAsset.blocked);
674
739
  continue;
675
740
  }
676
- const logicalId = stringField(preparedAsset.asset, 'id');
741
+ const logicalId = rawStringField(preparedAsset.asset, 'id');
677
742
  const finalCandidate = preparedAsset.forced
678
743
  ? {
679
744
  ...candidate,
@@ -794,6 +859,7 @@ function emptyPreview(scope) {
794
859
  unsupported: 0,
795
860
  integrityError: 0,
796
861
  wouldImport: 0,
862
+ unverifiedWouldImport: 0,
797
863
  forcedImport: 0,
798
864
  skippedLimit: 0,
799
865
  fetchFailed: 0,
@@ -827,6 +893,7 @@ function emptyCounts(uniqueRemote = 0) {
827
893
  unsupported: 0,
828
894
  integrityError: 0,
829
895
  wouldImport: 0,
896
+ unverifiedWouldImport: 0,
830
897
  forcedImport: 0,
831
898
  skippedLimit: 0,
832
899
  fetchFailed: 0,
@@ -940,6 +1007,8 @@ async function listAll(hub, opts, pageSize, failures, budget) {
940
1007
  failures.push({ stage: 'list', scope: opts.scope, reason: 'malformed_page' });
941
1008
  break;
942
1009
  }
1010
+ const hasMore = result['hasMore'];
1011
+ const nextCursor = result['nextCursor'];
943
1012
  const pageRows = result['assets'];
944
1013
  if (pageRows.length > requestedPageLimit) {
945
1014
  failures.push({ stage: 'list', scope: opts.scope, reason: 'oversized_page' });
@@ -959,15 +1028,22 @@ async function listAll(hub, opts, pageSize, failures, budget) {
959
1028
  continue;
960
1029
  }
961
1030
  rows.push(row);
962
- const assetId = stringField(row, 'asset_id');
1031
+ const assetId = rawStringField(row, 'asset_id');
963
1032
  if (assetId)
964
1033
  budget.uniqueAssetIds.add(assetId);
965
1034
  }
966
1035
  const uniqueProgress = budget.uniqueAssetIds.size - uniqueBefore;
967
- if (!result['hasMore']) {
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' });
1042
+ break;
1043
+ }
1044
+ if (!hasMore) {
968
1045
  return { rows, complete: consumedPageRows === pageRows.length, nextCursor: undefined };
969
1046
  }
970
- const nextCursor = result['nextCursor'];
971
1047
  if (typeof nextCursor !== 'string' || !nextCursor.trim()) {
972
1048
  failures.push({ stage: 'list', scope: opts.scope, reason: 'invalid_remote_pagination' });
973
1049
  break;
@@ -986,10 +1062,6 @@ async function listAll(hub, opts, pageSize, failures, budget) {
986
1062
  failures.push({ stage: 'list', scope: opts.scope, reason: 'no_unique_progress_limit' });
987
1063
  break;
988
1064
  }
989
- if (!isValidOpaqueCursor(nextCursor)) {
990
- failures.push({ stage: 'list', scope: opts.scope, reason: 'malformed_cursor' });
991
- break;
992
- }
993
1065
  if (nextCursor === cursor || seenCursors.has(nextCursor)) {
994
1066
  failures.push({ stage: 'list', scope: opts.scope, reason: 'invalid_remote_pagination' });
995
1067
  break;
@@ -1012,28 +1084,112 @@ function isValidOpaqueCursor(cursor) {
1012
1084
  }
1013
1085
  return true;
1014
1086
  }
1015
- function addUnique(target, missingAssetId, row, source) {
1016
- const assetId = stringField(row, 'asset_id');
1087
+ function addUnique(target, missingAssetId, conflictingDuplicateAssetIds, row, source) {
1088
+ const assetId = rawStringField(row, 'asset_id');
1017
1089
  if (!assetId) {
1018
1090
  missingAssetId.push({ row, source });
1019
1091
  return;
1020
1092
  }
1021
- if (target.has(assetId))
1093
+ const existing = target.get(assetId);
1094
+ if (!existing) {
1095
+ target.set(assetId, { row, source });
1022
1096
  return;
1023
- target.set(assetId, { row, source });
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
+ }
1024
1178
  }
1025
1179
  async function localIndex(store) {
1026
1180
  const byAssetId = new Set();
1027
1181
  const logical = new Map();
1182
+ const recordsByAssetId = new Map();
1028
1183
  for (const kind of ['Gene', 'Capsule']) {
1029
1184
  for (const row of await store.list(kind, Number.MAX_SAFE_INTEGER)) {
1030
1185
  byAssetId.add(row.asset_id);
1031
- const logicalId = stringField(row, 'id');
1186
+ recordsByAssetId.set(row.asset_id, row);
1187
+ const logicalId = rawStringField(row, 'id');
1032
1188
  if (logicalId)
1033
1189
  logical.set(`${kind}:${logicalId}`, row.asset_id);
1034
1190
  }
1035
1191
  }
1036
- return { byAssetId, logical };
1192
+ return { byAssetId, logical, recordsByAssetId };
1037
1193
  }
1038
1194
  async function listLocalExportAssets(store, opts) {
1039
1195
  const kinds = opts.type ? [opts.type] : ['Gene', 'Capsule'];
@@ -1046,8 +1202,8 @@ async function listLocalExportAssets(store, opts) {
1046
1202
  }
1047
1203
  return assets.slice(0, opts.limit);
1048
1204
  }
1049
- function classifyRemote(row, source, local) {
1050
- const assetId = stringField(row, 'asset_id') ?? MISSING_ASSET_ID;
1205
+ function classifyRemote(row, source, local, provenanceSnapshot) {
1206
+ const assetId = rawStringField(row, 'asset_id') ?? MISSING_ASSET_ID;
1051
1207
  const type = remoteType(row);
1052
1208
  const logicalId = remoteLogicalId(row);
1053
1209
  const status = stringField(row, 'status');
@@ -1060,20 +1216,67 @@ function classifyRemote(row, source, local) {
1060
1216
  };
1061
1217
  if (assetId === MISSING_ASSET_ID)
1062
1218
  return { ...base, action: 'integrity_error' };
1063
- if (isRemoteTombstone(row))
1219
+ if (!isContentAssetId(assetId))
1220
+ return { ...base, action: 'integrity_error' };
1221
+ if (unwrapLiveHubDelivery(row, assetId).invalid)
1222
+ return { ...base, action: 'integrity_error' };
1223
+ if (isRemoteTombstoneDelivery(row))
1064
1224
  return { ...base, action: 'tombstone' };
1065
1225
  if (type !== 'Gene' && type !== 'Capsule')
1066
1226
  return { ...base, action: 'unsupported_type' };
1067
- if (remotePayloadIntegrityInvalid(row, type, assetId))
1227
+ const payloadVerification = inspectRemotePayload(row, type, assetId);
1228
+ if (payloadVerification === 'invalid')
1068
1229
  return { ...base, action: 'integrity_error' };
1069
- if (local.byAssetId.has(assetId))
1070
- return { ...base, action: 'already_local' };
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
+ }
1071
1274
  if (logicalId) {
1072
1275
  const localAssetId = local.logical.get(`${type}:${logicalId}`);
1073
1276
  if (localAssetId && localAssetId !== assetId)
1074
- return { ...base, action: 'id_collision', collisionWithAssetId: localAssetId };
1277
+ return { ...verifiedBase, action: 'id_collision', collisionWithAssetId: localAssetId };
1075
1278
  }
1076
- return { ...base, action: 'would_import' };
1279
+ return { ...verifiedBase, action: 'would_import' };
1077
1280
  }
1078
1281
  function classifyGepxAssets(pkg, opts, local) {
1079
1282
  const classified = uniqueGepxAssets(pkg)
@@ -1150,14 +1353,14 @@ function indexUniqueGepxProvenance(pkg) {
1150
1353
  return indexed;
1151
1354
  }
1152
1355
  function normalizeGepxAsset(asset, provenance) {
1153
- const cleaned = stripHubMetadata(asset);
1154
- const assetId = stringField(cleaned, 'asset_id') ?? stringField(asset, 'asset_id') ?? MISSING_ASSET_ID;
1356
+ const cleaned = { ...asset };
1357
+ const assetId = rawStringField(cleaned, 'asset_id') ?? MISSING_ASSET_ID;
1155
1358
  const type = cleaned.type === 'Gene' || cleaned.type === 'Capsule' ? cleaned.type : undefined;
1156
- const logicalId = stringField(cleaned, 'id');
1359
+ const logicalId = rawStringField(cleaned, 'id');
1157
1360
  let integrityError = false;
1158
1361
  let frozenUnverified = false;
1159
1362
  if (type) {
1160
- const claimed = stringField(cleaned, 'asset_id');
1363
+ const claimed = rawStringField(cleaned, 'asset_id');
1161
1364
  const fullAsset = looksLikeFullAsset(cleaned, type);
1162
1365
  const computed = fullAsset ? wire.computeAssetId(cleaned) : undefined;
1163
1366
  const supportedFrozenProvenance = provenance
@@ -1177,6 +1380,7 @@ function normalizeGepxAsset(asset, provenance) {
1177
1380
  && provenance.frozenContentId === computed);
1178
1381
  integrityError = assetId === MISSING_ASSET_ID
1179
1382
  || !claimed
1383
+ || !isContentAssetId(assetId)
1180
1384
  || !fullAsset
1181
1385
  || !computed
1182
1386
  || claimed !== assetId
@@ -1203,6 +1407,7 @@ function countsFromCandidates(base, candidates) {
1203
1407
  unsupported: 0,
1204
1408
  integrityError: 0,
1205
1409
  wouldImport: 0,
1410
+ unverifiedWouldImport: 0,
1206
1411
  forcedImport: 0,
1207
1412
  skippedLimit: 0,
1208
1413
  fetchFailed: 0,
@@ -1229,6 +1434,9 @@ function countsFromCandidates(base, candidates) {
1229
1434
  counts.unsupported += 1;
1230
1435
  else if (candidate.action === 'integrity_error')
1231
1436
  counts.integrityError += 1;
1437
+ if (candidate.action === 'would_import' && candidate.verification === 'unverified') {
1438
+ counts.unverifiedWouldImport += 1;
1439
+ }
1232
1440
  }
1233
1441
  return counts;
1234
1442
  }
@@ -1243,41 +1451,221 @@ function isBlockedCandidate(candidate) {
1243
1451
  && candidate.action !== 'already_local'
1244
1452
  && candidate.action !== 'skipped_limit';
1245
1453
  }
1246
- function remotePayloadIntegrityInvalid(row, type, assetId) {
1247
- const payload = asRecord(row.payload);
1248
- const source = payload ?? row;
1249
- if (!looksLikeFullAsset(source, type))
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))
1250
1490
  return false;
1251
- const candidate = stripHubMetadata({ ...source, type, asset_id: stringField(source, 'asset_id') ?? assetId });
1252
- return Boolean(candidate.asset_id && wire.computeAssetId(candidate) !== candidate.asset_id);
1491
+ if (remoteComputed === assetId)
1492
+ return true;
1493
+ return isActiveFrozenWaiver(provenance, assetId, remoteComputed, true);
1253
1494
  }
1254
- function prepareFetchedAsset(candidate, fetched, localAssetIds, logical, force) {
1255
- const type = fetched.type === 'Gene' || fetched.type === 'Capsule' ? fetched.type : undefined;
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)));
1506
+ }
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;
1256
1559
  if (!type)
1257
- return { blocked: { ...candidate, type: fetched.type ?? candidate.type, action: 'unsupported_type' } };
1560
+ return { blocked: { ...candidate, type: delivered.type ?? candidate.type, action: 'unsupported_type' } };
1258
1561
  if (type !== candidate.type)
1259
1562
  throw new SyncAbortError('integrity_error', 'Hub asset type changed before import');
1260
- const cleaned = stripHubMetadata(fetched);
1261
- const claimed = stringField(cleaned, 'asset_id');
1262
- const computed = wire.computeAssetId(cleaned);
1263
- if (!claimed || !computed || claimed !== computed || claimed !== candidate.assetId) {
1264
- throw new SyncAbortError('integrity_error', 'Hub asset integrity verification failed before import');
1265
- }
1563
+ const cleaned = stripHubDeliveryMetadataForIntegrity(delivered);
1564
+ const claimed = rawStringField(cleaned, 'asset_id');
1266
1565
  if (!looksLikeFullAsset(cleaned, type)) {
1267
1566
  throw new SyncAbortError('integrity_error', 'Hub asset payload is incomplete');
1268
1567
  }
1269
- if (localAssetIds.has(cleaned.asset_id))
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) {
1270
1589
  return { blocked: { ...candidate, action: 'already_local' } };
1271
- const logicalId = stringField(cleaned, 'id');
1590
+ }
1272
1591
  if (logicalId) {
1273
1592
  const localAssetId = logical.get(`${type}:${logicalId}`);
1274
1593
  if (localAssetId && localAssetId !== cleaned.asset_id) {
1275
1594
  if (force)
1276
- return { asset: cleaned, forced: true, collisionWithAssetId: localAssetId };
1595
+ return { asset: cleaned, ...verification, forced: true, collisionWithAssetId: localAssetId };
1277
1596
  return { blocked: { ...candidate, logicalId, action: 'id_collision', collisionWithAssetId: localAssetId } };
1278
1597
  }
1279
1598
  }
1280
- 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;
1281
1669
  }
1282
1670
  function resumePlannedCandidates(candidates, previousRun, inventoryComplete) {
1283
1671
  const plan = previousRun.plan;
@@ -1338,7 +1726,7 @@ function mergeCandidatePlan(previous, current) {
1338
1726
  function assertNoConflictingGepxDuplicates(pkg) {
1339
1727
  const seen = new Map();
1340
1728
  for (const asset of pkg.assets) {
1341
- const assetId = stringField(asset, 'asset_id');
1729
+ const assetId = rawStringField(asset, 'asset_id');
1342
1730
  if (!assetId)
1343
1731
  continue;
1344
1732
  const serialized = JSON.stringify(asset);
@@ -1458,18 +1846,9 @@ async function readBackStoredAsset(store, assetId, expected, allowFrozenUnverifi
1458
1846
  && expected
1459
1847
  && assetstore.frozenAssetRecordsEqual(stored, expected)
1460
1848
  && computed === expectedComputed);
1461
- const supportedFrozenProvenance = provenance?.assetId === assetId
1462
- && provenance.trusted === false
1463
- && provenance.decision === undefined
1464
- && provenance.decidedBy === undefined
1465
- && provenance.promotedBy === undefined
1466
- && ((provenance.source === 'hub'
1467
- && (provenance.reason === 'unverified_hub_rewrite' || provenance.reason === 'unverified_hub_synthesized'))
1468
- || (provenance.source === 'migrated' && provenance.reason === 'unverified_gepx_import'));
1469
1849
  const provenanceBoundFrozenBody = Boolean(stored
1470
1850
  && computed
1471
- && supportedFrozenProvenance
1472
- && provenance.frozenContentId === computed);
1851
+ && isActiveFrozenWaiver(provenance, assetId, computed));
1473
1852
  if (!stored ||
1474
1853
  stored.asset_id !== assetId ||
1475
1854
  (!exactFrozenBody && !provenanceBoundFrozenBody && computed !== assetId) ||
@@ -1488,14 +1867,14 @@ function appendSyncRecord(syncLedger, candidate, asset, runKey, inventoryKey, ex
1488
1867
  remoteAssetId: candidate.assetId,
1489
1868
  runKey,
1490
1869
  inventoryKey,
1491
- ...(stringField(asset, 'id') ? { logicalId: stringField(asset, 'id') } : {}),
1870
+ ...(rawStringField(asset, 'id') ? { logicalId: rawStringField(asset, 'id') } : {}),
1492
1871
  ...(candidate.status ? { status: candidate.status } : {}),
1493
1872
  ...extra,
1494
1873
  });
1495
1874
  }
1496
1875
  function syncRecordMatches(record, candidate, asset) {
1497
1876
  const scope = candidate.source === 'published' ? 'published' : 'purchased';
1498
- const logicalId = stringField(asset, 'id');
1877
+ const logicalId = rawStringField(asset, 'id');
1499
1878
  return record.assetId === candidate.assetId &&
1500
1879
  record.remoteAssetId === candidate.assetId &&
1501
1880
  record.type === asset.type &&
@@ -1504,24 +1883,25 @@ function syncRecordMatches(record, candidate, asset) {
1504
1883
  (!logicalId || record.logicalId === logicalId);
1505
1884
  }
1506
1885
  function preparePackagedAsset(candidate, asset, localAssetIds, logical, force, frozenUnverified = false) {
1507
- const cleaned = stripHubMetadata(asset);
1886
+ const cleaned = { ...asset };
1508
1887
  const type = cleaned.type === 'Gene' || cleaned.type === 'Capsule' ? cleaned.type : undefined;
1509
1888
  if (!type)
1510
1889
  return { blocked: { ...candidate, type: cleaned.type ?? candidate.type, action: 'unsupported_type' } };
1511
1890
  if (type !== candidate.type)
1512
1891
  return { blocked: { ...candidate, type, action: 'unsupported_type' } };
1513
- const claimed = stringField(cleaned, 'asset_id');
1892
+ const claimed = rawStringField(cleaned, 'asset_id');
1514
1893
  const computed = wire.computeAssetId(cleaned);
1515
1894
  if (!claimed
1516
1895
  || !computed
1517
1896
  || (claimed !== computed && !frozenUnverified)
1518
1897
  || claimed !== candidate.assetId
1898
+ || !isContentAssetId(claimed)
1519
1899
  || !looksLikeFullAsset(cleaned, type)) {
1520
1900
  throw new SyncAbortError('integrity_error', '.gepx package integrity verification failed before import');
1521
1901
  }
1522
1902
  if (localAssetIds.has(cleaned.asset_id))
1523
1903
  return { blocked: { ...candidate, action: 'already_local' } };
1524
- const logicalId = stringField(cleaned, 'id');
1904
+ const logicalId = rawStringField(cleaned, 'id');
1525
1905
  if (logicalId) {
1526
1906
  const localAssetId = logical.get(`${type}:${logicalId}`);
1527
1907
  if (localAssetId && localAssetId !== cleaned.asset_id) {
@@ -1548,33 +1928,32 @@ function looksLikeFullAsset(value, type) {
1548
1928
  stringField(value, 'summary') &&
1549
1929
  asRecord(value['outcome']));
1550
1930
  }
1551
- function stripHubMetadata(asset) {
1552
- const out = {};
1553
- for (const [key, value] of Object.entries(asset))
1554
- if (!HUB_METADATA_KEYS.has(key))
1555
- out[key] = value;
1556
- return out;
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']));
1557
1946
  }
1558
1947
  function readGepxPackage(path) {
1559
1948
  if (!path)
1560
1949
  throw new SyncAbortError('invalid_arg', '--import requires a file');
1561
- if (!existsSync(path))
1562
- throw new SyncAbortError('gepx_read_failed', 'could not read .gepx file');
1950
+ let parsed;
1563
1951
  try {
1564
- const stat = statSync(path);
1565
- if (!stat.isFile() || stat.size > MAX_GEPX_BYTES)
1566
- throw new SyncAbortError('invalid_gepx', 'invalid .gepx package');
1952
+ parsed = JSON.parse(readBoundedGepxText(path));
1567
1953
  }
1568
1954
  catch (error) {
1569
1955
  if (error instanceof SyncAbortError)
1570
1956
  throw error;
1571
- throw new SyncAbortError('gepx_read_failed', 'could not read .gepx file');
1572
- }
1573
- let parsed;
1574
- try {
1575
- parsed = JSON.parse(readFileSync(path, 'utf8'));
1576
- }
1577
- catch {
1578
1957
  throw new SyncAbortError('invalid_gepx', 'invalid .gepx package');
1579
1958
  }
1580
1959
  const obj = asRecord(parsed);
@@ -1591,9 +1970,7 @@ function readGepxPackage(path) {
1591
1970
  const malformedAssets = [];
1592
1971
  obj['assets'].forEach((rawAsset, index) => {
1593
1972
  const asset = asRecord(rawAsset);
1594
- const assetId = asset && typeof asset['asset_id'] === 'string' && asset['asset_id'].trim()
1595
- ? asset['asset_id']
1596
- : undefined;
1973
+ const assetId = asset ? rawStringField(asset, 'asset_id') : undefined;
1597
1974
  if (!asset || !assetId) {
1598
1975
  malformedAssets.push({ index, ...(assetId ? { assetId } : {}) });
1599
1976
  return;
@@ -1616,13 +1993,93 @@ function readGepxPackage(path) {
1616
1993
  sync,
1617
1994
  };
1618
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
+ }
1619
2076
  function parseGepxProvenanceRecord(value) {
1620
2077
  if (!value)
1621
2078
  return null;
1622
- const assetId = stringField(value, 'assetId');
2079
+ const assetId = rawStringField(value, 'assetId');
1623
2080
  const source = stringField(value, 'source');
1624
2081
  const at = stringField(value, 'at');
1625
- const frozenContentId = stringField(value, 'frozenContentId');
2082
+ const frozenContentId = rawStringField(value, 'frozenContentId');
1626
2083
  if (!assetId
1627
2084
  || !at
1628
2085
  || Number.isNaN(Date.parse(at))
@@ -1651,12 +2108,12 @@ function parseGepxProvenanceRecord(value) {
1651
2108
  function parseGepxSyncRecord(value) {
1652
2109
  if (!value)
1653
2110
  return null;
1654
- const assetId = stringField(value, 'assetId');
1655
- const type = stringField(value, 'type');
1656
- const source = stringField(value, 'source');
1657
- const scope = stringField(value, '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');
1658
2115
  const syncedAt = stringField(value, 'syncedAt');
1659
- const remoteAssetId = stringField(value, 'remoteAssetId');
2116
+ const remoteAssetId = rawStringField(value, 'remoteAssetId');
1660
2117
  if (!assetId || (type !== 'Gene' && type !== 'Capsule') || source !== 'hub' || (scope !== 'purchased' && scope !== 'published') || !syncedAt || !remoteAssetId) {
1661
2118
  return null;
1662
2119
  }
@@ -1667,48 +2124,72 @@ function parseGepxSyncRecord(value) {
1667
2124
  scope,
1668
2125
  syncedAt,
1669
2126
  remoteAssetId,
1670
- ...(stringField(value, 'logicalId') ? { logicalId: stringField(value, 'logicalId') } : {}),
2127
+ ...(rawStringField(value, 'logicalId') ? { logicalId: rawStringField(value, 'logicalId') } : {}),
1671
2128
  ...(stringField(value, 'status') ? { status: stringField(value, 'status') } : {}),
1672
2129
  ...(value['forced'] === true ? { forced: true } : {}),
1673
- ...(stringField(value, 'collisionWithAssetId') ? { collisionWithAssetId: stringField(value, 'collisionWithAssetId') } : {}),
2130
+ ...(rawStringField(value, 'collisionWithAssetId') ? { collisionWithAssetId: rawStringField(value, 'collisionWithAssetId') } : {}),
1674
2131
  };
1675
2132
  }
1676
2133
  function remoteType(row) {
1677
- const payload = asRecord(row.payload);
1678
- const raw = stringField(row, 'type') ?? stringField(row, 'asset_type') ?? (payload ? stringField(payload, 'type') : undefined);
2134
+ const raw = remoteDeclaredType(row);
1679
2135
  return raw === 'Gene' || raw === 'Capsule' ? raw : undefined;
1680
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
+ }
1681
2143
  function remoteLogicalId(row) {
1682
2144
  const payload = asRecord(row.payload);
1683
- return stringField(row, 'id') ?? stringField(row, 'local_id') ?? (payload ? stringField(payload, 'id') : undefined);
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);
1684
2154
  }
1685
2155
  function isRemoteTombstone(row) {
1686
2156
  return stringField(row, 'status')?.toLowerCase() === 'revoked'
1687
2157
  || stringField(row, 'trust_state')?.toLowerCase() === 'revoked';
1688
2158
  }
2159
+ function isRemoteTombstoneDelivery(row) {
2160
+ if (isRemoteTombstone(row))
2161
+ return true;
2162
+ const nested = asRecord(row.payload);
2163
+ return nested ? isRemoteTombstone(nested) : false;
2164
+ }
1689
2165
  function emitTextPreview(preview, out) {
1690
2166
  const c = preview.counts;
1691
2167
  out(`sync preview: scope=${preview.scope} purchased=${c.remotePurchased} published=${c.remotePublished} unique=${c.uniqueRemote}`);
1692
- out(` would_import=${c.wouldImport} forced_import=${c.forcedImport} skipped_limit=${c.skippedLimit} fetch_failed=${c.fetchFailed} write_failed=${c.writeFailed} already_local=${c.alreadyLocal} tombstone=${c.tombstone} id_collision=${c.idCollision} unsupported=${c.unsupported} integrity_error=${c.integrityError}`);
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}`);
1693
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}`);
1694
2170
  emitTextNextCursors(preview.nextCursors, out);
1695
2171
  for (const candidate of preview.candidates.slice(0, 10)) {
1696
- 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)}`);
1697
2173
  }
1698
2174
  }
1699
2175
  function emitTextWrite(result, out) {
1700
2176
  const c = result.counts;
1701
2177
  out(`sync ${result.mode}: scope=${result.scope} purchased=${c.remotePurchased} published=${c.remotePublished} unique=${c.uniqueRemote}`);
1702
- out(` written=${result.written.length} blocked=${result.blocked.length} would_import=${c.wouldImport} forced_import=${c.forcedImport} skipped_limit=${c.skippedLimit} fetch_failed=${c.fetchFailed} write_failed=${c.writeFailed} already_local=${c.alreadyLocal} tombstone=${c.tombstone} id_collision=${c.idCollision} unsupported=${c.unsupported} integrity_error=${c.integrityError}`);
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}`);
1703
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}`);
1704
2180
  emitTextNextCursors(result.nextCursors, out);
1705
2181
  for (const asset of result.written.slice(0, 10)) {
1706
- out(` imported: ${asset.type} ${asset.assetId}${asset.logicalId ? ` (${asset.logicalId})` : ''}`);
2182
+ out(` imported: ${asset.type} ${asset.assetId}${asset.logicalId ? ` (${asset.logicalId})` : ''}${formatHubVerification(asset)}`);
1707
2183
  }
1708
2184
  for (const candidate of result.blocked.slice(0, 10)) {
1709
2185
  out(` blocked/${candidate.action}: ${candidate.type} ${candidate.assetId}${candidate.logicalId ? ` (${candidate.logicalId})` : ''}`);
1710
2186
  }
1711
2187
  }
2188
+ function formatHubVerification(value) {
2189
+ if (value.verification !== 'unverified')
2190
+ return '';
2191
+ return ` [verification=unverified${value.verificationReason ? ` reason=${value.verificationReason}` : ''}]`;
2192
+ }
1712
2193
  function emitTextNextCursors(nextCursors, out) {
1713
2194
  if (nextCursors.purchased)
1714
2195
  out(` next_purchased_cursor=${nextCursors.purchased}`);
@@ -1757,16 +2238,22 @@ function loadSyncEnv(env) {
1757
2238
  throw new SyncAbortError('env_file_unavailable', 'Configured environment file is unavailable');
1758
2239
  }
1759
2240
  function emitFailure(reason, message, jsonOut, out, err) {
1760
- const payload = { ok: false, group: GROUP, reason, message: redact(message) };
2241
+ const payload = { ok: false, group: GROUP, reason, message: formatTerminalText(message) };
1761
2242
  if (jsonOut)
1762
- out(JSON.stringify(payload));
2243
+ out(stringifyJsonOutput(payload));
1763
2244
  else
1764
- err(`sync failed (${reason}): ${payload.message}`);
2245
+ err(formatTerminalText(`sync failed (${reason}): ${message}`));
1765
2246
  return 1;
1766
2247
  }
1767
2248
  function mapSyncError(error) {
1768
2249
  if (error instanceof SyncAbortError)
1769
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
+ }
1770
2257
  if (error instanceof assetstore.InvalidConditionalPutResultError) {
1771
2258
  return { reason: 'conditional_write_invalid', message: 'Conditional asset write returned an invalid result' };
1772
2259
  }
@@ -1887,15 +2374,15 @@ function cursorFingerprintsMatch(left, right) {
1887
2374
  }
1888
2375
  function syncInventoryIdentity(opts, env, deps) {
1889
2376
  const privateMode = isPrivateHubMode(env);
2377
+ const suppliedIdentityFingerprint = suppliedResumeIdentityFingerprint(deps);
1890
2378
  return {
1891
2379
  mode: String(env['EVOMAP_HUB_MODE'] ?? 'public').trim().toLowerCase(),
1892
2380
  hubUrl: privateMode ? requirePrivateHubUrl(env) : resolveHubUrl(env),
1893
2381
  account: privateMode
1894
2382
  ? firstNonEmptyEnv(env, ['EVOMAP_ENTERPRISE_SUBJECT', 'EVOMAP_PRIVATE_SUBJECT', 'PHUB_ENTERPRISE_SUBJECT', 'USER']) ?? 'evolver-proxy'
1895
2383
  : '',
1896
- credentialFingerprint: privateMode
1897
- ? syncCredentialFingerprint(env)
1898
- : publicResumeIdentityFingerprint(env, deps),
2384
+ credentialFingerprint: suppliedIdentityFingerprint
2385
+ ?? (privateMode ? syncCredentialFingerprint(env) : publicResumeIdentityFingerprint(env, deps)),
1899
2386
  scope: opts.scope,
1900
2387
  type: opts.type ?? '',
1901
2388
  status: opts.status,
@@ -1979,9 +2466,6 @@ function reconcileInventorySnapshot(snapshot, missingRemote) {
1979
2466
  };
1980
2467
  }
1981
2468
  function publicResumeIdentityFingerprint(env, deps) {
1982
- const supplied = deps.resumeIdentityFingerprint?.trim();
1983
- if (supplied)
1984
- return createHash('sha256').update(supplied).digest('hex');
1985
2469
  if (!deps.hub)
1986
2470
  return resolveRecipeHubResumeIdentityFingerprint(env);
1987
2471
  return createHash('sha256').update(JSON.stringify({
@@ -2068,16 +2552,119 @@ function reconcile(candidates, failures, imported, final, inventoryComplete, mis
2068
2552
  function storeBaseDir(store, deps) {
2069
2553
  return store instanceof assetstore.LocalJsonlProvider ? store.baseDir : deps.assetsDir ?? events.assetsDir();
2070
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
+ }
2071
2567
  function redact(value) {
2072
2568
  return value
2073
2569
  .replace(/\bBearer\s+[A-Za-z0-9._~+/=-]+/gi, 'Bearer [redacted]')
2074
2570
  .replace(/\b([A-Z][A-Z0-9_]*(?:_SECRET|_TOKEN))\b\s*[:=]\s*["']?[^"',\s;}]+/g, '$1=[redacted]')
2075
2571
  .replace(/\b(authorization|node_secret|nodeSecret|access_token|refresh_token|token|secret)\b\s*[:=]\s*["']?[^"',\s;}]+/gi, '$1=[redacted]');
2076
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
+ }
2077
2651
  function asRecord(value) {
2078
2652
  return value && typeof value === 'object' && !Array.isArray(value) ? value : undefined;
2079
2653
  }
2080
2654
  function stringField(value, key) {
2081
2655
  const raw = value[key];
2082
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
+ });
2083
2670
  }