@evomap/evolver-cli 2.0.2 → 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 {};