@evomap/evolver-cli 2.0.0-beta.2 → 2.0.0-beta.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/dist/antiGeneBenchmark.js +2 -0
  2. package/dist/antiGeneRollout.js +9 -3
  3. package/dist/assetHealth.d.ts +6 -0
  4. package/dist/assetHealth.js +107 -0
  5. package/dist/assetRepair.d.ts +24 -0
  6. package/dist/assetRepair.js +172 -0
  7. package/dist/assetSidecarRecovery.d.ts +14 -0
  8. package/dist/assetSidecarRecovery.js +171 -0
  9. package/dist/assetTrust.d.ts +24 -0
  10. package/dist/assetTrust.js +231 -0
  11. package/dist/atp.d.ts +10 -5
  12. package/dist/atp.js +119 -26
  13. package/dist/atpAutoBuyer.d.ts +120 -0
  14. package/dist/atpAutoBuyer.js +814 -0
  15. package/dist/atpAutoDeliver.js +2 -2
  16. package/dist/autoDistillAntiGene.js +7 -5
  17. package/dist/autoDistillLlm.d.ts +26 -0
  18. package/dist/autoDistillLlm.js +119 -22
  19. package/dist/autoDistillTranscript.js +3 -2
  20. package/dist/autoexec.d.ts +111 -24
  21. package/dist/autoexec.js +887 -120
  22. package/dist/autoexecConfig.d.ts +10 -0
  23. package/dist/autoexecConfig.js +69 -0
  24. package/dist/cli.js +13 -0
  25. package/dist/cliContracts.d.ts +33 -2
  26. package/dist/cliContracts.js +818 -78
  27. package/dist/commandCatalog.d.ts +72 -0
  28. package/dist/commandCatalog.js +120 -0
  29. package/dist/commands.d.ts +1 -0
  30. package/dist/commands.js +1 -0
  31. package/dist/curriculumCapabilityGaps.d.ts +6 -0
  32. package/dist/curriculumCapabilityGaps.js +24 -0
  33. package/dist/cycleConsumer.d.ts +17 -2
  34. package/dist/cycleConsumer.js +374 -50
  35. package/dist/dashboard.d.ts +13 -1
  36. package/dist/dashboard.js +235 -18
  37. package/dist/dispatch.d.ts +9 -2
  38. package/dist/dispatch.js +29 -6
  39. package/dist/distillAdmission.d.ts +13 -0
  40. package/dist/distillAdmission.js +35 -0
  41. package/dist/distillObserver.js +27 -12
  42. package/dist/distillPrimitives.d.ts +11 -8
  43. package/dist/distillPrimitives.js +116 -22
  44. package/dist/doctor.d.ts +13 -0
  45. package/dist/doctor.js +177 -10
  46. package/dist/identityHome.d.ts +9 -0
  47. package/dist/identityHome.js +47 -0
  48. package/dist/index.d.ts +73 -40
  49. package/dist/index.js +745 -207
  50. package/dist/issueReport.d.ts +7 -0
  51. package/dist/issueReport.js +291 -0
  52. package/dist/learningTrace.d.ts +15 -0
  53. package/dist/learningTrace.js +73 -0
  54. package/dist/lifecycle.d.ts +199 -2
  55. package/dist/lifecycle.js +4999 -152
  56. package/dist/lifecycleBootstrapTransaction.d.ts +235 -0
  57. package/dist/lifecycleBootstrapTransaction.js +2182 -0
  58. package/dist/localMemoryGraph.d.ts +184 -0
  59. package/dist/localMemoryGraph.js +2689 -0
  60. package/dist/login.d.ts +1 -1
  61. package/dist/login.js +3 -3
  62. package/dist/materialPackage.js +3 -6
  63. package/dist/materialSnapshot.d.ts +35 -1
  64. package/dist/materialSnapshot.js +265 -18
  65. package/dist/memoryGraphOps.d.ts +8 -0
  66. package/dist/memoryGraphOps.js +140 -0
  67. package/dist/migrate/assetFormatMap.d.ts +61 -0
  68. package/dist/migrate/assetFormatMap.js +53 -0
  69. package/dist/migrate/envTranslate.d.ts +26 -0
  70. package/dist/migrate/envTranslate.js +147 -0
  71. package/dist/migrate/fieldMap.d.ts +7 -5
  72. package/dist/migrate/fieldMap.js +20 -14
  73. package/dist/migrate/oauthImport.d.ts +66 -0
  74. package/dist/migrate/oauthImport.js +667 -0
  75. package/dist/migrate/v1Import.d.ts +98 -1
  76. package/dist/migrate/v1Import.js +1532 -71
  77. package/dist/modelCompatibility.d.ts +10 -0
  78. package/dist/modelCompatibility.js +296 -0
  79. package/dist/promptRecallHook.d.ts +24 -0
  80. package/dist/promptRecallHook.js +425 -0
  81. package/dist/recallVerifyReport.d.ts +37 -0
  82. package/dist/recallVerifyReport.js +244 -0
  83. package/dist/recipe.d.ts +14 -2
  84. package/dist/recipe.js +543 -65
  85. package/dist/repairedAssetStore.d.ts +2 -0
  86. package/dist/repairedAssetStore.js +12 -0
  87. package/dist/requiredSandboxValidation.d.ts +5 -0
  88. package/dist/requiredSandboxValidation.js +4 -0
  89. package/dist/reuse.d.ts +18 -4
  90. package/dist/reuse.js +375 -107
  91. package/dist/reviewFilter.d.ts +3 -1
  92. package/dist/reviewFilter.js +3 -1
  93. package/dist/runtimeCapabilities.d.ts +18 -0
  94. package/dist/runtimeCapabilities.js +81 -0
  95. package/dist/runtimeSessionSource.d.ts +8 -2
  96. package/dist/runtimeSessionSource.js +63 -11
  97. package/dist/selectionPolicyConfig.d.ts +8 -0
  98. package/dist/selectionPolicyConfig.js +18 -0
  99. package/dist/semanticIdfConfig.d.ts +2 -0
  100. package/dist/semanticIdfConfig.js +4 -0
  101. package/dist/sessionIngest.d.ts +43 -0
  102. package/dist/sessionIngest.js +180 -0
  103. package/dist/setupHooks.d.ts +5 -0
  104. package/dist/setupHooks.js +330 -14
  105. package/dist/skill2gep.d.ts +13 -9
  106. package/dist/skill2gep.js +99 -36
  107. package/dist/skillDistill.d.ts +8 -4
  108. package/dist/skillDistill.js +39 -9
  109. package/dist/solo/mode.js +1 -0
  110. package/dist/sync.d.ts +13 -1
  111. package/dist/sync.js +1947 -265
  112. package/dist/thesis.d.ts +1 -1
  113. package/dist/thesis.js +20 -3
  114. package/dist/trajectoryExport.js +21 -3
  115. package/dist/v1Compat.d.ts +1 -0
  116. package/dist/v1Compat.js +9 -0
  117. package/dist/valueDigest.js +8 -1
  118. package/dist/windowsLegacyTaskCleanup.d.ts +228 -0
  119. package/dist/windowsLegacyTaskCleanup.js +1475 -0
  120. package/dist/workflow.d.ts +39 -0
  121. package/dist/workflow.js +386 -0
  122. package/dist/workflowRuntime.d.ts +66 -0
  123. package/dist/workflowRuntime.js +638 -0
  124. package/package.json +14 -7
package/dist/reuse.js CHANGED
@@ -10,10 +10,11 @@
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';
15
- import { loadEnvFileFromEnv } from '@evomap/evolver-mcp';
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
+ import { loadEnvFileFromEnv, proxyClientFromEnv } from '@evomap/evolver-mcp';
16
16
  import { createRecipeHubFromEnv } from './recipe.js';
17
+ import { getCliVersion } from './version.js';
17
18
  const REUSE_CONTRACT = 'reuse.v1';
18
19
  const MAX_ID_LENGTH = 200;
19
20
  const REUSE_USAGE = [
@@ -23,27 +24,6 @@ const REUSE_USAGE = [
23
24
  // Flags that consume the following token as their value. firstPositional must skip those values so a flag value
24
25
  // (e.g. the `reference` in `--mode reference`) is never mistaken for a bare positional asset id.
25
26
  const VALUE_FLAGS = new Set(['--id', '--mode', '--run']);
26
- const HUB_METADATA_KEYS = new Set([
27
- 'credit_cost',
28
- 'gdi_score',
29
- 'success_rate',
30
- 'reuse_count',
31
- 'ranking_score',
32
- 'source_node_id',
33
- 'fetched_at',
34
- 'receipt',
35
- 'hub_receipt',
36
- 'already_purchased',
37
- '_semantic_similarity',
38
- 'semantic_similarity',
39
- '_search_score',
40
- 'search_score',
41
- '_match_score',
42
- 'match_score',
43
- '_retrieval_rank',
44
- 'retrieval_rank',
45
- 'original_asset_id',
46
- ]);
47
27
  export async function runReuseCommand(argv, deps = {}) {
48
28
  const ctx = {
49
29
  jsonOut: argv.includes('--json'),
@@ -72,31 +52,125 @@ export async function runReuseCommand(argv, deps = {}) {
72
52
  const env = deps.env ?? process.env;
73
53
  // Keep the native reuse path aligned with publish/contract transport: env-file values must be present before
74
54
  // dry-run checks and Hub construction. The loader mutates `env` and does not expose secret values.
75
- loadEnvFileFromEnv(env);
76
- const store = deps.store ?? new assetstore.LocalJsonlProvider(events.assetsDir());
55
+ const envFile = loadEnvFileFromEnv(env);
56
+ if (envFile.error)
57
+ throw new Error('failed to load EVOLVER_ENV_FILE');
58
+ const store = deps.store ?? new assetstore.LocalJsonlProvider(deps.assetsDir ?? events.assetsDir(env));
77
59
  // 1) Already in the local recall library → reuse is idempotent: log + ok, no hub round-trip.
78
60
  const local = await resolveLocalReuseAsset(store, opts.id);
79
61
  if (local) {
80
- logReuse(deps, opts, local, 'local');
81
- return emit({ ok: true, status: 'ok', message: 'asset already in local recall library' }, ctx);
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
+ }
82
70
  }
83
71
  // 2) Dry-run: describe the intended pull, touch nothing.
84
72
  if (isHubDryRunEnabled(env)) {
85
- 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);
86
74
  }
87
75
  // 3) Pull the global asset by id, write it into the local recall library (put dedups → idempotent on repeat).
88
- const hub = deps.hub ?? createRecipeHubFromEnv(env, deps.connectHub ?? connectPublicHub);
89
- const asset = await hub.fetchAssetById(opts.id);
90
- if (!asset)
91
- return emit({ ok: false, status: 'not_found', message: `asset ${opts.id} not found on the hub` }, ctx);
92
- const cleaned = await ingestHubAsset(store, deps, asset, opts.id);
93
- logReuse(deps, opts, cleaned, 'hub');
94
- return emit({ ok: true, status: 'ok', message: 'reused into local recall library' }, ctx);
76
+ const hub = deps.hub ?? createReuseFetcherFromEnv(env, deps);
77
+ // One-shot CLIs never heartbeat, so the hub may hold no env fingerprint for this node and its anti-abuse
78
+ // layer then 403s /a2a/fetch (`bulk_fetch_blocked: IP antibody`, #555). A fingerprinted hello
79
+ // (rotate:false + preserveCredentials:true) neither requests nor applies credential mutation while establishing
80
+ // trust. Best-effort by design:
81
+ // a hello failure must not block the fetch — the fetch's own error path classifies precisely.
82
+ await establishReuseTrust(hub);
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);
91
+ logReuse(deps, opts, record, 'hub');
92
+ // Both land the asset (exit 0). A verified reuse is a plain success; an unverified one is a first-class
93
+ // success too — the operator's save happened — but carries reason `unverified` so the desktop adapter can
94
+ // surface "added (unverified)" instead of a plain "added". status stays `ok` so older desktop builds, which
95
+ // key success on status==='ok' and ignore reason, keep working unchanged.
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);
95
106
  }
96
107
  catch (e) {
97
108
  return emit(mapError(e), ctx);
98
109
  }
99
110
  }
111
+ function createReuseFetcherFromEnv(env, deps) {
112
+ const hubMode = configuredHubMode(env);
113
+ if (hubMode === 'public') {
114
+ return createRecipeHubFromEnv(env, deps.connectHub ?? connectPublicHub);
115
+ }
116
+ const proxy = (deps.resolveProxyClient ?? proxyClientFromEnv)(env);
117
+ if (!proxy)
118
+ throw new Error('private Hub proxy is not configured');
119
+ return {
120
+ fetchAssetById: async (assetId) => {
121
+ const body = await proxy.fetchAsset({ assetId, expectedHubMode: 'private' });
122
+ return selectPrivateReuseAsset(body, assetId);
123
+ },
124
+ };
125
+ }
126
+ function configuredHubMode(env) {
127
+ const value = String(env['EVOMAP_HUB_MODE'] ?? 'public').trim().toLowerCase();
128
+ if (value === 'public' || value === 'private')
129
+ return value;
130
+ throw new Error('EVOMAP_HUB_MODE must be public or private');
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
+ }
100
174
  /** Flags this CLI understands. parseReuseArgs walks argv and rejects anything outside this set with reason
101
175
  * `unsupported` so a typoed flag never silently falls through to a Hub round-trip — review blocker on V1 #283
102
176
  * (the previous tightening lived only in cliContracts.ts; dispatch.ts routes `reuse` here, so this is the path
@@ -120,7 +194,7 @@ export function parseReuseArgs(argv) {
120
194
  const eq = token.indexOf('=');
121
195
  const flag = eq >= 0 ? token.slice(0, eq) : token;
122
196
  if (!KNOWN_REUSE_FLAGS.has(flag))
123
- return { ok: false, status: 'unsupported', error: `unsupported reuse argument: ${flag}` };
197
+ return { ok: false, status: 'unsupported', error: 'unsupported reuse argument' };
124
198
  if (eq < 0 && VALUE_FLAGS.has(flag)) {
125
199
  // Value flag in space form consumes the next token; skip it so it doesn't get re-checked as a flag/positional.
126
200
  const next = argv[i + 1];
@@ -133,10 +207,10 @@ export function parseReuseArgs(argv) {
133
207
  // `--`-prefixed check above and would otherwise be silently accepted as an asset id, violating the
134
208
  // fail-closed contract. Legal asset ids (`sha256:…`, `gene_distilled_…`, logical ids) never start with `-`.
135
209
  if (token.startsWith('-'))
136
- return { ok: false, status: 'unsupported', error: `unsupported reuse argument: ${token}` };
210
+ return { ok: false, status: 'unsupported', error: 'unsupported reuse argument' };
137
211
  // First (and only) bare positional is the asset id; further positionals are unsupported.
138
212
  if (positional !== undefined)
139
- return { ok: false, status: 'unsupported', error: `unsupported reuse argument: ${token}` };
213
+ return { ok: false, status: 'unsupported', error: 'unsupported reuse argument' };
140
214
  positional = token;
141
215
  }
142
216
  if (!jsonOut)
@@ -145,7 +219,7 @@ export function parseReuseArgs(argv) {
145
219
  // typo'd/extra arg — or a conflicting second id — pass fail-OPEN, contradicting the fail-closed contract.
146
220
  const idFromFlag = flagValue(argv, '--id');
147
221
  if (idFromFlag !== null && positional !== undefined) {
148
- return { ok: false, status: 'unsupported', error: `unsupported reuse argument: ${positional}` };
222
+ return { ok: false, status: 'unsupported', error: 'unsupported reuse argument' };
149
223
  }
150
224
  const id = idFromFlag ?? positional;
151
225
  if (!id)
@@ -158,91 +232,282 @@ export function parseReuseArgs(argv) {
158
232
  const runId = flagValue(argv, '--run');
159
233
  return { ok: true, value: { id, mode: modeRaw === 'direct' ? 'direct' : 'reference', ...(runId ? { runId } : {}) } };
160
234
  }
235
+ // Integrity rejection is a first-class outcome, not an internal fault: the hub demonstrably rewrites
236
+ // delivered payloads (injected `validation`, wholesale `payload_backfill_reason` synthesis — #570), so the
237
+ // desktop adapter needs a typed reason to tell "this asset cannot be verified" apart from "the engine broke".
238
+ // Messages are fixed strings by construction (hard rule 2: nothing dynamic can reach a stream).
239
+ class ReuseIntegrityError extends Error {
240
+ }
241
+ const INTEGRITY_MISMATCH_MESSAGE = 'hub-delivered content does not match the asset content fingerprint';
242
+ const INTEGRITY_BACKFILLED_MESSAGE = 'hub delivered a synthesized payload for this asset; the original published content is unavailable for verification';
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';
246
+ function integrityError(synthesized) {
247
+ return new ReuseIntegrityError(synthesized ? INTEGRITY_BACKFILLED_MESSAGE : INTEGRITY_MISMATCH_MESSAGE);
248
+ }
161
249
  async function ingestHubAsset(store, deps, asset, requestedId) {
162
- const cleaned = stripHubMetadata(asset);
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
+ }
163
276
  const actualAssetId = wire.computeAssetId(cleaned);
164
- const contentAssetId = stringField(cleaned, 'asset_id');
165
- if (!actualAssetId || !contentAssetId || actualAssetId !== contentAssetId) {
166
- throw new Error('asset integrity verification failed');
277
+ if (!actualAssetId || !isContentAssetId(actualAssetId)) {
278
+ // Malformed beyond classification — no computable hash or no declared id — stays a hard reject.
279
+ throw integrityError(synthesized);
167
280
  }
168
- if (isContentAssetId(requestedId) && actualAssetId !== requestedId) {
169
- throw new Error('asset integrity verification failed');
281
+ // Identity guards stay STRICT: a hub that returned a DIFFERENT asset than requested (a self-consistent asset
282
+ // B under a request for A, or a different logical id) is a delivery fault, not the hub's known content-rewrite
283
+ // of the RIGHT asset — reject it so a reuse never silently pulls the wrong gene.
284
+ if (requestedId.startsWith('sha256:')) {
285
+ if (!isContentAssetId(requestedId))
286
+ throw integrityError(synthesized);
287
+ if (contentAssetId !== requestedId)
288
+ throw integrityError(synthesized);
170
289
  }
171
- if (!isContentAssetId(requestedId) && stringField(cleaned, 'id') !== requestedId) {
172
- throw new Error('asset integrity verification failed');
290
+ else if (stringField(cleaned, 'id') !== requestedId) {
291
+ throw new ReuseIntegrityError(INTEGRITY_LOGICAL_ID_MESSAGE);
173
292
  }
174
- await assertNoLocalReuseIdConflict(cleaned, store);
175
293
  const provenance = new assetstore.ProvenanceStore(storeBaseDir(store, deps));
176
- const stored = await assetstore.ingestUntrusted(store, provenance, cleaned, 'hub');
177
- return { ...cleaned, asset_id: stored.asset_id };
294
+ // Identity is confirmed; now content integrity. When the (marker-free) payload hashes to its declared id it
295
+ // lands verified (still sidecar-marked untrusted per #30). When it does NOT, the hub rewrote the delivered
296
+ // bytes of the right asset (#570) — DOWNGRADE instead of reject: freeze it under the network id and mark it
297
+ // unverified so the save actually happens and the loop (which already reuses hub content without
298
+ // re-verifying) can use it, while trust-first selection keeps it out of the reasoning pool until promotion.
299
+ if (actualAssetId === contentAssetId) {
300
+ const stored = await assetstore.ingestUntrustedConditional(store, provenance, cleaned);
301
+ if (stored.status === 'logical_collision')
302
+ throw new Error('local asset id conflict');
303
+ return { record: { ...cleaned, asset_id: stored.asset_id }, verified: true, repaired: false };
304
+ }
305
+ const reason = synthesized ? 'unverified_hub_synthesized' : 'unverified_hub_rewrite';
306
+ const stored = await assetstore.ingestUnverifiedConditional(store, provenance, cleaned, reason);
307
+ if (stored.status === 'logical_collision')
308
+ throw new Error('local asset id conflict');
309
+ return { record: { ...cleaned, asset_id: stored.asset_id }, verified: false, repaired: repair.repaired };
178
310
  }
179
- async function resolveLocalReuseAsset(store, id) {
180
- const direct = await store.get(id);
181
- if (direct)
182
- return direct;
183
- for (const kind of ['Gene', 'Capsule']) {
184
- const rows = await store.list(kind, 10_000);
185
- const match = rows.find((row) => stringField(row, 'id') === id || String(row.asset_id) === id);
186
- if (match)
187
- return match;
311
+ /**
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.
315
+ */
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)}` };
188
322
  }
189
- return null;
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
+ };
190
329
  }
191
- async function assertNoLocalReuseIdConflict(asset, store) {
192
- if (asset.type !== 'Gene' && asset.type !== 'Capsule')
193
- return;
194
- const id = stringField(asset, 'id');
195
- if (!id)
196
- return;
197
- const rows = await store.list(asset.type, 10_000);
198
- const local = rows.find((row) => stringField(row, 'id') === id);
199
- if (!local)
200
- return;
201
- const incomingAssetId = wire.computeAssetId(asset);
202
- const localAssetId = wire.computeAssetId(local);
203
- if (incomingAssetId !== localAssetId)
204
- throw new Error('local asset id conflict');
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] };
357
+ }
358
+ async function resolveLocalReuseAsset(store, id) {
359
+ // A logical id does not identify an asset type. Gene and Capsule ids may overlap, so only the Hub can resolve
360
+ // which remote asset the caller requested; treating either local type as a hit can silently reuse the wrong one.
361
+ return isContentAssetId(id) ? store.get(id) : null;
362
+ }
363
+ function unwrapHubAssetContent(asset) {
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);
382
+ }
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);
396
+ }
397
+ return { content: payload, synthesized };
205
398
  }
206
- function stripHubMetadata(asset) {
207
- const out = {};
208
- for (const [key, value] of Object.entries(asset))
209
- if (!HUB_METADATA_KEYS.has(key))
210
- out[key] = value;
211
- 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
+ });
212
404
  }
213
405
  function storeBaseDir(store, deps) {
214
- return store instanceof assetstore.LocalJsonlProvider ? store.baseDir : deps.assetsDir ?? events.assetsDir();
406
+ return store instanceof assetstore.LocalJsonlProvider
407
+ ? store.baseDir
408
+ : deps.assetsDir ?? events.assetsDir(deps.env ?? process.env);
409
+ }
410
+ function localReuseDisposition(asset, store, deps) {
411
+ const record = new assetstore.ProvenanceStore(storeBaseDir(store, deps)).get(asset.asset_id);
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';
420
+ const supportedReason = (record?.source === 'hub'
421
+ && (record.reason === 'unverified_hub_rewrite' || record.reason === 'unverified_hub_synthesized')) || (record?.source === 'migrated' && record.reason === 'unverified_gepx_import');
422
+ const isActiveWaiver = supportedReason
423
+ && record.trusted === false
424
+ && record.decision === undefined
425
+ && record.decidedBy === undefined
426
+ && record.promotedBy === undefined
427
+ && record.frozenContentId === wire.computeAssetId(asset);
428
+ return isActiveWaiver ? 'reusable' : 'refetch';
215
429
  }
216
430
  function stringField(record, key) {
217
431
  const value = record[key];
218
432
  return typeof value === 'string' && value.length > 0 ? value : undefined;
219
433
  }
220
434
  function isContentAssetId(value) {
221
- return value.startsWith('sha256:');
435
+ return /^sha256:[0-9a-f]{64}$/.test(value);
222
436
  }
223
437
  function logReuse(deps, opts, asset, source) {
224
438
  // AssetCallLog.append is best-effort (never throws) — a logging failure must not break the reuse write.
225
- const callLog = deps.callLog ?? new hubNs.AssetCallLog(events.assetCallLogPath());
226
- callLog.append({
227
- action: 'asset_reuse',
228
- asset_id: asset.asset_id,
229
- asset_type: asset.type,
230
- mode: opts.mode,
231
- ...(opts.runId ? { run_id: opts.runId } : {}),
232
- extra: { source },
233
- });
439
+ const callLog = deps.callLog ?? new hubNs.AssetCallLog(events.assetCallLogPath(deps.env ?? process.env));
440
+ let indexedTokenCost;
441
+ try {
442
+ indexedTokenCost = callLog.assetCostIndex?.()[asset.asset_id];
443
+ }
444
+ catch { /* fall back to the estimator */ }
445
+ const savings = hubNs.reuseSavingsForAsset(asset, opts.mode, indexedTokenCost);
446
+ try {
447
+ callLog.append({
448
+ action: opts.mode === 'reference' ? 'asset_reference' : 'asset_reuse',
449
+ asset_id: asset.asset_id,
450
+ asset_type: asset.type,
451
+ mode: opts.mode,
452
+ tokens_saved: savings.tokens_saved,
453
+ tokens_saved_basis: savings.tokens_saved_basis,
454
+ ...(opts.runId ? { run_id: opts.runId } : {}),
455
+ extra: { source },
456
+ });
457
+ }
458
+ catch { /* an injected logger must preserve the production logger's non-fatal contract */ }
459
+ }
460
+ async function establishReuseTrust(hub) {
461
+ if (typeof hub.hello !== 'function')
462
+ return;
463
+ try {
464
+ await hub.hello({ rotate: false, evolverVersion: getCliVersion(), preserveCredentials: true });
465
+ }
466
+ catch { /* fetch decides the outcome */ }
467
+ }
468
+ const ANTI_ABUSE_BLOCK_MESSAGE = 'hub anti-abuse temporarily blocked asset fetch for this node; keep the local Evolver proxy running so the node builds trust, then retry';
469
+ function antiAbuseOutcome() {
470
+ return { ok: false, status: 'rate_limited', message: ANTI_ABUSE_BLOCK_MESSAGE };
471
+ }
472
+ function isAntiAbuseFetchBlock(status, code) {
473
+ return status === 403 && code !== undefined && /antibody|bulk_fetch|anti[-_]?abuse/i.test(code);
474
+ }
475
+ function hubErrorField(body) {
476
+ if (!body || typeof body !== 'object')
477
+ return undefined;
478
+ const err = body['error'];
479
+ return typeof err === 'string' ? err : undefined;
480
+ }
481
+ function recordValue(value) {
482
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
483
+ }
484
+ function optionalRecord(value) {
485
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : undefined;
234
486
  }
235
487
  function mapError(e) {
236
- if (e instanceof AuthError)
488
+ if (e instanceof ReuseIntegrityError) {
489
+ return { ok: false, status: 'integrity_failed', message: e.message };
490
+ }
491
+ if (e instanceof AuthError) {
492
+ // hubFetch raises AuthError for BOTH 401 and 403, so the hub's anti-abuse 403
493
+ // (`bulk_fetch_blocked: IP antibody active`) used to be misreported as "log in" — it is an
494
+ // abuse-control block on a perfectly healthy credential, not an auth failure (#555).
495
+ if (isAntiAbuseFetchBlock(e.status, e.errorCode))
496
+ return antiAbuseOutcome();
237
497
  return { ok: false, status: 'unauthorized', message: 'hub authentication failed; run `evolver login` or set EVOMAP_NODE_SECRET' };
498
+ }
238
499
  if (e instanceof HubUnreachableError)
239
500
  return { ok: false, status: 'network', message: 'hub is unreachable' };
240
501
  if (e instanceof HubClientError) {
502
+ if (e.status === 429)
503
+ return { ok: false, status: 'rate_limited', message: 'hub rate limited the request; retry later' };
504
+ if (isAntiAbuseFetchBlock(e.status, hubErrorField(e.body)))
505
+ return antiAbuseOutcome();
241
506
  if (e.status === 401 || e.status === 403)
242
507
  return { ok: false, status: 'unauthorized', message: 'hub authentication failed; run `evolver login` or set EVOMAP_NODE_SECRET' };
243
508
  if (e.status === 404)
244
509
  return { ok: false, status: 'not_found', message: 'asset not found on the hub' };
245
- if (e.status === 429 || e.status >= 500)
510
+ if (e.status >= 500)
246
511
  return { ok: false, status: 'network', message: 'hub is temporarily unavailable' };
247
512
  return { ok: false, status: 'internal_error', message: 'hub rejected the reuse request' };
248
513
  }
@@ -250,21 +515,33 @@ function mapError(e) {
250
515
  // a bad URL is a configuration gap, NOT an auth failure — conflating them would tell the operator/desktop adapter
251
516
  // to "log in" when the real fix is to correct the Hub URL.
252
517
  const msg = e instanceof Error ? e.message : String(e);
518
+ if (/failed to load EVOLVER_ENV_FILE/i.test(msg)) {
519
+ return { ok: false, status: 'unavailable', message: 'failed to load EVOLVER_ENV_FILE' };
520
+ }
521
+ if (/EVOMAP_HUB_MODE must be public or private/i.test(msg)) {
522
+ return { ok: false, status: 'unavailable', message: 'EVOMAP_HUB_MODE must be public or private' };
523
+ }
524
+ if (/private Hub proxy is not configured/i.test(msg)) {
525
+ return { ok: false, status: 'unavailable', message: 'private Hub proxy is not configured' };
526
+ }
253
527
  if (/Hub URL|EVOMAP_HUB_URL|A2A_HUB_URL/i.test(msg)) {
254
- return { ok: false, status: 'unavailable', message: redact(msg) };
528
+ return { ok: false, status: 'unavailable', message: 'hub URL configuration is invalid' };
255
529
  }
256
530
  if (/Hub credentials|node identity|evolver login|EVOMAP_NODE_SECRET/i.test(msg)) {
257
- 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' };
258
532
  }
259
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)) {
260
534
  return { ok: false, status: 'network', message: 'hub is unreachable' };
261
535
  }
262
- 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' };
263
540
  }
264
541
  function emit(outcome, ctx) {
265
542
  if (ctx.jsonOut) {
266
543
  // stdout ONLY, exactly one object — the desktop adapter json.Unmarshals the whole stdout stream.
267
- const envelope = { ok: outcome.ok, contract: REUSE_CONTRACT, status: outcome.status, reason: outcome.status, message: outcome.message };
544
+ const envelope = { ok: outcome.ok, contract: REUSE_CONTRACT, status: outcome.status, reason: outcome.reason ?? outcome.status, message: outcome.message };
268
545
  ctx.stdout(JSON.stringify(envelope));
269
546
  }
270
547
  else if (outcome.ok) {
@@ -275,15 +552,6 @@ function emit(outcome, ctx) {
275
552
  }
276
553
  return outcome.ok ? 0 : 1;
277
554
  }
278
- /** Defensive redaction so a stray credential in an error string never reaches stdout/stderr. */
279
- function redact(value) {
280
- return value
281
- .replace(/\bBearer\s+[A-Za-z0-9._~+/=-]+/gi, 'Bearer [redacted]')
282
- .replace(/\b([A-Z][A-Z0-9_]*(?:_SECRET|_TOKEN))\b\s*[:=]\s*["']?[^"',\s;}]+/g, '$1=[redacted]')
283
- .replace(/\b(authorization|node_secret|nodeSecret|access_token|refresh_token|token|secret)\b\s*[:=]\s*["']?[^"',\s;}]+/gi, '$1=[redacted]')
284
- .replace(/\bsk-[A-Za-z0-9-]{16,}/g, 'sk-[redacted]')
285
- .replace(/\bgh[pousr]_[A-Za-z0-9]{20,}/g, 'gh_[redacted]');
286
- }
287
555
  function flagValue(args, flag) {
288
556
  for (let i = 0; i < args.length; i += 1) {
289
557
  const token = args[i];
@@ -1,4 +1,6 @@
1
1
  import { assetstore } from '@evomap/evolver-core';
2
2
  export declare const reviewLedgerForStore: typeof assetstore.reviewLedgerForStore;
3
3
  export declare const provenanceStoreForStore: typeof assetstore.provenanceStoreForStore;
4
- export declare const listApprovedGenes: typeof assetstore.listApprovedGenes;
4
+ export declare const listApprovedGenes: typeof assetstore.listApprovedGenes;
5
+ export declare const pendingReviewRecords: typeof assetstore.pendingReviewRecords;
6
+ export declare const pendingGeneReviewRecords: typeof assetstore.pendingGeneReviewRecords;
@@ -3,4 +3,6 @@
3
3
  import { assetstore } from '@evomap/evolver-core';
4
4
  export const reviewLedgerForStore = assetstore.reviewLedgerForStore;
5
5
  export const provenanceStoreForStore = assetstore.provenanceStoreForStore;
6
- export const listApprovedGenes = assetstore.listApprovedGenes;
6
+ export const listApprovedGenes = assetstore.listApprovedGenes;
7
+ export const pendingReviewRecords = assetstore.pendingReviewRecords;
8
+ export const pendingGeneReviewRecords = assetstore.pendingGeneReviewRecords;
@@ -0,0 +1,18 @@
1
+ type RuntimeCapabilityStatus = 'supported' | 'experimental' | 'unsupported';
2
+ type RuntimeCapabilityId = 'claude-code' | 'codex' | 'cursor' | 'gemini' | 'antigravity' | 'kimi' | 'kiro' | 'opencode' | 'generic-chat';
3
+ interface RuntimeCapability {
4
+ status: RuntimeCapabilityStatus;
5
+ evidence: string;
6
+ }
7
+ interface RuntimeCapabilityEntry {
8
+ runtime: RuntimeCapabilityId;
9
+ ingest: RuntimeCapability;
10
+ inject: RuntimeCapability;
11
+ execute: RuntimeCapability;
12
+ verify: RuntimeCapability;
13
+ resume: RuntimeCapability;
14
+ }
15
+ /** Product-level runtime matrix. A transcript parser never implies execution, verification, or resumability. */
16
+ export declare const RUNTIME_CAPABILITY_MATRIX: Readonly<Record<RuntimeCapabilityId, RuntimeCapabilityEntry>>;
17
+ export declare function runtimeCapabilities(): RuntimeCapabilityEntry[];
18
+ export {};