@evomap/evolver-cli 2.0.8 → 2.0.15

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.
@@ -1,18 +1,24 @@
1
1
  import { existsSync, readFileSync, statSync } from 'node:fs';
2
- import { isAbsolute, resolve } from 'node:path';
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]',
19
+ 'usage: evolver publish --asset <gene_id_or_path> --asset <capsule_id_or_path> --json [--dry-run] [--repair]',
15
20
  ' evolver publish --gene <id_or_path> --capsule <id_or_path> --json [--dry-run]',
21
+ ' evolver publish --gene <id_or_path> --auto-pair --json [--dry-run]',
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
  }
@@ -167,7 +176,12 @@ export async function runPublishCommand(args, deps = {}) {
167
176
  }
168
177
  const transport = deps.transport ?? createDefaultTransport(runtimeDeps);
169
178
  const validate = deps.validate ?? transport.validate;
170
- const validation = await validate(bundle.sanitized);
179
+ // A field-level refusal is a defect in the RECORD, not a verdict on the work in it. Read the Hub's own
180
+ // `details[]`, mend what is mechanically derivable, and (only when asked) try once more — otherwise the
181
+ // envelope still carries the plan, so the operator can see the asset is salvageable instead of losing it.
182
+ const validationAttempt = await callHubWithRepair(validate, bundle.sanitized, parsed.repair === true);
183
+ const validation = validationAttempt.result;
184
+ let effectiveAssets = validationAttempt.assets;
171
185
  const validationCredits = extractCredits(validation.body);
172
186
  const validationUnavailable = transport.validationCapabilityOptional === true
173
187
  && isValidationCapabilityUnavailable(validation.body);
@@ -187,34 +201,44 @@ export async function runPublishCommand(args, deps = {}) {
187
201
  bundle.gates.quality = 'fail';
188
202
  if (!bundle.blockReasons.includes('quality_gate_failed'))
189
203
  bundle.blockReasons.push('quality_gate_failed');
190
- return write(dryRunEnvelope(bundle, validationCredits, detail), 0);
204
+ return write(dryRunEnvelope(bundle, validationCredits, detail, validationAttempt), 0);
191
205
  }
192
- return write(publishFailure(reason, publishReasonMessage(reason), {
206
+ return write(publishFailure(reason, publishReasonMessage(reason, runtimeDeps.env), {
193
207
  retryable: publishRetryable(reason),
194
208
  mode: parsed.dryRun ? 'dry_run' : 'publish',
195
209
  gates: parsed.dryRun ? bundle.gates : { ...bundle.gates, quality: 'fail' },
196
210
  assets: bundle.assets,
197
211
  ...(detail ? { detail } : {}),
198
212
  ...(validationCredits ? { credits: validationCredits } : {}),
213
+ ...repairEnvelopeField(validationAttempt),
199
214
  }), 1);
200
215
  }
201
216
  if (parsed.dryRun)
202
- return write(dryRunEnvelope(bundle, validationCredits), 0);
217
+ return write(dryRunEnvelope(bundle, validationCredits, undefined, validationAttempt), 0);
203
218
  const publish = deps.publish ?? transport.publish;
204
- const published = await publish(bundle.sanitized);
219
+ const publishAttempt = await callHubWithRepair(publish, effectiveAssets, parsed.repair === true);
220
+ const published = publishAttempt.result;
221
+ effectiveAssets = publishAttempt.assets;
222
+ const repairApplied = mergeRepairAttempts(validationAttempt, publishAttempt);
205
223
  const publishCredits = extractCredits(published.body);
206
224
  if (!published.ok) {
207
225
  const reason = publishReasonFromResponse(published.status, published.body);
208
226
  const detail = hubDetailFromBody(published.body);
209
- return write(publishFailure(reason, publishReasonMessage(reason), {
227
+ return write(publishFailure(reason, publishReasonMessage(reason, runtimeDeps.env), {
210
228
  retryable: publishRetryable(reason),
211
229
  mode: 'publish',
212
230
  gates: bundle.gates,
213
231
  assets: bundle.assets,
214
232
  ...(detail ? { detail } : {}),
215
233
  ...(publishCredits ? { credits: publishCredits } : {}),
234
+ ...repairEnvelopeField(repairApplied),
216
235
  }), 1);
217
236
  }
237
+ // The repaired records are what the network now holds. Persist them so the local library and the Hub do
238
+ // not silently diverge; a storage failure is reported, never fatal — the publish already happened.
239
+ const repairPersisted = repairApplied?.applied === true
240
+ ? await persistRepairedBundle(effectiveAssets, bundle.sanitized, runtimeDeps)
241
+ : undefined;
218
242
  const payload = payloadRecord(published.body);
219
243
  const decision = stringField(payload, 'decision');
220
244
  const hubReason = stringField(payload, 'reason');
@@ -242,7 +266,8 @@ export async function runPublishCommand(args, deps = {}) {
242
266
  }
243
267
  const receiptId = stringField(payload, 'receipt_id');
244
268
  const bundleId = stringField(payload, 'bundle_id');
245
- appendPublishedCapsuleCall(bundle, deps, { status, receiptId, bundleId });
269
+ const publishedBundle = { ...bundle, sanitized: [...effectiveAssets] };
270
+ appendPublishedCapsuleCall(publishedBundle, deps, { status, receiptId, bundleId });
246
271
  return write({
247
272
  ok: true,
248
273
  contract: PUBLISH_CONTRACT,
@@ -252,12 +277,14 @@ export async function runPublishCommand(args, deps = {}) {
252
277
  ...(receiptId ? { receipt_id: receiptId } : {}),
253
278
  ...(bundleId ? { bundle_id: bundleId } : {}),
254
279
  ...(safetyCandidate ? { hub_reason: hubReason } : {}),
255
- assets: bundle.assets,
280
+ // What the Hub actually holds — after a repair that is the mended record, not the one first submitted.
281
+ assets: repairApplied?.applied === true ? summarizePublishAssets(effectiveAssets) : bundle.assets,
256
282
  ...(publishCredits ? { credits: publishCredits } : {}),
283
+ ...repairEnvelopeField(repairApplied, repairPersisted),
257
284
  }, 0);
258
285
  }
259
286
  catch (err) {
260
- const failure = classifyError(err, 'publish');
287
+ const failure = classifyError(err, 'publish', runtimeDeps.env ?? process.env);
261
288
  return write(publishFailure(failure.reason, failure.message, {
262
289
  retryable: failure.retryable,
263
290
  mode: parsed.dryRun ? 'dry_run' : 'publish',
@@ -265,6 +292,78 @@ export async function runPublishCommand(args, deps = {}) {
265
292
  }
266
293
  });
267
294
  }
295
+ async function callHubWithRepair(call, assets, allowRepair) {
296
+ const first = await call(assets);
297
+ if (first.ok)
298
+ return { result: first, assets, applied: false, entries: [] };
299
+ const plan = planBundleRepair(assets, first.body);
300
+ // Retry only when the WHOLE bundle is mended. One unrepairable asset means the Hub will refuse the bundle
301
+ // again for the same reason, and a second refusal costs the operator another paid round-trip for nothing.
302
+ const repairable = plan.entries.some((entry) => entry.repair_status === 'repaired')
303
+ && plan.entries.every((entry) => entry.repair_status !== 'unrepairable');
304
+ if (!repairable || !allowRepair)
305
+ return { result: first, assets, applied: false, entries: plan.entries };
306
+ // Exactly one retry: a Hub that refuses the mended record too is telling us the defect is not mechanical,
307
+ // and a repair loop against a paid endpoint is how you burn credits without converging.
308
+ const retried = await call(plan.assets);
309
+ return { result: retried, assets: plan.assets, applied: true, entries: plan.entries };
310
+ }
311
+ function planBundleRepair(assets, rejectionBody) {
312
+ const hubIssues = assetrepair.hubRejectionIssues(rejectionBody, {
313
+ assetTypes: assets.map((asset) => (typeof asset.type === 'string' ? asset.type : undefined)),
314
+ });
315
+ const bundleIssues = hubIssues.byAssetIndex.get(-1) ?? [];
316
+ const repaired = [];
317
+ const entries = [];
318
+ for (const [index, asset] of assets.entries()) {
319
+ const issues = [...(hubIssues.byAssetIndex.get(index) ?? []), ...bundleIssues];
320
+ const report = assetrepair.repairAssetRecord(asset, { hubIssues: issues });
321
+ repaired.push(report.asset ?? asset);
322
+ entries.push({
323
+ ...(asset.asset_id ? { asset_id: asset.asset_id } : {}),
324
+ ...(report.asset && report.asset.asset_id !== asset.asset_id ? { repaired_asset_id: report.asset.asset_id } : {}),
325
+ repair_status: report.status,
326
+ changes: report.changes.map((change) => `${change.path}: ${change.action}`),
327
+ blockers: report.blockers.map(repairBlockerText),
328
+ });
329
+ }
330
+ return { assets: repaired, entries };
331
+ }
332
+ function repairBlockerText(blocker) {
333
+ return `${blocker.path || '(record)'}: ${stripControlChars(blocker.message).replace(/\s+/g, ' ').trim()}`.slice(0, HUB_DETAIL_MAX_CHARS);
334
+ }
335
+ /** Report the LATER attempt's plan: it is the one describing the bundle that was actually refused last. */
336
+ function mergeRepairAttempts(validation, publish) {
337
+ if (publish.applied || publish.entries.length > 0) {
338
+ return { ...publish, applied: publish.applied || validation.applied };
339
+ }
340
+ return validation.entries.length > 0 || validation.applied ? validation : undefined;
341
+ }
342
+ function repairEnvelopeField(attempt, persisted) {
343
+ if (!attempt || (attempt.entries.length === 0 && !attempt.applied))
344
+ return {};
345
+ return {
346
+ repair: {
347
+ applied: attempt.applied,
348
+ ...(persisted !== undefined ? { persisted } : {}),
349
+ ...(attempt.applied ? {} : { hint: 're-run with --repair to publish the mended record' }),
350
+ assets: attempt.entries,
351
+ },
352
+ };
353
+ }
354
+ async function persistRepairedBundle(published, submitted, deps) {
355
+ const env = deps.env ?? process.env;
356
+ const store = deps.assetStore ?? new assetstore.LocalJsonlProvider(contractAssetsDir(deps));
357
+ // Only the records repair actually changed are new locally; the untouched ones are already stored.
358
+ const changed = published.filter((asset, index) => asset.asset_id !== submitted[index]?.asset_id);
359
+ try {
360
+ const stored = await Promise.all(changed.map((asset) => storeRepairedAsset(asset, store, env)));
361
+ return stored.every(Boolean);
362
+ }
363
+ catch {
364
+ return false;
365
+ }
366
+ }
268
367
  function appendPublishedCapsuleCall(bundle, deps, receipt) {
269
368
  const capsuleIndex = bundle.sanitized.findIndex((asset) => asset.type === 'Capsule');
270
369
  if (capsuleIndex < 0)
@@ -329,7 +428,13 @@ export function parseReuseArgs(args) {
329
428
  }
330
429
  export function parsePublishArgs(args) {
331
430
  const assetRefs = [];
431
+ let geneRef;
432
+ let geneCount = 0;
433
+ let capsuleRef;
434
+ let hasUntypedAsset = false;
435
+ let autoPair = false;
332
436
  let dryRun = false;
437
+ let repair = false;
333
438
  let jsonOut = false;
334
439
  for (let i = 0; i < args.length; i++) {
335
440
  const token = args[i];
@@ -343,34 +448,67 @@ export function parsePublishArgs(args) {
343
448
  jsonOut = true;
344
449
  continue;
345
450
  }
451
+ if (token === '--auto-pair') {
452
+ autoPair = true;
453
+ continue;
454
+ }
455
+ if (token === '--repair') {
456
+ repair = true;
457
+ continue;
458
+ }
346
459
  const equalFlag = [...ASSET_FLAGS].find((flag) => token.startsWith(`${flag}=`));
347
460
  if (equalFlag) {
348
461
  const value = token.slice(equalFlag.length + 1).trim();
349
462
  if (!value)
350
463
  return { ok: false, reason: 'bundle_required', message: `${equalFlag} requires a value` };
351
464
  assetRefs.push(value);
465
+ if (equalFlag === '--gene') {
466
+ geneRef = value;
467
+ geneCount++;
468
+ }
469
+ if (equalFlag === '--capsule')
470
+ capsuleRef = value;
471
+ if (equalFlag === '--asset')
472
+ hasUntypedAsset = true;
352
473
  continue;
353
474
  }
354
475
  if (ASSET_FLAGS.has(token)) {
355
476
  const next = args[i + 1];
356
477
  if (!next || next.startsWith('--'))
357
478
  return { ok: false, reason: 'bundle_required', message: `${token} requires a value` };
358
- assetRefs.push(next.trim());
479
+ const value = next.trim();
480
+ if (!value)
481
+ return { ok: false, reason: 'bundle_required', message: `${token} requires a value` };
482
+ assetRefs.push(value);
483
+ if (token === '--gene') {
484
+ geneRef = value;
485
+ geneCount++;
486
+ }
487
+ if (token === '--capsule')
488
+ capsuleRef = value;
489
+ if (token === '--asset')
490
+ hasUntypedAsset = true;
359
491
  i++;
360
492
  continue;
361
493
  }
362
494
  if (!token.startsWith('--'))
363
- return { ok: false, reason: 'unsupported', message: 'unsupported publish argument' };
364
- return { ok: false, reason: 'unsupported', message: 'unsupported publish flag' };
495
+ return { ok: false, reason: 'unsupported', message: 'unsupported publish argument; did you mean --asset <id|path>?' };
496
+ if (token === '--home' || token.startsWith('--home=') || token === '--evomap-home' || token.startsWith('--evomap-home=')) {
497
+ return { ok: false, reason: 'unsupported', message: 'publish does not accept home flags; set EVOLVER_HOME or EVOMAP_HOME before running evolver publish' };
498
+ }
499
+ return { ok: false, reason: 'unsupported', message: "unsupported publish flag; run 'evolver publish --help'" };
365
500
  }
366
501
  if (!jsonOut)
367
502
  return { ok: false, reason: 'unsupported', message: 'publish requires --json' };
368
- const refs = assetRefs.filter(Boolean);
503
+ if (autoPair && (geneCount !== 1 || !geneRef || capsuleRef || hasUntypedAsset)) {
504
+ return { ok: false, reason: 'bundle_required', message: '--auto-pair requires exactly one explicit --gene and no --asset or --capsule' };
505
+ }
506
+ const refs = assetRefs;
369
507
  if (refs.length === 0)
370
508
  return { ok: false, reason: 'bundle_required', message: 'publish requires --asset <id|path>' };
371
509
  if (refs.length > MAX_ASSETS)
372
510
  return { ok: false, reason: 'bundle_required', message: `publish supports at most ${MAX_ASSETS} assets` };
373
- return { ok: true, assetRefs: refs, dryRun, jsonOut };
511
+ return { ok: true, assetRefs: refs, ...(geneRef ? { geneRef } : {}), ...(autoPair ? { autoPair: true } : {}), dryRun, repair, jsonOut };
374
512
  }
375
513
  export async function buildPublishBundle(refs, deps = {}) {
376
514
  let original;
@@ -578,7 +716,8 @@ function withRecomputedAssetId(asset) {
578
716
  const assetId = wire.computeAssetId(asset);
579
717
  return { ...asset, asset_id: assetId ?? asset.asset_id };
580
718
  }
581
- async function loadAssetRef(ref, deps) {
719
+ /** Resolve `<asset_id|logical_id|path>` the way publish does. Shared so `asset-repair` speaks the same refs. */
720
+ export async function loadAssetRef(ref, deps) {
582
721
  if (looksLikeFile(ref)) {
583
722
  try {
584
723
  return normalizeAsset(JSON.parse(readFileSync(resolve(ref), 'utf8')));
@@ -596,37 +735,96 @@ async function loadAssetRef(ref, deps) {
596
735
  const fromStore = await findAssetInStore(ref, store);
597
736
  // `not_found`, not `schema_invalid`: nothing was located, so no schema was
598
737
  // 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
- }
738
+ if (!fromStore)
739
+ throw new ContractError('not_found', 'asset not found');
604
740
  return normalizeAsset(fromStore);
605
741
  }
606
742
  const assetsDir = contractAssetsDir(deps);
607
743
  const readOnly = loadLocalAssetsReadOnly(assetsDir, ref);
608
- const found = readOnly.find((asset) => asset.asset_id === ref || stringField(asset, 'id') === ref);
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.
744
+ const byAssetId = readOnly.filter((asset) => asset.asset_id === ref);
745
+ if (byAssetId.length > 1)
746
+ throw new ContractError('not_found', 'asset reference is ambiguous');
747
+ let found = byAssetId[0];
612
748
  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})`);
749
+ const exactLogical = readOnly.filter((asset) => stringField(asset, 'id') === ref);
750
+ if (exactLogical.length > 1)
751
+ throw new ContractError('not_found', 'asset reference is ambiguous');
752
+ found = exactLogical[0];
616
753
  }
754
+ if (!found) {
755
+ const fallback = prefixedLogicalRef(ref);
756
+ if (fallback) {
757
+ const matches = readOnly.filter((asset) => asset.type === fallback.kind && stringField(asset, 'id') === fallback.id);
758
+ if (matches.length > 1)
759
+ throw new ContractError('not_found', 'asset reference is ambiguous');
760
+ found = matches[0];
761
+ }
762
+ }
763
+ if (!found)
764
+ throw new ContractError('not_found', 'asset not found');
617
765
  return normalizeAsset(found);
618
766
  }
767
+ function prefixedLogicalRef(ref) {
768
+ const match = /^(gene|capsule):(.+)$/.exec(ref);
769
+ if (!match?.[2])
770
+ return null;
771
+ return { kind: match[1] === 'gene' ? 'Gene' : 'Capsule', id: match[2] };
772
+ }
773
+ async function findLogicalAsset(store, id, kind) {
774
+ if (store.findByLogicalId) {
775
+ const matches = await store.findByLogicalId(id, 2, kind);
776
+ if (matches.length > 1)
777
+ throw new ContractError('not_found', 'asset reference is ambiguous');
778
+ return matches[0] ?? null;
779
+ }
780
+ const scanLimit = 10_000;
781
+ const rows = await store.list(kind, scanLimit + 1);
782
+ if (rows.length > scanLimit)
783
+ throw new ContractError('not_found', 'asset lookup is truncated; use an exact asset_id');
784
+ const matches = rows.filter((asset) => stringField(asset, 'id') === id);
785
+ if (matches.length > 1)
786
+ throw new ContractError('not_found', 'asset reference is ambiguous');
787
+ return matches[0] ?? null;
788
+ }
619
789
  async function findAssetInStore(ref, store) {
620
790
  const byAssetId = await store.get(ref);
621
791
  if (byAssetId)
622
792
  return byAssetId;
623
- for (const kind of ['Gene', 'Capsule', 'EvolutionEvent']) {
624
- const rows = await store.list(kind, 10_000);
625
- const found = rows.find((asset) => stringField(asset, 'id') === ref);
626
- if (found)
627
- return found;
793
+ const exact = await findLogicalAsset(store, ref);
794
+ if (exact)
795
+ return exact;
796
+ const fallback = prefixedLogicalRef(ref);
797
+ return fallback ? findLogicalAsset(store, fallback.id, fallback.kind) : null;
798
+ }
799
+ async function autoPairPublishRefs(refs, geneRef, deps) {
800
+ const store = deps.assetStore ?? new assetstore.LocalJsonlProvider(contractAssetsDir(deps));
801
+ if (!(store instanceof assetstore.LocalJsonlProvider)) {
802
+ throw new ContractError('bundle_required', '--auto-pair requires a local asset store; pass --capsule <id|path> explicitly');
803
+ }
804
+ const gene = await loadAssetRef(geneRef, { ...deps, assetStore: store });
805
+ if (gene.type !== 'Gene')
806
+ throw new ContractError('bundle_required', '--auto-pair requires a Gene reference');
807
+ const geneIds = new Set([gene.asset_id, stringField(gene, 'id')].filter((id) => Boolean(id)));
808
+ const trust = new assetstore.ProvenanceStore(store.baseDir).snapshot();
809
+ const candidates = store.listAll('Capsule').filter((candidate) => {
810
+ if (!geneIds.has(String(candidate['gene'] ?? '')))
811
+ return false;
812
+ const outcome = asRecord(candidate['outcome']);
813
+ if (outcome?.['status'] !== 'success')
814
+ return false;
815
+ if (trust.get(candidate.asset_id)?.trusted === false)
816
+ return false;
817
+ if (!wire.validateWireDeep(candidate).ok)
818
+ return false;
819
+ return wire.verifyAssetId(candidate);
820
+ });
821
+ if (candidates.length === 0) {
822
+ throw new ContractError('bundle_required', 'no eligible successful Capsule found; pass --capsule <id|path> explicitly');
823
+ }
824
+ if (candidates.length > 1) {
825
+ throw new ContractError('bundle_required', 'multiple eligible Capsules found; pass --capsule <id|path> explicitly');
628
826
  }
629
- return null;
827
+ return [...refs, candidates[0].asset_id];
630
828
  }
631
829
  function loadLocalAssetsReadOnly(baseDir, targetRef) {
632
830
  return [
@@ -708,7 +906,7 @@ function checkBundle(bundle) {
708
906
  return { ok: false, message: 'publish supports one Gene + one Capsule + optional one EvolutionEvent bundle' };
709
907
  }
710
908
  if (genes.length === 0 || capsules.length === 0)
711
- return { ok: false, message: 'publish requires Gene + Capsule bundle' };
909
+ return { ok: false, message: BUNDLE_REQUIRED_MESSAGE };
712
910
  const gene = genes[0];
713
911
  const capsule = capsules[0];
714
912
  const geneIds = new Set([gene.asset_id, stringField(gene, 'id')].filter((id) => Boolean(id)));
@@ -752,7 +950,7 @@ function storeBaseDir(store, deps) {
752
950
  function contractAssetsDir(deps) {
753
951
  return deps.assetsDir ?? events.assetsDir(deps.env ?? process.env);
754
952
  }
755
- function dryRunEnvelope(bundle, credits, blockDetail) {
953
+ function dryRunEnvelope(bundle, credits, blockDetail, repairAttempt) {
756
954
  const suppressPayload = bundle.blockReasons.includes('leak_detected');
757
955
  // Collect detailed messages for block reasons
758
956
  const blockDetails = [];
@@ -776,6 +974,7 @@ function dryRunEnvelope(bundle, credits, blockDetail) {
776
974
  ...(suppressPayload ? {} : { payload: { assets: bundle.sanitized } }),
777
975
  gates: bundle.gates,
778
976
  ...(credits ? { credits } : {}),
977
+ ...repairEnvelopeField(repairAttempt),
779
978
  };
780
979
  }
781
980
  function publishFailure(reason, message, opts) {
@@ -787,6 +986,7 @@ function publishFailure(reason, message, opts) {
787
986
  ...(opts.assets ? { assets: opts.assets } : {}),
788
987
  ...(opts.detail ? { detail: opts.detail } : {}),
789
988
  ...(opts.credits ? { credits: opts.credits } : {}),
989
+ ...(opts.repair ? { repair: opts.repair } : {}),
790
990
  reason,
791
991
  retryable: opts.retryable,
792
992
  message,
@@ -1032,20 +1232,28 @@ function isAuthLikeError(err) {
1032
1232
  const message = err instanceof Error ? err.message : String(err);
1033
1233
  return /oauth|login|credential|auth|401|403|node_secret/i.test(message);
1034
1234
  }
1035
- function classifyError(err, command) {
1235
+ function classifyError(err, command, env = {}) {
1036
1236
  if (err instanceof ContractError)
1037
1237
  return { reason: err.reason, message: err.safeMessage, retryable: err.reason === 'network_error' };
1038
1238
  if (err instanceof AuthError)
1039
- return { reason: 'auth_required', message: 'Hub authentication required', retryable: false };
1239
+ return {
1240
+ reason: 'auth_required',
1241
+ message: command === 'publish' ? publishAuthRequiredMessage(env) : 'Hub authentication required',
1242
+ retryable: false,
1243
+ };
1040
1244
  if (err instanceof HubUnreachableError)
1041
1245
  return { reason: 'network_error', message: 'Hub unreachable', retryable: true };
1042
1246
  if (err instanceof HubClientError) {
1043
1247
  const reason = stableContractReasonFromBody(err.body) ?? (command === 'reuse' ? reuseReasonFromStatus(err.status) : publishReasonFromStatus(err.status));
1044
- return { reason, message: command === 'publish' ? publishReasonMessage(reason) : reuseReasonMessage(reason), retryable: publishRetryable(reason) };
1248
+ return { reason, message: command === 'publish' ? publishReasonMessage(reason, env) : reuseReasonMessage(reason), retryable: publishRetryable(reason) };
1045
1249
  }
1046
1250
  const message = err instanceof Error ? err.message : String(err);
1047
1251
  if (/oauth|login|credential|auth|401|403|node_secret/i.test(message))
1048
- return { reason: 'auth_required', message: 'Hub authentication required', retryable: false };
1252
+ return {
1253
+ reason: 'auth_required',
1254
+ message: command === 'publish' ? publishAuthRequiredMessage(env) : 'Hub authentication required',
1255
+ retryable: false,
1256
+ };
1049
1257
  if (/network|fetch failed|ECONN|ENOTFOUND|ETIMEDOUT|hub 5\d\d/i.test(message))
1050
1258
  return { reason: 'network_error', message: 'Hub unreachable', retryable: true };
1051
1259
  return { reason: 'internal_error', message: `evolver ${command} failed`, retryable: false };
@@ -1074,11 +1282,22 @@ function publishReasonFromResponse(status, body) {
1074
1282
  function publishRetryable(reason) {
1075
1283
  return reason === 'network_error';
1076
1284
  }
1077
- function publishReasonMessage(reason) {
1285
+ function publishAuthRequiredMessage(env) {
1286
+ const rawMode = env['EVOMAP_HUB_MODE']?.trim().toLowerCase();
1287
+ if (rawMode && rawMode !== 'public' && rawMode !== 'private') {
1288
+ return 'Hub authentication failed; verify EVOMAP_HUB_MODE and the configured credentials';
1289
+ }
1290
+ if (rawMode === 'private')
1291
+ return PRIVATE_AUTH_REQUIRED_MESSAGE;
1292
+ return resolveExplicitNodeCredentials(env).nodeSecret
1293
+ ? LEGACY_AUTH_REQUIRED_MESSAGE
1294
+ : OAUTH_AUTH_REQUIRED_MESSAGE;
1295
+ }
1296
+ function publishReasonMessage(reason, env = {}) {
1078
1297
  const map = {
1079
1298
  missing_id: 'missing asset id',
1080
1299
  cli_unavailable: 'evolver CLI unavailable',
1081
- auth_required: 'Hub authentication required',
1300
+ auth_required: publishAuthRequiredMessage(env),
1082
1301
  not_found: 'asset not found',
1083
1302
  network_error: 'Hub unreachable',
1084
1303
  unsupported: 'publish unsupported',
@@ -1086,7 +1305,7 @@ function publishReasonMessage(reason) {
1086
1305
  redaction_unavailable: 'redaction unavailable',
1087
1306
  leak_detected: 'leak detected after redaction',
1088
1307
  schema_invalid: 'asset schema is invalid',
1089
- bundle_required: 'publish requires a complete asset bundle',
1308
+ bundle_required: BUNDLE_REQUIRED_MESSAGE,
1090
1309
  quality_gate_failed: 'Hub quality gate failed',
1091
1310
  gene_unproven: 'gene has no proven success yet — run it to a successful outcome before publishing',
1092
1311
  insufficient_credits: 'insufficient credits',
@@ -1260,12 +1479,6 @@ function looksLikeFile(value) {
1260
1479
  return false;
1261
1480
  }
1262
1481
  }
1263
- function looksLikeAssetPath(value) {
1264
- return isAbsolute(value)
1265
- || /^[A-Za-z]:/.test(value)
1266
- || /[\\/]/.test(value)
1267
- || /\.jsonl?$/i.test(value);
1268
- }
1269
1482
  function isRecord(value) {
1270
1483
  return Boolean(value && typeof value === 'object' && !Array.isArray(value));
1271
1484
  }
package/dist/dispatch.js CHANGED
@@ -32,6 +32,7 @@ import { runDashboardCommand } from './dashboard.js';
32
32
  import { runIssueReportCommand } from './issueReport.js';
33
33
  import { runAssetTrustCommand } from './assetTrust.js';
34
34
  import { runAssetHealthCommand } from './assetHealth.js';
35
+ import { runAssetRepairCommand } from './assetRepair.js';
35
36
  import { runV1FetchCompat, runV1RunCompat, runV1SolidifyCompat, runV1WebuiCompat, runV1ExecCompat } from './v1Compat.js';
36
37
  import { runWorkflowCommand } from './workflow.js';
37
38
  import { runMemoryGraphCommand } from './memoryGraphOps.js';
@@ -81,6 +82,7 @@ export const ASYNC_COMMANDS = {
81
82
  'issue-report': runIssueReportCommand,
82
83
  'asset-trust': runAssetTrustCommand,
83
84
  'asset-health': runAssetHealthCommand,
85
+ 'asset-repair': runAssetRepairCommand,
84
86
  proxy: runProxyCommand,
85
87
  run: runV1RunCompat,
86
88
  solidify: runV1SolidifyCompat,
@@ -47,9 +47,24 @@ export function makeDistillDrain(c) {
47
47
  for (const source of sources) {
48
48
  if (drafted >= draftLimit)
49
49
  return { ack: false, drafted };
50
- const candidate = draftGeneCandidate(source.turns, signals.extractSignals(source.turns), source.agent);
51
- if (!candidate)
50
+ const draftedCandidate = draftGeneCandidate(source.turns, signals.extractSignals(source.turns), source.agent);
51
+ if (!draftedCandidate)
52
52
  continue; // too thin to distill
53
+ // Carry producer-resolved task domain into draft signals_match so selection can score domain evidence.
54
+ // Only attach when the source already carries a resolved slug (fail-closed stamp at ingest).
55
+ let candidate = draftedCandidate;
56
+ if (source.taskDomain) {
57
+ try {
58
+ const domainToken = signals.taskDomainSignal(source.taskDomain);
59
+ const existingSignals = candidate.signals_match ?? [];
60
+ if (!existingSignals.includes(domainToken)) {
61
+ candidate = { ...candidate, signals_match: [...existingSignals, domainToken] };
62
+ }
63
+ }
64
+ catch {
65
+ // Invalid slug on the source — leave signals_match untouched (never invent).
66
+ }
67
+ }
53
68
  // Value/novelty gate (#117 improvement 3): drop thin / near-duplicate drafts BEFORE they reach the human
54
69
  // review queue. Ack the material (a deliberate skip, not a failure — nothing to retry).
55
70
  const { admission, existing } = await assessDraftAdmissionFromStore(c.store, candidate);
@@ -14,6 +14,8 @@ interface SnapshotSource {
14
14
  label: string;
15
15
  sessionId?: string;
16
16
  resumeIdentityProvenance?: 'canonical_native_transcript';
17
+ /** Optional resolved task domain slug; omitted for old snapshots / unresolved sources. */
18
+ taskDomain?: string;
17
19
  evidenceSummary: RuntimeSessionEvidenceSummary;
18
20
  turns: SnapshotTurn[];
19
21
  }
@@ -204,11 +204,15 @@ export function buildRuntimeSessionMaterialSnapshot(sources, maxChars = DEFAULT_
204
204
  const safeSessionId = source.sessionId
205
205
  ? snapshotIdentity(source.sessionId, SNAPSHOT_IDENTITY_MAX_CHARS)
206
206
  : '';
207
+ const safeTaskDomain = source.taskDomain
208
+ ? snapshotIdentity(source.taskDomain, SNAPSHOT_AGENT_MAX_CHARS)
209
+ : '';
207
210
  snapshotSources.push({
208
211
  agent: snapshotIdentity(source.agent, SNAPSHOT_AGENT_MAX_CHARS) || 'unknown',
209
212
  label: snapshotIdentity(source.label, SNAPSHOT_IDENTITY_MAX_CHARS) || 'unknown',
210
213
  ...(safeSessionId ? { sessionId: safeSessionId } : {}),
211
214
  ...(source.resumeIdentityProvenance ? { resumeIdentityProvenance: source.resumeIdentityProvenance } : {}),
215
+ ...(safeTaskDomain ? { taskDomain: safeTaskDomain } : {}),
212
216
  evidenceSummary,
213
217
  turns,
214
218
  });
@@ -274,11 +278,15 @@ function sourceFromSnapshot(value) {
274
278
  const resumeIdentityProvenance = value['resumeIdentityProvenance'] === 'canonical_native_transcript'
275
279
  ? value['resumeIdentityProvenance']
276
280
  : undefined;
281
+ const taskDomain = typeof value['taskDomain'] === 'string' && value['taskDomain'].trim()
282
+ ? value['taskDomain'].trim()
283
+ : undefined;
277
284
  return {
278
285
  agent,
279
286
  label,
280
287
  ...(sessionId ? { sessionId } : {}),
281
288
  ...(resumeIdentityProvenance ? { resumeIdentityProvenance } : {}),
289
+ ...(taskDomain ? { taskDomain } : {}),
282
290
  turns,
283
291
  };
284
292
  }
@@ -0,0 +1,2 @@
1
+ import { assetstore } from '@evomap/evolver-core';
2
+ export declare function storeRepairedAsset(asset: assetstore.AssetRecord, store: assetstore.AssetStoreProvider, env: NodeJS.ProcessEnv): Promise<boolean>;
@@ -0,0 +1,12 @@
1
+ // Where a repaired asset lands locally. Shared by `asset-repair --apply` and `publish --repair` so a repair
2
+ // means the same thing on both paths: LOCAL content (it hashes to its own recomputed id), written alongside the
3
+ // original under that id — never over it, and never deleting what it was derived from.
4
+ import { assetstore, events } from '@evomap/evolver-core';
5
+ export async function storeRepairedAsset(asset, store, env) {
6
+ const baseDir = store instanceof assetstore.LocalJsonlProvider ? store.baseDir : events.assetsDir(env);
7
+ const provenance = new assetstore.ProvenanceStore(baseDir);
8
+ // The repaired record keeps the original's logical id on purpose (it is the same asset, mended), so the
9
+ // logical-collision guard has to be told this collision is expected rather than a conflicting write.
10
+ const result = await assetstore.ingestUntrustedConditional(store, provenance, asset, { allowLogicalCollision: true }, 'local');
11
+ return result.status !== 'logical_collision' && result.stored;
12
+ }