@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.
@@ -0,0 +1,2 @@
1
+ import { assetstore } from '@evomap/evolver-core';
2
+ export declare function storeRepairedAsset(asset: assetstore.AssetRecord, store: assetstore.AssetStoreProvider, env: NodeJS.ProcessEnv): Promise<boolean>;
@@ -0,0 +1,12 @@
1
+ // Where a repaired asset lands locally. Shared by `asset-repair --apply` and `publish --repair` so a repair
2
+ // means the same thing on both paths: LOCAL content (it hashes to its own recomputed id), written alongside the
3
+ // original under that id — never over it, and never deleting what it was derived from.
4
+ import { assetstore, events } from '@evomap/evolver-core';
5
+ export async function storeRepairedAsset(asset, store, env) {
6
+ const baseDir = store instanceof assetstore.LocalJsonlProvider ? store.baseDir : events.assetsDir(env);
7
+ const provenance = new assetstore.ProvenanceStore(baseDir);
8
+ // The repaired record keeps the original's logical id on purpose (it is the same asset, mended), so the
9
+ // logical-collision guard has to be told this collision is expected rather than a conflicting write.
10
+ const result = await assetstore.ingestUntrustedConditional(store, provenance, asset, { allowLogicalCollision: true }, 'local');
11
+ return result.status !== 'logical_collision' && result.stored;
12
+ }
package/dist/reuse.d.ts CHANGED
@@ -14,7 +14,10 @@ export interface ReuseEnvelope {
14
14
  /** Minimal hub surface this command needs: a single fetch-by-id, plus an optional trust-establishing hello
15
15
  * (PublicHubCapability satisfies both; a bare fetcher in tests may omit hello). */
16
16
  type AssetByIdFetcher = {
17
- fetchAssetById(assetId: string): Promise<assetstore.AssetRecord | null>;
17
+ fetchAssetById(assetId: string, options?: hubNs.FetchAssetByIdOptions): Promise<assetstore.AssetRecord | null>;
18
+ /** Preferred: says WHY there is no asset, so "the hub does not have it" and "the hub delivered something
19
+ * unusable" stop sharing one status. Optional so a bare fetcher (tests, private proxy) still satisfies this. */
20
+ fetchAssetDeliveryById?(assetId: string, options?: hubNs.FetchAssetByIdOptions): Promise<hubNs.AssetDeliveryOutcome>;
18
21
  hello?(opts: PublicHelloOptions): Promise<unknown>;
19
22
  };
20
23
  type PrivateReuseProxy = {
package/dist/reuse.js CHANGED
@@ -10,8 +10,8 @@
10
10
  // and degrades to the agent `/pack apply` path on any non-ok result. Two hard rules follow:
11
11
  // 1. Print EXACTLY ONE envelope object to STDOUT on BOTH success and failure (in --json mode).
12
12
  // 2. NEVER let a token/secret reach any stream — error text is mapped to fixed messages / redacted.
13
- import { assetstore, events, hub as hubNs, wire } from '@evomap/evolver-core';
14
- import { AuthError, HubClientError, HubUnreachableError, connectPublicHub, isHubDryRunEnabled } from '@evomap/evolver-adapter-public';
13
+ import { assetrepair, assetstore, events, hub as hubNs, wire } from '@evomap/evolver-core';
14
+ import { AuthError, HubClientError, HubUnreachableError, connectPublicHub, isHubDryRunEnabled, stripHubDeliveryMetadataForIntegrity, } from '@evomap/evolver-adapter-public';
15
15
  import { loadEnvFileFromEnv, proxyClientFromEnv } from '@evomap/evolver-mcp';
16
16
  import { createRecipeHubFromEnv } from './recipe.js';
17
17
  import { getCliVersion } from './version.js';
@@ -24,29 +24,6 @@ const REUSE_USAGE = [
24
24
  // Flags that consume the following token as their value. firstPositional must skip those values so a flag value
25
25
  // (e.g. the `reference` in `--mode reference`) is never mistaken for a bare positional asset id.
26
26
  const VALUE_FLAGS = new Set(['--id', '--mode', '--run']);
27
- // Keep this list limited to Hub-only fields. `confidence` is canonical Capsule content and must
28
- // survive integrity verification even though delivery rows also use a field with that name.
29
- const HUB_METADATA_KEYS = new Set([
30
- 'credit_cost',
31
- 'gdi_score',
32
- 'success_rate',
33
- 'reuse_count',
34
- 'ranking_score',
35
- 'source_node_id',
36
- 'fetched_at',
37
- 'receipt',
38
- 'hub_receipt',
39
- 'already_purchased',
40
- '_semantic_similarity',
41
- 'semantic_similarity',
42
- '_search_score',
43
- 'search_score',
44
- '_match_score',
45
- 'match_score',
46
- '_retrieval_rank',
47
- 'retrieval_rank',
48
- 'original_asset_id',
49
- ]);
50
27
  export async function runReuseCommand(argv, deps = {}) {
51
28
  const ctx = {
52
29
  jsonOut: argv.includes('--json'),
@@ -81,13 +58,19 @@ export async function runReuseCommand(argv, deps = {}) {
81
58
  const store = deps.store ?? new assetstore.LocalJsonlProvider(deps.assetsDir ?? events.assetsDir(env));
82
59
  // 1) Already in the local recall library → reuse is idempotent: log + ok, no hub round-trip.
83
60
  const local = await resolveLocalReuseAsset(store, opts.id);
84
- if (local && !isUnsafeUnverifiedLocalAsset(local, store, deps)) {
85
- logReuse(deps, opts, local, 'local');
86
- return emit({ ok: true, status: 'ok', message: 'asset already in local recall library' }, ctx);
61
+ if (local) {
62
+ const disposition = localReuseDisposition(local, store, deps);
63
+ if (disposition === 'revoked') {
64
+ return emit({ ok: false, status: 'integrity_failed', message: 'local asset has been revoked' }, ctx);
65
+ }
66
+ if (disposition === 'reusable') {
67
+ logReuse(deps, opts, local, 'local');
68
+ return emit({ ok: true, status: 'ok', message: 'asset already in local recall library' }, ctx);
69
+ }
87
70
  }
88
71
  // 2) Dry-run: describe the intended pull, touch nothing.
89
72
  if (isHubDryRunEnabled(env)) {
90
- return emit({ ok: true, status: 'dry_run', message: `would fetch ${opts.id} and write it to the local recall library` }, ctx);
73
+ return emit({ ok: true, status: 'dry_run', message: 'would fetch the requested asset and write it to the local recall library' }, ctx);
91
74
  }
92
75
  // 3) Pull the global asset by id, write it into the local recall library (put dedups → idempotent on repeat).
93
76
  const hub = deps.hub ?? createReuseFetcherFromEnv(env, deps);
@@ -97,23 +80,29 @@ export async function runReuseCommand(argv, deps = {}) {
97
80
  // trust. Best-effort by design:
98
81
  // a hello failure must not block the fetch — the fetch's own error path classifies precisely.
99
82
  await establishReuseTrust(hub);
100
- const asset = await hub.fetchAssetById(opts.id);
101
- if (!asset)
102
- return emit({ ok: false, status: 'not_found', message: `asset ${opts.id} not found on the hub` }, ctx);
103
- const { record, verified } = await ingestHubAsset(store, deps, asset, opts.id);
83
+ // This command owns the quarantine path below. Keep the shared adapter strict for every other caller and
84
+ // explicitly request an exact declared-ID delivery only where we will revalidate and freeze it as unverified.
85
+ const delivery = await fetchReuseDelivery(hub, opts.id);
86
+ if (delivery.status === 'absent')
87
+ return emit({ ok: false, status: 'not_found', message: 'asset not found on the hub' }, ctx);
88
+ if (delivery.status === 'rejected')
89
+ return emit(rejectedDeliveryOutcome(delivery.reason), ctx);
90
+ const { record, verified, repaired } = await ingestHubAsset(store, deps, delivery.asset, opts.id);
104
91
  logReuse(deps, opts, record, 'hub');
105
92
  // Both land the asset (exit 0). A verified reuse is a plain success; an unverified one is a first-class
106
93
  // success too — the operator's save happened — but carries reason `unverified` so the desktop adapter can
107
94
  // surface "added (unverified)" instead of a plain "added". status stays `ok` so older desktop builds, which
108
95
  // key success on status==='ok' and ignore reason, keep working unchanged.
109
- return emit(verified
110
- ? { ok: true, status: 'ok', message: 'reused into local recall library' }
111
- : {
112
- ok: true,
113
- status: 'ok',
114
- reason: 'unverified',
115
- message: 'reused into local recall library as untrusted: hub-delivered content does not match its content fingerprint and could not be verified',
116
- }, ctx);
96
+ if (verified)
97
+ return emit({ ok: true, status: 'ok', message: 'reused into local recall library' }, ctx);
98
+ return emit({
99
+ ok: true,
100
+ status: 'ok',
101
+ reason: 'unverified',
102
+ message: repaired
103
+ ? 'reused into local recall library as untrusted: hub-delivered content was incomplete and was repaired to a schema-valid record; it does not match its content fingerprint and could not be verified'
104
+ : 'reused into local recall library as untrusted: hub-delivered content does not match its content fingerprint and could not be verified',
105
+ }, ctx);
117
106
  }
118
107
  catch (e) {
119
108
  return emit(mapError(e), ctx);
@@ -130,14 +119,7 @@ function createReuseFetcherFromEnv(env, deps) {
130
119
  return {
131
120
  fetchAssetById: async (assetId) => {
132
121
  const body = await proxy.fetchAsset({ assetId, expectedHubMode: 'private' });
133
- const root = recordValue(body);
134
- const payload = recordValue(root['payload']);
135
- const assets = Array.isArray(root['assets']) ? root['assets'] : Array.isArray(payload['assets']) ? payload['assets'] : [];
136
- const asset = assets.find((candidate) => {
137
- const record = recordValue(candidate);
138
- return record['asset_id'] === assetId || record['id'] === assetId;
139
- });
140
- return asset && typeof asset === 'object' && !Array.isArray(asset) ? asset : null;
122
+ return selectPrivateReuseAsset(body, assetId);
141
123
  },
142
124
  };
143
125
  }
@@ -147,6 +129,48 @@ function configuredHubMode(env) {
147
129
  return value;
148
130
  throw new Error('EVOMAP_HUB_MODE must be public or private');
149
131
  }
132
+ function selectPrivateReuseAsset(body, requestedId) {
133
+ const root = recordValue(body);
134
+ const payload = recordValue(root['payload']);
135
+ const candidates = Array.isArray(root['assets'])
136
+ ? root['assets']
137
+ : Array.isArray(payload['assets'])
138
+ ? payload['assets']
139
+ : [];
140
+ const matches = [];
141
+ for (const candidate of candidates) {
142
+ const record = optionalRecord(candidate);
143
+ if (!record || !privateDeliveryMatchesRequestedId(record, requestedId))
144
+ continue;
145
+ const asset = record;
146
+ const delivery = unwrapHubAssetContent(asset);
147
+ const cleaned = stripHubDeliveryMetadataForIntegrity(delivery.content);
148
+ let canonical;
149
+ try {
150
+ canonical = wire.canonicalize(cleaned);
151
+ }
152
+ catch {
153
+ throw integrityError(delivery.synthesized);
154
+ }
155
+ matches.push({ asset, canonical, synthesized: delivery.synthesized });
156
+ }
157
+ if (matches.length === 0)
158
+ return null;
159
+ if (matches.some((match) => match.canonical !== matches[0].canonical)) {
160
+ throw integrityError(matches.some((match) => match.synthesized));
161
+ }
162
+ return matches.find((match) => match.synthesized)?.asset ?? matches[0].asset;
163
+ }
164
+ function privateDeliveryMatchesRequestedId(record, requestedId) {
165
+ const payload = optionalRecord(record['payload']);
166
+ if (requestedId.startsWith('sha256:')) {
167
+ return stringField(record, 'asset_id') === requestedId
168
+ || (payload !== undefined && stringField(payload, 'asset_id') === requestedId);
169
+ }
170
+ return stringField(record, 'id') === requestedId
171
+ || stringField(record, 'local_id') === requestedId
172
+ || (payload !== undefined && stringField(payload, 'id') === requestedId);
173
+ }
150
174
  /** Flags this CLI understands. parseReuseArgs walks argv and rejects anything outside this set with reason
151
175
  * `unsupported` so a typoed flag never silently falls through to a Hub round-trip — review blocker on V1 #283
152
176
  * (the previous tightening lived only in cliContracts.ts; dispatch.ts routes `reuse` here, so this is the path
@@ -170,7 +194,7 @@ export function parseReuseArgs(argv) {
170
194
  const eq = token.indexOf('=');
171
195
  const flag = eq >= 0 ? token.slice(0, eq) : token;
172
196
  if (!KNOWN_REUSE_FLAGS.has(flag))
173
- return { ok: false, status: 'unsupported', error: `unsupported reuse argument: ${flag}` };
197
+ return { ok: false, status: 'unsupported', error: 'unsupported reuse argument' };
174
198
  if (eq < 0 && VALUE_FLAGS.has(flag)) {
175
199
  // Value flag in space form consumes the next token; skip it so it doesn't get re-checked as a flag/positional.
176
200
  const next = argv[i + 1];
@@ -183,10 +207,10 @@ export function parseReuseArgs(argv) {
183
207
  // `--`-prefixed check above and would otherwise be silently accepted as an asset id, violating the
184
208
  // fail-closed contract. Legal asset ids (`sha256:…`, `gene_distilled_…`, logical ids) never start with `-`.
185
209
  if (token.startsWith('-'))
186
- return { ok: false, status: 'unsupported', error: `unsupported reuse argument: ${token}` };
210
+ return { ok: false, status: 'unsupported', error: 'unsupported reuse argument' };
187
211
  // First (and only) bare positional is the asset id; further positionals are unsupported.
188
212
  if (positional !== undefined)
189
- return { ok: false, status: 'unsupported', error: `unsupported reuse argument: ${token}` };
213
+ return { ok: false, status: 'unsupported', error: 'unsupported reuse argument' };
190
214
  positional = token;
191
215
  }
192
216
  if (!jsonOut)
@@ -195,7 +219,7 @@ export function parseReuseArgs(argv) {
195
219
  // typo'd/extra arg — or a conflicting second id — pass fail-OPEN, contradicting the fail-closed contract.
196
220
  const idFromFlag = flagValue(argv, '--id');
197
221
  if (idFromFlag !== null && positional !== undefined) {
198
- return { ok: false, status: 'unsupported', error: `unsupported reuse argument: ${positional}` };
222
+ return { ok: false, status: 'unsupported', error: 'unsupported reuse argument' };
199
223
  }
200
224
  const id = idFromFlag ?? positional;
201
225
  if (!id)
@@ -217,29 +241,49 @@ class ReuseIntegrityError extends Error {
217
241
  const INTEGRITY_MISMATCH_MESSAGE = 'hub-delivered content does not match the asset content fingerprint';
218
242
  const INTEGRITY_BACKFILLED_MESSAGE = 'hub delivered a synthesized payload for this asset; the original published content is unavailable for verification';
219
243
  const INTEGRITY_LOGICAL_ID_MESSAGE = 'hub-delivered asset does not match the requested logical id';
244
+ const INTEGRITY_INCOMPLETE_MESSAGE = 'hub-delivered content is missing fields that cannot be repaired without the original publisher';
245
+ const INTEGRITY_REVOKED_MESSAGE = 'hub-delivered asset has been revoked';
220
246
  function integrityError(synthesized) {
221
247
  return new ReuseIntegrityError(synthesized ? INTEGRITY_BACKFILLED_MESSAGE : INTEGRITY_MISMATCH_MESSAGE);
222
248
  }
223
249
  async function ingestHubAsset(store, deps, asset, requestedId) {
224
- const delivered = stripHubMetadata(unwrapHubAssetContent(asset));
225
- // `payload_backfill_reason` is a hub DELIVERY marker (unwrapHubAssetContent lifts it onto the content so a
226
- // synthesized payload can be classified). It is NOT publisher content, so it must be excluded from EVERY hash
227
- // — identity, the local-conflict check, AND the stored bytes — and never persisted. Capture the
228
- // classification fact, then drop the marker ONCE, up front: hashing it here but stripping it before storage
229
- // made assertNoLocalReuseIdConflict hash a different byte string than what landed on disk, throwing a false
230
- // id conflict on the second reuse of the same synthesized asset (Bugbot HIGH, broke idempotency).
231
- const synthesized = stringField(delivered, 'payload_backfill_reason') !== undefined;
232
- const cleaned = withoutHubDeliveryMarkers(delivered);
250
+ const delivery = unwrapHubAssetContent(asset);
251
+ // Use the same content projection as the public adapter and sync. Delivery metadata is classified first, then
252
+ // removed from every hash and from the stored bytes; Capsule confidence remains canonical content.
253
+ const projection = stripHubDeliveryMetadataForIntegrity(delivery.content);
254
+ const synthesized = delivery.synthesized;
255
+ const type = stringField(projection, 'type');
256
+ const contentAssetId = stringField(projection, 'asset_id');
257
+ if ((type !== 'Gene' && type !== 'Capsule') || !contentAssetId || !isContentAssetId(contentAssetId)) {
258
+ throw integrityError(synthesized);
259
+ }
260
+ // The hub delivers a LOSSY projection of the published record (dropped `schema_version`/`id`, emptied
261
+ // `constraints`, extra non-schema keys — measured across promoted genes on 2026-08-14), so a schema verdict
262
+ // here is a verdict on the DELIVERY, not on the asset. Repair it into a storable record instead of throwing
263
+ // the asset away; the identity guards below stay untouched, and the result is still quarantined as unverified.
264
+ const repair = repairHubProjection(projection, contentAssetId);
265
+ if (!repair.ok)
266
+ throw new ReuseIntegrityError(repair.message);
267
+ const cleaned = repair.record;
268
+ try {
269
+ assetstore.assertCapsuleGeneBinding(cleaned);
270
+ }
271
+ catch (error) {
272
+ if (error instanceof assetstore.CapsuleGeneBindingError)
273
+ throw integrityError(synthesized);
274
+ throw error;
275
+ }
233
276
  const actualAssetId = wire.computeAssetId(cleaned);
234
- const contentAssetId = stringField(cleaned, 'asset_id');
235
- if (!actualAssetId || !contentAssetId) {
277
+ if (!actualAssetId || !isContentAssetId(actualAssetId)) {
236
278
  // Malformed beyond classification — no computable hash or no declared id — stays a hard reject.
237
279
  throw integrityError(synthesized);
238
280
  }
239
281
  // Identity guards stay STRICT: a hub that returned a DIFFERENT asset than requested (a self-consistent asset
240
282
  // B under a request for A, or a different logical id) is a delivery fault, not the hub's known content-rewrite
241
283
  // of the RIGHT asset — reject it so a reuse never silently pulls the wrong gene.
242
- if (isContentAssetId(requestedId)) {
284
+ if (requestedId.startsWith('sha256:')) {
285
+ if (!isContentAssetId(requestedId))
286
+ throw integrityError(synthesized);
243
287
  if (contentAssetId !== requestedId)
244
288
  throw integrityError(synthesized);
245
289
  }
@@ -256,23 +300,60 @@ async function ingestHubAsset(store, deps, asset, requestedId) {
256
300
  const stored = await assetstore.ingestUntrustedConditional(store, provenance, cleaned);
257
301
  if (stored.status === 'logical_collision')
258
302
  throw new Error('local asset id conflict');
259
- return { record: { ...cleaned, asset_id: stored.asset_id }, verified: true };
303
+ return { record: { ...cleaned, asset_id: stored.asset_id }, verified: true, repaired: false };
260
304
  }
261
305
  const reason = synthesized ? 'unverified_hub_synthesized' : 'unverified_hub_rewrite';
262
306
  const stored = await assetstore.ingestUnverifiedConditional(store, provenance, cleaned, reason);
263
307
  if (stored.status === 'logical_collision')
264
308
  throw new Error('local asset id conflict');
265
- return { record: { ...cleaned, asset_id: stored.asset_id }, verified: false };
309
+ return { record: { ...cleaned, asset_id: stored.asset_id }, verified: false, repaired: repair.repaired };
266
310
  }
267
311
  /**
268
- * Drop hub DELIVERY markers that unwrapHubAssetContent lifts onto the content for classification but that must
269
- * never reach content-addressed storage. Right now that is `payload_backfill_reason`; keeping this as a named
270
- * helper localizes the "these keys describe HOW the hub delivered the asset, not the asset" rule.
312
+ * Make a hub delivery storable without letting it drift off the network identity it was fetched under.
313
+ * `repairAssetRecord` re-derives `asset_id` from the repaired content by design; here the DECLARED network id
314
+ * must survive instead, because the quarantine write freezes the repaired body under that id.
271
315
  */
272
- function withoutHubDeliveryMarkers(asset) {
273
- const rest = { ...asset };
274
- delete rest['payload_backfill_reason'];
275
- return rest;
316
+ function repairHubProjection(projection, declaredAssetId) {
317
+ const report = assetrepair.repairAssetRecord(projection);
318
+ if (report.status === 'already_valid')
319
+ return { ok: true, record: projection, repaired: false };
320
+ if (report.status === 'unrepairable') {
321
+ return { ok: false, message: `${INTEGRITY_INCOMPLETE_MESSAGE}: ${blockerSummary(report.blockers)}` };
322
+ }
323
+ const repairedContent = report.changes.some((change) => change.path !== 'asset_id');
324
+ return {
325
+ ok: true,
326
+ record: { ...report.asset, asset_id: declaredAssetId },
327
+ repaired: repairedContent,
328
+ };
329
+ }
330
+ // Hard rule 2 of this command: nothing dynamic reaches a stream unfiltered. Field paths come from the schema
331
+ // gate, but an `additionalProperties` path is named by hub-controlled content — so only plain field-path shapes
332
+ // pass, and only a handful of them.
333
+ const SAFE_FIELD_PATH = /^[A-Za-z0-9_.[\]]{1,40}$/;
334
+ function blockerSummary(blockers) {
335
+ const fields = [...new Set(blockers.map((blocker) => blocker.path))]
336
+ .filter((path) => SAFE_FIELD_PATH.test(path))
337
+ .slice(0, 5);
338
+ return fields.length > 0 ? `unrepairable fields: ${fields.join(', ')}` : 'the delivered record could not be classified';
339
+ }
340
+ async function fetchReuseDelivery(hub, assetId) {
341
+ const options = { allowUnverifiedExactIdentity: true };
342
+ if (hub.fetchAssetDeliveryById)
343
+ return hub.fetchAssetDeliveryById(assetId, options);
344
+ const asset = await hub.fetchAssetById(assetId, options);
345
+ return asset ? { status: 'delivered', asset, verified: true } : { status: 'absent' };
346
+ }
347
+ // A delivered-but-refused asset is NOT a missing asset. Reporting both as `not_found` sent operators looking for
348
+ // an asset the hub was serving the whole time; each rejection now names what the hub actually did.
349
+ function rejectedDeliveryOutcome(reason) {
350
+ const messages = {
351
+ identity_mismatch: 'hub delivered an asset whose identity does not match the requested id',
352
+ revoked: INTEGRITY_REVOKED_MESSAGE,
353
+ ambiguous: 'hub delivered conflicting copies of the requested asset',
354
+ unverified_not_allowed: INTEGRITY_MISMATCH_MESSAGE,
355
+ };
356
+ return { ok: false, status: 'integrity_failed', message: messages[reason] };
276
357
  }
277
358
  async function resolveLocalReuseAsset(store, id) {
278
359
  // A logical id does not identify an asset type. Gene and Capsule ids may overlap, so only the Hub can resolve
@@ -280,35 +361,62 @@ async function resolveLocalReuseAsset(store, id) {
280
361
  return isContentAssetId(id) ? store.get(id) : null;
281
362
  }
282
363
  function unwrapHubAssetContent(asset) {
283
- const payload = asset.payload;
284
- if (payload && typeof payload === 'object' && !Array.isArray(payload) && stringField(payload, 'asset_id')) {
285
- const content = payload;
286
- const backfillReason = stringField(asset, 'payload_backfill_reason');
287
- if (backfillReason && stringField(payload, 'payload_backfill_reason') === undefined) {
288
- return { ...content, payload_backfill_reason: backfillReason };
364
+ const row = asset;
365
+ const payload = optionalRecord(row['payload']);
366
+ // Revocation is a delivery decision, not canonical content. Reject it before wrapper unwrapping or metadata
367
+ // stripping can erase the marker and accidentally turn a revoked listing/fetch race into an ingestible asset.
368
+ if (hasRevokedDeliveryMarker(row) || (payload !== undefined && hasRevokedDeliveryMarker(payload))) {
369
+ throw new ReuseIntegrityError(INTEGRITY_REVOKED_MESSAGE);
370
+ }
371
+ const outerType = stringField(row, 'type');
372
+ const innerType = payload ? stringField(payload, 'type') : undefined;
373
+ const synthesized = stringField(row, 'payload_backfill_reason') !== undefined
374
+ || (payload !== undefined && stringField(payload, 'payload_backfill_reason') !== undefined);
375
+ // A typed row is already a raw GEP record. Do not reinterpret a canonical payload field as a delivery wrapper.
376
+ if (outerType !== undefined || !payload || innerType === undefined) {
377
+ const transportType = stringField(row, 'asset_type');
378
+ const transportLogicalId = stringField(row, 'local_id');
379
+ if ((transportType !== undefined && transportType !== outerType)
380
+ || (transportLogicalId !== undefined && transportLogicalId !== stringField(row, 'id'))) {
381
+ throw integrityError(synthesized);
289
382
  }
290
- return content;
383
+ return { content: asset, synthesized };
384
+ }
385
+ const outerAssetId = stringField(row, 'asset_id');
386
+ const innerAssetId = stringField(payload, 'asset_id');
387
+ const outerAssetType = stringField(row, 'asset_type');
388
+ const innerLogicalId = stringField(payload, 'id');
389
+ if (!outerAssetId
390
+ || !innerAssetId
391
+ || outerAssetId !== innerAssetId
392
+ || (outerAssetType !== undefined && outerAssetType !== innerType)
393
+ || (stringField(row, 'id') !== undefined && stringField(row, 'id') !== innerLogicalId)
394
+ || (stringField(row, 'local_id') !== undefined && stringField(row, 'local_id') !== innerLogicalId)) {
395
+ throw integrityError(synthesized);
291
396
  }
292
- return asset;
397
+ return { content: payload, synthesized };
293
398
  }
294
- function stripHubMetadata(asset) {
295
- const out = {};
296
- for (const [key, value] of Object.entries(asset))
297
- if (!HUB_METADATA_KEYS.has(key))
298
- out[key] = value;
299
- return out;
399
+ function hasRevokedDeliveryMarker(record) {
400
+ return ['status', 'trust_state'].some((key) => {
401
+ const value = record[key];
402
+ return typeof value === 'string' && value.trim().toLowerCase() === 'revoked';
403
+ });
300
404
  }
301
405
  function storeBaseDir(store, deps) {
302
406
  return store instanceof assetstore.LocalJsonlProvider
303
407
  ? store.baseDir
304
408
  : deps.assetsDir ?? events.assetsDir(deps.env ?? process.env);
305
409
  }
306
- function isUnsafeUnverifiedLocalAsset(asset, store, deps) {
307
- if (wire.verifyAssetId(asset))
308
- return false;
410
+ function localReuseDisposition(asset, store, deps) {
309
411
  const record = new assetstore.ProvenanceStore(storeBaseDir(store, deps)).get(asset.asset_id);
310
- if (record?.trusted === true || record?.decision !== undefined)
311
- return false;
412
+ // An explicit revoke dominates content-hash validity and every prior trust state. Do not let a canonical body
413
+ // bypass the operator decision, and do not fall through to Hub refetch: this local id is intentionally blocked.
414
+ if (record?.decision === 'revoked')
415
+ return 'revoked';
416
+ if (wire.verifyAssetId(asset))
417
+ return 'reusable';
418
+ if (record?.trusted === true || record?.decision === 'promoted')
419
+ return 'reusable';
312
420
  const supportedReason = (record?.source === 'hub'
313
421
  && (record.reason === 'unverified_hub_rewrite' || record.reason === 'unverified_hub_synthesized')) || (record?.source === 'migrated' && record.reason === 'unverified_gepx_import');
314
422
  const isActiveWaiver = supportedReason
@@ -317,14 +425,14 @@ function isUnsafeUnverifiedLocalAsset(asset, store, deps) {
317
425
  && record.decidedBy === undefined
318
426
  && record.promotedBy === undefined
319
427
  && record.frozenContentId === wire.computeAssetId(asset);
320
- return !isActiveWaiver;
428
+ return isActiveWaiver ? 'reusable' : 'refetch';
321
429
  }
322
430
  function stringField(record, key) {
323
431
  const value = record[key];
324
432
  return typeof value === 'string' && value.length > 0 ? value : undefined;
325
433
  }
326
434
  function isContentAssetId(value) {
327
- return value.startsWith('sha256:');
435
+ return /^sha256:[0-9a-f]{64}$/.test(value);
328
436
  }
329
437
  function logReuse(deps, opts, asset, source) {
330
438
  // AssetCallLog.append is best-effort (never throws) — a logging failure must not break the reuse write.
@@ -373,6 +481,9 @@ function hubErrorField(body) {
373
481
  function recordValue(value) {
374
482
  return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
375
483
  }
484
+ function optionalRecord(value) {
485
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : undefined;
486
+ }
376
487
  function mapError(e) {
377
488
  if (e instanceof ReuseIntegrityError) {
378
489
  return { ok: false, status: 'integrity_failed', message: e.message };
@@ -414,15 +525,18 @@ function mapError(e) {
414
525
  return { ok: false, status: 'unavailable', message: 'private Hub proxy is not configured' };
415
526
  }
416
527
  if (/Hub URL|EVOMAP_HUB_URL|A2A_HUB_URL/i.test(msg)) {
417
- return { ok: false, status: 'unavailable', message: redact(msg) };
528
+ return { ok: false, status: 'unavailable', message: 'hub URL configuration is invalid' };
418
529
  }
419
530
  if (/Hub credentials|node identity|evolver login|EVOMAP_NODE_SECRET/i.test(msg)) {
420
- return { ok: false, status: 'unauthorized', message: redact(msg) };
531
+ return { ok: false, status: 'unauthorized', message: 'hub authentication failed; run `evolver login` or set EVOMAP_NODE_SECRET' };
421
532
  }
422
533
  if (/\b(?:hub|http)\s*5\d\d\b/i.test(msg) || /\b(network|fetch failed|ECONN[A-Z_]*|ENOTFOUND|ETIMEDOUT)\b/i.test(msg)) {
423
534
  return { ok: false, status: 'network', message: 'hub is unreachable' };
424
535
  }
425
- return { ok: false, status: 'internal_error', message: redact(msg) };
536
+ if (msg === 'local asset id conflict') {
537
+ return { ok: false, status: 'internal_error', message: 'local asset id conflict' };
538
+ }
539
+ return { ok: false, status: 'internal_error', message: 'reuse operation failed' };
426
540
  }
427
541
  function emit(outcome, ctx) {
428
542
  if (ctx.jsonOut) {
@@ -438,15 +552,6 @@ function emit(outcome, ctx) {
438
552
  }
439
553
  return outcome.ok ? 0 : 1;
440
554
  }
441
- /** Defensive redaction so a stray credential in an error string never reaches stdout/stderr. */
442
- function redact(value) {
443
- return value
444
- .replace(/\bBearer\s+[A-Za-z0-9._~+/=-]+/gi, 'Bearer [redacted]')
445
- .replace(/\b([A-Z][A-Z0-9_]*(?:_SECRET|_TOKEN))\b\s*[:=]\s*["']?[^"',\s;}]+/g, '$1=[redacted]')
446
- .replace(/\b(authorization|node_secret|nodeSecret|access_token|refresh_token|token|secret)\b\s*[:=]\s*["']?[^"',\s;}]+/gi, '$1=[redacted]')
447
- .replace(/\bsk-[A-Za-z0-9-]{16,}/g, 'sk-[redacted]')
448
- .replace(/\bgh[pousr]_[A-Za-z0-9]{20,}/g, 'gh_[redacted]');
449
- }
450
555
  function flagValue(args, flag) {
451
556
  for (let i = 0; i < args.length; i += 1) {
452
557
  const token = args[i];
package/dist/sync.d.ts CHANGED
@@ -5,7 +5,7 @@ export interface SyncAccountAssetLister {
5
5
  listAccountAssets(opts: AccountAssetListOptions): Promise<AccountAssetListResult>;
6
6
  }
7
7
  export interface SyncAccountAssetHub extends SyncAccountAssetLister {
8
- fetchAssetById(assetId: string): Promise<assetstore.AssetRecord | null>;
8
+ fetchAssetById(assetId: string, options?: hubNs.FetchAssetByIdOptions): Promise<assetstore.AssetRecord | null>;
9
9
  }
10
10
  export interface SyncCliDeps {
11
11
  hub?: SyncAccountAssetLister | SyncAccountAssetHub;