@evomap/evolver-cli 2.0.0-beta.9 → 2.0.0

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 (87) hide show
  1. package/dist/antiGeneBenchmark.js +2 -0
  2. package/dist/antiGeneRollout.js +9 -3
  3. package/dist/assetHealth.js +2 -0
  4. package/dist/assetTrust.js +14 -1
  5. package/dist/atp.d.ts +10 -5
  6. package/dist/atp.js +119 -26
  7. package/dist/atpAutoBuyer.d.ts +120 -0
  8. package/dist/atpAutoBuyer.js +814 -0
  9. package/dist/atpAutoDeliver.js +2 -2
  10. package/dist/autoDistillLlm.js +2 -1
  11. package/dist/autoDistillTranscript.js +3 -2
  12. package/dist/autoexec.d.ts +101 -13
  13. package/dist/autoexec.js +794 -91
  14. package/dist/cli.js +13 -0
  15. package/dist/cliContracts.d.ts +23 -2
  16. package/dist/cliContracts.js +504 -54
  17. package/dist/commands.d.ts +1 -0
  18. package/dist/commands.js +1 -0
  19. package/dist/curriculumCapabilityGaps.d.ts +6 -0
  20. package/dist/curriculumCapabilityGaps.js +24 -0
  21. package/dist/cycleConsumer.d.ts +13 -0
  22. package/dist/cycleConsumer.js +186 -20
  23. package/dist/dashboard.js +47 -9
  24. package/dist/dispatch.js +8 -2
  25. package/dist/distillPrimitives.d.ts +3 -2
  26. package/dist/distillPrimitives.js +80 -12
  27. package/dist/doctor.js +120 -11
  28. package/dist/identityHome.d.ts +9 -0
  29. package/dist/identityHome.js +47 -0
  30. package/dist/index.d.ts +70 -40
  31. package/dist/index.js +581 -193
  32. package/dist/learningTrace.d.ts +15 -0
  33. package/dist/learningTrace.js +73 -0
  34. package/dist/lifecycle.d.ts +67 -1
  35. package/dist/lifecycle.js +738 -44
  36. package/dist/localMemoryGraph.d.ts +90 -3
  37. package/dist/localMemoryGraph.js +2031 -231
  38. package/dist/login.d.ts +1 -1
  39. package/dist/login.js +3 -3
  40. package/dist/materialSnapshot.d.ts +9 -1
  41. package/dist/materialSnapshot.js +23 -6
  42. package/dist/memoryGraphOps.d.ts +8 -0
  43. package/dist/memoryGraphOps.js +140 -0
  44. package/dist/migrate/assetFormatMap.d.ts +61 -0
  45. package/dist/migrate/assetFormatMap.js +53 -0
  46. package/dist/migrate/envTranslate.d.ts +26 -0
  47. package/dist/migrate/envTranslate.js +147 -0
  48. package/dist/migrate/fieldMap.d.ts +4 -2
  49. package/dist/migrate/fieldMap.js +9 -5
  50. package/dist/migrate/oauthImport.d.ts +66 -0
  51. package/dist/migrate/oauthImport.js +667 -0
  52. package/dist/migrate/v1Import.d.ts +92 -1
  53. package/dist/migrate/v1Import.js +1481 -141
  54. package/dist/promptRecallHook.d.ts +24 -0
  55. package/dist/promptRecallHook.js +425 -0
  56. package/dist/recallVerifyReport.d.ts +37 -0
  57. package/dist/recallVerifyReport.js +244 -0
  58. package/dist/recipe.d.ts +7 -1
  59. package/dist/recipe.js +426 -56
  60. package/dist/requiredSandboxValidation.d.ts +5 -0
  61. package/dist/requiredSandboxValidation.js +4 -0
  62. package/dist/reuse.d.ts +9 -0
  63. package/dist/reuse.js +151 -56
  64. package/dist/runtimeCapabilities.js +15 -15
  65. package/dist/runtimeSessionSource.d.ts +3 -2
  66. package/dist/runtimeSessionSource.js +63 -11
  67. package/dist/selectionPolicyConfig.d.ts +8 -0
  68. package/dist/selectionPolicyConfig.js +18 -0
  69. package/dist/semanticIdfConfig.d.ts +2 -0
  70. package/dist/semanticIdfConfig.js +4 -0
  71. package/dist/sessionIngest.d.ts +37 -0
  72. package/dist/sessionIngest.js +156 -0
  73. package/dist/setupHooks.js +95 -1
  74. package/dist/skill2gep.d.ts +13 -9
  75. package/dist/skill2gep.js +42 -30
  76. package/dist/skillDistill.d.ts +8 -4
  77. package/dist/skillDistill.js +38 -9
  78. package/dist/solo/mode.js +1 -0
  79. package/dist/sync.d.ts +12 -0
  80. package/dist/sync.js +1246 -151
  81. package/dist/thesis.d.ts +1 -1
  82. package/dist/thesis.js +20 -3
  83. package/dist/trajectoryExport.js +21 -3
  84. package/dist/v1Compat.d.ts +1 -0
  85. package/dist/v1Compat.js +9 -0
  86. package/dist/workflowRuntime.js +24 -18
  87. package/package.json +11 -8
@@ -1,10 +1,11 @@
1
1
  import { existsSync, readFileSync, statSync } from 'node:fs';
2
- import { resolve } from 'node:path';
2
+ import { isAbsolute, resolve } from 'node:path';
3
3
  import { inspect, format } from 'node:util';
4
- import { assetstore, events, hub, wire } from '@evomap/evolver-core';
4
+ import { 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 { resolveExplicitNodeCredentials, resolveIdentityHome } from './identityHome.js';
8
9
  const REUSE_CONTRACT = 'reuse.v1';
9
10
  const PUBLISH_CONTRACT = 'publish.v1';
10
11
  const REVERSIBILITY = 'irreversible';
@@ -27,7 +28,9 @@ const STABLE_CONTRACT_REASONS = new Set([
27
28
  'schema_invalid',
28
29
  'bundle_required',
29
30
  'quality_gate_failed',
31
+ 'gene_unproven',
30
32
  'insufficient_credits',
33
+ 'unsafe_validation_command',
31
34
  ]);
32
35
  const HUB_METADATA_KEYS = new Set([
33
36
  'credit_cost',
@@ -64,23 +67,38 @@ class ContractError extends Error {
64
67
  export async function runReuseCommand(args, deps = {}) {
65
68
  const out = deps.out ?? process.stdout;
66
69
  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);
70
+ if (!parsed.ok || !parsed.assetId) {
71
+ return writeJson(out, reuseFailure(parsed.reason ?? 'missing_id', parsed.message ?? 'reuse requires --id <asset_id>'), 1, deps);
72
+ }
73
+ let runtimeDeps;
74
+ try {
75
+ runtimeDeps = { ...deps, env: loadContractEnv(deps) };
76
+ }
77
+ catch (err) {
78
+ const failure = classifyError(err, 'reuse');
79
+ return writeJson(out, reuseFailure(failure.reason, failure.message), 1, deps);
80
+ }
81
+ const write = (value, code) => writeJson(out, value, code, runtimeDeps);
70
82
  const assetId = parsed.assetId;
71
- return withMachineJsonConsole(Boolean(parsed.jsonOut), deps, async () => {
83
+ return withMachineJsonConsole(Boolean(parsed.jsonOut), runtimeDeps, async () => {
72
84
  try {
73
- const fetcher = deps.fetchAssetById ?? deps.transport?.fetchAssetById ?? createDefaultTransport(deps).fetchAssetById;
85
+ const fetcher = runtimeDeps.fetchAssetById
86
+ ?? runtimeDeps.transport?.fetchAssetById
87
+ ?? createDefaultTransport(runtimeDeps).fetchAssetById;
74
88
  const asset = await fetcher(assetId);
75
89
  if (!asset)
76
90
  return write(reuseFailure('not_found', 'asset not found'), 1);
77
91
  const cleaned = stripHubMetadata(asset);
78
- if (wire.computeAssetId(cleaned) !== assetId) {
92
+ const computedAssetId = wire.computeAssetId(cleaned);
93
+ const identityMatches = assetId.startsWith('sha256:')
94
+ ? computedAssetId === assetId
95
+ : stringField(cleaned, 'id') === assetId && computedAssetId === cleaned.asset_id;
96
+ if (!identityMatches) {
79
97
  return write(reuseFailure('internal_error', 'asset integrity verification failed'), 1);
80
98
  }
81
- const store = deps.assetStore ?? new assetstore.LocalJsonlProvider(deps.assetsDir ?? events.assetsDir());
99
+ const store = runtimeDeps.assetStore ?? new assetstore.LocalJsonlProvider(contractAssetsDir(runtimeDeps));
82
100
  await assertNoLocalReuseIdConflict(cleaned, store);
83
- const provenance = new assetstore.ProvenanceStore(storeBaseDir(store, deps));
101
+ const provenance = new assetstore.ProvenanceStore(storeBaseDir(store, runtimeDeps));
84
102
  const stored = await assetstore.ingestUntrusted(store, provenance, cleaned, 'hub');
85
103
  return write({
86
104
  ok: true,
@@ -111,14 +129,27 @@ export async function runPublishCommand(args, deps = {}) {
111
129
  return 0;
112
130
  }
113
131
  const parsed = parsePublishArgs(args);
114
- const write = (value, code) => writeJson(out, value, code, deps);
115
132
  if (!parsed.ok || !parsed.assetRefs) {
116
- return write(publishFailure(parsed.reason ?? 'bundle_required', parsed.message ?? publishReasonMessage('bundle_required'), { retryable: false }), 1);
133
+ return writeJson(out, publishFailure(parsed.reason ?? 'bundle_required', parsed.message ?? publishReasonMessage('bundle_required'), { retryable: false }), 1, deps);
117
134
  }
118
135
  const assetRefs = parsed.assetRefs;
119
- return withMachineJsonConsole(Boolean(parsed.jsonOut), deps, async () => {
136
+ let runtimeDeps;
137
+ try {
138
+ const inheritedEnv = deps.env ?? process.env;
139
+ const runtimeEnv = loadContractEnv(deps);
140
+ runtimeDeps = { ...deps, env: preserveInheritedSecrets(runtimeEnv, inheritedEnv) };
141
+ }
142
+ catch (err) {
143
+ const failure = classifyError(err, 'publish');
144
+ return writeJson(out, publishFailure(failure.reason, failure.message, {
145
+ retryable: failure.retryable,
146
+ mode: parsed.dryRun ? 'dry_run' : 'publish',
147
+ }), 1, deps);
148
+ }
149
+ const write = (value, code) => writeJson(out, value, code, runtimeDeps);
150
+ return withMachineJsonConsole(Boolean(parsed.jsonOut), runtimeDeps, async () => {
120
151
  try {
121
- const bundle = await buildPublishBundle(assetRefs, deps);
152
+ const bundle = await buildPublishBundle(assetRefs, runtimeDeps);
122
153
  if (!bundle.ok) {
123
154
  return write(publishFailure(bundle.reason, bundle.message, { retryable: false, gates: bundle.gates }), 1);
124
155
  }
@@ -126,30 +157,44 @@ export async function runPublishCommand(args, deps = {}) {
126
157
  if (parsed.dryRun)
127
158
  return write(dryRunEnvelope(bundle), 0);
128
159
  const reason = bundle.blockReasons[0] ?? 'internal_error';
129
- return write(publishFailure(reason, publishReasonMessage(reason), {
160
+ const detailMessage = bundle.blockMessages?.[reason];
161
+ return write(publishFailure(reason, detailMessage ?? publishReasonMessage(reason), {
130
162
  retryable: false,
131
163
  mode: 'publish',
132
164
  gates: bundle.gates,
133
165
  assets: bundle.assets,
134
166
  }), 1);
135
167
  }
136
- const transport = deps.transport ?? createDefaultTransport(deps);
168
+ const transport = deps.transport ?? createDefaultTransport(runtimeDeps);
137
169
  const validate = deps.validate ?? transport.validate;
138
170
  const validation = await validate(bundle.sanitized);
139
171
  const validationCredits = extractCredits(validation.body);
140
- if (!validation.ok) {
172
+ const validationUnavailable = transport.validationCapabilityOptional === true
173
+ && isValidationCapabilityUnavailable(validation.body);
174
+ if (!validation.ok && !(validationUnavailable && !parsed.dryRun)) {
175
+ if (validationUnavailable) {
176
+ return write(publishFailure('unsupported', publishReasonMessage('unsupported'), {
177
+ retryable: false,
178
+ mode: 'dry_run',
179
+ gates: bundle.gates,
180
+ assets: bundle.assets,
181
+ detail: 'Private Hub validation is not configured',
182
+ }), 1);
183
+ }
141
184
  const reason = publishReasonFromResponse(validation.status, validation.body);
185
+ const detail = hubDetailFromBody(validation.body);
142
186
  if (parsed.dryRun && reason === 'quality_gate_failed') {
143
187
  bundle.gates.quality = 'fail';
144
188
  if (!bundle.blockReasons.includes('quality_gate_failed'))
145
189
  bundle.blockReasons.push('quality_gate_failed');
146
- return write(dryRunEnvelope(bundle, validationCredits), 0);
190
+ return write(dryRunEnvelope(bundle, validationCredits, detail), 0);
147
191
  }
148
192
  return write(publishFailure(reason, publishReasonMessage(reason), {
149
193
  retryable: publishRetryable(reason),
150
194
  mode: parsed.dryRun ? 'dry_run' : 'publish',
151
195
  gates: parsed.dryRun ? bundle.gates : { ...bundle.gates, quality: 'fail' },
152
196
  assets: bundle.assets,
197
+ ...(detail ? { detail } : {}),
153
198
  ...(validationCredits ? { credits: validationCredits } : {}),
154
199
  }), 1);
155
200
  }
@@ -160,25 +205,32 @@ export async function runPublishCommand(args, deps = {}) {
160
205
  const publishCredits = extractCredits(published.body);
161
206
  if (!published.ok) {
162
207
  const reason = publishReasonFromResponse(published.status, published.body);
208
+ const detail = hubDetailFromBody(published.body);
163
209
  return write(publishFailure(reason, publishReasonMessage(reason), {
164
210
  retryable: publishRetryable(reason),
165
211
  mode: 'publish',
166
212
  gates: bundle.gates,
167
213
  assets: bundle.assets,
214
+ ...(detail ? { detail } : {}),
168
215
  ...(publishCredits ? { credits: publishCredits } : {}),
169
216
  }), 1);
170
217
  }
171
218
  const payload = payloadRecord(published.body);
172
- if (stringField(payload, 'decision') === 'quarantine') {
219
+ const decision = stringField(payload, 'decision');
220
+ const hubReason = stringField(payload, 'reason');
221
+ const safetyCandidate = decision === 'quarantine' && hubReason === 'safety_candidate';
222
+ if (decision === 'quarantine' && !safetyCandidate) {
223
+ const detail = hubDetailFromBody(published.body);
173
224
  return write(publishFailure('quality_gate_failed', publishReasonMessage('quality_gate_failed'), {
174
225
  retryable: false,
175
226
  mode: 'publish',
176
227
  gates: { ...bundle.gates, quality: 'fail' },
177
228
  assets: bundle.assets,
229
+ ...(detail ? { detail } : {}),
178
230
  ...(publishCredits ? { credits: publishCredits } : {}),
179
231
  }), 1);
180
232
  }
181
- const status = normalizePublishStatus(published.body);
233
+ const status = safetyCandidate ? 'queued' : normalizePublishStatus(published.body);
182
234
  if (!status) {
183
235
  return write(publishFailure('internal_error', 'Hub publish response missing lifecycle status', {
184
236
  retryable: false,
@@ -190,6 +242,7 @@ export async function runPublishCommand(args, deps = {}) {
190
242
  }
191
243
  const receiptId = stringField(payload, 'receipt_id');
192
244
  const bundleId = stringField(payload, 'bundle_id');
245
+ appendPublishedCapsuleCall(bundle, deps, { status, receiptId, bundleId });
193
246
  return write({
194
247
  ok: true,
195
248
  contract: PUBLISH_CONTRACT,
@@ -198,6 +251,7 @@ export async function runPublishCommand(args, deps = {}) {
198
251
  reversibility: REVERSIBILITY,
199
252
  ...(receiptId ? { receipt_id: receiptId } : {}),
200
253
  ...(bundleId ? { bundle_id: bundleId } : {}),
254
+ ...(safetyCandidate ? { hub_reason: hubReason } : {}),
201
255
  assets: bundle.assets,
202
256
  ...(publishCredits ? { credits: publishCredits } : {}),
203
257
  }, 0);
@@ -211,6 +265,35 @@ export async function runPublishCommand(args, deps = {}) {
211
265
  }
212
266
  });
213
267
  }
268
+ function appendPublishedCapsuleCall(bundle, deps, receipt) {
269
+ const capsuleIndex = bundle.sanitized.findIndex((asset) => asset.type === 'Capsule');
270
+ if (capsuleIndex < 0)
271
+ return;
272
+ const publishedCapsule = bundle.sanitized[capsuleIndex];
273
+ const originalCapsule = bundle.original[capsuleIndex];
274
+ if (!publishedCapsule)
275
+ return;
276
+ const tokensSpent = hub.assetDerivationTokenCost(originalCapsule);
277
+ const trigger = Array.isArray(publishedCapsule['trigger'])
278
+ ? publishedCapsule['trigger'].filter((value) => typeof value === 'string')
279
+ : undefined;
280
+ try {
281
+ const callLog = deps.callLog ?? new hub.AssetCallLog(events.assetCallLogPath(deps.env ?? process.env));
282
+ callLog.append({
283
+ action: 'asset_publish',
284
+ asset_id: publishedCapsule.asset_id,
285
+ asset_type: 'Capsule',
286
+ ...(trigger ? { signals: trigger } : {}),
287
+ ...(tokensSpent !== undefined ? { tokens_spent: tokensSpent } : {}),
288
+ extra: {
289
+ status: receipt.status,
290
+ ...(receipt.receiptId ? { receipt_id: receipt.receiptId } : {}),
291
+ ...(receipt.bundleId ? { bundle_id: receipt.bundleId } : {}),
292
+ },
293
+ });
294
+ }
295
+ catch { /* a local audit failure must never change an accepted Hub publish */ }
296
+ }
214
297
  export function parseReuseArgs(args) {
215
298
  let id;
216
299
  let jsonOut = false;
@@ -295,8 +378,18 @@ export async function buildPublishBundle(refs, deps = {}) {
295
378
  original = await Promise.all(refs.map((ref) => loadAssetRef(ref, deps)));
296
379
  }
297
380
  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' } };
381
+ // Report what actually went wrong. Overwriting every failure with "asset
382
+ // schema is invalid" hid the common case — a ref that resolved to nothing —
383
+ // behind a claim about a schema that was never read, leaving a user who
384
+ // could not publish with no way to tell a missing asset from a bad one.
385
+ const reason = err instanceof ContractError ? err.reason : 'internal_error';
386
+ const message = err instanceof ContractError ? err.safeMessage : publishReasonMessage(reason);
387
+ return {
388
+ ok: false,
389
+ reason,
390
+ message,
391
+ gates: reason === 'schema_invalid' ? { schema: 'fail' } : {},
392
+ };
300
393
  }
301
394
  const bundleCheck = checkBundle(original);
302
395
  if (!bundleCheck.ok)
@@ -313,22 +406,149 @@ export async function buildPublishBundle(refs, deps = {}) {
313
406
  return { ok: false, reason: 'bundle_required', message: finalBundleCheck.message, gates: { redaction: 'pass', schema: 'pass', bundle: 'fail' } };
314
407
  }
315
408
  const leak = finalPayloadLeakCheck(sanitized, deps.env ?? process.env);
409
+ // Local quality gate: a gene may only publish once it has TRULY succeeded at
410
+ // least once. Minting sets `confidence` from self-report / text completeness,
411
+ // which never proves the gene worked; without this check an unproven gene
412
+ // leaks to the Hub and comes back as an opaque `quality_gate_failed` after a
413
+ // round-trip. Assessing the gene's outcome evidence here fails fast, locally,
414
+ // with a precise reason. Read-only: aggregates the local capsule history.
415
+ const geneEvidence = await assessPublishGeneEvidence(original, deps);
416
+ const geneProven = geneEvidence?.eligible ?? true;
417
+ // Local quality gate: validation command safety check.
418
+ // Only applies to Gene assets. Checks that all validation commands are safe
419
+ // (e.g., no `node -e`, no shell metacharacters).
420
+ const validationCommandResult = checkValidationCommands(original);
316
421
  const gates = {
317
422
  redaction: 'pass',
318
423
  leak: leak.blocked ? 'fail' : 'pass',
319
424
  schema: 'pass',
320
425
  bundle: 'pass',
321
- quality: 'pass',
426
+ quality: geneProven ? 'pass' : 'fail',
427
+ validation_command: validationCommandResult.allowed ? 'pass' : 'fail',
322
428
  };
429
+ const blockReasons = [];
430
+ const blockMessages = {};
431
+ if (leak.blocked)
432
+ blockReasons.push('leak_detected');
433
+ if (!geneProven)
434
+ blockReasons.push('gene_unproven');
435
+ if (!validationCommandResult.allowed) {
436
+ blockReasons.push('unsafe_validation_command');
437
+ if (validationCommandResult.message) {
438
+ blockMessages['unsafe_validation_command'] = validationCommandResult.message;
439
+ }
440
+ }
323
441
  return {
324
442
  ok: true,
325
443
  original,
326
444
  sanitized,
327
- blockReasons: leak.blocked ? ['leak_detected'] : [],
445
+ blockReasons,
446
+ blockMessages,
328
447
  gates,
329
448
  assets: summarizePublishAssets(sanitized),
330
449
  };
331
450
  }
451
+ // Assess whether the bundle's Gene has proven success in the local capsule
452
+ // history. Fail-open (returns null) when there is no gene id or the store read
453
+ // throws — the pre-check only ADDS a local gate; the Hub still gates, so an
454
+ // infra hiccup must not block an otherwise-valid publish.
455
+ async function assessPublishGeneEvidence(original, deps) {
456
+ const gene = original.find((asset) => asset.type === 'Gene');
457
+ if (!gene)
458
+ return null;
459
+ const businessId = stringField(gene, 'id');
460
+ const assetId = typeof gene.asset_id === 'string' ? gene.asset_id : undefined;
461
+ const geneId = businessId ?? assetId;
462
+ if (!geneId)
463
+ return null;
464
+ try {
465
+ const store = deps.assetStore ?? new assetstore.LocalJsonlProvider(contractAssetsDir(deps));
466
+ const primary = await algo.assessGenePublishEvidence(store, geneId);
467
+ // Capsules key their `gene` link by the gene's business id in production;
468
+ // some stores (and legacy fixtures) key it by asset_id. Mixed histories can
469
+ // contain failures under the business id and a success under asset_id, so
470
+ // both aliases must contribute to the gate rather than only falling back
471
+ // when the primary alias has no rows at all.
472
+ if (assetId && assetId !== geneId) {
473
+ const byAssetId = await algo.assessGenePublishEvidence(store, assetId);
474
+ const combined = {
475
+ success: primary.success + byAssetId.success,
476
+ failed: primary.failed + byAssetId.failed,
477
+ inert: primary.inert + byAssetId.inert,
478
+ total: primary.total + byAssetId.total,
479
+ };
480
+ const eligible = algo.isGenePublishEligible(combined);
481
+ return {
482
+ geneId,
483
+ ...combined,
484
+ eligible,
485
+ reason: eligible ? 'eligible' : 'no_proven_success',
486
+ };
487
+ }
488
+ return primary;
489
+ }
490
+ catch {
491
+ return null;
492
+ }
493
+ }
494
+ /**
495
+ * 检查 Gene 资产中的验证命令是否安全。
496
+ * 只检查 Gene 类型的资产,不影响 Capsule 或 EvolutionEvent。
497
+ * 如果 Gene 有 validation 数组,会检查每条命令是否符合安全策略。
498
+ * 不安全的命令(如 `node -e`、包含 shell 元字符等)会阻止发布。
499
+ */
500
+ function checkValidationCommands(original) {
501
+ const gene = original.find((asset) => asset.type === 'Gene');
502
+ if (!gene)
503
+ return { allowed: true, unsafeCommands: [] };
504
+ const validation = gene['validation'];
505
+ if (!Array.isArray(validation) || validation.length === 0) {
506
+ return { allowed: true, unsafeCommands: [] };
507
+ }
508
+ const unsafeCommands = [];
509
+ for (const cmd of validation) {
510
+ if (typeof cmd !== 'string')
511
+ continue;
512
+ if (!verify.isValidationCommandAllowed(cmd)) {
513
+ unsafeCommands.push(cmd);
514
+ }
515
+ }
516
+ if (unsafeCommands.length === 0) {
517
+ return { allowed: true, unsafeCommands: [] };
518
+ }
519
+ // 构建诊断信息(不暴露原始命令文本,避免泄露安全策略细节)
520
+ const reasons = new Set();
521
+ for (const cmd of unsafeCommands) {
522
+ if (/`|\$\(/.test(cmd)) {
523
+ reasons.add('command_substitution');
524
+ continue;
525
+ }
526
+ const stripped = cmd.replace(/"[^"]*"/g, '').replace(/'[^']*'/g, '');
527
+ if (verify.SHELL_METACHARS.test(stripped)) {
528
+ reasons.add('shell_metacharacters');
529
+ continue;
530
+ }
531
+ const tokens = cmd.split(/\s+/);
532
+ const executable = tokens[0] ?? '';
533
+ const args = tokens.slice(1);
534
+ const badFlag = verify.isNodeExecutable(executable) ? verify.nodeFlagViolation(executable, args) : null;
535
+ if (badFlag) {
536
+ reasons.add('blocked_node_flag');
537
+ continue;
538
+ }
539
+ if (!cmd.trim().startsWith('node ')) {
540
+ reasons.add('non_node_command');
541
+ }
542
+ else {
543
+ reasons.add('unsafe_pattern');
544
+ }
545
+ }
546
+ return {
547
+ allowed: false,
548
+ unsafeCommands,
549
+ message: `validation command rejected: ${[...reasons].join(', ')}`,
550
+ };
551
+ }
332
552
  function sanitizePublishBundle(original) {
333
553
  const sanitized = original.map((asset) => hub.sanitizeAsset(stripPublishMetadata(asset)));
334
554
  const finalGeneIdByOriginalRef = new Map();
@@ -359,19 +579,41 @@ function withRecomputedAssetId(asset) {
359
579
  return { ...asset, asset_id: assetId ?? asset.asset_id };
360
580
  }
361
581
  async function loadAssetRef(ref, deps) {
362
- if (looksLikeFile(ref))
363
- return normalizeAsset(JSON.parse(readFileSync(resolve(ref), 'utf8')));
582
+ if (looksLikeFile(ref)) {
583
+ try {
584
+ return normalizeAsset(JSON.parse(readFileSync(resolve(ref), 'utf8')));
585
+ }
586
+ catch (err) {
587
+ if (err instanceof ContractError)
588
+ throw err;
589
+ if (err instanceof SyntaxError)
590
+ throw new ContractError('schema_invalid', 'asset schema is invalid');
591
+ throw err;
592
+ }
593
+ }
364
594
  const store = deps.assetStore;
365
595
  if (store) {
366
596
  const fromStore = await findAssetInStore(ref, store);
367
- if (!fromStore)
368
- throw new ContractError('schema_invalid', 'asset not found');
597
+ // `not_found`, not `schema_invalid`: nothing was located, so no schema was
598
+ // ever read. `reuse` already reports this ref-resolution failure that way.
599
+ if (!fromStore) {
600
+ if (looksLikeAssetPath(ref))
601
+ throw new ContractError('not_found', `asset file not found: ${ref}`);
602
+ throw new ContractError('not_found', `asset not found: ${ref}`);
603
+ }
369
604
  return normalizeAsset(fromStore);
370
605
  }
371
- const readOnly = loadLocalAssetsReadOnly(deps.assetsDir ?? events.assetsDir());
606
+ const assetsDir = contractAssetsDir(deps);
607
+ const readOnly = loadLocalAssetsReadOnly(assetsDir, ref);
372
608
  const found = readOnly.find((asset) => asset.asset_id === ref || stringField(asset, 'id') === ref);
373
- if (!found)
374
- throw new ContractError('schema_invalid', 'asset not found');
609
+ // Name the directory that was searched: the common cause is a store written
610
+ // by an embedder under its own home while the CLI reads the default one, and
611
+ // without the path there is nothing for the user to compare against.
612
+ if (!found) {
613
+ if (looksLikeAssetPath(ref))
614
+ throw new ContractError('not_found', `asset file not found: ${ref}`);
615
+ throw new ContractError('not_found', `asset not found: ${ref} (searched ${assetsDir})`);
616
+ }
375
617
  return normalizeAsset(found);
376
618
  }
377
619
  async function findAssetInStore(ref, store) {
@@ -386,16 +628,19 @@ async function findAssetInStore(ref, store) {
386
628
  }
387
629
  return null;
388
630
  }
389
- function loadLocalAssetsReadOnly(baseDir) {
631
+ function loadLocalAssetsReadOnly(baseDir, targetRef) {
390
632
  return [
391
- ...loadLocalGenesReadOnly(baseDir),
392
- ...readJsonLines(`${baseDir}/capsules.jsonl`, 'Capsule'),
393
- ...readJsonLines(`${baseDir}/events.jsonl`, 'EvolutionEvent'),
633
+ ...loadLocalGenesReadOnly(baseDir, targetRef),
634
+ ...readJsonLines(`${baseDir}/capsules.jsonl`, 'Capsule', targetRef),
635
+ ...readJsonLines(`${baseDir}/events.jsonl`, 'EvolutionEvent', targetRef),
394
636
  ];
395
637
  }
396
- function loadLocalGenesReadOnly(baseDir) {
638
+ function loadLocalGenesReadOnly(baseDir, targetRef) {
397
639
  const byId = new Map();
398
- for (const gene of [...readGenesEnvelopeReadOnly(`${baseDir}/genes.json`), ...readJsonLines(`${baseDir}/genes.jsonl`, 'Gene')]) {
640
+ for (const gene of [
641
+ ...readGenesEnvelopeReadOnly(`${baseDir}/genes.json`),
642
+ ...readJsonLines(`${baseDir}/genes.jsonl`, 'Gene', targetRef),
643
+ ]) {
399
644
  const id = stringField(gene, 'id') ?? gene.asset_id;
400
645
  if (id && !byId.has(id))
401
646
  byId.set(id, gene);
@@ -410,11 +655,15 @@ function readGenesEnvelopeReadOnly(filePath) {
410
655
  const envelopeGenes = isRecord(parsed) && Array.isArray(parsed['genes']) ? parsed['genes'] : [];
411
656
  return envelopeGenes.filter(isRecord).map((gene) => normalizeAsset({ ...gene, type: 'Gene' }));
412
657
  }
413
- catch {
414
- throw new ContractError('schema_invalid', 'asset schema is invalid');
658
+ catch (err) {
659
+ if (err instanceof ContractError)
660
+ throw err;
661
+ if (err instanceof SyntaxError)
662
+ throw new ContractError('schema_invalid', 'asset schema is invalid');
663
+ throw err;
415
664
  }
416
665
  }
417
- function readJsonLines(filePath, type) {
666
+ function readJsonLines(filePath, type, targetRef) {
418
667
  if (!existsSync(filePath))
419
668
  return [];
420
669
  try {
@@ -423,12 +672,24 @@ function readJsonLines(filePath, type) {
423
672
  .map((line) => line.trim())
424
673
  .filter(Boolean)
425
674
  .map((line) => JSON.parse(line))
426
- .filter(isRecord)
427
- .filter((asset) => asset['type'] === type)
675
+ .filter((asset) => {
676
+ if (!isRecord(asset))
677
+ return false;
678
+ if (asset['type'] === type)
679
+ return true;
680
+ if (stringField(asset, 'asset_id') === targetRef || stringField(asset, 'id') === targetRef) {
681
+ throw new ContractError('schema_invalid', 'asset schema is invalid');
682
+ }
683
+ return false;
684
+ })
428
685
  .map(normalizeAsset);
429
686
  }
430
- catch {
431
- throw new ContractError('schema_invalid', 'asset schema is invalid');
687
+ catch (err) {
688
+ if (err instanceof ContractError)
689
+ throw err;
690
+ if (err instanceof SyntaxError)
691
+ throw new ContractError('schema_invalid', 'asset schema is invalid');
692
+ throw err;
432
693
  }
433
694
  }
434
695
  function normalizeAsset(value) {
@@ -486,10 +747,23 @@ function stripPublishMetadata(asset) {
486
747
  return stripHubMetadata(asset);
487
748
  }
488
749
  function storeBaseDir(store, deps) {
489
- return store instanceof assetstore.LocalJsonlProvider ? store.baseDir : deps.assetsDir ?? events.assetsDir();
750
+ return store instanceof assetstore.LocalJsonlProvider ? store.baseDir : contractAssetsDir(deps);
751
+ }
752
+ function contractAssetsDir(deps) {
753
+ return deps.assetsDir ?? events.assetsDir(deps.env ?? process.env);
490
754
  }
491
- function dryRunEnvelope(bundle, credits) {
755
+ function dryRunEnvelope(bundle, credits, blockDetail) {
492
756
  const suppressPayload = bundle.blockReasons.includes('leak_detected');
757
+ // Collect detailed messages for block reasons
758
+ const blockDetails = [];
759
+ if (blockDetail)
760
+ blockDetails.push(blockDetail);
761
+ for (const reason of bundle.blockReasons) {
762
+ const detailMessage = bundle.blockMessages?.[reason];
763
+ if (detailMessage && !blockDetails.includes(detailMessage)) {
764
+ blockDetails.push(detailMessage);
765
+ }
766
+ }
493
767
  return {
494
768
  ok: true,
495
769
  contract: PUBLISH_CONTRACT,
@@ -497,6 +771,7 @@ function dryRunEnvelope(bundle, credits) {
497
771
  reversibility: REVERSIBILITY,
498
772
  blocked: bundle.blockReasons.length > 0,
499
773
  block_reasons: bundle.blockReasons,
774
+ ...(blockDetails.length > 0 ? { block_details: blockDetails } : {}),
500
775
  assets: bundle.assets,
501
776
  ...(suppressPayload ? {} : { payload: { assets: bundle.sanitized } }),
502
777
  gates: bundle.gates,
@@ -510,6 +785,7 @@ function publishFailure(reason, message, opts) {
510
785
  ...(opts.mode ? { mode: opts.mode } : {}),
511
786
  ...(opts.gates ? { gates: opts.gates } : {}),
512
787
  ...(opts.assets ? { assets: opts.assets } : {}),
788
+ ...(opts.detail ? { detail: opts.detail } : {}),
513
789
  ...(opts.credits ? { credits: opts.credits } : {}),
514
790
  reason,
515
791
  retryable: opts.retryable,
@@ -589,13 +865,19 @@ async function withMachineJsonConsole(enabled, deps, fn) {
589
865
  }
590
866
  }
591
867
  function createDefaultTransport(deps) {
592
- const env = deps.env ?? process.env;
593
- loadEnvFileFromEnv(env);
868
+ const env = loadContractEnv(deps);
869
+ const hubMode = configuredHubMode(env);
870
+ if (hubMode === 'private') {
871
+ return createPrivateTransport(env, deps.resolveProxyClient ?? resolveDefaultPrivateProxy);
872
+ }
594
873
  const hubUrl = resolveHubUrl(env);
595
- const evomapDir = resolveAtpHome(env);
596
- const sender = resolveAtpSenderId(env);
597
- const senderId = () => sender ?? env['A2A_NODE_ID']?.trim();
598
- const nodeSecret = env['EVOMAP_NODE_SECRET']?.trim() || env['A2A_NODE_SECRET']?.trim();
874
+ const evomapDir = resolveIdentityHome(env);
875
+ const explicitCredentials = resolveExplicitNodeCredentials(env);
876
+ const { nodeSecret } = explicitCredentials;
877
+ const sender = nodeSecret
878
+ ? explicitCredentials.senderId ?? resolveAtpSenderId(env)
879
+ : resolveAtpSenderId(env);
880
+ const senderId = () => sender;
599
881
  const connected = nodeSecret
600
882
  ? connectPublicHub({ hubUrl, authMode: 'legacy', evomapDir, nodeSecret, senderId })
601
883
  : connectPublicHub({ hubUrl, authMode: 'oauth', evomapDir, senderId });
@@ -625,6 +907,127 @@ function createDefaultTransport(deps) {
625
907
  publish: (bundle) => call('/a2a/publish', 'publish', bundle),
626
908
  };
627
909
  }
910
+ function loadContractEnv(deps) {
911
+ const env = { ...(deps.env ?? process.env) };
912
+ const envFile = loadEnvFileFromEnv(env);
913
+ if (envFile.error)
914
+ throw new Error('failed to load EVOLVER_ENV_FILE');
915
+ return env;
916
+ }
917
+ function preserveInheritedSecrets(runtimeEnv, inheritedEnv) {
918
+ const env = { ...runtimeEnv };
919
+ let index = 0;
920
+ for (const [key, value] of Object.entries(inheritedEnv)) {
921
+ if (!value || value === runtimeEnv[key] || !/SECRET|TOKEN|API[_-]?KEY|PASSWORD|AUTH|CREDENTIAL/i.test(key))
922
+ continue;
923
+ env[`EVOLVER_INHERITED_SECRET_${index++}`] = value;
924
+ }
925
+ return env;
926
+ }
927
+ function configuredHubMode(env) {
928
+ const value = String(env['EVOMAP_HUB_MODE'] ?? 'public').trim().toLowerCase();
929
+ if (value === 'public' || value === 'private')
930
+ return value;
931
+ throw new Error('EVOMAP_HUB_MODE must be public or private');
932
+ }
933
+ function resolveDefaultPrivateProxy(env) {
934
+ return proxyClientFromEnv(env);
935
+ }
936
+ function createPrivateTransport(env, resolveProxy) {
937
+ const proxy = resolveProxy(env);
938
+ if (!proxy)
939
+ throw new Error('private Hub proxy credentials are not configured');
940
+ const privateModeReady = assertPrivateProxyMode(proxy);
941
+ return {
942
+ validationCapabilityOptional: true,
943
+ fetchAssetById: async (assetId) => {
944
+ try {
945
+ await privateModeReady;
946
+ const body = await proxy.fetchAsset({ assetId, expectedHubMode: 'private' });
947
+ return privateProxyAssets(body).find((asset) => (asset.asset_id === assetId || stringField(asset, 'id') === assetId)) ?? null;
948
+ }
949
+ catch (err) {
950
+ if (err instanceof ContractError)
951
+ throw err;
952
+ const message = err instanceof Error ? err.message : String(err);
953
+ if (message === 'proxy_hub_mode_mismatch' || isAuthLikeError(err)) {
954
+ throw new ContractError('auth_required', 'private Hub proxy authentication required');
955
+ }
956
+ throw new ContractError('network_error', 'Hub unreachable');
957
+ }
958
+ },
959
+ validate: async (bundle) => {
960
+ try {
961
+ await privateModeReady;
962
+ const body = await proxy.validateAssetBundle({ assets: [...bundle], expected_hub_mode: 'private' });
963
+ return { ok: hasExplicitValidatePass(body), status: 200, body };
964
+ }
965
+ catch (err) {
966
+ if (err instanceof ContractError)
967
+ throw err;
968
+ return privateProxyFailure(err);
969
+ }
970
+ },
971
+ publish: async (bundle) => {
972
+ try {
973
+ await privateModeReady;
974
+ const body = normalizePrivatePublishBody(await proxy.submitAssetBundle({
975
+ assets: [...bundle],
976
+ expected_hub_mode: 'private',
977
+ }));
978
+ return { ok: !privatePublishExplicitFailure(body) && normalizePublishStatus(body) !== undefined, status: 200, body };
979
+ }
980
+ catch (err) {
981
+ if (err instanceof ContractError)
982
+ throw err;
983
+ return privateProxyFailure(err);
984
+ }
985
+ },
986
+ };
987
+ }
988
+ async function assertPrivateProxyMode(proxy) {
989
+ const status = asRecord(await proxy.status()) ?? {};
990
+ if (status['hub_mode'] !== 'private') {
991
+ throw new ContractError('auth_required', 'private Hub proxy mode mismatch');
992
+ }
993
+ }
994
+ function isValidationCapabilityUnavailable(body) {
995
+ const root = asRecord(body) ?? {};
996
+ const payload = asRecord(root['payload']) ?? {};
997
+ return (root['reason'] ?? payload['reason']) === 'validate_not_configured';
998
+ }
999
+ function privateProxyAssets(body) {
1000
+ const root = asRecord(body) ?? {};
1001
+ const payload = asRecord(root['payload']) ?? {};
1002
+ const rows = Array.isArray(root['assets']) ? root['assets'] : Array.isArray(payload['assets']) ? payload['assets'] : [];
1003
+ return rows.filter((asset) => Boolean(asset && typeof asset === 'object' && !Array.isArray(asset)));
1004
+ }
1005
+ function normalizePrivatePublishBody(body) {
1006
+ const root = asRecord(body);
1007
+ if (!root)
1008
+ return body;
1009
+ const payload = asRecord(root['payload']);
1010
+ if (payload) {
1011
+ return { ...root, payload: normalizePrivatePublishLayer(payload) };
1012
+ }
1013
+ return normalizePrivatePublishLayer(root);
1014
+ }
1015
+ function normalizePrivatePublishLayer(body) {
1016
+ const receiptId = stringField(body, 'receipt_id') ?? stringField(body, 'receiptId');
1017
+ return {
1018
+ ...body,
1019
+ ...(stringField(body, 'status') === 'pending' ? { status: 'queued' } : {}),
1020
+ ...(receiptId ? { receipt_id: receiptId } : {}),
1021
+ };
1022
+ }
1023
+ function privatePublishExplicitFailure(body) {
1024
+ const root = asRecord(body) ?? {};
1025
+ const payload = asRecord(root['payload']) ?? {};
1026
+ return root['ok'] === false || root['stored'] === false || payload['ok'] === false || payload['stored'] === false;
1027
+ }
1028
+ function privateProxyFailure(err) {
1029
+ return { ok: false, status: isAuthLikeError(err) ? 401 : 0 };
1030
+ }
628
1031
  function isAuthLikeError(err) {
629
1032
  const message = err instanceof Error ? err.message : String(err);
630
1033
  return /oauth|login|credential|auth|401|403|node_secret/i.test(message);
@@ -685,7 +1088,9 @@ function publishReasonMessage(reason) {
685
1088
  schema_invalid: 'asset schema is invalid',
686
1089
  bundle_required: 'publish requires a complete asset bundle',
687
1090
  quality_gate_failed: 'Hub quality gate failed',
1091
+ gene_unproven: 'gene has no proven success yet — run it to a successful outcome before publishing',
688
1092
  insufficient_credits: 'insufficient credits',
1093
+ unsafe_validation_command: 'validation command contains unsafe patterns (e.g., node -e, shell metacharacters) blocked by sandbox security policy',
689
1094
  };
690
1095
  return map[reason] ?? map.internal_error;
691
1096
  }
@@ -740,6 +1145,8 @@ export function hasExplicitValidatePass(body) {
740
1145
  function normalizePublishStatus(body) {
741
1146
  const payload = payloadRecord(body);
742
1147
  const status = stringField(payload, 'status');
1148
+ if (status === 'candidate')
1149
+ return 'queued';
743
1150
  if (status === 'queued' || status === 'accepted' || status === 'published')
744
1151
  return status;
745
1152
  if (status)
@@ -757,6 +1164,43 @@ function payloadRecord(body) {
757
1164
  const root = asRecord(body) ?? {};
758
1165
  return asRecord(root['payload']) ?? root;
759
1166
  }
1167
+ // The Hub answers a rejected publish with the SPECIFIC rule that failed
1168
+ // ("gene_validation_required: ..."), which our stable ContractReason enum
1169
+ // necessarily flattens to `quality_gate_failed`. Keeping only the flattened code
1170
+ // leaves every caller — the desktop wizard above all — with a red gate and no
1171
+ // way to act on it, so the detail rides along in a separate additive field.
1172
+ // Capped and control-character-stripped: it is Hub-authored text that ends up in
1173
+ // a machine-readable envelope on stdout.
1174
+ const HUB_DETAIL_MAX_CHARS = 300;
1175
+ function stripControlChars(value) {
1176
+ let out = '';
1177
+ for (const ch of value) {
1178
+ const code = ch.codePointAt(0) ?? 0;
1179
+ out += code < 0x20 || code === 0x7f ? ' ' : ch;
1180
+ }
1181
+ return out;
1182
+ }
1183
+ function hubDetailFromBody(body) {
1184
+ const root = asRecord(body) ?? {};
1185
+ const payload = payloadRecord(body);
1186
+ // Take the first candidate that ISN'T already a stable contract token: those
1187
+ // are what `reason` carries, so emitting one here would repeat the flattened
1188
+ // code this field exists to supplement. The Hub is free to put the token in
1189
+ // `reason` and the rule text in `error` (or the reverse), so order alone
1190
+ // cannot pick the informative one.
1191
+ const raw = [
1192
+ stringField(root, 'error'),
1193
+ stringField(root, 'reason'),
1194
+ stringField(payload, 'error'),
1195
+ stringField(payload, 'reason'),
1196
+ ].find((candidate) => candidate && !isStableContractReason(candidate.trim()));
1197
+ if (!raw)
1198
+ return undefined;
1199
+ const detail = stripControlChars(raw).replace(/\s+/g, ' ').trim();
1200
+ if (!detail)
1201
+ return undefined;
1202
+ return detail.length > HUB_DETAIL_MAX_CHARS ? `${detail.slice(0, HUB_DETAIL_MAX_CHARS)}…` : detail;
1203
+ }
760
1204
  function stableContractReasonFromBody(body) {
761
1205
  const payload = payloadRecord(body);
762
1206
  const reason = stringField(payload, 'reason') ?? stringField(payload, 'error');
@@ -816,6 +1260,12 @@ function looksLikeFile(value) {
816
1260
  return false;
817
1261
  }
818
1262
  }
1263
+ function looksLikeAssetPath(value) {
1264
+ return isAbsolute(value)
1265
+ || /^[A-Za-z]:/.test(value)
1266
+ || /[\\/]/.test(value)
1267
+ || /\.jsonl?$/i.test(value);
1268
+ }
819
1269
  function isRecord(value) {
820
1270
  return Boolean(value && typeof value === 'object' && !Array.isArray(value));
821
1271
  }