@evomap/evolver-cli 2.0.8 → 2.0.12

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.
@@ -0,0 +1,24 @@
1
+ import { assetstore } from '@evomap/evolver-core';
2
+ import { type CliContractDeps } from './cliContracts.js';
3
+ export interface AssetRepairDeps extends CliContractDeps {
4
+ stdout?: (line: string) => void;
5
+ stderr?: (line: string) => void;
6
+ store?: assetstore.AssetStoreProvider;
7
+ readRejection?: (path: string) => string;
8
+ }
9
+ interface ParsedArgs {
10
+ refs: string[];
11
+ rejectionPath?: string;
12
+ apply: boolean;
13
+ jsonOut: boolean;
14
+ }
15
+ export declare function runAssetRepairCommand(argv: readonly string[], deps?: AssetRepairDeps): Promise<number>;
16
+ export declare function parseAssetRepairArgs(argv: readonly string[]): {
17
+ ok: true;
18
+ value: ParsedArgs;
19
+ } | {
20
+ ok: false;
21
+ error: string;
22
+ value?: ParsedArgs;
23
+ };
24
+ export {};
@@ -0,0 +1,164 @@
1
+ // `evolver asset-repair --asset <id|path> [--rejection <file|->] [--apply] --json`
2
+ //
3
+ // An asset the network refuses is not automatically a bad asset: the Hub rejects field-by-field (missing
4
+ // `asset_id`, a key its envelope does not allow), and its own deliveries come back stripped of fields the GEP
5
+ // schema requires. Before this command the only options were "publish failed, good luck" and "asset discarded",
6
+ // so distilled work was lost to defects that are mechanically fixable.
7
+ //
8
+ // This command reads the refusal — the local schema gate, plus the Hub's own `details[]` when the operator
9
+ // feeds the rejection body back in — and reports exactly what it can fix and what it cannot. `--apply` writes
10
+ // the repaired record into the local recall library under its recomputed content id; the original is left
11
+ // untouched, so a repair is additive and the operator can still publish either one.
12
+ import { readFileSync } from 'node:fs';
13
+ import { resolve } from 'node:path';
14
+ import { assetrepair, assetstore, events } from '@evomap/evolver-core';
15
+ import { loadEnvFileFromEnv } from '@evomap/evolver-mcp';
16
+ import { loadAssetRef } from './cliContracts.js';
17
+ import { storeRepairedAsset } from './repairedAssetStore.js';
18
+ const CONTRACT = 'asset_repair.v1';
19
+ const ASSET_REPAIR_USAGE = [
20
+ 'usage: evolver asset-repair --asset <id|path> [--asset <id|path>] --json [--rejection <file|->] [--apply]',
21
+ ].join('\n');
22
+ export async function runAssetRepairCommand(argv, deps = {}) {
23
+ const stdout = deps.stdout ?? ((line) => { process.stdout.write(`${line}\n`); });
24
+ const stderr = deps.stderr ?? ((line) => { process.stderr.write(`${line}\n`); });
25
+ if (argv.includes('--help') || argv.includes('-h')) {
26
+ stdout(ASSET_REPAIR_USAGE);
27
+ return 0;
28
+ }
29
+ const parsed = parseAssetRepairArgs(argv);
30
+ if (!parsed.ok)
31
+ return emit({ status: 'invalid_arg', message: parsed.error, assets: [] }, parsed.value?.jsonOut ?? argv.includes('--json'), stdout, stderr);
32
+ const { refs, rejectionPath, apply, jsonOut } = parsed.value;
33
+ const env = deps.env ?? process.env;
34
+ loadEnvFileFromEnv(env);
35
+ let hubIssuesByIndex;
36
+ try {
37
+ hubIssuesByIndex = rejectionPath === undefined
38
+ ? new Map()
39
+ : assetrepair.hubRejectionIssues(JSON.parse(readRejectionBody(rejectionPath, deps))).byAssetIndex;
40
+ }
41
+ catch {
42
+ return emit({ status: 'invalid_arg', message: 'rejection body is not readable JSON', assets: [] }, jsonOut, stdout, stderr);
43
+ }
44
+ const store = deps.store ?? new assetstore.LocalJsonlProvider(events.assetsDir(env));
45
+ const outcomes = [];
46
+ for (const [index, ref] of refs.entries()) {
47
+ try {
48
+ outcomes.push(await repairOne(ref, index, { deps, env, store, apply, hubIssuesByIndex }));
49
+ }
50
+ catch {
51
+ // Ref resolution is the only failure mode here, and its message is caller-controlled text — report the
52
+ // ref we were given, never the underlying error string.
53
+ outcomes.push({ ref, repair_status: 'not_found', changes: [], blockers: [] });
54
+ }
55
+ }
56
+ const status = outcomes.some((outcome) => outcome.repair_status === 'not_found')
57
+ ? 'not_found'
58
+ : outcomes.some((outcome) => outcome.repair_status === 'unrepairable')
59
+ ? 'unrepairable'
60
+ : 'ok';
61
+ return emit({ status, message: summaryMessage(status, apply), assets: outcomes }, jsonOut, stdout, stderr);
62
+ }
63
+ async function repairOne(ref, index, ctx) {
64
+ const original = await loadAssetRef(ref, { ...ctx.deps, env: ctx.env });
65
+ const hubIssues = [...(ctx.hubIssuesByIndex.get(index) ?? []), ...(ctx.hubIssuesByIndex.get(-1) ?? [])];
66
+ const report = assetrepair.repairAssetRecord(original, { hubIssues });
67
+ const base = {
68
+ ref,
69
+ repair_status: report.status,
70
+ ...(original.asset_id ? { asset_id: original.asset_id } : {}),
71
+ changes: report.changes,
72
+ blockers: report.blockers,
73
+ };
74
+ if (report.status !== 'repaired' || !report.asset)
75
+ return base;
76
+ const repairedAssetId = report.asset.asset_id;
77
+ if (!ctx.apply)
78
+ return { ...base, repaired_asset_id: repairedAssetId, stored: false };
79
+ const stored = await storeRepairedAsset(report.asset, ctx.store, ctx.env);
80
+ return { ...base, repaired_asset_id: repairedAssetId, stored };
81
+ }
82
+ export function parseAssetRepairArgs(argv) {
83
+ const refs = [];
84
+ let rejectionPath;
85
+ let apply = false;
86
+ let jsonOut = false;
87
+ for (let i = 0; i < argv.length; i += 1) {
88
+ const token = argv[i];
89
+ if (token === undefined)
90
+ continue;
91
+ if (token === '--json') {
92
+ jsonOut = true;
93
+ continue;
94
+ }
95
+ if (token === '--apply') {
96
+ apply = true;
97
+ continue;
98
+ }
99
+ const valued = valueOf(token, argv, i);
100
+ if (valued?.flag === '--asset') {
101
+ refs.push(valued.value);
102
+ i += valued.consumed;
103
+ continue;
104
+ }
105
+ if (valued?.flag === '--rejection') {
106
+ rejectionPath = valued.value;
107
+ i += valued.consumed;
108
+ continue;
109
+ }
110
+ if (token === '--asset' || token === '--rejection')
111
+ return { ok: false, error: `${token} requires a value` };
112
+ return { ok: false, error: 'unsupported asset-repair argument' };
113
+ }
114
+ if (!jsonOut)
115
+ return { ok: false, error: 'asset-repair requires --json' };
116
+ if (refs.length === 0)
117
+ return { ok: false, error: 'asset-repair requires --asset <id|path>', value: { refs, apply, jsonOut } };
118
+ return { ok: true, value: { refs, ...(rejectionPath !== undefined ? { rejectionPath } : {}), apply, jsonOut } };
119
+ }
120
+ function valueOf(token, argv, index) {
121
+ for (const flag of ['--asset', '--rejection']) {
122
+ if (token.startsWith(`${flag}=`)) {
123
+ const value = token.slice(flag.length + 1).trim();
124
+ return value ? { flag, value, consumed: 0 } : undefined;
125
+ }
126
+ if (token === flag) {
127
+ const next = argv[index + 1]?.trim();
128
+ return next && !next.startsWith('--') ? { flag, value: next, consumed: 1 } : undefined;
129
+ }
130
+ }
131
+ return undefined;
132
+ }
133
+ function readRejectionBody(path, deps) {
134
+ if (deps.readRejection)
135
+ return deps.readRejection(path);
136
+ return readFileSync(path === '-' ? 0 : resolve(path), 'utf8');
137
+ }
138
+ function summaryMessage(status, apply) {
139
+ if (status === 'not_found')
140
+ return 'one or more asset references could not be resolved';
141
+ if (status === 'unrepairable')
142
+ return 'one or more assets need fields that cannot be derived; see blockers';
143
+ return apply ? 'repaired assets written to the local recall library' : 'repair plan only; re-run with --apply to write it';
144
+ }
145
+ function emit(result, jsonOut, stdout, stderr) {
146
+ const ok = result.status === 'ok';
147
+ if (jsonOut) {
148
+ stdout(JSON.stringify({ ok, contract: CONTRACT, status: result.status, message: result.message, assets: result.assets }));
149
+ return ok ? 0 : 1;
150
+ }
151
+ for (const asset of result.assets) {
152
+ const detail = asset.repair_status === 'repaired'
153
+ ? `${asset.changes.length} change(s)${asset.repaired_asset_id ? ` → ${asset.repaired_asset_id}` : ''}`
154
+ : asset.repair_status === 'unrepairable'
155
+ ? `blocked on ${asset.blockers.map((blocker) => blocker.path).join(', ')}`
156
+ : asset.repair_status;
157
+ stdout(`asset-repair ${asset.ref}: ${detail}`);
158
+ }
159
+ if (ok)
160
+ stdout(`asset-repair: ${result.message}`);
161
+ else
162
+ stderr(`asset-repair failed (${result.status}): ${result.message}`);
163
+ return ok ? 0 : 1;
164
+ }
@@ -62,6 +62,26 @@ export declare function p3Decide(mode: Exclude<AutoDistillLlmMode, 'off'>, rec:
62
62
  cooldownMs?: number;
63
63
  maxAttempts?: number;
64
64
  }): 'spawn' | 'enforced_idempotent_skip' | 'shadow_idempotent_skip' | 'failed_exhausted' | 'p3_cooldown';
65
+ /**
66
+ * Resolve a distilled candidate's hard scope facets against the vocabulary the existing genes actually declare.
67
+ *
68
+ * This closes the failure the autonomous-scope experiment isolated (bench/thesis/result-recovery-autoscope-joint-metric.json):
69
+ * a distiller told that `required:<tag>` is a hard facet chose one in 5/5 runs and aimed it at the right dimension, but
70
+ * wrote `required:v2` where the live signal is `rounding-v2`. A facet is matched against live signals, so it never
71
+ * matched and the asset was never eligible anywhere. The distiller cannot be blamed for that: it reads solved code and
72
+ * never observes the retrieval vocabulary. Here the substrate supplies what it cannot see.
73
+ *
74
+ * Conservative by construction: only an exact hit or a single unambiguous qualifier relation is rewritten. Ambiguous
75
+ * and unknown tags are left EXACTLY as the distiller wrote them, because silently retargeting a scope key on a weak
76
+ * similarity would be a worse governance failure than an unmatched facet — scope decides what enters agent context.
77
+ */
78
+ export declare function resolveCandidateScopeFacets(candidate: algo.GeneCandidate, existingGenes: readonly assetstore.AssetRecord[]): {
79
+ candidate: algo.GeneCandidate;
80
+ rewrites: Array<{
81
+ from: string;
82
+ to: string;
83
+ }>;
84
+ };
65
85
  export declare function parseDistillOutput(stdout: string): unknown | null;
66
86
  export declare function asGeneCandidate(value: unknown): algo.GeneCandidate | null;
67
87
  export declare function jaccardDuplicate(candidate: algo.GeneCandidate, existing: readonly algo.ExistingGeneRef[], threshold?: number): string | null;
@@ -2,7 +2,7 @@ import { createHash, randomUUID } from 'node:crypto';
2
2
  import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';
3
3
  import { tmpdir } from 'node:os';
4
4
  import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
5
- import { algo, assetstore, events, exec, hub, verify } from '@evomap/evolver-core';
5
+ import { algo, assetstore, events, exec, hub, signals, verify } from '@evomap/evolver-core';
6
6
  import { runRequiredSandboxedValidation } from './requiredSandboxValidation.js';
7
7
  const DEFAULT_MIN_CAPSULES = 10;
8
8
  const DEFAULT_MAX_CAPSULES = 24;
@@ -99,6 +99,37 @@ function normalizedSignals(record) {
99
99
  const raw = record['signals_match'];
100
100
  return Array.isArray(raw) ? raw.map(String).filter(Boolean) : [];
101
101
  }
102
+ /**
103
+ * Resolve a distilled candidate's hard scope facets against the vocabulary the existing genes actually declare.
104
+ *
105
+ * This closes the failure the autonomous-scope experiment isolated (bench/thesis/result-recovery-autoscope-joint-metric.json):
106
+ * a distiller told that `required:<tag>` is a hard facet chose one in 5/5 runs and aimed it at the right dimension, but
107
+ * wrote `required:v2` where the live signal is `rounding-v2`. A facet is matched against live signals, so it never
108
+ * matched and the asset was never eligible anywhere. The distiller cannot be blamed for that: it reads solved code and
109
+ * never observes the retrieval vocabulary. Here the substrate supplies what it cannot see.
110
+ *
111
+ * Conservative by construction: only an exact hit or a single unambiguous qualifier relation is rewritten. Ambiguous
112
+ * and unknown tags are left EXACTLY as the distiller wrote them, because silently retargeting a scope key on a weak
113
+ * similarity would be a worse governance failure than an unmatched facet — scope decides what enters agent context.
114
+ */
115
+ export function resolveCandidateScopeFacets(candidate, existingGenes) {
116
+ const tags = candidate.signals_match?.map(String) ?? [];
117
+ if (tags.length === 0 || existingGenes.length === 0)
118
+ return { candidate, rewrites: [] };
119
+ const vocab = signals.scopeVocabularyFromRecords(existingGenes);
120
+ const rewrites = [];
121
+ const next = tags.map((tag) => {
122
+ if (!tag.startsWith('required:'))
123
+ return tag;
124
+ const r = signals.resolveScopeTag(tag, vocab);
125
+ if (r.status !== 'resolved')
126
+ return tag;
127
+ const to = `required:${r.resolved}`;
128
+ rewrites.push({ from: tag, to });
129
+ return to;
130
+ });
131
+ return rewrites.length > 0 ? { candidate: { ...candidate, signals_match: next }, rewrites } : { candidate, rewrites: [] };
132
+ }
102
133
  function existingGeneRefs(records) {
103
134
  return records.map((record) => ({
104
135
  id: typeof record['id'] === 'string' ? record['id'] : undefined,
@@ -144,6 +175,15 @@ function buildDistillPrompt(input) {
144
175
  signals_match: gene['signals_match'],
145
176
  summary: gene['summary'],
146
177
  })));
178
+ // Scope-language alignment (review ②): show the model the signals the store ACTUALLY uses BEFORE it chooses a
179
+ // scope facet. The autonomous-scope experiment (result-recovery-autoscope-joint-metric.json) isolated the
180
+ // failure as structural, not a model weakness — the distiller reads solved source code and never observes the
181
+ // retrieval vocabulary its consumers present, so it wrote `required:v2` where the live signal was `rounding-v2`
182
+ // and the asset matched nothing. `resolveCandidateScopeFacets` corrects that post-hoc only for the single
183
+ // unambiguous qualifier relation; surfacing the real vocabulary up front lets the model pick a signal that
184
+ // EXISTS in the first place, covering the ambiguous/unknown cases the post-hoc rewrite deliberately refuses to
185
+ // guess. Descriptive, not prescriptive: it does not forbid a genuinely new signal, only makes the real ones visible.
186
+ const vocab = signals.scopeVocabularyFromRecords(input.existingGenes);
147
187
  return [
148
188
  'You are synthesizing one high-quality EvoMap Gene from recurring successful Capsules.',
149
189
  'Return only JSON. Do not use markdown. Do not include commentary.',
@@ -154,11 +194,19 @@ function buildDistillPrompt(input) {
154
194
  '- Strategy steps must be concrete, defensive, and reusable.',
155
195
  '- Validation must be light. Prefer ["node --version"]. Do not use test suites, node --test, jest, mocha, or node -e.',
156
196
  '- Avoid duplicating existing genes.',
197
+ // Scope facets are matched against LIVE retrieval signals, so a facet naming a signal that does not exist is
198
+ // dead on arrival. Reuse a signal from OBSERVED_SIGNALS below when it names the scope you mean; only invent a
199
+ // new signal for a genuinely new scope dimension. For a hard scope facet write `required:<signal>` using the
200
+ // EXACT signal string as it appears there (e.g. `required:rounding-v2`, never a bare qualifier like `required:v2`).
201
+ '- Scope signals must name signals that exist: reuse an OBSERVED_SIGNALS entry verbatim unless the scope is genuinely new.',
157
202
  '',
158
203
  'Required JSON shape:',
159
204
  '{"type":"Gene","id":"gene_distilled_<descriptive-kebab-name>","summary":"...","category":"repair|optimize|innovate|explore","signals_match":["signal"],"preconditions":["condition"],"strategy":["step"],"constraints":{"max_files":3,"forbidden_paths":[".git","node_modules"]},"validation":["node --version"]}',
160
205
  '',
161
206
  `DATA_HASH: ${input.dataHash}`,
207
+ 'OBSERVED_SIGNALS (signal (asset_count), most-used first — reuse these exact strings for scope):',
208
+ signals.renderScopeVocabulary(vocab),
209
+ '',
162
210
  'SUCCESS_CAPSULES:',
163
211
  JSON.stringify(capsules, null, 2),
164
212
  '',
@@ -509,7 +557,13 @@ export async function autoDistillLlm(options) {
509
557
  return { ok: false, mode, reason: 'no_gene_in_response', dataHash: input.dataHash };
510
558
  }
511
559
  const existing = existingGeneRefs(input.existingGenes);
512
- const normalized = normalizeValidation(candidate0, cwd).candidate;
560
+ // Resolve hard scope facets against the observed vocabulary BEFORE dedup/intake, so a near-miss facet
561
+ // (`required:v2` for a store that declares `rounding-v2`) becomes eligible instead of silently unmatched.
562
+ const scoped = resolveCandidateScopeFacets(candidate0, input.existingGenes);
563
+ if (scoped.rewrites.length > 0) {
564
+ console.warn(`[AutoDistill] resolved scope facet(s) against store vocabulary: ${scoped.rewrites.map((r) => `${r.from} -> ${r.to}`).join(', ')}`);
565
+ }
566
+ const normalized = normalizeValidation(scoped.candidate, cwd).candidate;
513
567
  const duplicate = jaccardDuplicate(normalized, existing, envFloat(env, 'EVOLVER_AUTO_DISTILL_LLM_DUP_JACCARD', DEFAULT_DUP_JACCARD));
514
568
  if (duplicate) {
515
569
  patchState(statePath, input.dataHash, { failed_attempts_inc: true }, hashCap);
@@ -13,7 +13,10 @@ export interface ReuseParseResult {
13
13
  export interface PublishParseResult {
14
14
  ok: boolean;
15
15
  assetRefs?: string[];
16
+ geneRef?: string;
17
+ autoPair?: boolean;
16
18
  dryRun?: boolean;
19
+ repair?: boolean;
17
20
  jsonOut?: boolean;
18
21
  reason?: ContractReason;
19
22
  message?: string;
@@ -88,6 +91,8 @@ export declare function runPublishCommand(args: readonly string[], deps?: CliCon
88
91
  export declare function parseReuseArgs(args: readonly string[]): ReuseParseResult;
89
92
  export declare function parsePublishArgs(args: readonly string[]): PublishParseResult;
90
93
  export declare function buildPublishBundle(refs: readonly string[], deps?: CliContractDeps): Promise<PublishBundleResult>;
94
+ /** Resolve `<asset_id|logical_id|path>` the way publish does. Shared so `asset-repair` speaks the same refs. */
95
+ export declare function loadAssetRef(ref: string, deps: CliContractDeps): Promise<assetstore.AssetRecord>;
91
96
  export declare function hasExplicitValidatePass(body: unknown): boolean;
92
97
  export declare function _inspectCliContractsForTest(value: unknown): string;
93
98
  export {};
@@ -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);
@@ -189,32 +203,42 @@ export async function runPublishCommand(args, deps = {}) {
189
203
  bundle.blockReasons.push('quality_gate_failed');
190
204
  return write(dryRunEnvelope(bundle, validationCredits, detail), 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,76 @@ 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
+ const bundleIssues = hubIssues.byAssetIndex.get(-1) ?? [];
314
+ const repaired = [];
315
+ const entries = [];
316
+ for (const [index, asset] of assets.entries()) {
317
+ const issues = [...(hubIssues.byAssetIndex.get(index) ?? []), ...bundleIssues];
318
+ const report = assetrepair.repairAssetRecord(asset, { hubIssues: issues });
319
+ repaired.push(report.asset ?? asset);
320
+ entries.push({
321
+ ...(asset.asset_id ? { asset_id: asset.asset_id } : {}),
322
+ ...(report.asset && report.asset.asset_id !== asset.asset_id ? { repaired_asset_id: report.asset.asset_id } : {}),
323
+ repair_status: report.status,
324
+ changes: report.changes.map((change) => `${change.path}: ${change.action}`),
325
+ blockers: report.blockers.map(repairBlockerText),
326
+ });
327
+ }
328
+ return { assets: repaired, entries };
329
+ }
330
+ function repairBlockerText(blocker) {
331
+ return `${blocker.path || '(record)'}: ${stripControlChars(blocker.message).replace(/\s+/g, ' ').trim()}`.slice(0, HUB_DETAIL_MAX_CHARS);
332
+ }
333
+ /** Report the LATER attempt's plan: it is the one describing the bundle that was actually refused last. */
334
+ function mergeRepairAttempts(validation, publish) {
335
+ if (publish.applied || publish.entries.length > 0) {
336
+ return { ...publish, applied: publish.applied || validation.applied };
337
+ }
338
+ return validation.entries.length > 0 || validation.applied ? validation : undefined;
339
+ }
340
+ function repairEnvelopeField(attempt, persisted) {
341
+ if (!attempt || (attempt.entries.length === 0 && !attempt.applied))
342
+ return {};
343
+ return {
344
+ repair: {
345
+ applied: attempt.applied,
346
+ ...(persisted !== undefined ? { persisted } : {}),
347
+ ...(attempt.applied ? {} : { hint: 're-run with --repair to publish the mended record' }),
348
+ assets: attempt.entries,
349
+ },
350
+ };
351
+ }
352
+ async function persistRepairedBundle(published, submitted, deps) {
353
+ const env = deps.env ?? process.env;
354
+ const store = deps.assetStore ?? new assetstore.LocalJsonlProvider(contractAssetsDir(deps));
355
+ // Only the records repair actually changed are new locally; the untouched ones are already stored.
356
+ const changed = published.filter((asset, index) => asset.asset_id !== submitted[index]?.asset_id);
357
+ try {
358
+ const stored = await Promise.all(changed.map((asset) => storeRepairedAsset(asset, store, env)));
359
+ return stored.every(Boolean);
360
+ }
361
+ catch {
362
+ return false;
363
+ }
364
+ }
268
365
  function appendPublishedCapsuleCall(bundle, deps, receipt) {
269
366
  const capsuleIndex = bundle.sanitized.findIndex((asset) => asset.type === 'Capsule');
270
367
  if (capsuleIndex < 0)
@@ -329,7 +426,13 @@ export function parseReuseArgs(args) {
329
426
  }
330
427
  export function parsePublishArgs(args) {
331
428
  const assetRefs = [];
429
+ let geneRef;
430
+ let geneCount = 0;
431
+ let capsuleRef;
432
+ let hasUntypedAsset = false;
433
+ let autoPair = false;
332
434
  let dryRun = false;
435
+ let repair = false;
333
436
  let jsonOut = false;
334
437
  for (let i = 0; i < args.length; i++) {
335
438
  const token = args[i];
@@ -343,34 +446,67 @@ export function parsePublishArgs(args) {
343
446
  jsonOut = true;
344
447
  continue;
345
448
  }
449
+ if (token === '--auto-pair') {
450
+ autoPair = true;
451
+ continue;
452
+ }
453
+ if (token === '--repair') {
454
+ repair = true;
455
+ continue;
456
+ }
346
457
  const equalFlag = [...ASSET_FLAGS].find((flag) => token.startsWith(`${flag}=`));
347
458
  if (equalFlag) {
348
459
  const value = token.slice(equalFlag.length + 1).trim();
349
460
  if (!value)
350
461
  return { ok: false, reason: 'bundle_required', message: `${equalFlag} requires a value` };
351
462
  assetRefs.push(value);
463
+ if (equalFlag === '--gene') {
464
+ geneRef = value;
465
+ geneCount++;
466
+ }
467
+ if (equalFlag === '--capsule')
468
+ capsuleRef = value;
469
+ if (equalFlag === '--asset')
470
+ hasUntypedAsset = true;
352
471
  continue;
353
472
  }
354
473
  if (ASSET_FLAGS.has(token)) {
355
474
  const next = args[i + 1];
356
475
  if (!next || next.startsWith('--'))
357
476
  return { ok: false, reason: 'bundle_required', message: `${token} requires a value` };
358
- assetRefs.push(next.trim());
477
+ const value = next.trim();
478
+ if (!value)
479
+ return { ok: false, reason: 'bundle_required', message: `${token} requires a value` };
480
+ assetRefs.push(value);
481
+ if (token === '--gene') {
482
+ geneRef = value;
483
+ geneCount++;
484
+ }
485
+ if (token === '--capsule')
486
+ capsuleRef = value;
487
+ if (token === '--asset')
488
+ hasUntypedAsset = true;
359
489
  i++;
360
490
  continue;
361
491
  }
362
492
  if (!token.startsWith('--'))
363
- return { ok: false, reason: 'unsupported', message: 'unsupported publish argument' };
364
- return { ok: false, reason: 'unsupported', message: 'unsupported publish flag' };
493
+ return { ok: false, reason: 'unsupported', message: 'unsupported publish argument; did you mean --asset <id|path>?' };
494
+ if (token === '--home' || token.startsWith('--home=') || token === '--evomap-home' || token.startsWith('--evomap-home=')) {
495
+ return { ok: false, reason: 'unsupported', message: 'publish does not accept home flags; set EVOLVER_HOME or EVOMAP_HOME before running evolver publish' };
496
+ }
497
+ return { ok: false, reason: 'unsupported', message: "unsupported publish flag; run 'evolver publish --help'" };
365
498
  }
366
499
  if (!jsonOut)
367
500
  return { ok: false, reason: 'unsupported', message: 'publish requires --json' };
368
- const refs = assetRefs.filter(Boolean);
501
+ if (autoPair && (geneCount !== 1 || !geneRef || capsuleRef || hasUntypedAsset)) {
502
+ return { ok: false, reason: 'bundle_required', message: '--auto-pair requires exactly one explicit --gene and no --asset or --capsule' };
503
+ }
504
+ const refs = assetRefs;
369
505
  if (refs.length === 0)
370
506
  return { ok: false, reason: 'bundle_required', message: 'publish requires --asset <id|path>' };
371
507
  if (refs.length > MAX_ASSETS)
372
508
  return { ok: false, reason: 'bundle_required', message: `publish supports at most ${MAX_ASSETS} assets` };
373
- return { ok: true, assetRefs: refs, dryRun, jsonOut };
509
+ return { ok: true, assetRefs: refs, ...(geneRef ? { geneRef } : {}), ...(autoPair ? { autoPair: true } : {}), dryRun, repair, jsonOut };
374
510
  }
375
511
  export async function buildPublishBundle(refs, deps = {}) {
376
512
  let original;
@@ -578,7 +714,8 @@ function withRecomputedAssetId(asset) {
578
714
  const assetId = wire.computeAssetId(asset);
579
715
  return { ...asset, asset_id: assetId ?? asset.asset_id };
580
716
  }
581
- async function loadAssetRef(ref, deps) {
717
+ /** Resolve `<asset_id|logical_id|path>` the way publish does. Shared so `asset-repair` speaks the same refs. */
718
+ export async function loadAssetRef(ref, deps) {
582
719
  if (looksLikeFile(ref)) {
583
720
  try {
584
721
  return normalizeAsset(JSON.parse(readFileSync(resolve(ref), 'utf8')));
@@ -596,37 +733,96 @@ async function loadAssetRef(ref, deps) {
596
733
  const fromStore = await findAssetInStore(ref, store);
597
734
  // `not_found`, not `schema_invalid`: nothing was located, so no schema was
598
735
  // 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
- }
736
+ if (!fromStore)
737
+ throw new ContractError('not_found', 'asset not found');
604
738
  return normalizeAsset(fromStore);
605
739
  }
606
740
  const assetsDir = contractAssetsDir(deps);
607
741
  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.
742
+ const byAssetId = readOnly.filter((asset) => asset.asset_id === ref);
743
+ if (byAssetId.length > 1)
744
+ throw new ContractError('not_found', 'asset reference is ambiguous');
745
+ let found = byAssetId[0];
612
746
  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})`);
747
+ const exactLogical = readOnly.filter((asset) => stringField(asset, 'id') === ref);
748
+ if (exactLogical.length > 1)
749
+ throw new ContractError('not_found', 'asset reference is ambiguous');
750
+ found = exactLogical[0];
751
+ }
752
+ if (!found) {
753
+ const fallback = prefixedLogicalRef(ref);
754
+ if (fallback) {
755
+ const matches = readOnly.filter((asset) => asset.type === fallback.kind && stringField(asset, 'id') === fallback.id);
756
+ if (matches.length > 1)
757
+ throw new ContractError('not_found', 'asset reference is ambiguous');
758
+ found = matches[0];
759
+ }
616
760
  }
761
+ if (!found)
762
+ throw new ContractError('not_found', 'asset not found');
617
763
  return normalizeAsset(found);
618
764
  }
765
+ function prefixedLogicalRef(ref) {
766
+ const match = /^(gene|capsule):(.+)$/.exec(ref);
767
+ if (!match?.[2])
768
+ return null;
769
+ return { kind: match[1] === 'gene' ? 'Gene' : 'Capsule', id: match[2] };
770
+ }
771
+ async function findLogicalAsset(store, id, kind) {
772
+ if (store.findByLogicalId) {
773
+ const matches = await store.findByLogicalId(id, 2, kind);
774
+ if (matches.length > 1)
775
+ throw new ContractError('not_found', 'asset reference is ambiguous');
776
+ return matches[0] ?? null;
777
+ }
778
+ const scanLimit = 10_000;
779
+ const rows = await store.list(kind, scanLimit + 1);
780
+ if (rows.length > scanLimit)
781
+ throw new ContractError('not_found', 'asset lookup is truncated; use an exact asset_id');
782
+ const matches = rows.filter((asset) => stringField(asset, 'id') === id);
783
+ if (matches.length > 1)
784
+ throw new ContractError('not_found', 'asset reference is ambiguous');
785
+ return matches[0] ?? null;
786
+ }
619
787
  async function findAssetInStore(ref, store) {
620
788
  const byAssetId = await store.get(ref);
621
789
  if (byAssetId)
622
790
  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;
791
+ const exact = await findLogicalAsset(store, ref);
792
+ if (exact)
793
+ return exact;
794
+ const fallback = prefixedLogicalRef(ref);
795
+ return fallback ? findLogicalAsset(store, fallback.id, fallback.kind) : null;
796
+ }
797
+ async function autoPairPublishRefs(refs, geneRef, deps) {
798
+ const store = deps.assetStore ?? new assetstore.LocalJsonlProvider(contractAssetsDir(deps));
799
+ if (!(store instanceof assetstore.LocalJsonlProvider)) {
800
+ throw new ContractError('bundle_required', '--auto-pair requires a local asset store; pass --capsule <id|path> explicitly');
628
801
  }
629
- return null;
802
+ const gene = await loadAssetRef(geneRef, { ...deps, assetStore: store });
803
+ if (gene.type !== 'Gene')
804
+ throw new ContractError('bundle_required', '--auto-pair requires a Gene reference');
805
+ const geneIds = new Set([gene.asset_id, stringField(gene, 'id')].filter((id) => Boolean(id)));
806
+ const trust = new assetstore.ProvenanceStore(store.baseDir).snapshot();
807
+ const candidates = store.listAll('Capsule').filter((candidate) => {
808
+ if (!geneIds.has(String(candidate['gene'] ?? '')))
809
+ return false;
810
+ const outcome = asRecord(candidate['outcome']);
811
+ if (outcome?.['status'] !== 'success')
812
+ return false;
813
+ if (trust.get(candidate.asset_id)?.trusted === false)
814
+ return false;
815
+ if (!wire.validateWireDeep(candidate).ok)
816
+ return false;
817
+ return wire.verifyAssetId(candidate);
818
+ });
819
+ if (candidates.length === 0) {
820
+ throw new ContractError('bundle_required', 'no eligible successful Capsule found; pass --capsule <id|path> explicitly');
821
+ }
822
+ if (candidates.length > 1) {
823
+ throw new ContractError('bundle_required', 'multiple eligible Capsules found; pass --capsule <id|path> explicitly');
824
+ }
825
+ return [...refs, candidates[0].asset_id];
630
826
  }
631
827
  function loadLocalAssetsReadOnly(baseDir, targetRef) {
632
828
  return [
@@ -708,7 +904,7 @@ function checkBundle(bundle) {
708
904
  return { ok: false, message: 'publish supports one Gene + one Capsule + optional one EvolutionEvent bundle' };
709
905
  }
710
906
  if (genes.length === 0 || capsules.length === 0)
711
- return { ok: false, message: 'publish requires Gene + Capsule bundle' };
907
+ return { ok: false, message: BUNDLE_REQUIRED_MESSAGE };
712
908
  const gene = genes[0];
713
909
  const capsule = capsules[0];
714
910
  const geneIds = new Set([gene.asset_id, stringField(gene, 'id')].filter((id) => Boolean(id)));
@@ -752,7 +948,7 @@ function storeBaseDir(store, deps) {
752
948
  function contractAssetsDir(deps) {
753
949
  return deps.assetsDir ?? events.assetsDir(deps.env ?? process.env);
754
950
  }
755
- function dryRunEnvelope(bundle, credits, blockDetail) {
951
+ function dryRunEnvelope(bundle, credits, blockDetail, repairAttempt) {
756
952
  const suppressPayload = bundle.blockReasons.includes('leak_detected');
757
953
  // Collect detailed messages for block reasons
758
954
  const blockDetails = [];
@@ -776,6 +972,7 @@ function dryRunEnvelope(bundle, credits, blockDetail) {
776
972
  ...(suppressPayload ? {} : { payload: { assets: bundle.sanitized } }),
777
973
  gates: bundle.gates,
778
974
  ...(credits ? { credits } : {}),
975
+ ...repairEnvelopeField(repairAttempt),
779
976
  };
780
977
  }
781
978
  function publishFailure(reason, message, opts) {
@@ -787,6 +984,7 @@ function publishFailure(reason, message, opts) {
787
984
  ...(opts.assets ? { assets: opts.assets } : {}),
788
985
  ...(opts.detail ? { detail: opts.detail } : {}),
789
986
  ...(opts.credits ? { credits: opts.credits } : {}),
987
+ ...(opts.repair ? { repair: opts.repair } : {}),
790
988
  reason,
791
989
  retryable: opts.retryable,
792
990
  message,
@@ -1032,20 +1230,28 @@ function isAuthLikeError(err) {
1032
1230
  const message = err instanceof Error ? err.message : String(err);
1033
1231
  return /oauth|login|credential|auth|401|403|node_secret/i.test(message);
1034
1232
  }
1035
- function classifyError(err, command) {
1233
+ function classifyError(err, command, env = {}) {
1036
1234
  if (err instanceof ContractError)
1037
1235
  return { reason: err.reason, message: err.safeMessage, retryable: err.reason === 'network_error' };
1038
1236
  if (err instanceof AuthError)
1039
- return { reason: 'auth_required', message: 'Hub authentication required', retryable: false };
1237
+ return {
1238
+ reason: 'auth_required',
1239
+ message: command === 'publish' ? publishAuthRequiredMessage(env) : 'Hub authentication required',
1240
+ retryable: false,
1241
+ };
1040
1242
  if (err instanceof HubUnreachableError)
1041
1243
  return { reason: 'network_error', message: 'Hub unreachable', retryable: true };
1042
1244
  if (err instanceof HubClientError) {
1043
1245
  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) };
1246
+ return { reason, message: command === 'publish' ? publishReasonMessage(reason, env) : reuseReasonMessage(reason), retryable: publishRetryable(reason) };
1045
1247
  }
1046
1248
  const message = err instanceof Error ? err.message : String(err);
1047
1249
  if (/oauth|login|credential|auth|401|403|node_secret/i.test(message))
1048
- return { reason: 'auth_required', message: 'Hub authentication required', retryable: false };
1250
+ return {
1251
+ reason: 'auth_required',
1252
+ message: command === 'publish' ? publishAuthRequiredMessage(env) : 'Hub authentication required',
1253
+ retryable: false,
1254
+ };
1049
1255
  if (/network|fetch failed|ECONN|ENOTFOUND|ETIMEDOUT|hub 5\d\d/i.test(message))
1050
1256
  return { reason: 'network_error', message: 'Hub unreachable', retryable: true };
1051
1257
  return { reason: 'internal_error', message: `evolver ${command} failed`, retryable: false };
@@ -1074,11 +1280,22 @@ function publishReasonFromResponse(status, body) {
1074
1280
  function publishRetryable(reason) {
1075
1281
  return reason === 'network_error';
1076
1282
  }
1077
- function publishReasonMessage(reason) {
1283
+ function publishAuthRequiredMessage(env) {
1284
+ const rawMode = env['EVOMAP_HUB_MODE']?.trim().toLowerCase();
1285
+ if (rawMode && rawMode !== 'public' && rawMode !== 'private') {
1286
+ return 'Hub authentication failed; verify EVOMAP_HUB_MODE and the configured credentials';
1287
+ }
1288
+ if (rawMode === 'private')
1289
+ return PRIVATE_AUTH_REQUIRED_MESSAGE;
1290
+ return resolveExplicitNodeCredentials(env).nodeSecret
1291
+ ? LEGACY_AUTH_REQUIRED_MESSAGE
1292
+ : OAUTH_AUTH_REQUIRED_MESSAGE;
1293
+ }
1294
+ function publishReasonMessage(reason, env = {}) {
1078
1295
  const map = {
1079
1296
  missing_id: 'missing asset id',
1080
1297
  cli_unavailable: 'evolver CLI unavailable',
1081
- auth_required: 'Hub authentication required',
1298
+ auth_required: publishAuthRequiredMessage(env),
1082
1299
  not_found: 'asset not found',
1083
1300
  network_error: 'Hub unreachable',
1084
1301
  unsupported: 'publish unsupported',
@@ -1086,7 +1303,7 @@ function publishReasonMessage(reason) {
1086
1303
  redaction_unavailable: 'redaction unavailable',
1087
1304
  leak_detected: 'leak detected after redaction',
1088
1305
  schema_invalid: 'asset schema is invalid',
1089
- bundle_required: 'publish requires a complete asset bundle',
1306
+ bundle_required: BUNDLE_REQUIRED_MESSAGE,
1090
1307
  quality_gate_failed: 'Hub quality gate failed',
1091
1308
  gene_unproven: 'gene has no proven success yet — run it to a successful outcome before publishing',
1092
1309
  insufficient_credits: 'insufficient credits',
@@ -1260,12 +1477,6 @@ function looksLikeFile(value) {
1260
1477
  return false;
1261
1478
  }
1262
1479
  }
1263
- function looksLikeAssetPath(value) {
1264
- return isAbsolute(value)
1265
- || /^[A-Za-z]:/.test(value)
1266
- || /[\\/]/.test(value)
1267
- || /\.jsonl?$/i.test(value);
1268
- }
1269
1480
  function isRecord(value) {
1270
1481
  return Boolean(value && typeof value === 'object' && !Array.isArray(value));
1271
1482
  }
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,
@@ -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
+ }
package/dist/reuse.d.ts CHANGED
@@ -15,6 +15,9 @@ export interface ReuseEnvelope {
15
15
  * (PublicHubCapability satisfies both; a bare fetcher in tests may omit hello). */
16
16
  type AssetByIdFetcher = {
17
17
  fetchAssetById(assetId: string, options?: hubNs.FetchAssetByIdOptions): Promise<assetstore.AssetRecord | null>;
18
+ /** Preferred: says WHY there is no asset, so "the hub does not have it" and "the hub delivered something
19
+ * unusable" stop sharing one status. Optional so a bare fetcher (tests, private proxy) still satisfies this. */
20
+ fetchAssetDeliveryById?(assetId: string, options?: hubNs.FetchAssetByIdOptions): Promise<hubNs.AssetDeliveryOutcome>;
18
21
  hello?(opts: PublicHelloOptions): Promise<unknown>;
19
22
  };
20
23
  type PrivateReuseProxy = {
package/dist/reuse.js CHANGED
@@ -10,7 +10,7 @@
10
10
  // and degrades to the agent `/pack apply` path on any non-ok result. Two hard rules follow:
11
11
  // 1. Print EXACTLY ONE envelope object to STDOUT on BOTH success and failure (in --json mode).
12
12
  // 2. NEVER let a token/secret reach any stream — error text is mapped to fixed messages / redacted.
13
- import { assetstore, events, hub as hubNs, wire } from '@evomap/evolver-core';
13
+ import { assetrepair, assetstore, events, hub as hubNs, wire } from '@evomap/evolver-core';
14
14
  import { AuthError, HubClientError, HubUnreachableError, connectPublicHub, isHubDryRunEnabled, stripHubDeliveryMetadataForIntegrity, } from '@evomap/evolver-adapter-public';
15
15
  import { loadEnvFileFromEnv, proxyClientFromEnv } from '@evomap/evolver-mcp';
16
16
  import { createRecipeHubFromEnv } from './recipe.js';
@@ -82,23 +82,27 @@ export async function runReuseCommand(argv, deps = {}) {
82
82
  await establishReuseTrust(hub);
83
83
  // This command owns the quarantine path below. Keep the shared adapter strict for every other caller and
84
84
  // explicitly request an exact declared-ID delivery only where we will revalidate and freeze it as unverified.
85
- const asset = await hub.fetchAssetById(opts.id, { allowUnverifiedExactIdentity: true });
86
- if (!asset)
85
+ const delivery = await fetchReuseDelivery(hub, opts.id);
86
+ if (delivery.status === 'absent')
87
87
  return emit({ ok: false, status: 'not_found', message: 'asset not found on the hub' }, ctx);
88
- const { record, verified } = await ingestHubAsset(store, deps, asset, opts.id);
88
+ if (delivery.status === 'rejected')
89
+ return emit(rejectedDeliveryOutcome(delivery.reason), ctx);
90
+ const { record, verified, repaired } = await ingestHubAsset(store, deps, delivery.asset, opts.id);
89
91
  logReuse(deps, opts, record, 'hub');
90
92
  // Both land the asset (exit 0). A verified reuse is a plain success; an unverified one is a first-class
91
93
  // success too — the operator's save happened — but carries reason `unverified` so the desktop adapter can
92
94
  // surface "added (unverified)" instead of a plain "added". status stays `ok` so older desktop builds, which
93
95
  // key success on status==='ok' and ignore reason, keep working unchanged.
94
- return emit(verified
95
- ? { ok: true, status: 'ok', message: 'reused into local recall library' }
96
- : {
97
- ok: true,
98
- status: 'ok',
99
- reason: 'unverified',
100
- message: 'reused into local recall library as untrusted: hub-delivered content does not match its content fingerprint and could not be verified',
101
- }, ctx);
96
+ if (verified)
97
+ return emit({ ok: true, status: 'ok', message: 'reused into local recall library' }, ctx);
98
+ return emit({
99
+ ok: true,
100
+ status: 'ok',
101
+ reason: 'unverified',
102
+ message: repaired
103
+ ? 'reused into local recall library as untrusted: hub-delivered content was incomplete and was repaired to a schema-valid record; it does not match its content fingerprint and could not be verified'
104
+ : 'reused into local recall library as untrusted: hub-delivered content does not match its content fingerprint and could not be verified',
105
+ }, ctx);
102
106
  }
103
107
  catch (e) {
104
108
  return emit(mapError(e), ctx);
@@ -237,6 +241,7 @@ class ReuseIntegrityError extends Error {
237
241
  const INTEGRITY_MISMATCH_MESSAGE = 'hub-delivered content does not match the asset content fingerprint';
238
242
  const INTEGRITY_BACKFILLED_MESSAGE = 'hub delivered a synthesized payload for this asset; the original published content is unavailable for verification';
239
243
  const INTEGRITY_LOGICAL_ID_MESSAGE = 'hub-delivered asset does not match the requested logical id';
244
+ const INTEGRITY_INCOMPLETE_MESSAGE = 'hub-delivered content is missing fields that cannot be repaired without the original publisher';
240
245
  const INTEGRITY_REVOKED_MESSAGE = 'hub-delivered asset has been revoked';
241
246
  function integrityError(synthesized) {
242
247
  return new ReuseIntegrityError(synthesized ? INTEGRITY_BACKFILLED_MESSAGE : INTEGRITY_MISMATCH_MESSAGE);
@@ -245,16 +250,21 @@ async function ingestHubAsset(store, deps, asset, requestedId) {
245
250
  const delivery = unwrapHubAssetContent(asset);
246
251
  // Use the same content projection as the public adapter and sync. Delivery metadata is classified first, then
247
252
  // removed from every hash and from the stored bytes; Capsule confidence remains canonical content.
248
- const cleaned = stripHubDeliveryMetadataForIntegrity(delivery.content);
253
+ const projection = stripHubDeliveryMetadataForIntegrity(delivery.content);
249
254
  const synthesized = delivery.synthesized;
250
- const type = stringField(cleaned, 'type');
251
- const contentAssetId = stringField(cleaned, 'asset_id');
252
- if ((type !== 'Gene' && type !== 'Capsule')
253
- || !contentAssetId
254
- || !isContentAssetId(contentAssetId)
255
- || !wire.validateWireDeep(cleaned).ok) {
255
+ const type = stringField(projection, 'type');
256
+ const contentAssetId = stringField(projection, 'asset_id');
257
+ if ((type !== 'Gene' && type !== 'Capsule') || !contentAssetId || !isContentAssetId(contentAssetId)) {
256
258
  throw integrityError(synthesized);
257
259
  }
260
+ // The hub delivers a LOSSY projection of the published record (dropped `schema_version`/`id`, emptied
261
+ // `constraints`, extra non-schema keys — measured across promoted genes on 2026-08-14), so a schema verdict
262
+ // here is a verdict on the DELIVERY, not on the asset. Repair it into a storable record instead of throwing
263
+ // the asset away; the identity guards below stay untouched, and the result is still quarantined as unverified.
264
+ const repair = repairHubProjection(projection, contentAssetId);
265
+ if (!repair.ok)
266
+ throw new ReuseIntegrityError(repair.message);
267
+ const cleaned = repair.record;
258
268
  try {
259
269
  assetstore.assertCapsuleGeneBinding(cleaned);
260
270
  }
@@ -290,13 +300,60 @@ async function ingestHubAsset(store, deps, asset, requestedId) {
290
300
  const stored = await assetstore.ingestUntrustedConditional(store, provenance, cleaned);
291
301
  if (stored.status === 'logical_collision')
292
302
  throw new Error('local asset id conflict');
293
- return { record: { ...cleaned, asset_id: stored.asset_id }, verified: true };
303
+ return { record: { ...cleaned, asset_id: stored.asset_id }, verified: true, repaired: false };
294
304
  }
295
305
  const reason = synthesized ? 'unverified_hub_synthesized' : 'unverified_hub_rewrite';
296
306
  const stored = await assetstore.ingestUnverifiedConditional(store, provenance, cleaned, reason);
297
307
  if (stored.status === 'logical_collision')
298
308
  throw new Error('local asset id conflict');
299
- return { record: { ...cleaned, asset_id: stored.asset_id }, verified: false };
309
+ return { record: { ...cleaned, asset_id: stored.asset_id }, verified: false, repaired: repair.repaired };
310
+ }
311
+ /**
312
+ * Make a hub delivery storable without letting it drift off the network identity it was fetched under.
313
+ * `repairAssetRecord` re-derives `asset_id` from the repaired content by design; here the DECLARED network id
314
+ * must survive instead, because the quarantine write freezes the repaired body under that id.
315
+ */
316
+ function repairHubProjection(projection, declaredAssetId) {
317
+ const report = assetrepair.repairAssetRecord(projection);
318
+ if (report.status === 'already_valid')
319
+ return { ok: true, record: projection, repaired: false };
320
+ if (report.status === 'unrepairable') {
321
+ return { ok: false, message: `${INTEGRITY_INCOMPLETE_MESSAGE}: ${blockerSummary(report.blockers)}` };
322
+ }
323
+ const repairedContent = report.changes.some((change) => change.path !== 'asset_id');
324
+ return {
325
+ ok: true,
326
+ record: { ...report.asset, asset_id: declaredAssetId },
327
+ repaired: repairedContent,
328
+ };
329
+ }
330
+ // Hard rule 2 of this command: nothing dynamic reaches a stream unfiltered. Field paths come from the schema
331
+ // gate, but an `additionalProperties` path is named by hub-controlled content — so only plain field-path shapes
332
+ // pass, and only a handful of them.
333
+ const SAFE_FIELD_PATH = /^[A-Za-z0-9_.[\]]{1,40}$/;
334
+ function blockerSummary(blockers) {
335
+ const fields = [...new Set(blockers.map((blocker) => blocker.path))]
336
+ .filter((path) => SAFE_FIELD_PATH.test(path))
337
+ .slice(0, 5);
338
+ return fields.length > 0 ? `unrepairable fields: ${fields.join(', ')}` : 'the delivered record could not be classified';
339
+ }
340
+ async function fetchReuseDelivery(hub, assetId) {
341
+ const options = { allowUnverifiedExactIdentity: true };
342
+ if (hub.fetchAssetDeliveryById)
343
+ return hub.fetchAssetDeliveryById(assetId, options);
344
+ const asset = await hub.fetchAssetById(assetId, options);
345
+ return asset ? { status: 'delivered', asset, verified: true } : { status: 'absent' };
346
+ }
347
+ // A delivered-but-refused asset is NOT a missing asset. Reporting both as `not_found` sent operators looking for
348
+ // an asset the hub was serving the whole time; each rejection now names what the hub actually did.
349
+ function rejectedDeliveryOutcome(reason) {
350
+ const messages = {
351
+ identity_mismatch: 'hub delivered an asset whose identity does not match the requested id',
352
+ revoked: INTEGRITY_REVOKED_MESSAGE,
353
+ ambiguous: 'hub delivered conflicting copies of the requested asset',
354
+ unverified_not_allowed: INTEGRITY_MISMATCH_MESSAGE,
355
+ };
356
+ return { ok: false, status: 'integrity_failed', message: messages[reason] };
300
357
  }
301
358
  async function resolveLocalReuseAsset(store, id) {
302
359
  // A logical id does not identify an asset type. Gene and Capsule ids may overlap, so only the Hub can resolve
@@ -1,7 +1,7 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { realpathSync, statSync } from 'node:fs';
3
3
  import { basename, dirname, isAbsolute, join, resolve, sep } from 'node:path';
4
- import { algo, assetstore, events, exec, verify, wire, workflow } from '@evomap/evolver-core';
4
+ import { algo, assetstore, events, exec, schema, verify, wire, workflow } from '@evomap/evolver-core';
5
5
  import { readAutoExecConfig } from './autoexecConfig.js';
6
6
  import { runRequiredSandboxedValidation } from './requiredSandboxValidation.js';
7
7
  const DEFAULT_MAX_CONCURRENT_RUNS = 4;
@@ -256,10 +256,11 @@ function safeScore(value) {
256
256
  return Number.isFinite(value) ? Math.max(0, Math.min(1, value)) : 0;
257
257
  }
258
258
  function diffSummary(result) {
259
- const diff = result.proofOfWork?.kind === 'git_diff' ? result.proofOfWork.gitDiff : undefined;
259
+ // #961: snake_case 优先, 兼容读旧 camelCase 存量资产(gitDiffOf).
260
+ const diff = result.proofOfWork?.kind === 'git_diff' ? schema.gitDiffOf(result.proofOfWork) : undefined;
260
261
  return {
261
- changedFiles: Number.isSafeInteger(diff?.files) && (diff?.files ?? -1) >= 0 ? diff.files : 0,
262
- changedLines: Number.isSafeInteger(diff?.lines) && (diff?.lines ?? -1) >= 0 ? diff.lines : 0,
262
+ changedFiles: Number.isSafeInteger(diff?.files) && (diff?.files ?? -1) >= 0 ? (diff?.files ?? 0) : 0,
263
+ changedLines: Number.isSafeInteger(diff?.lines) && (diff?.lines ?? -1) >= 0 ? (diff?.lines ?? 0) : 0,
263
264
  };
264
265
  }
265
266
  async function requireReviewedGene(context, store, provenance, review) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@evomap/evolver-cli",
3
- "version": "2.0.8",
3
+ "version": "2.0.12",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "engines": {
@@ -23,12 +23,12 @@
23
23
  }
24
24
  },
25
25
  "dependencies": {
26
- "@evomap/evolver-core": "2.0.8",
27
- "@evomap/evolver-adapter-public": "2.0.8",
28
- "@evomap/evolver-mcp": "2.0.8",
29
- "@evomap/evolver-proxy": "2.0.8",
30
- "@evomap/evolver-runtime-adapters": "2.0.8",
31
- "@evomap/evolver-webui": "2.0.8"
26
+ "@evomap/evolver-core": "2.0.12",
27
+ "@evomap/evolver-adapter-public": "2.0.12",
28
+ "@evomap/evolver-mcp": "2.0.12",
29
+ "@evomap/evolver-proxy": "2.0.12",
30
+ "@evomap/evolver-runtime-adapters": "2.0.12",
31
+ "@evomap/evolver-webui": "2.0.12"
32
32
  },
33
33
  "repository": {
34
34
  "type": "git",