@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
@@ -1,17 +1,24 @@
1
1
  import { existsSync, readFileSync, statSync } from 'node:fs';
2
2
  import { resolve } from 'node:path';
3
3
  import { inspect, format } from 'node:util';
4
- import { assetstore, events, hub, wire } from '@evomap/evolver-core';
4
+ import { assetrepair, assetstore, events, hub, wire, algo, verify } from '@evomap/evolver-core';
5
5
  import { AuthError, HubClientError, HubFetch, HubUnreachableError, connectPublicHub, gepEnvelope, globalFetchLike, resolveHubUrl, } from '@evomap/evolver-adapter-public';
6
- import { loadEnvFileFromEnv } from '@evomap/evolver-mcp';
7
- import { resolveAtpHome, resolveAtpSenderId } from './atp.js';
6
+ import { loadEnvFileFromEnv, proxyClientFromEnv } from '@evomap/evolver-mcp';
7
+ import { resolveAtpSenderId } from './atp.js';
8
+ import { storeRepairedAsset } from './repairedAssetStore.js';
9
+ import { resolveExplicitNodeCredentials, resolveIdentityHome } from './identityHome.js';
8
10
  const REUSE_CONTRACT = 'reuse.v1';
9
11
  const PUBLISH_CONTRACT = 'publish.v1';
10
12
  const REVERSIBILITY = 'irreversible';
13
+ const OAUTH_AUTH_REQUIRED_MESSAGE = "Hub authentication required; run 'evolver login' and retry";
14
+ const LEGACY_AUTH_REQUIRED_MESSAGE = 'Hub node authentication failed; verify the configured node credentials and retry';
15
+ const PRIVATE_AUTH_REQUIRED_MESSAGE = 'Private Hub authentication failed; verify proxy enrollment, credentials, and hub mode';
16
+ const BUNDLE_REQUIRED_MESSAGE = 'publish requires Gene + Capsule bundle; pass --gene <id|path> --capsule <id|path>';
11
17
  const MAX_ASSETS = 50;
12
18
  const PUBLISH_USAGE = [
13
- 'usage: evolver publish --asset <gene_id_or_path> --asset <capsule_id_or_path> --json [--dry-run]',
14
- ' evolver publish --gene <id_or_path> --capsule <id_or_path> --json [--dry-run]',
19
+ 'usage: evolver publish --asset <gene_id_or_path> --asset <capsule_id_or_path> --json [--dry-run] [--repair] [--no-recipe]',
20
+ ' evolver publish --gene <id_or_path> --capsule <id_or_path> --json [--dry-run] [--no-recipe]',
21
+ ' evolver publish --gene <id_or_path> --auto-pair --json [--dry-run] [--no-recipe]',
15
22
  ].join('\n');
16
23
  const ASSET_FLAGS = new Set(['--asset', '--gene', '--capsule', '--event']);
17
24
  const STABLE_CONTRACT_REASONS = new Set([
@@ -27,7 +34,9 @@ const STABLE_CONTRACT_REASONS = new Set([
27
34
  'schema_invalid',
28
35
  'bundle_required',
29
36
  'quality_gate_failed',
37
+ 'gene_unproven',
30
38
  'insufficient_credits',
39
+ 'unsafe_validation_command',
31
40
  ]);
32
41
  const HUB_METADATA_KEYS = new Set([
33
42
  'credit_cost',
@@ -64,23 +73,38 @@ class ContractError extends Error {
64
73
  export async function runReuseCommand(args, deps = {}) {
65
74
  const out = deps.out ?? process.stdout;
66
75
  const parsed = parseReuseArgs(args);
67
- const write = (value, code) => writeJson(out, value, code, deps);
68
- if (!parsed.ok || !parsed.assetId)
69
- return write(reuseFailure(parsed.reason ?? 'missing_id', parsed.message ?? 'reuse requires --id <asset_id>'), 1);
76
+ if (!parsed.ok || !parsed.assetId) {
77
+ return writeJson(out, reuseFailure(parsed.reason ?? 'missing_id', parsed.message ?? 'reuse requires --id <asset_id>'), 1, deps);
78
+ }
79
+ let runtimeDeps;
80
+ try {
81
+ runtimeDeps = { ...deps, env: loadContractEnv(deps) };
82
+ }
83
+ catch (err) {
84
+ const failure = classifyError(err, 'reuse');
85
+ return writeJson(out, reuseFailure(failure.reason, failure.message), 1, deps);
86
+ }
87
+ const write = (value, code) => writeJson(out, value, code, runtimeDeps);
70
88
  const assetId = parsed.assetId;
71
- return withMachineJsonConsole(Boolean(parsed.jsonOut), deps, async () => {
89
+ return withMachineJsonConsole(Boolean(parsed.jsonOut), runtimeDeps, async () => {
72
90
  try {
73
- const fetcher = deps.fetchAssetById ?? deps.transport?.fetchAssetById ?? createDefaultTransport(deps).fetchAssetById;
91
+ const fetcher = runtimeDeps.fetchAssetById
92
+ ?? runtimeDeps.transport?.fetchAssetById
93
+ ?? createDefaultTransport(runtimeDeps).fetchAssetById;
74
94
  const asset = await fetcher(assetId);
75
95
  if (!asset)
76
96
  return write(reuseFailure('not_found', 'asset not found'), 1);
77
97
  const cleaned = stripHubMetadata(asset);
78
- if (wire.computeAssetId(cleaned) !== assetId) {
98
+ const computedAssetId = wire.computeAssetId(cleaned);
99
+ const identityMatches = assetId.startsWith('sha256:')
100
+ ? computedAssetId === assetId
101
+ : stringField(cleaned, 'id') === assetId && computedAssetId === cleaned.asset_id;
102
+ if (!identityMatches) {
79
103
  return write(reuseFailure('internal_error', 'asset integrity verification failed'), 1);
80
104
  }
81
- const store = deps.assetStore ?? new assetstore.LocalJsonlProvider(deps.assetsDir ?? events.assetsDir());
105
+ const store = runtimeDeps.assetStore ?? new assetstore.LocalJsonlProvider(contractAssetsDir(runtimeDeps));
82
106
  await assertNoLocalReuseIdConflict(cleaned, store);
83
- const provenance = new assetstore.ProvenanceStore(storeBaseDir(store, deps));
107
+ const provenance = new assetstore.ProvenanceStore(storeBaseDir(store, runtimeDeps));
84
108
  const stored = await assetstore.ingestUntrusted(store, provenance, cleaned, 'hub');
85
109
  return write({
86
110
  ok: true,
@@ -111,14 +135,30 @@ export async function runPublishCommand(args, deps = {}) {
111
135
  return 0;
112
136
  }
113
137
  const parsed = parsePublishArgs(args);
114
- const write = (value, code) => writeJson(out, value, code, deps);
115
138
  if (!parsed.ok || !parsed.assetRefs) {
116
- return write(publishFailure(parsed.reason ?? 'bundle_required', parsed.message ?? publishReasonMessage('bundle_required'), { retryable: false }), 1);
139
+ return writeJson(out, publishFailure(parsed.reason ?? 'bundle_required', parsed.message ?? publishReasonMessage('bundle_required'), { retryable: false }), 1, deps);
117
140
  }
118
141
  const assetRefs = parsed.assetRefs;
119
- return withMachineJsonConsole(Boolean(parsed.jsonOut), deps, async () => {
142
+ let runtimeDeps;
143
+ try {
144
+ const inheritedEnv = deps.env ?? process.env;
145
+ const runtimeEnv = loadContractEnv(deps);
146
+ runtimeDeps = { ...deps, env: preserveInheritedSecrets(runtimeEnv, inheritedEnv) };
147
+ }
148
+ catch (err) {
149
+ const failure = classifyError(err, 'publish', deps.env ?? process.env);
150
+ return writeJson(out, publishFailure(failure.reason, failure.message, {
151
+ retryable: failure.retryable,
152
+ mode: parsed.dryRun ? 'dry_run' : 'publish',
153
+ }), 1, deps);
154
+ }
155
+ const write = (value, code) => writeJson(out, value, code, runtimeDeps);
156
+ return withMachineJsonConsole(Boolean(parsed.jsonOut), runtimeDeps, async () => {
120
157
  try {
121
- const bundle = await buildPublishBundle(assetRefs, deps);
158
+ const effectiveRefs = parsed.autoPair
159
+ ? await autoPairPublishRefs(assetRefs, parsed.geneRef, runtimeDeps)
160
+ : assetRefs;
161
+ const bundle = await buildPublishBundle(effectiveRefs, runtimeDeps);
122
162
  if (!bundle.ok) {
123
163
  return write(publishFailure(bundle.reason, bundle.message, { retryable: false, gates: bundle.gates }), 1);
124
164
  }
@@ -126,59 +166,97 @@ export async function runPublishCommand(args, deps = {}) {
126
166
  if (parsed.dryRun)
127
167
  return write(dryRunEnvelope(bundle), 0);
128
168
  const reason = bundle.blockReasons[0] ?? 'internal_error';
129
- return write(publishFailure(reason, publishReasonMessage(reason), {
169
+ const detailMessage = bundle.blockMessages?.[reason];
170
+ return write(publishFailure(reason, detailMessage ?? publishReasonMessage(reason), {
130
171
  retryable: false,
131
172
  mode: 'publish',
132
173
  gates: bundle.gates,
133
174
  assets: bundle.assets,
134
175
  }), 1);
135
176
  }
136
- const transport = deps.transport ?? createDefaultTransport(deps);
177
+ const transport = deps.transport ?? createDefaultTransport(runtimeDeps, {
178
+ composeRecipe: parsed.noRecipe !== true,
179
+ });
137
180
  const validate = deps.validate ?? transport.validate;
138
- const validation = await validate(bundle.sanitized);
181
+ // A field-level refusal is a defect in the RECORD, not a verdict on the work in it. Read the Hub's own
182
+ // `details[]`, mend what is mechanically derivable, and (only when asked) try once more — otherwise the
183
+ // envelope still carries the plan, so the operator can see the asset is salvageable instead of losing it.
184
+ const validationAttempt = await callHubWithRepair(validate, bundle.sanitized, parsed.repair === true);
185
+ const validation = validationAttempt.result;
186
+ let effectiveAssets = validationAttempt.assets;
139
187
  const validationCredits = extractCredits(validation.body);
140
- if (!validation.ok) {
188
+ const validationUnavailable = transport.validationCapabilityOptional === true
189
+ && isValidationCapabilityUnavailable(validation.body);
190
+ if (!validation.ok && !(validationUnavailable && !parsed.dryRun)) {
191
+ if (validationUnavailable) {
192
+ return write(publishFailure('unsupported', publishReasonMessage('unsupported'), {
193
+ retryable: false,
194
+ mode: 'dry_run',
195
+ gates: bundle.gates,
196
+ assets: bundle.assets,
197
+ detail: 'Private Hub validation is not configured',
198
+ }), 1);
199
+ }
141
200
  const reason = publishReasonFromResponse(validation.status, validation.body);
201
+ const detail = hubDetailFromBody(validation.body);
142
202
  if (parsed.dryRun && reason === 'quality_gate_failed') {
143
203
  bundle.gates.quality = 'fail';
144
204
  if (!bundle.blockReasons.includes('quality_gate_failed'))
145
205
  bundle.blockReasons.push('quality_gate_failed');
146
- return write(dryRunEnvelope(bundle, validationCredits), 0);
206
+ return write(dryRunEnvelope(bundle, validationCredits, detail, validationAttempt), 0);
147
207
  }
148
- return write(publishFailure(reason, publishReasonMessage(reason), {
208
+ return write(publishFailure(reason, publishReasonMessage(reason, runtimeDeps.env), {
149
209
  retryable: publishRetryable(reason),
150
210
  mode: parsed.dryRun ? 'dry_run' : 'publish',
151
211
  gates: parsed.dryRun ? bundle.gates : { ...bundle.gates, quality: 'fail' },
152
212
  assets: bundle.assets,
213
+ ...(detail ? { detail } : {}),
153
214
  ...(validationCredits ? { credits: validationCredits } : {}),
215
+ ...repairEnvelopeField(validationAttempt),
154
216
  }), 1);
155
217
  }
156
218
  if (parsed.dryRun)
157
- return write(dryRunEnvelope(bundle, validationCredits), 0);
219
+ return write(dryRunEnvelope(bundle, validationCredits, undefined, validationAttempt), 0);
158
220
  const publish = deps.publish ?? transport.publish;
159
- const published = await publish(bundle.sanitized);
221
+ const publishAttempt = await callHubWithRepair(publish, effectiveAssets, parsed.repair === true);
222
+ const published = publishAttempt.result;
223
+ effectiveAssets = publishAttempt.assets;
224
+ const repairApplied = mergeRepairAttempts(validationAttempt, publishAttempt);
160
225
  const publishCredits = extractCredits(published.body);
161
226
  if (!published.ok) {
162
227
  const reason = publishReasonFromResponse(published.status, published.body);
163
- return write(publishFailure(reason, publishReasonMessage(reason), {
228
+ const detail = hubDetailFromBody(published.body);
229
+ return write(publishFailure(reason, publishReasonMessage(reason, runtimeDeps.env), {
164
230
  retryable: publishRetryable(reason),
165
231
  mode: 'publish',
166
232
  gates: bundle.gates,
167
233
  assets: bundle.assets,
234
+ ...(detail ? { detail } : {}),
168
235
  ...(publishCredits ? { credits: publishCredits } : {}),
236
+ ...repairEnvelopeField(repairApplied),
169
237
  }), 1);
170
238
  }
239
+ // The repaired records are what the network now holds. Persist them so the local library and the Hub do
240
+ // not silently diverge; a storage failure is reported, never fatal — the publish already happened.
241
+ const repairPersisted = repairApplied?.applied === true
242
+ ? await persistRepairedBundle(effectiveAssets, bundle.sanitized, runtimeDeps)
243
+ : undefined;
171
244
  const payload = payloadRecord(published.body);
172
- if (stringField(payload, 'decision') === 'quarantine') {
245
+ const decision = stringField(payload, 'decision');
246
+ const hubReason = stringField(payload, 'reason');
247
+ const safetyCandidate = decision === 'quarantine' && hubReason === 'safety_candidate';
248
+ if (decision === 'quarantine' && !safetyCandidate) {
249
+ const detail = hubDetailFromBody(published.body);
173
250
  return write(publishFailure('quality_gate_failed', publishReasonMessage('quality_gate_failed'), {
174
251
  retryable: false,
175
252
  mode: 'publish',
176
253
  gates: { ...bundle.gates, quality: 'fail' },
177
254
  assets: bundle.assets,
255
+ ...(detail ? { detail } : {}),
178
256
  ...(publishCredits ? { credits: publishCredits } : {}),
179
257
  }), 1);
180
258
  }
181
- const status = normalizePublishStatus(published.body);
259
+ const status = safetyCandidate ? 'queued' : normalizePublishStatus(published.body);
182
260
  if (!status) {
183
261
  return write(publishFailure('internal_error', 'Hub publish response missing lifecycle status', {
184
262
  retryable: false,
@@ -190,6 +268,11 @@ export async function runPublishCommand(args, deps = {}) {
190
268
  }
191
269
  const receiptId = stringField(payload, 'receipt_id');
192
270
  const bundleId = stringField(payload, 'bundle_id');
271
+ const publishedBundle = { ...bundle, sanitized: [...effectiveAssets] };
272
+ appendPublishedCapsuleCall(publishedBundle, deps, { status, receiptId, bundleId });
273
+ const recipeId = parsed.noRecipe || deps.publish
274
+ ? undefined
275
+ : await composePublishedRecipe(transport, effectiveAssets);
193
276
  return write({
194
277
  ok: true,
195
278
  contract: PUBLISH_CONTRACT,
@@ -198,12 +281,17 @@ export async function runPublishCommand(args, deps = {}) {
198
281
  reversibility: REVERSIBILITY,
199
282
  ...(receiptId ? { receipt_id: receiptId } : {}),
200
283
  ...(bundleId ? { bundle_id: bundleId } : {}),
201
- assets: bundle.assets,
284
+ ...(recipeId ? { recipe_id: recipeId } : {}),
285
+ ...(safetyCandidate ? { hub_reason: hubReason } : {}),
286
+ gates: bundle.gates,
287
+ // What the Hub actually holds — after a repair that is the mended record, not the one first submitted.
288
+ assets: repairApplied?.applied === true ? summarizePublishAssets(effectiveAssets) : bundle.assets,
202
289
  ...(publishCredits ? { credits: publishCredits } : {}),
290
+ ...repairEnvelopeField(repairApplied, repairPersisted),
203
291
  }, 0);
204
292
  }
205
293
  catch (err) {
206
- const failure = classifyError(err, 'publish');
294
+ const failure = classifyError(err, 'publish', runtimeDeps.env ?? process.env);
207
295
  return write(publishFailure(failure.reason, failure.message, {
208
296
  retryable: failure.retryable,
209
297
  mode: parsed.dryRun ? 'dry_run' : 'publish',
@@ -211,6 +299,107 @@ export async function runPublishCommand(args, deps = {}) {
211
299
  }
212
300
  });
213
301
  }
302
+ async function callHubWithRepair(call, assets, allowRepair) {
303
+ const first = await call(assets);
304
+ if (first.ok)
305
+ return { result: first, assets, applied: false, entries: [] };
306
+ const plan = planBundleRepair(assets, first.body);
307
+ // Retry only when the WHOLE bundle is mended. One unrepairable asset means the Hub will refuse the bundle
308
+ // again for the same reason, and a second refusal costs the operator another paid round-trip for nothing.
309
+ const repairable = plan.entries.some((entry) => entry.repair_status === 'repaired')
310
+ && plan.entries.every((entry) => entry.repair_status !== 'unrepairable');
311
+ if (!repairable || !allowRepair)
312
+ return { result: first, assets, applied: false, entries: plan.entries };
313
+ // Exactly one retry: a Hub that refuses the mended record too is telling us the defect is not mechanical,
314
+ // and a repair loop against a paid endpoint is how you burn credits without converging.
315
+ const retried = await call(plan.assets);
316
+ return { result: retried, assets: plan.assets, applied: true, entries: plan.entries };
317
+ }
318
+ function planBundleRepair(assets, rejectionBody) {
319
+ const hubIssues = assetrepair.hubRejectionIssues(rejectionBody, {
320
+ assetTypes: assets.map((asset) => (typeof asset.type === 'string' ? asset.type : undefined)),
321
+ });
322
+ const bundleIssues = hubIssues.byAssetIndex.get(-1) ?? [];
323
+ const repaired = [];
324
+ const entries = [];
325
+ for (const [index, asset] of assets.entries()) {
326
+ const issues = [...(hubIssues.byAssetIndex.get(index) ?? []), ...bundleIssues];
327
+ const report = assetrepair.repairAssetRecord(asset, { hubIssues: issues });
328
+ repaired.push(report.asset ?? asset);
329
+ entries.push({
330
+ ...(asset.asset_id ? { asset_id: asset.asset_id } : {}),
331
+ ...(report.asset && report.asset.asset_id !== asset.asset_id ? { repaired_asset_id: report.asset.asset_id } : {}),
332
+ repair_status: report.status,
333
+ changes: report.changes.map((change) => `${change.path}: ${change.action}`),
334
+ blockers: report.blockers.map(repairBlockerText),
335
+ });
336
+ }
337
+ return { assets: repaired, entries };
338
+ }
339
+ function repairBlockerText(blocker) {
340
+ return `${blocker.path || '(record)'}: ${stripControlChars(blocker.message).replace(/\s+/g, ' ').trim()}`.slice(0, HUB_DETAIL_MAX_CHARS);
341
+ }
342
+ /** Report the LATER attempt's plan: it is the one describing the bundle that was actually refused last. */
343
+ function mergeRepairAttempts(validation, publish) {
344
+ if (publish.applied || publish.entries.length > 0) {
345
+ return { ...publish, applied: publish.applied || validation.applied };
346
+ }
347
+ return validation.entries.length > 0 || validation.applied ? validation : undefined;
348
+ }
349
+ function repairEnvelopeField(attempt, persisted) {
350
+ if (!attempt || (attempt.entries.length === 0 && !attempt.applied))
351
+ return {};
352
+ return {
353
+ repair: {
354
+ applied: attempt.applied,
355
+ ...(persisted !== undefined ? { persisted } : {}),
356
+ ...(attempt.applied ? {} : { hint: 're-run with --repair to publish the mended record' }),
357
+ assets: attempt.entries,
358
+ },
359
+ };
360
+ }
361
+ async function persistRepairedBundle(published, submitted, deps) {
362
+ const env = deps.env ?? process.env;
363
+ const store = deps.assetStore ?? new assetstore.LocalJsonlProvider(contractAssetsDir(deps));
364
+ // Only the records repair actually changed are new locally; the untouched ones are already stored.
365
+ const changed = published.filter((asset, index) => asset.asset_id !== submitted[index]?.asset_id);
366
+ try {
367
+ const stored = await Promise.all(changed.map((asset) => storeRepairedAsset(asset, store, env)));
368
+ return stored.every(Boolean);
369
+ }
370
+ catch {
371
+ return false;
372
+ }
373
+ }
374
+ function appendPublishedCapsuleCall(bundle, deps, receipt) {
375
+ const capsuleIndex = bundle.sanitized.findIndex((asset) => asset.type === 'Capsule');
376
+ if (capsuleIndex < 0)
377
+ return;
378
+ const publishedCapsule = bundle.sanitized[capsuleIndex];
379
+ const originalCapsule = bundle.original[capsuleIndex];
380
+ if (!publishedCapsule)
381
+ return;
382
+ const tokensSpent = hub.assetDerivationTokenCost(originalCapsule);
383
+ const trigger = Array.isArray(publishedCapsule['trigger'])
384
+ ? publishedCapsule['trigger'].filter((value) => typeof value === 'string')
385
+ : undefined;
386
+ try {
387
+ const callLog = deps.callLog ?? new hub.AssetCallLog(events.assetCallLogPath(deps.env ?? process.env));
388
+ callLog.append({
389
+ action: 'asset_publish',
390
+ asset_id: publishedCapsule.asset_id,
391
+ asset_type: 'Capsule',
392
+ ...(trigger ? { signals: trigger } : {}),
393
+ ...(tokensSpent !== undefined ? { tokens_spent: tokensSpent } : {}),
394
+ extra: {
395
+ status: receipt.status,
396
+ ...(receipt.receiptId ? { receipt_id: receipt.receiptId } : {}),
397
+ ...(receipt.bundleId ? { bundle_id: receipt.bundleId } : {}),
398
+ },
399
+ });
400
+ }
401
+ catch { /* a local audit failure must never change an accepted Hub publish */ }
402
+ }
214
403
  export function parseReuseArgs(args) {
215
404
  let id;
216
405
  let jsonOut = false;
@@ -246,7 +435,14 @@ export function parseReuseArgs(args) {
246
435
  }
247
436
  export function parsePublishArgs(args) {
248
437
  const assetRefs = [];
438
+ let geneRef;
439
+ let geneCount = 0;
440
+ let capsuleRef;
441
+ let hasUntypedAsset = false;
442
+ let autoPair = false;
249
443
  let dryRun = false;
444
+ let repair = false;
445
+ let noRecipe = false;
250
446
  let jsonOut = false;
251
447
  for (let i = 0; i < args.length; i++) {
252
448
  const token = args[i];
@@ -260,34 +456,80 @@ export function parsePublishArgs(args) {
260
456
  jsonOut = true;
261
457
  continue;
262
458
  }
459
+ if (token === '--auto-pair') {
460
+ autoPair = true;
461
+ continue;
462
+ }
463
+ if (token === '--repair') {
464
+ repair = true;
465
+ continue;
466
+ }
467
+ if (token === '--no-recipe') {
468
+ noRecipe = true;
469
+ continue;
470
+ }
263
471
  const equalFlag = [...ASSET_FLAGS].find((flag) => token.startsWith(`${flag}=`));
264
472
  if (equalFlag) {
265
473
  const value = token.slice(equalFlag.length + 1).trim();
266
474
  if (!value)
267
475
  return { ok: false, reason: 'bundle_required', message: `${equalFlag} requires a value` };
268
476
  assetRefs.push(value);
477
+ if (equalFlag === '--gene') {
478
+ geneRef = value;
479
+ geneCount++;
480
+ }
481
+ if (equalFlag === '--capsule')
482
+ capsuleRef = value;
483
+ if (equalFlag === '--asset')
484
+ hasUntypedAsset = true;
269
485
  continue;
270
486
  }
271
487
  if (ASSET_FLAGS.has(token)) {
272
488
  const next = args[i + 1];
273
489
  if (!next || next.startsWith('--'))
274
490
  return { ok: false, reason: 'bundle_required', message: `${token} requires a value` };
275
- assetRefs.push(next.trim());
491
+ const value = next.trim();
492
+ if (!value)
493
+ return { ok: false, reason: 'bundle_required', message: `${token} requires a value` };
494
+ assetRefs.push(value);
495
+ if (token === '--gene') {
496
+ geneRef = value;
497
+ geneCount++;
498
+ }
499
+ if (token === '--capsule')
500
+ capsuleRef = value;
501
+ if (token === '--asset')
502
+ hasUntypedAsset = true;
276
503
  i++;
277
504
  continue;
278
505
  }
279
506
  if (!token.startsWith('--'))
280
- return { ok: false, reason: 'unsupported', message: 'unsupported publish argument' };
281
- return { ok: false, reason: 'unsupported', message: 'unsupported publish flag' };
507
+ return { ok: false, reason: 'unsupported', message: 'unsupported publish argument; did you mean --asset <id|path>?' };
508
+ if (token === '--home' || token.startsWith('--home=') || token === '--evomap-home' || token.startsWith('--evomap-home=')) {
509
+ return { ok: false, reason: 'unsupported', message: 'publish does not accept home flags; set EVOLVER_HOME or EVOMAP_HOME before running evolver publish' };
510
+ }
511
+ return { ok: false, reason: 'unsupported', message: "unsupported publish flag; run 'evolver publish --help'" };
282
512
  }
283
513
  if (!jsonOut)
284
514
  return { ok: false, reason: 'unsupported', message: 'publish requires --json' };
285
- const refs = assetRefs.filter(Boolean);
515
+ if (autoPair && (geneCount !== 1 || !geneRef || capsuleRef || hasUntypedAsset)) {
516
+ return { ok: false, reason: 'bundle_required', message: '--auto-pair requires exactly one explicit --gene and no --asset or --capsule' };
517
+ }
518
+ const refs = assetRefs;
286
519
  if (refs.length === 0)
287
520
  return { ok: false, reason: 'bundle_required', message: 'publish requires --asset <id|path>' };
288
521
  if (refs.length > MAX_ASSETS)
289
522
  return { ok: false, reason: 'bundle_required', message: `publish supports at most ${MAX_ASSETS} assets` };
290
- return { ok: true, assetRefs: refs, dryRun, jsonOut };
523
+ return {
524
+ ok: true,
525
+ assetRefs: refs,
526
+ ...(geneRef ? { geneRef } : {}),
527
+ ...(autoPair ? { autoPair: true } : {}),
528
+ dryRun,
529
+ repair,
530
+ ...(noRecipe ? { noRecipe: true } : {}),
531
+ jsonOut,
532
+ };
291
533
  }
292
534
  export async function buildPublishBundle(refs, deps = {}) {
293
535
  let original;
@@ -295,8 +537,18 @@ export async function buildPublishBundle(refs, deps = {}) {
295
537
  original = await Promise.all(refs.map((ref) => loadAssetRef(ref, deps)));
296
538
  }
297
539
  catch (err) {
298
- const reason = err instanceof ContractError ? err.reason : 'schema_invalid';
299
- return { ok: false, reason, message: reason === 'bundle_required' ? publishReasonMessage(reason) : 'asset schema is invalid', gates: { schema: 'fail' } };
540
+ // Report what actually went wrong. Overwriting every failure with "asset
541
+ // schema is invalid" hid the common case — a ref that resolved to nothing —
542
+ // behind a claim about a schema that was never read, leaving a user who
543
+ // could not publish with no way to tell a missing asset from a bad one.
544
+ const reason = err instanceof ContractError ? err.reason : 'internal_error';
545
+ const message = err instanceof ContractError ? err.safeMessage : publishReasonMessage(reason);
546
+ return {
547
+ ok: false,
548
+ reason,
549
+ message,
550
+ gates: reason === 'schema_invalid' ? { schema: 'fail' } : {},
551
+ };
300
552
  }
301
553
  const bundleCheck = checkBundle(original);
302
554
  if (!bundleCheck.ok)
@@ -313,22 +565,166 @@ export async function buildPublishBundle(refs, deps = {}) {
313
565
  return { ok: false, reason: 'bundle_required', message: finalBundleCheck.message, gates: { redaction: 'pass', schema: 'pass', bundle: 'fail' } };
314
566
  }
315
567
  const leak = finalPayloadLeakCheck(sanitized, deps.env ?? process.env);
568
+ // Local quality gate: a gene may only publish once it has TRULY succeeded at
569
+ // least once. Minting sets `confidence` from self-report / text completeness,
570
+ // which never proves the gene worked; without this check an unproven gene
571
+ // leaks to the Hub and comes back as an opaque `quality_gate_failed` after a
572
+ // round-trip. Assessing the gene's outcome evidence here fails fast, locally,
573
+ // with a precise reason. Read-only: aggregates the local capsule history.
574
+ const geneEvidence = await assessPublishGeneEvidence(original, deps);
575
+ const geneProven = geneEvidence?.eligible ?? true;
576
+ // Local quality gate: validation command safety check.
577
+ // Only applies to Gene assets. Checks that all validation commands are safe
578
+ // (e.g., no `node -e`, no shell metacharacters).
579
+ const validationCommandResult = checkValidationCommands(original);
316
580
  const gates = {
317
581
  redaction: 'pass',
318
582
  leak: leak.blocked ? 'fail' : 'pass',
319
583
  schema: 'pass',
320
584
  bundle: 'pass',
321
- quality: 'pass',
585
+ quality: geneProven ? 'pass' : 'fail',
586
+ quality_evidence: geneEvidence?.source ?? 'unavailable',
587
+ validation_command: validationCommandResult.allowed ? 'pass' : 'fail',
322
588
  };
589
+ const blockReasons = [];
590
+ const blockMessages = {};
591
+ if (leak.blocked)
592
+ blockReasons.push('leak_detected');
593
+ if (!geneProven)
594
+ blockReasons.push('gene_unproven');
595
+ if (!validationCommandResult.allowed) {
596
+ blockReasons.push('unsafe_validation_command');
597
+ if (validationCommandResult.message) {
598
+ blockMessages['unsafe_validation_command'] = validationCommandResult.message;
599
+ }
600
+ }
323
601
  return {
324
602
  ok: true,
325
603
  original,
326
604
  sanitized,
327
- blockReasons: leak.blocked ? ['leak_detected'] : [],
605
+ blockReasons,
606
+ blockMessages,
328
607
  gates,
329
608
  assets: summarizePublishAssets(sanitized),
330
609
  };
331
610
  }
611
+ // 评估 bundle 中 Gene 的成功证据。历史记录来自本地 Capsule store;显式提交的、
612
+ // 通过完整校验的成功 Capsule 也可作为首次发布的 seed。没有 gene id 或 store
613
+ // 读取失败时保持 fail-open,因为这道预检只增加本地门槛,最终质量判定仍由 Hub 负责。
614
+ async function assessPublishGeneEvidence(original, deps) {
615
+ const gene = original.find((asset) => asset.type === 'Gene');
616
+ if (!gene)
617
+ return null;
618
+ const businessId = stringField(gene, 'id');
619
+ const assetId = typeof gene.asset_id === 'string' ? gene.asset_id : undefined;
620
+ const geneId = businessId ?? assetId;
621
+ if (!geneId)
622
+ return null;
623
+ const geneIds = new Set([businessId, assetId].filter((id) => Boolean(id)));
624
+ const hasBundleSeed = hasVerifiedSuccessfulBundleCapsule(original, geneIds);
625
+ try {
626
+ const store = deps.assetStore ?? new assetstore.LocalJsonlProvider(contractAssetsDir(deps));
627
+ const primary = await algo.assessGenePublishEvidence(store, geneId);
628
+ // Capsules key their `gene` link by the gene's business id in production;
629
+ // some stores (and legacy fixtures) key it by asset_id. Mixed histories can
630
+ // contain failures under the business id and a success under asset_id, so
631
+ // both aliases must contribute to the gate rather than only falling back
632
+ // when the primary alias has no rows at all.
633
+ const byAssetId = assetId && assetId !== geneId
634
+ ? await algo.assessGenePublishEvidence(store, assetId)
635
+ : undefined;
636
+ const localEvidence = {
637
+ success: primary.success + (byAssetId?.success ?? 0),
638
+ inert: primary.inert + (byAssetId?.inert ?? 0),
639
+ };
640
+ if (algo.isGenePublishEligible(localEvidence))
641
+ return { eligible: true, source: 'local_history' };
642
+ if (hasBundleSeed)
643
+ return { eligible: true, source: 'bundle_seed' };
644
+ return { eligible: false, source: 'none' };
645
+ }
646
+ catch {
647
+ // 本地 store 不可用时保持历史 fail-open 行为。显式 Capsule 只有在上面的
648
+ // content hash 和 wire schema 校验都通过后才会计入,非法文件不会变成证据。
649
+ if (hasBundleSeed)
650
+ return { eligible: true, source: 'bundle_seed' };
651
+ return null;
652
+ }
653
+ }
654
+ /**
655
+ * 首次发布可以把已经生成的成功 Capsule 作为同一 bundle 的证据提交。
656
+ * 之前这里只读取本地 capsules.jsonl,导致 `--gene file --capsule file`
657
+ * 即使带有成功 Capsule 也在到达 Hub 前被 `gene_unproven` 拦截。
658
+ *
659
+ * 外部文件不是本地历史,必须先通过完整 wire schema 和 content hash 校验;
660
+ * 失败或缺少成功 outcome 的 Capsule 不会解锁 quality gate。该证据只用于
661
+ * 本地预检,Hub 仍然负责最终质量判定和持久化。
662
+ */
663
+ function hasVerifiedSuccessfulBundleCapsule(original, geneIds) {
664
+ const capsule = original.find((asset) => (asset.type === 'Capsule' && geneIds.has(stringField(asset, 'gene') ?? '')));
665
+ if (!capsule || !wire.validateWireDeep(capsule).ok || !wire.verifyAssetId(capsule)) {
666
+ return false;
667
+ }
668
+ return stringField(asRecord(capsule['outcome']), 'status') === 'success';
669
+ }
670
+ /**
671
+ * 检查 Gene 资产中的验证命令是否安全。
672
+ * 只检查 Gene 类型的资产,不影响 Capsule 或 EvolutionEvent。
673
+ * 如果 Gene 有 validation 数组,会检查每条命令是否符合安全策略。
674
+ * 不安全的命令(如 `node -e`、包含 shell 元字符等)会阻止发布。
675
+ */
676
+ function checkValidationCommands(original) {
677
+ const gene = original.find((asset) => asset.type === 'Gene');
678
+ if (!gene)
679
+ return { allowed: true, unsafeCommands: [] };
680
+ const validation = gene['validation'];
681
+ if (!Array.isArray(validation) || validation.length === 0) {
682
+ return { allowed: true, unsafeCommands: [] };
683
+ }
684
+ const unsafeCommands = [];
685
+ for (const cmd of validation) {
686
+ if (typeof cmd !== 'string')
687
+ continue;
688
+ if (!verify.isValidationCommandAllowed(cmd)) {
689
+ unsafeCommands.push(cmd);
690
+ }
691
+ }
692
+ if (unsafeCommands.length === 0) {
693
+ return { allowed: true, unsafeCommands: [] };
694
+ }
695
+ // 构建诊断信息(不暴露原始命令文本,避免泄露安全策略细节)
696
+ const reasons = new Set();
697
+ for (const cmd of unsafeCommands) {
698
+ if (/`|\$\(/.test(cmd)) {
699
+ reasons.add('command_substitution');
700
+ continue;
701
+ }
702
+ const stripped = cmd.replace(/"[^"]*"/g, '').replace(/'[^']*'/g, '');
703
+ if (verify.SHELL_METACHARS.test(stripped)) {
704
+ reasons.add('shell_metacharacters');
705
+ continue;
706
+ }
707
+ const tokens = cmd.split(/\s+/);
708
+ const executable = tokens[0] ?? '';
709
+ const args = tokens.slice(1);
710
+ const badFlag = verify.isNodeExecutable(executable) ? verify.nodeFlagViolation(executable, args) : null;
711
+ if (badFlag) {
712
+ reasons.add('blocked_node_flag');
713
+ continue;
714
+ }
715
+ if (!cmd.trim().startsWith('node ')) {
716
+ reasons.add('non_node_command');
717
+ }
718
+ else {
719
+ reasons.add('unsafe_pattern');
720
+ }
721
+ }
722
+ return {
723
+ allowed: false,
724
+ unsafeCommands,
725
+ message: `validation command rejected: ${[...reasons].join(', ')}`,
726
+ };
727
+ }
332
728
  function sanitizePublishBundle(original) {
333
729
  const sanitized = original.map((asset) => hub.sanitizeAsset(stripPublishMetadata(asset)));
334
730
  const finalGeneIdByOriginalRef = new Map();
@@ -358,42 +754,152 @@ function withRecomputedAssetId(asset) {
358
754
  const assetId = wire.computeAssetId(asset);
359
755
  return { ...asset, asset_id: assetId ?? asset.asset_id };
360
756
  }
361
- async function loadAssetRef(ref, deps) {
362
- if (looksLikeFile(ref))
363
- return normalizeAsset(JSON.parse(readFileSync(resolve(ref), 'utf8')));
757
+ /** Resolve `<asset_id|logical_id|path>` the way publish does. Shared so `asset-repair` speaks the same refs. */
758
+ export async function loadAssetRef(ref, deps) {
759
+ if (looksLikeFile(ref)) {
760
+ try {
761
+ return normalizeAsset(JSON.parse(readFileSync(resolve(ref), 'utf8')));
762
+ }
763
+ catch (err) {
764
+ if (err instanceof ContractError)
765
+ throw err;
766
+ if (err instanceof SyntaxError)
767
+ throw new ContractError('schema_invalid', 'asset schema is invalid');
768
+ throw err;
769
+ }
770
+ }
364
771
  const store = deps.assetStore;
365
772
  if (store) {
366
773
  const fromStore = await findAssetInStore(ref, store);
774
+ // `not_found`, not `schema_invalid`: nothing was located, so no schema was
775
+ // ever read. `reuse` already reports this ref-resolution failure that way.
367
776
  if (!fromStore)
368
- throw new ContractError('schema_invalid', 'asset not found');
777
+ throw new ContractError('not_found', 'asset not found');
369
778
  return normalizeAsset(fromStore);
370
779
  }
371
- const readOnly = loadLocalAssetsReadOnly(deps.assetsDir ?? events.assetsDir());
372
- const found = readOnly.find((asset) => asset.asset_id === ref || stringField(asset, 'id') === ref);
780
+ const assetsDir = contractAssetsDir(deps);
781
+ const readOnly = loadLocalAssetsReadOnly(assetsDir, ref);
782
+ const byAssetId = readOnly.filter((asset) => asset.asset_id === ref);
783
+ if (byAssetId.length > 1)
784
+ throw new ContractError('not_found', 'asset reference is ambiguous');
785
+ let found = byAssetId[0];
786
+ if (!found) {
787
+ const exactLogical = readOnly.filter((asset) => stringField(asset, 'id') === ref);
788
+ if (exactLogical.length > 1)
789
+ throw new ContractError('not_found', 'asset reference is ambiguous');
790
+ found = exactLogical[0];
791
+ }
792
+ if (!found) {
793
+ const fallback = prefixedLogicalRef(ref);
794
+ if (fallback) {
795
+ const matches = readOnly.filter((asset) => asset.type === fallback.kind && stringField(asset, 'id') === fallback.id);
796
+ if (matches.length > 1)
797
+ throw new ContractError('not_found', 'asset reference is ambiguous');
798
+ found = matches[0];
799
+ }
800
+ }
373
801
  if (!found)
374
- throw new ContractError('schema_invalid', 'asset not found');
802
+ throw new ContractError('not_found', 'asset not found');
375
803
  return normalizeAsset(found);
376
804
  }
805
+ function prefixedLogicalRef(ref) {
806
+ const match = /^(gene|capsule):(.+)$/.exec(ref);
807
+ if (!match?.[2])
808
+ return null;
809
+ return { kind: match[1] === 'gene' ? 'Gene' : 'Capsule', id: match[2] };
810
+ }
811
+ async function findLogicalAsset(store, id, kind) {
812
+ if (store.findByLogicalId) {
813
+ const matches = await store.findByLogicalId(id, 2, kind);
814
+ if (matches.length > 1)
815
+ throw new ContractError('not_found', 'asset reference is ambiguous');
816
+ return matches[0] ?? null;
817
+ }
818
+ const scanLimit = 10_000;
819
+ const rows = await store.list(kind, scanLimit + 1);
820
+ if (rows.length > scanLimit)
821
+ throw new ContractError('not_found', 'asset lookup is truncated; use an exact asset_id');
822
+ const matches = rows.filter((asset) => stringField(asset, 'id') === id);
823
+ if (matches.length > 1)
824
+ throw new ContractError('not_found', 'asset reference is ambiguous');
825
+ return matches[0] ?? null;
826
+ }
377
827
  async function findAssetInStore(ref, store) {
378
828
  const byAssetId = await store.get(ref);
379
829
  if (byAssetId)
380
830
  return byAssetId;
381
- for (const kind of ['Gene', 'Capsule', 'EvolutionEvent']) {
382
- const rows = await store.list(kind, 10_000);
383
- const found = rows.find((asset) => stringField(asset, 'id') === ref);
384
- if (found)
385
- return found;
831
+ const exact = await findLogicalAsset(store, ref);
832
+ if (exact)
833
+ return exact;
834
+ const fallback = prefixedLogicalRef(ref);
835
+ return fallback ? findLogicalAsset(store, fallback.id, fallback.kind) : null;
836
+ }
837
+ async function autoPairPublishRefs(refs, geneRef, deps) {
838
+ const store = deps.assetStore ?? new assetstore.LocalJsonlProvider(contractAssetsDir(deps));
839
+ if (!(store instanceof assetstore.LocalJsonlProvider)) {
840
+ throw new ContractError('bundle_required', '--auto-pair requires a local asset store; pass --capsule <id|path> explicitly');
386
841
  }
387
- return null;
842
+ const gene = await loadAssetRef(geneRef, { ...deps, assetStore: store });
843
+ if (gene.type !== 'Gene')
844
+ throw new ContractError('bundle_required', '--auto-pair requires a Gene reference');
845
+ const geneIds = new Set([gene.asset_id, stringField(gene, 'id')].filter((id) => Boolean(id)));
846
+ const trust = new assetstore.ProvenanceStore(store.baseDir).snapshot();
847
+ const candidates = store.listAll('Capsule').filter((candidate) => {
848
+ if (!geneIds.has(String(candidate['gene'] ?? '')))
849
+ return false;
850
+ const outcome = asRecord(candidate['outcome']);
851
+ if (outcome?.['status'] !== 'success')
852
+ return false;
853
+ if (trust.get(candidate.asset_id)?.trusted === false)
854
+ return false;
855
+ if (!wire.validateWireDeep(candidate).ok)
856
+ return false;
857
+ return wire.verifyAssetId(candidate);
858
+ });
859
+ if (candidates.length === 0) {
860
+ throw new ContractError('bundle_required', 'no eligible successful Capsule found; pass --capsule <id|path> explicitly');
861
+ }
862
+ if (candidates.length > 1) {
863
+ throw new ContractError('bundle_required', 'multiple eligible Capsules found; pass --capsule <id|path> explicitly');
864
+ }
865
+ return [...refs, candidates[0].asset_id];
388
866
  }
389
- function loadLocalAssetsReadOnly(baseDir) {
867
+ function loadLocalAssetsReadOnly(baseDir, targetRef) {
390
868
  return [
391
- ...readJsonLines(`${baseDir}/genes.jsonl`, 'Gene'),
392
- ...readJsonLines(`${baseDir}/capsules.jsonl`, 'Capsule'),
393
- ...readJsonLines(`${baseDir}/events.jsonl`, 'EvolutionEvent'),
869
+ ...loadLocalGenesReadOnly(baseDir, targetRef),
870
+ ...readJsonLines(`${baseDir}/capsules.jsonl`, 'Capsule', targetRef),
871
+ ...readJsonLines(`${baseDir}/events.jsonl`, 'EvolutionEvent', targetRef),
394
872
  ];
395
873
  }
396
- function readJsonLines(filePath, type) {
874
+ function loadLocalGenesReadOnly(baseDir, targetRef) {
875
+ const byId = new Map();
876
+ for (const gene of [
877
+ ...readGenesEnvelopeReadOnly(`${baseDir}/genes.json`),
878
+ ...readJsonLines(`${baseDir}/genes.jsonl`, 'Gene', targetRef),
879
+ ]) {
880
+ const id = stringField(gene, 'id') ?? gene.asset_id;
881
+ if (id && !byId.has(id))
882
+ byId.set(id, gene);
883
+ }
884
+ return [...byId.values()];
885
+ }
886
+ function readGenesEnvelopeReadOnly(filePath) {
887
+ if (!existsSync(filePath))
888
+ return [];
889
+ try {
890
+ const parsed = JSON.parse(readFileSync(filePath, 'utf8'));
891
+ const envelopeGenes = isRecord(parsed) && Array.isArray(parsed['genes']) ? parsed['genes'] : [];
892
+ return envelopeGenes.filter(isRecord).map((gene) => normalizeAsset({ ...gene, type: 'Gene' }));
893
+ }
894
+ catch (err) {
895
+ if (err instanceof ContractError)
896
+ throw err;
897
+ if (err instanceof SyntaxError)
898
+ throw new ContractError('schema_invalid', 'asset schema is invalid');
899
+ throw err;
900
+ }
901
+ }
902
+ function readJsonLines(filePath, type, targetRef) {
397
903
  if (!existsSync(filePath))
398
904
  return [];
399
905
  try {
@@ -402,12 +908,24 @@ function readJsonLines(filePath, type) {
402
908
  .map((line) => line.trim())
403
909
  .filter(Boolean)
404
910
  .map((line) => JSON.parse(line))
405
- .filter(isRecord)
406
- .filter((asset) => asset['type'] === type)
911
+ .filter((asset) => {
912
+ if (!isRecord(asset))
913
+ return false;
914
+ if (asset['type'] === type)
915
+ return true;
916
+ if (stringField(asset, 'asset_id') === targetRef || stringField(asset, 'id') === targetRef) {
917
+ throw new ContractError('schema_invalid', 'asset schema is invalid');
918
+ }
919
+ return false;
920
+ })
407
921
  .map(normalizeAsset);
408
922
  }
409
- catch {
410
- throw new ContractError('schema_invalid', 'asset schema is invalid');
923
+ catch (err) {
924
+ if (err instanceof ContractError)
925
+ throw err;
926
+ if (err instanceof SyntaxError)
927
+ throw new ContractError('schema_invalid', 'asset schema is invalid');
928
+ throw err;
411
929
  }
412
930
  }
413
931
  function normalizeAsset(value) {
@@ -426,7 +944,7 @@ function checkBundle(bundle) {
426
944
  return { ok: false, message: 'publish supports one Gene + one Capsule + optional one EvolutionEvent bundle' };
427
945
  }
428
946
  if (genes.length === 0 || capsules.length === 0)
429
- return { ok: false, message: 'publish requires Gene + Capsule bundle' };
947
+ return { ok: false, message: BUNDLE_REQUIRED_MESSAGE };
430
948
  const gene = genes[0];
431
949
  const capsule = capsules[0];
432
950
  const geneIds = new Set([gene.asset_id, stringField(gene, 'id')].filter((id) => Boolean(id)));
@@ -465,10 +983,23 @@ function stripPublishMetadata(asset) {
465
983
  return stripHubMetadata(asset);
466
984
  }
467
985
  function storeBaseDir(store, deps) {
468
- return store instanceof assetstore.LocalJsonlProvider ? store.baseDir : deps.assetsDir ?? events.assetsDir();
986
+ return store instanceof assetstore.LocalJsonlProvider ? store.baseDir : contractAssetsDir(deps);
987
+ }
988
+ function contractAssetsDir(deps) {
989
+ return deps.assetsDir ?? events.assetsDir(deps.env ?? process.env);
469
990
  }
470
- function dryRunEnvelope(bundle, credits) {
991
+ function dryRunEnvelope(bundle, credits, blockDetail, repairAttempt) {
471
992
  const suppressPayload = bundle.blockReasons.includes('leak_detected');
993
+ // Collect detailed messages for block reasons
994
+ const blockDetails = [];
995
+ if (blockDetail)
996
+ blockDetails.push(blockDetail);
997
+ for (const reason of bundle.blockReasons) {
998
+ const detailMessage = bundle.blockMessages?.[reason];
999
+ if (detailMessage && !blockDetails.includes(detailMessage)) {
1000
+ blockDetails.push(detailMessage);
1001
+ }
1002
+ }
472
1003
  return {
473
1004
  ok: true,
474
1005
  contract: PUBLISH_CONTRACT,
@@ -476,10 +1007,12 @@ function dryRunEnvelope(bundle, credits) {
476
1007
  reversibility: REVERSIBILITY,
477
1008
  blocked: bundle.blockReasons.length > 0,
478
1009
  block_reasons: bundle.blockReasons,
1010
+ ...(blockDetails.length > 0 ? { block_details: blockDetails } : {}),
479
1011
  assets: bundle.assets,
480
1012
  ...(suppressPayload ? {} : { payload: { assets: bundle.sanitized } }),
481
1013
  gates: bundle.gates,
482
1014
  ...(credits ? { credits } : {}),
1015
+ ...repairEnvelopeField(repairAttempt),
483
1016
  };
484
1017
  }
485
1018
  function publishFailure(reason, message, opts) {
@@ -489,7 +1022,9 @@ function publishFailure(reason, message, opts) {
489
1022
  ...(opts.mode ? { mode: opts.mode } : {}),
490
1023
  ...(opts.gates ? { gates: opts.gates } : {}),
491
1024
  ...(opts.assets ? { assets: opts.assets } : {}),
1025
+ ...(opts.detail ? { detail: opts.detail } : {}),
492
1026
  ...(opts.credits ? { credits: opts.credits } : {}),
1027
+ ...(opts.repair ? { repair: opts.repair } : {}),
493
1028
  reason,
494
1029
  retryable: opts.retryable,
495
1030
  message,
@@ -567,14 +1102,34 @@ async function withMachineJsonConsole(enabled, deps, fn) {
567
1102
  machineJsonStdoutBypass = previousBypass;
568
1103
  }
569
1104
  }
570
- function createDefaultTransport(deps) {
571
- const env = deps.env ?? process.env;
572
- loadEnvFileFromEnv(env);
1105
+ async function composePublishedRecipe(transport, assets) {
1106
+ if (!transport.composeRecipe)
1107
+ return undefined;
1108
+ try {
1109
+ const composed = await transport.composeRecipe({
1110
+ compose_recipe: true,
1111
+ assets: [...assets],
1112
+ });
1113
+ return composed.ok && composed.recipeId ? composed.recipeId : undefined;
1114
+ }
1115
+ catch {
1116
+ return undefined;
1117
+ }
1118
+ }
1119
+ function createDefaultTransport(deps, opts = {}) {
1120
+ const env = loadContractEnv(deps);
1121
+ const hubMode = configuredHubMode(env);
1122
+ if (hubMode === 'private') {
1123
+ return createPrivateTransport(env, deps.resolveProxyClient ?? resolveDefaultPrivateProxy, opts.composeRecipe !== false);
1124
+ }
573
1125
  const hubUrl = resolveHubUrl(env);
574
- const evomapDir = resolveAtpHome(env);
575
- const sender = resolveAtpSenderId(env);
576
- const senderId = () => sender ?? env['A2A_NODE_ID']?.trim();
577
- const nodeSecret = env['EVOMAP_NODE_SECRET']?.trim() || env['A2A_NODE_SECRET']?.trim();
1126
+ const evomapDir = resolveIdentityHome(env);
1127
+ const explicitCredentials = resolveExplicitNodeCredentials(env);
1128
+ const { nodeSecret } = explicitCredentials;
1129
+ const sender = nodeSecret
1130
+ ? explicitCredentials.senderId ?? resolveAtpSenderId(env)
1131
+ : resolveAtpSenderId(env);
1132
+ const senderId = () => sender;
578
1133
  const connected = nodeSecret
579
1134
  ? connectPublicHub({ hubUrl, authMode: 'legacy', evomapDir, nodeSecret, senderId })
580
1135
  : connectPublicHub({ hubUrl, authMode: 'oauth', evomapDir, senderId });
@@ -602,26 +1157,159 @@ function createDefaultTransport(deps) {
602
1157
  fetchAssetById: (assetId) => connected.hub.fetchAssetById(assetId),
603
1158
  validate: (bundle) => call('/a2a/validate', 'validate', bundle),
604
1159
  publish: (bundle) => call('/a2a/publish', 'publish', bundle),
1160
+ ...(opts.composeRecipe === false ? {} : {
1161
+ composeRecipe: (payload) => hub.composeRecipeAfterAssetPublish(connected.hub, payload),
1162
+ }),
1163
+ };
1164
+ }
1165
+ function loadContractEnv(deps) {
1166
+ const env = { ...(deps.env ?? process.env) };
1167
+ const envFile = loadEnvFileFromEnv(env);
1168
+ if (envFile.error)
1169
+ throw new Error('failed to load EVOLVER_ENV_FILE');
1170
+ return env;
1171
+ }
1172
+ function preserveInheritedSecrets(runtimeEnv, inheritedEnv) {
1173
+ const env = { ...runtimeEnv };
1174
+ let index = 0;
1175
+ for (const [key, value] of Object.entries(inheritedEnv)) {
1176
+ if (!value || value === runtimeEnv[key] || !/SECRET|TOKEN|API[_-]?KEY|PASSWORD|AUTH|CREDENTIAL/i.test(key))
1177
+ continue;
1178
+ env[`EVOLVER_INHERITED_SECRET_${index++}`] = value;
1179
+ }
1180
+ return env;
1181
+ }
1182
+ function configuredHubMode(env) {
1183
+ const value = String(env['EVOMAP_HUB_MODE'] ?? 'public').trim().toLowerCase();
1184
+ if (value === 'public' || value === 'private')
1185
+ return value;
1186
+ throw new Error('EVOMAP_HUB_MODE must be public or private');
1187
+ }
1188
+ function resolveDefaultPrivateProxy(env) {
1189
+ return proxyClientFromEnv(env);
1190
+ }
1191
+ function createPrivateTransport(env, resolveProxy, composeRecipe = true) {
1192
+ const proxy = resolveProxy(env);
1193
+ if (!proxy)
1194
+ throw new Error('private Hub proxy credentials are not configured');
1195
+ const privateModeReady = assertPrivateProxyMode(proxy);
1196
+ return {
1197
+ validationCapabilityOptional: true,
1198
+ fetchAssetById: async (assetId) => {
1199
+ try {
1200
+ await privateModeReady;
1201
+ const body = await proxy.fetchAsset({ assetId, expectedHubMode: 'private' });
1202
+ return privateProxyAssets(body).find((asset) => (asset.asset_id === assetId || stringField(asset, 'id') === assetId)) ?? null;
1203
+ }
1204
+ catch (err) {
1205
+ if (err instanceof ContractError)
1206
+ throw err;
1207
+ const message = err instanceof Error ? err.message : String(err);
1208
+ if (message === 'proxy_hub_mode_mismatch' || isAuthLikeError(err)) {
1209
+ throw new ContractError('auth_required', 'private Hub proxy authentication required');
1210
+ }
1211
+ throw new ContractError('network_error', 'Hub unreachable');
1212
+ }
1213
+ },
1214
+ validate: async (bundle) => {
1215
+ try {
1216
+ await privateModeReady;
1217
+ const body = await proxy.validateAssetBundle({ assets: [...bundle], expected_hub_mode: 'private' });
1218
+ return { ok: hasExplicitValidatePass(body), status: 200, body };
1219
+ }
1220
+ catch (err) {
1221
+ if (err instanceof ContractError)
1222
+ throw err;
1223
+ return privateProxyFailure(err);
1224
+ }
1225
+ },
1226
+ publish: async (bundle) => {
1227
+ try {
1228
+ await privateModeReady;
1229
+ const body = normalizePrivatePublishBody(await proxy.submitAssetBundle({
1230
+ assets: [...bundle],
1231
+ expected_hub_mode: 'private',
1232
+ ...(composeRecipe ? {} : { compose_recipe: false }),
1233
+ }));
1234
+ return { ok: !privatePublishExplicitFailure(body) && normalizePublishStatus(body) !== undefined, status: 200, body };
1235
+ }
1236
+ catch (err) {
1237
+ if (err instanceof ContractError)
1238
+ throw err;
1239
+ return privateProxyFailure(err);
1240
+ }
1241
+ },
605
1242
  };
606
1243
  }
1244
+ async function assertPrivateProxyMode(proxy) {
1245
+ const status = asRecord(await proxy.status()) ?? {};
1246
+ if (status['hub_mode'] !== 'private') {
1247
+ throw new ContractError('auth_required', 'private Hub proxy mode mismatch');
1248
+ }
1249
+ }
1250
+ function isValidationCapabilityUnavailable(body) {
1251
+ const root = asRecord(body) ?? {};
1252
+ const payload = asRecord(root['payload']) ?? {};
1253
+ return (root['reason'] ?? payload['reason']) === 'validate_not_configured';
1254
+ }
1255
+ function privateProxyAssets(body) {
1256
+ const root = asRecord(body) ?? {};
1257
+ const payload = asRecord(root['payload']) ?? {};
1258
+ const rows = Array.isArray(root['assets']) ? root['assets'] : Array.isArray(payload['assets']) ? payload['assets'] : [];
1259
+ return rows.filter((asset) => Boolean(asset && typeof asset === 'object' && !Array.isArray(asset)));
1260
+ }
1261
+ function normalizePrivatePublishBody(body) {
1262
+ const root = asRecord(body);
1263
+ if (!root)
1264
+ return body;
1265
+ const payload = asRecord(root['payload']);
1266
+ if (payload) {
1267
+ return { ...root, payload: normalizePrivatePublishLayer(payload) };
1268
+ }
1269
+ return normalizePrivatePublishLayer(root);
1270
+ }
1271
+ function normalizePrivatePublishLayer(body) {
1272
+ const receiptId = stringField(body, 'receipt_id') ?? stringField(body, 'receiptId');
1273
+ return {
1274
+ ...body,
1275
+ ...(stringField(body, 'status') === 'pending' ? { status: 'queued' } : {}),
1276
+ ...(receiptId ? { receipt_id: receiptId } : {}),
1277
+ };
1278
+ }
1279
+ function privatePublishExplicitFailure(body) {
1280
+ const root = asRecord(body) ?? {};
1281
+ const payload = asRecord(root['payload']) ?? {};
1282
+ return root['ok'] === false || root['stored'] === false || payload['ok'] === false || payload['stored'] === false;
1283
+ }
1284
+ function privateProxyFailure(err) {
1285
+ return { ok: false, status: isAuthLikeError(err) ? 401 : 0 };
1286
+ }
607
1287
  function isAuthLikeError(err) {
608
1288
  const message = err instanceof Error ? err.message : String(err);
609
1289
  return /oauth|login|credential|auth|401|403|node_secret/i.test(message);
610
1290
  }
611
- function classifyError(err, command) {
1291
+ function classifyError(err, command, env = {}) {
612
1292
  if (err instanceof ContractError)
613
1293
  return { reason: err.reason, message: err.safeMessage, retryable: err.reason === 'network_error' };
614
1294
  if (err instanceof AuthError)
615
- return { reason: 'auth_required', message: 'Hub authentication required', retryable: false };
1295
+ return {
1296
+ reason: 'auth_required',
1297
+ message: command === 'publish' ? publishAuthRequiredMessage(env) : 'Hub authentication required',
1298
+ retryable: false,
1299
+ };
616
1300
  if (err instanceof HubUnreachableError)
617
1301
  return { reason: 'network_error', message: 'Hub unreachable', retryable: true };
618
1302
  if (err instanceof HubClientError) {
619
1303
  const reason = stableContractReasonFromBody(err.body) ?? (command === 'reuse' ? reuseReasonFromStatus(err.status) : publishReasonFromStatus(err.status));
620
- return { reason, message: command === 'publish' ? publishReasonMessage(reason) : reuseReasonMessage(reason), retryable: publishRetryable(reason) };
1304
+ return { reason, message: command === 'publish' ? publishReasonMessage(reason, env) : reuseReasonMessage(reason), retryable: publishRetryable(reason) };
621
1305
  }
622
1306
  const message = err instanceof Error ? err.message : String(err);
623
1307
  if (/oauth|login|credential|auth|401|403|node_secret/i.test(message))
624
- return { reason: 'auth_required', message: 'Hub authentication required', retryable: false };
1308
+ return {
1309
+ reason: 'auth_required',
1310
+ message: command === 'publish' ? publishAuthRequiredMessage(env) : 'Hub authentication required',
1311
+ retryable: false,
1312
+ };
625
1313
  if (/network|fetch failed|ECONN|ENOTFOUND|ETIMEDOUT|hub 5\d\d/i.test(message))
626
1314
  return { reason: 'network_error', message: 'Hub unreachable', retryable: true };
627
1315
  return { reason: 'internal_error', message: `evolver ${command} failed`, retryable: false };
@@ -650,11 +1338,22 @@ function publishReasonFromResponse(status, body) {
650
1338
  function publishRetryable(reason) {
651
1339
  return reason === 'network_error';
652
1340
  }
653
- function publishReasonMessage(reason) {
1341
+ function publishAuthRequiredMessage(env) {
1342
+ const rawMode = env['EVOMAP_HUB_MODE']?.trim().toLowerCase();
1343
+ if (rawMode && rawMode !== 'public' && rawMode !== 'private') {
1344
+ return 'Hub authentication failed; verify EVOMAP_HUB_MODE and the configured credentials';
1345
+ }
1346
+ if (rawMode === 'private')
1347
+ return PRIVATE_AUTH_REQUIRED_MESSAGE;
1348
+ return resolveExplicitNodeCredentials(env).nodeSecret
1349
+ ? LEGACY_AUTH_REQUIRED_MESSAGE
1350
+ : OAUTH_AUTH_REQUIRED_MESSAGE;
1351
+ }
1352
+ function publishReasonMessage(reason, env = {}) {
654
1353
  const map = {
655
1354
  missing_id: 'missing asset id',
656
1355
  cli_unavailable: 'evolver CLI unavailable',
657
- auth_required: 'Hub authentication required',
1356
+ auth_required: publishAuthRequiredMessage(env),
658
1357
  not_found: 'asset not found',
659
1358
  network_error: 'Hub unreachable',
660
1359
  unsupported: 'publish unsupported',
@@ -662,9 +1361,11 @@ function publishReasonMessage(reason) {
662
1361
  redaction_unavailable: 'redaction unavailable',
663
1362
  leak_detected: 'leak detected after redaction',
664
1363
  schema_invalid: 'asset schema is invalid',
665
- bundle_required: 'publish requires a complete asset bundle',
1364
+ bundle_required: BUNDLE_REQUIRED_MESSAGE,
666
1365
  quality_gate_failed: 'Hub quality gate failed',
1366
+ gene_unproven: 'gene has no proven success yet — run it to a successful outcome before publishing',
667
1367
  insufficient_credits: 'insufficient credits',
1368
+ unsafe_validation_command: 'validation command contains unsafe patterns (e.g., node -e, shell metacharacters) blocked by sandbox security policy',
668
1369
  };
669
1370
  return map[reason] ?? map.internal_error;
670
1371
  }
@@ -719,6 +1420,8 @@ export function hasExplicitValidatePass(body) {
719
1420
  function normalizePublishStatus(body) {
720
1421
  const payload = payloadRecord(body);
721
1422
  const status = stringField(payload, 'status');
1423
+ if (status === 'candidate')
1424
+ return 'queued';
722
1425
  if (status === 'queued' || status === 'accepted' || status === 'published')
723
1426
  return status;
724
1427
  if (status)
@@ -736,6 +1439,43 @@ function payloadRecord(body) {
736
1439
  const root = asRecord(body) ?? {};
737
1440
  return asRecord(root['payload']) ?? root;
738
1441
  }
1442
+ // The Hub answers a rejected publish with the SPECIFIC rule that failed
1443
+ // ("gene_validation_required: ..."), which our stable ContractReason enum
1444
+ // necessarily flattens to `quality_gate_failed`. Keeping only the flattened code
1445
+ // leaves every caller — the desktop wizard above all — with a red gate and no
1446
+ // way to act on it, so the detail rides along in a separate additive field.
1447
+ // Capped and control-character-stripped: it is Hub-authored text that ends up in
1448
+ // a machine-readable envelope on stdout.
1449
+ const HUB_DETAIL_MAX_CHARS = 300;
1450
+ function stripControlChars(value) {
1451
+ let out = '';
1452
+ for (const ch of value) {
1453
+ const code = ch.codePointAt(0) ?? 0;
1454
+ out += code < 0x20 || code === 0x7f ? ' ' : ch;
1455
+ }
1456
+ return out;
1457
+ }
1458
+ function hubDetailFromBody(body) {
1459
+ const root = asRecord(body) ?? {};
1460
+ const payload = payloadRecord(body);
1461
+ // Take the first candidate that ISN'T already a stable contract token: those
1462
+ // are what `reason` carries, so emitting one here would repeat the flattened
1463
+ // code this field exists to supplement. The Hub is free to put the token in
1464
+ // `reason` and the rule text in `error` (or the reverse), so order alone
1465
+ // cannot pick the informative one.
1466
+ const raw = [
1467
+ stringField(root, 'error'),
1468
+ stringField(root, 'reason'),
1469
+ stringField(payload, 'error'),
1470
+ stringField(payload, 'reason'),
1471
+ ].find((candidate) => candidate && !isStableContractReason(candidate.trim()));
1472
+ if (!raw)
1473
+ return undefined;
1474
+ const detail = stripControlChars(raw).replace(/\s+/g, ' ').trim();
1475
+ if (!detail)
1476
+ return undefined;
1477
+ return detail.length > HUB_DETAIL_MAX_CHARS ? `${detail.slice(0, HUB_DETAIL_MAX_CHARS)}…` : detail;
1478
+ }
739
1479
  function stableContractReasonFromBody(body) {
740
1480
  const payload = payloadRecord(body);
741
1481
  const reason = stringField(payload, 'reason') ?? stringField(payload, 'error');