@evomap/evolver-cli 2.0.0-beta.19 → 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 (68) hide show
  1. package/dist/antiGeneBenchmark.js +2 -0
  2. package/dist/antiGeneRollout.js +2 -0
  3. package/dist/assetRepair.d.ts +24 -0
  4. package/dist/assetRepair.js +172 -0
  5. package/dist/autoDistillAntiGene.js +7 -5
  6. package/dist/autoDistillLlm.d.ts +20 -0
  7. package/dist/autoDistillLlm.js +77 -15
  8. package/dist/autoexec.d.ts +11 -0
  9. package/dist/autoexec.js +65 -10
  10. package/dist/autoexecConfig.js +2 -1
  11. package/dist/cliContracts.d.ts +10 -0
  12. package/dist/cliContracts.js +407 -81
  13. package/dist/commandCatalog.d.ts +72 -0
  14. package/dist/commandCatalog.js +120 -0
  15. package/dist/cycleConsumer.d.ts +9 -0
  16. package/dist/cycleConsumer.js +14 -3
  17. package/dist/dispatch.d.ts +0 -1
  18. package/dist/dispatch.js +10 -4
  19. package/dist/distillObserver.js +23 -6
  20. package/dist/doctor.d.ts +11 -0
  21. package/dist/doctor.js +81 -6
  22. package/dist/index.d.ts +5 -1
  23. package/dist/index.js +200 -68
  24. package/dist/lifecycle.d.ts +126 -3
  25. package/dist/lifecycle.js +4390 -188
  26. package/dist/lifecycleBootstrapTransaction.d.ts +235 -0
  27. package/dist/lifecycleBootstrapTransaction.js +2182 -0
  28. package/dist/localMemoryGraph.d.ts +90 -3
  29. package/dist/localMemoryGraph.js +2031 -231
  30. package/dist/materialSnapshot.d.ts +2 -0
  31. package/dist/materialSnapshot.js +8 -0
  32. package/dist/memoryGraphOps.d.ts +8 -0
  33. package/dist/memoryGraphOps.js +140 -0
  34. package/dist/migrate/assetFormatMap.d.ts +61 -0
  35. package/dist/migrate/assetFormatMap.js +53 -0
  36. package/dist/migrate/envTranslate.js +2 -0
  37. package/dist/migrate/fieldMap.d.ts +7 -5
  38. package/dist/migrate/fieldMap.js +20 -14
  39. package/dist/migrate/v1Import.d.ts +80 -1
  40. package/dist/migrate/v1Import.js +961 -120
  41. package/dist/modelCompatibility.d.ts +10 -0
  42. package/dist/modelCompatibility.js +296 -0
  43. package/dist/recipe.d.ts +7 -1
  44. package/dist/recipe.js +113 -11
  45. package/dist/repairedAssetStore.d.ts +2 -0
  46. package/dist/repairedAssetStore.js +12 -0
  47. package/dist/reuse.d.ts +4 -1
  48. package/dist/reuse.js +212 -107
  49. package/dist/reviewFilter.d.ts +3 -1
  50. package/dist/reviewFilter.js +3 -1
  51. package/dist/runtimeSessionSource.d.ts +5 -0
  52. package/dist/selectionPolicyConfig.d.ts +8 -0
  53. package/dist/selectionPolicyConfig.js +18 -0
  54. package/dist/semanticIdfConfig.d.ts +2 -0
  55. package/dist/semanticIdfConfig.js +4 -0
  56. package/dist/sessionIngest.d.ts +7 -1
  57. package/dist/sessionIngest.js +25 -1
  58. package/dist/setupHooks.js +12 -6
  59. package/dist/skill2gep.js +57 -6
  60. package/dist/skillDistill.js +1 -0
  61. package/dist/sync.d.ts +1 -1
  62. package/dist/sync.js +761 -174
  63. package/dist/thesis.js +2 -0
  64. package/dist/valueDigest.js +8 -1
  65. package/dist/windowsLegacyTaskCleanup.d.ts +228 -0
  66. package/dist/windowsLegacyTaskCleanup.js +1475 -0
  67. package/dist/workflowRuntime.js +7 -6
  68. package/package.json +7 -7
@@ -1,18 +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, algo, verify } 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
6
  import { loadEnvFileFromEnv, proxyClientFromEnv } from '@evomap/evolver-mcp';
7
7
  import { resolveAtpSenderId } from './atp.js';
8
+ import { storeRepairedAsset } from './repairedAssetStore.js';
8
9
  import { resolveExplicitNodeCredentials, resolveIdentityHome } from './identityHome.js';
9
10
  const REUSE_CONTRACT = 'reuse.v1';
10
11
  const PUBLISH_CONTRACT = 'publish.v1';
11
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>';
12
17
  const MAX_ASSETS = 50;
13
18
  const PUBLISH_USAGE = [
14
- 'usage: evolver publish --asset <gene_id_or_path> --asset <capsule_id_or_path> --json [--dry-run]',
15
- ' 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]',
16
22
  ].join('\n');
17
23
  const ASSET_FLAGS = new Set(['--asset', '--gene', '--capsule', '--event']);
18
24
  const STABLE_CONTRACT_REASONS = new Set([
@@ -140,7 +146,7 @@ export async function runPublishCommand(args, deps = {}) {
140
146
  runtimeDeps = { ...deps, env: preserveInheritedSecrets(runtimeEnv, inheritedEnv) };
141
147
  }
142
148
  catch (err) {
143
- const failure = classifyError(err, 'publish');
149
+ const failure = classifyError(err, 'publish', deps.env ?? process.env);
144
150
  return writeJson(out, publishFailure(failure.reason, failure.message, {
145
151
  retryable: failure.retryable,
146
152
  mode: parsed.dryRun ? 'dry_run' : 'publish',
@@ -149,7 +155,10 @@ export async function runPublishCommand(args, deps = {}) {
149
155
  const write = (value, code) => writeJson(out, value, code, runtimeDeps);
150
156
  return withMachineJsonConsole(Boolean(parsed.jsonOut), runtimeDeps, async () => {
151
157
  try {
152
- const bundle = await buildPublishBundle(assetRefs, runtimeDeps);
158
+ const effectiveRefs = parsed.autoPair
159
+ ? await autoPairPublishRefs(assetRefs, parsed.geneRef, runtimeDeps)
160
+ : assetRefs;
161
+ const bundle = await buildPublishBundle(effectiveRefs, runtimeDeps);
153
162
  if (!bundle.ok) {
154
163
  return write(publishFailure(bundle.reason, bundle.message, { retryable: false, gates: bundle.gates }), 1);
155
164
  }
@@ -165,9 +174,16 @@ export async function runPublishCommand(args, deps = {}) {
165
174
  assets: bundle.assets,
166
175
  }), 1);
167
176
  }
168
- const transport = deps.transport ?? createDefaultTransport(runtimeDeps);
177
+ const transport = deps.transport ?? createDefaultTransport(runtimeDeps, {
178
+ composeRecipe: parsed.noRecipe !== true,
179
+ });
169
180
  const validate = deps.validate ?? transport.validate;
170
- 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;
171
187
  const validationCredits = extractCredits(validation.body);
172
188
  const validationUnavailable = transport.validationCapabilityOptional === true
173
189
  && isValidationCapabilityUnavailable(validation.body);
@@ -187,34 +203,44 @@ export async function runPublishCommand(args, deps = {}) {
187
203
  bundle.gates.quality = 'fail';
188
204
  if (!bundle.blockReasons.includes('quality_gate_failed'))
189
205
  bundle.blockReasons.push('quality_gate_failed');
190
- return write(dryRunEnvelope(bundle, validationCredits, detail), 0);
206
+ return write(dryRunEnvelope(bundle, validationCredits, detail, validationAttempt), 0);
191
207
  }
192
- return write(publishFailure(reason, publishReasonMessage(reason), {
208
+ return write(publishFailure(reason, publishReasonMessage(reason, runtimeDeps.env), {
193
209
  retryable: publishRetryable(reason),
194
210
  mode: parsed.dryRun ? 'dry_run' : 'publish',
195
211
  gates: parsed.dryRun ? bundle.gates : { ...bundle.gates, quality: 'fail' },
196
212
  assets: bundle.assets,
197
213
  ...(detail ? { detail } : {}),
198
214
  ...(validationCredits ? { credits: validationCredits } : {}),
215
+ ...repairEnvelopeField(validationAttempt),
199
216
  }), 1);
200
217
  }
201
218
  if (parsed.dryRun)
202
- return write(dryRunEnvelope(bundle, validationCredits), 0);
219
+ return write(dryRunEnvelope(bundle, validationCredits, undefined, validationAttempt), 0);
203
220
  const publish = deps.publish ?? transport.publish;
204
- 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);
205
225
  const publishCredits = extractCredits(published.body);
206
226
  if (!published.ok) {
207
227
  const reason = publishReasonFromResponse(published.status, published.body);
208
228
  const detail = hubDetailFromBody(published.body);
209
- return write(publishFailure(reason, publishReasonMessage(reason), {
229
+ return write(publishFailure(reason, publishReasonMessage(reason, runtimeDeps.env), {
210
230
  retryable: publishRetryable(reason),
211
231
  mode: 'publish',
212
232
  gates: bundle.gates,
213
233
  assets: bundle.assets,
214
234
  ...(detail ? { detail } : {}),
215
235
  ...(publishCredits ? { credits: publishCredits } : {}),
236
+ ...repairEnvelopeField(repairApplied),
216
237
  }), 1);
217
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;
218
244
  const payload = payloadRecord(published.body);
219
245
  const decision = stringField(payload, 'decision');
220
246
  const hubReason = stringField(payload, 'reason');
@@ -242,7 +268,11 @@ export async function runPublishCommand(args, deps = {}) {
242
268
  }
243
269
  const receiptId = stringField(payload, 'receipt_id');
244
270
  const bundleId = stringField(payload, 'bundle_id');
245
- appendPublishedCapsuleCall(bundle, deps, { status, receiptId, bundleId });
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);
246
276
  return write({
247
277
  ok: true,
248
278
  contract: PUBLISH_CONTRACT,
@@ -251,13 +281,17 @@ export async function runPublishCommand(args, deps = {}) {
251
281
  reversibility: REVERSIBILITY,
252
282
  ...(receiptId ? { receipt_id: receiptId } : {}),
253
283
  ...(bundleId ? { bundle_id: bundleId } : {}),
284
+ ...(recipeId ? { recipe_id: recipeId } : {}),
254
285
  ...(safetyCandidate ? { hub_reason: hubReason } : {}),
255
- assets: bundle.assets,
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,
256
289
  ...(publishCredits ? { credits: publishCredits } : {}),
290
+ ...repairEnvelopeField(repairApplied, repairPersisted),
257
291
  }, 0);
258
292
  }
259
293
  catch (err) {
260
- const failure = classifyError(err, 'publish');
294
+ const failure = classifyError(err, 'publish', runtimeDeps.env ?? process.env);
261
295
  return write(publishFailure(failure.reason, failure.message, {
262
296
  retryable: failure.retryable,
263
297
  mode: parsed.dryRun ? 'dry_run' : 'publish',
@@ -265,6 +299,78 @@ export async function runPublishCommand(args, deps = {}) {
265
299
  }
266
300
  });
267
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
+ }
268
374
  function appendPublishedCapsuleCall(bundle, deps, receipt) {
269
375
  const capsuleIndex = bundle.sanitized.findIndex((asset) => asset.type === 'Capsule');
270
376
  if (capsuleIndex < 0)
@@ -329,7 +435,14 @@ export function parseReuseArgs(args) {
329
435
  }
330
436
  export function parsePublishArgs(args) {
331
437
  const assetRefs = [];
438
+ let geneRef;
439
+ let geneCount = 0;
440
+ let capsuleRef;
441
+ let hasUntypedAsset = false;
442
+ let autoPair = false;
332
443
  let dryRun = false;
444
+ let repair = false;
445
+ let noRecipe = false;
333
446
  let jsonOut = false;
334
447
  for (let i = 0; i < args.length; i++) {
335
448
  const token = args[i];
@@ -343,34 +456,80 @@ export function parsePublishArgs(args) {
343
456
  jsonOut = true;
344
457
  continue;
345
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
+ }
346
471
  const equalFlag = [...ASSET_FLAGS].find((flag) => token.startsWith(`${flag}=`));
347
472
  if (equalFlag) {
348
473
  const value = token.slice(equalFlag.length + 1).trim();
349
474
  if (!value)
350
475
  return { ok: false, reason: 'bundle_required', message: `${equalFlag} requires a value` };
351
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;
352
485
  continue;
353
486
  }
354
487
  if (ASSET_FLAGS.has(token)) {
355
488
  const next = args[i + 1];
356
489
  if (!next || next.startsWith('--'))
357
490
  return { ok: false, reason: 'bundle_required', message: `${token} requires a value` };
358
- 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;
359
503
  i++;
360
504
  continue;
361
505
  }
362
506
  if (!token.startsWith('--'))
363
- return { ok: false, reason: 'unsupported', message: 'unsupported publish argument' };
364
- 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'" };
365
512
  }
366
513
  if (!jsonOut)
367
514
  return { ok: false, reason: 'unsupported', message: 'publish requires --json' };
368
- 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;
369
519
  if (refs.length === 0)
370
520
  return { ok: false, reason: 'bundle_required', message: 'publish requires --asset <id|path>' };
371
521
  if (refs.length > MAX_ASSETS)
372
522
  return { ok: false, reason: 'bundle_required', message: `publish supports at most ${MAX_ASSETS} assets` };
373
- 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
+ };
374
533
  }
375
534
  export async function buildPublishBundle(refs, deps = {}) {
376
535
  let original;
@@ -378,8 +537,18 @@ export async function buildPublishBundle(refs, deps = {}) {
378
537
  original = await Promise.all(refs.map((ref) => loadAssetRef(ref, deps)));
379
538
  }
380
539
  catch (err) {
381
- const reason = err instanceof ContractError ? err.reason : 'schema_invalid';
382
- 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
+ };
383
552
  }
384
553
  const bundleCheck = checkBundle(original);
385
554
  if (!bundleCheck.ok)
@@ -414,6 +583,7 @@ export async function buildPublishBundle(refs, deps = {}) {
414
583
  schema: 'pass',
415
584
  bundle: 'pass',
416
585
  quality: geneProven ? 'pass' : 'fail',
586
+ quality_evidence: geneEvidence?.source ?? 'unavailable',
417
587
  validation_command: validationCommandResult.allowed ? 'pass' : 'fail',
418
588
  };
419
589
  const blockReasons = [];
@@ -438,10 +608,9 @@ export async function buildPublishBundle(refs, deps = {}) {
438
608
  assets: summarizePublishAssets(sanitized),
439
609
  };
440
610
  }
441
- // Assess whether the bundle's Gene has proven success in the local capsule
442
- // history. Fail-open (returns null) when there is no gene id or the store read
443
- // throws — the pre-check only ADDS a local gate; the Hub still gates, so an
444
- // infra hiccup must not block an otherwise-valid publish.
611
+ // 评估 bundle 中 Gene 的成功证据。历史记录来自本地 Capsule store;显式提交的、
612
+ // 通过完整校验的成功 Capsule 也可作为首次发布的 seed。没有 gene id 或 store
613
+ // 读取失败时保持 fail-open,因为这道预检只增加本地门槛,最终质量判定仍由 Hub 负责。
445
614
  async function assessPublishGeneEvidence(original, deps) {
446
615
  const gene = original.find((asset) => asset.type === 'Gene');
447
616
  if (!gene)
@@ -451,6 +620,8 @@ async function assessPublishGeneEvidence(original, deps) {
451
620
  const geneId = businessId ?? assetId;
452
621
  if (!geneId)
453
622
  return null;
623
+ const geneIds = new Set([businessId, assetId].filter((id) => Boolean(id)));
624
+ const hasBundleSeed = hasVerifiedSuccessfulBundleCapsule(original, geneIds);
454
625
  try {
455
626
  const store = deps.assetStore ?? new assetstore.LocalJsonlProvider(contractAssetsDir(deps));
456
627
  const primary = await algo.assessGenePublishEvidence(store, geneId);
@@ -459,28 +630,43 @@ async function assessPublishGeneEvidence(original, deps) {
459
630
  // contain failures under the business id and a success under asset_id, so
460
631
  // both aliases must contribute to the gate rather than only falling back
461
632
  // when the primary alias has no rows at all.
462
- if (assetId && assetId !== geneId) {
463
- const byAssetId = await algo.assessGenePublishEvidence(store, assetId);
464
- const combined = {
465
- success: primary.success + byAssetId.success,
466
- failed: primary.failed + byAssetId.failed,
467
- inert: primary.inert + byAssetId.inert,
468
- total: primary.total + byAssetId.total,
469
- };
470
- const eligible = algo.isGenePublishEligible(combined);
471
- return {
472
- geneId,
473
- ...combined,
474
- eligible,
475
- reason: eligible ? 'eligible' : 'no_proven_success',
476
- };
477
- }
478
- return primary;
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' };
479
645
  }
480
646
  catch {
647
+ // 本地 store 不可用时保持历史 fail-open 行为。显式 Capsule 只有在上面的
648
+ // content hash 和 wire schema 校验都通过后才会计入,非法文件不会变成证据。
649
+ if (hasBundleSeed)
650
+ return { eligible: true, source: 'bundle_seed' };
481
651
  return null;
482
652
  }
483
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
+ }
484
670
  /**
485
671
  * 检查 Gene 资产中的验证命令是否安全。
486
672
  * 只检查 Gene 类型的资产,不影响 Capsule 或 EvolutionEvent。
@@ -568,44 +754,129 @@ function withRecomputedAssetId(asset) {
568
754
  const assetId = wire.computeAssetId(asset);
569
755
  return { ...asset, asset_id: assetId ?? asset.asset_id };
570
756
  }
571
- async function loadAssetRef(ref, deps) {
572
- if (looksLikeFile(ref))
573
- 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
+ }
574
771
  const store = deps.assetStore;
575
772
  if (store) {
576
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.
577
776
  if (!fromStore)
578
- throw new ContractError('schema_invalid', 'asset not found');
777
+ throw new ContractError('not_found', 'asset not found');
579
778
  return normalizeAsset(fromStore);
580
779
  }
581
- const readOnly = loadLocalAssetsReadOnly(contractAssetsDir(deps));
582
- 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
+ }
583
801
  if (!found)
584
- throw new ContractError('schema_invalid', 'asset not found');
802
+ throw new ContractError('not_found', 'asset not found');
585
803
  return normalizeAsset(found);
586
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
+ }
587
827
  async function findAssetInStore(ref, store) {
588
828
  const byAssetId = await store.get(ref);
589
829
  if (byAssetId)
590
830
  return byAssetId;
591
- for (const kind of ['Gene', 'Capsule', 'EvolutionEvent']) {
592
- const rows = await store.list(kind, 10_000);
593
- const found = rows.find((asset) => stringField(asset, 'id') === ref);
594
- if (found)
595
- 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');
841
+ }
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');
596
864
  }
597
- return null;
865
+ return [...refs, candidates[0].asset_id];
598
866
  }
599
- function loadLocalAssetsReadOnly(baseDir) {
867
+ function loadLocalAssetsReadOnly(baseDir, targetRef) {
600
868
  return [
601
- ...loadLocalGenesReadOnly(baseDir),
602
- ...readJsonLines(`${baseDir}/capsules.jsonl`, 'Capsule'),
603
- ...readJsonLines(`${baseDir}/events.jsonl`, 'EvolutionEvent'),
869
+ ...loadLocalGenesReadOnly(baseDir, targetRef),
870
+ ...readJsonLines(`${baseDir}/capsules.jsonl`, 'Capsule', targetRef),
871
+ ...readJsonLines(`${baseDir}/events.jsonl`, 'EvolutionEvent', targetRef),
604
872
  ];
605
873
  }
606
- function loadLocalGenesReadOnly(baseDir) {
874
+ function loadLocalGenesReadOnly(baseDir, targetRef) {
607
875
  const byId = new Map();
608
- for (const gene of [...readGenesEnvelopeReadOnly(`${baseDir}/genes.json`), ...readJsonLines(`${baseDir}/genes.jsonl`, 'Gene')]) {
876
+ for (const gene of [
877
+ ...readGenesEnvelopeReadOnly(`${baseDir}/genes.json`),
878
+ ...readJsonLines(`${baseDir}/genes.jsonl`, 'Gene', targetRef),
879
+ ]) {
609
880
  const id = stringField(gene, 'id') ?? gene.asset_id;
610
881
  if (id && !byId.has(id))
611
882
  byId.set(id, gene);
@@ -620,11 +891,15 @@ function readGenesEnvelopeReadOnly(filePath) {
620
891
  const envelopeGenes = isRecord(parsed) && Array.isArray(parsed['genes']) ? parsed['genes'] : [];
621
892
  return envelopeGenes.filter(isRecord).map((gene) => normalizeAsset({ ...gene, type: 'Gene' }));
622
893
  }
623
- catch {
624
- throw new ContractError('schema_invalid', 'asset schema is invalid');
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;
625
900
  }
626
901
  }
627
- function readJsonLines(filePath, type) {
902
+ function readJsonLines(filePath, type, targetRef) {
628
903
  if (!existsSync(filePath))
629
904
  return [];
630
905
  try {
@@ -633,12 +908,24 @@ function readJsonLines(filePath, type) {
633
908
  .map((line) => line.trim())
634
909
  .filter(Boolean)
635
910
  .map((line) => JSON.parse(line))
636
- .filter(isRecord)
637
- .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
+ })
638
921
  .map(normalizeAsset);
639
922
  }
640
- catch {
641
- 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;
642
929
  }
643
930
  }
644
931
  function normalizeAsset(value) {
@@ -657,7 +944,7 @@ function checkBundle(bundle) {
657
944
  return { ok: false, message: 'publish supports one Gene + one Capsule + optional one EvolutionEvent bundle' };
658
945
  }
659
946
  if (genes.length === 0 || capsules.length === 0)
660
- return { ok: false, message: 'publish requires Gene + Capsule bundle' };
947
+ return { ok: false, message: BUNDLE_REQUIRED_MESSAGE };
661
948
  const gene = genes[0];
662
949
  const capsule = capsules[0];
663
950
  const geneIds = new Set([gene.asset_id, stringField(gene, 'id')].filter((id) => Boolean(id)));
@@ -701,7 +988,7 @@ function storeBaseDir(store, deps) {
701
988
  function contractAssetsDir(deps) {
702
989
  return deps.assetsDir ?? events.assetsDir(deps.env ?? process.env);
703
990
  }
704
- function dryRunEnvelope(bundle, credits, blockDetail) {
991
+ function dryRunEnvelope(bundle, credits, blockDetail, repairAttempt) {
705
992
  const suppressPayload = bundle.blockReasons.includes('leak_detected');
706
993
  // Collect detailed messages for block reasons
707
994
  const blockDetails = [];
@@ -725,6 +1012,7 @@ function dryRunEnvelope(bundle, credits, blockDetail) {
725
1012
  ...(suppressPayload ? {} : { payload: { assets: bundle.sanitized } }),
726
1013
  gates: bundle.gates,
727
1014
  ...(credits ? { credits } : {}),
1015
+ ...repairEnvelopeField(repairAttempt),
728
1016
  };
729
1017
  }
730
1018
  function publishFailure(reason, message, opts) {
@@ -736,6 +1024,7 @@ function publishFailure(reason, message, opts) {
736
1024
  ...(opts.assets ? { assets: opts.assets } : {}),
737
1025
  ...(opts.detail ? { detail: opts.detail } : {}),
738
1026
  ...(opts.credits ? { credits: opts.credits } : {}),
1027
+ ...(opts.repair ? { repair: opts.repair } : {}),
739
1028
  reason,
740
1029
  retryable: opts.retryable,
741
1030
  message,
@@ -813,11 +1102,25 @@ async function withMachineJsonConsole(enabled, deps, fn) {
813
1102
  machineJsonStdoutBypass = previousBypass;
814
1103
  }
815
1104
  }
816
- function createDefaultTransport(deps) {
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 = {}) {
817
1120
  const env = loadContractEnv(deps);
818
1121
  const hubMode = configuredHubMode(env);
819
1122
  if (hubMode === 'private') {
820
- return createPrivateTransport(env, deps.resolveProxyClient ?? resolveDefaultPrivateProxy);
1123
+ return createPrivateTransport(env, deps.resolveProxyClient ?? resolveDefaultPrivateProxy, opts.composeRecipe !== false);
821
1124
  }
822
1125
  const hubUrl = resolveHubUrl(env);
823
1126
  const evomapDir = resolveIdentityHome(env);
@@ -854,6 +1157,9 @@ function createDefaultTransport(deps) {
854
1157
  fetchAssetById: (assetId) => connected.hub.fetchAssetById(assetId),
855
1158
  validate: (bundle) => call('/a2a/validate', 'validate', bundle),
856
1159
  publish: (bundle) => call('/a2a/publish', 'publish', bundle),
1160
+ ...(opts.composeRecipe === false ? {} : {
1161
+ composeRecipe: (payload) => hub.composeRecipeAfterAssetPublish(connected.hub, payload),
1162
+ }),
857
1163
  };
858
1164
  }
859
1165
  function loadContractEnv(deps) {
@@ -882,7 +1188,7 @@ function configuredHubMode(env) {
882
1188
  function resolveDefaultPrivateProxy(env) {
883
1189
  return proxyClientFromEnv(env);
884
1190
  }
885
- function createPrivateTransport(env, resolveProxy) {
1191
+ function createPrivateTransport(env, resolveProxy, composeRecipe = true) {
886
1192
  const proxy = resolveProxy(env);
887
1193
  if (!proxy)
888
1194
  throw new Error('private Hub proxy credentials are not configured');
@@ -923,6 +1229,7 @@ function createPrivateTransport(env, resolveProxy) {
923
1229
  const body = normalizePrivatePublishBody(await proxy.submitAssetBundle({
924
1230
  assets: [...bundle],
925
1231
  expected_hub_mode: 'private',
1232
+ ...(composeRecipe ? {} : { compose_recipe: false }),
926
1233
  }));
927
1234
  return { ok: !privatePublishExplicitFailure(body) && normalizePublishStatus(body) !== undefined, status: 200, body };
928
1235
  }
@@ -981,20 +1288,28 @@ function isAuthLikeError(err) {
981
1288
  const message = err instanceof Error ? err.message : String(err);
982
1289
  return /oauth|login|credential|auth|401|403|node_secret/i.test(message);
983
1290
  }
984
- function classifyError(err, command) {
1291
+ function classifyError(err, command, env = {}) {
985
1292
  if (err instanceof ContractError)
986
1293
  return { reason: err.reason, message: err.safeMessage, retryable: err.reason === 'network_error' };
987
1294
  if (err instanceof AuthError)
988
- 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
+ };
989
1300
  if (err instanceof HubUnreachableError)
990
1301
  return { reason: 'network_error', message: 'Hub unreachable', retryable: true };
991
1302
  if (err instanceof HubClientError) {
992
1303
  const reason = stableContractReasonFromBody(err.body) ?? (command === 'reuse' ? reuseReasonFromStatus(err.status) : publishReasonFromStatus(err.status));
993
- 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) };
994
1305
  }
995
1306
  const message = err instanceof Error ? err.message : String(err);
996
1307
  if (/oauth|login|credential|auth|401|403|node_secret/i.test(message))
997
- 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
+ };
998
1313
  if (/network|fetch failed|ECONN|ENOTFOUND|ETIMEDOUT|hub 5\d\d/i.test(message))
999
1314
  return { reason: 'network_error', message: 'Hub unreachable', retryable: true };
1000
1315
  return { reason: 'internal_error', message: `evolver ${command} failed`, retryable: false };
@@ -1023,11 +1338,22 @@ function publishReasonFromResponse(status, body) {
1023
1338
  function publishRetryable(reason) {
1024
1339
  return reason === 'network_error';
1025
1340
  }
1026
- 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 = {}) {
1027
1353
  const map = {
1028
1354
  missing_id: 'missing asset id',
1029
1355
  cli_unavailable: 'evolver CLI unavailable',
1030
- auth_required: 'Hub authentication required',
1356
+ auth_required: publishAuthRequiredMessage(env),
1031
1357
  not_found: 'asset not found',
1032
1358
  network_error: 'Hub unreachable',
1033
1359
  unsupported: 'publish unsupported',
@@ -1035,7 +1361,7 @@ function publishReasonMessage(reason) {
1035
1361
  redaction_unavailable: 'redaction unavailable',
1036
1362
  leak_detected: 'leak detected after redaction',
1037
1363
  schema_invalid: 'asset schema is invalid',
1038
- bundle_required: 'publish requires a complete asset bundle',
1364
+ bundle_required: BUNDLE_REQUIRED_MESSAGE,
1039
1365
  quality_gate_failed: 'Hub quality gate failed',
1040
1366
  gene_unproven: 'gene has no proven success yet — run it to a successful outcome before publishing',
1041
1367
  insufficient_credits: 'insufficient credits',