@evomap/evolver-cli 2.0.0-beta.19 → 2.0.0-beta.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/dist/antiGeneBenchmark.js +2 -0
  2. package/dist/antiGeneRollout.js +2 -0
  3. package/dist/assetRepair.d.ts +24 -0
  4. package/dist/assetRepair.js +172 -0
  5. package/dist/autoDistillAntiGene.js +7 -5
  6. package/dist/autoDistillLlm.d.ts +20 -0
  7. package/dist/autoDistillLlm.js +77 -15
  8. package/dist/autoexec.d.ts +11 -0
  9. package/dist/autoexec.js +65 -10
  10. package/dist/autoexecConfig.js +2 -1
  11. package/dist/cliContracts.d.ts +10 -0
  12. package/dist/cliContracts.js +407 -81
  13. package/dist/commandCatalog.d.ts +72 -0
  14. package/dist/commandCatalog.js +120 -0
  15. package/dist/cycleConsumer.d.ts +9 -0
  16. package/dist/cycleConsumer.js +14 -3
  17. package/dist/dispatch.d.ts +0 -1
  18. package/dist/dispatch.js +10 -4
  19. package/dist/distillObserver.js +23 -6
  20. package/dist/doctor.d.ts +11 -0
  21. package/dist/doctor.js +81 -6
  22. package/dist/index.d.ts +5 -1
  23. package/dist/index.js +200 -68
  24. package/dist/lifecycle.d.ts +126 -3
  25. package/dist/lifecycle.js +4390 -188
  26. package/dist/lifecycleBootstrapTransaction.d.ts +235 -0
  27. package/dist/lifecycleBootstrapTransaction.js +2182 -0
  28. package/dist/localMemoryGraph.d.ts +90 -3
  29. package/dist/localMemoryGraph.js +2031 -231
  30. package/dist/materialSnapshot.d.ts +2 -0
  31. package/dist/materialSnapshot.js +8 -0
  32. package/dist/memoryGraphOps.d.ts +8 -0
  33. package/dist/memoryGraphOps.js +140 -0
  34. package/dist/migrate/assetFormatMap.d.ts +61 -0
  35. package/dist/migrate/assetFormatMap.js +53 -0
  36. package/dist/migrate/envTranslate.js +2 -0
  37. package/dist/migrate/fieldMap.d.ts +7 -5
  38. package/dist/migrate/fieldMap.js +20 -14
  39. package/dist/migrate/v1Import.d.ts +80 -1
  40. package/dist/migrate/v1Import.js +961 -120
  41. package/dist/modelCompatibility.d.ts +10 -0
  42. package/dist/modelCompatibility.js +296 -0
  43. package/dist/recipe.d.ts +7 -1
  44. package/dist/recipe.js +113 -11
  45. package/dist/repairedAssetStore.d.ts +2 -0
  46. package/dist/repairedAssetStore.js +12 -0
  47. package/dist/reuse.d.ts +4 -1
  48. package/dist/reuse.js +212 -107
  49. package/dist/reviewFilter.d.ts +3 -1
  50. package/dist/reviewFilter.js +3 -1
  51. package/dist/runtimeSessionSource.d.ts +5 -0
  52. package/dist/selectionPolicyConfig.d.ts +8 -0
  53. package/dist/selectionPolicyConfig.js +18 -0
  54. package/dist/semanticIdfConfig.d.ts +2 -0
  55. package/dist/semanticIdfConfig.js +4 -0
  56. package/dist/sessionIngest.d.ts +7 -1
  57. package/dist/sessionIngest.js +25 -1
  58. package/dist/setupHooks.js +12 -6
  59. package/dist/skill2gep.js +57 -6
  60. package/dist/skillDistill.js +1 -0
  61. package/dist/sync.d.ts +1 -1
  62. package/dist/sync.js +761 -174
  63. package/dist/thesis.js +2 -0
  64. package/dist/valueDigest.js +8 -1
  65. package/dist/windowsLegacyTaskCleanup.d.ts +228 -0
  66. package/dist/windowsLegacyTaskCleanup.js +1475 -0
  67. package/dist/workflowRuntime.js +7 -6
  68. package/package.json +7 -7
@@ -0,0 +1,10 @@
1
+ import { compatibility, exec, verify } from '@evomap/evolver-core';
2
+ export interface ModelCompatibilityReplayDeps {
3
+ spawn?: typeof exec.spawnCapture;
4
+ validation?: typeof verify.runSandboxedValidation;
5
+ isolationAvailable?: () => boolean;
6
+ }
7
+ declare function claudeArgs(test: compatibility.ReplayCase): string[];
8
+ export declare function runModelCompatibilityReplay(argv: string[], deps?: ModelCompatibilityReplayDeps): Promise<number>;
9
+ export declare const modelCompatibilityClaudeArgs: typeof claudeArgs;
10
+ export {};
@@ -0,0 +1,296 @@
1
+ import { compatibility, exec, verify } from '@evomap/evolver-core';
2
+ import { cpSync, existsSync, lstatSync, mkdtempSync, readFileSync, rmSync, statSync } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
5
+ const MAX_INPUT = 2 * 1024 * 1024;
6
+ const MAX_CASES = 256;
7
+ const EXIT_USAGE = 2;
8
+ const EXIT_RUNTIME = 3;
9
+ const EXIT_QUARANTINE = 4;
10
+ const RESULT_SCHEMA = {
11
+ type: 'object',
12
+ additionalProperties: false,
13
+ properties: {
14
+ status: { type: 'string', enum: ['completed'] },
15
+ task_family: { type: 'string' },
16
+ input_digest: { type: 'string' },
17
+ mode: { type: 'string', enum: ['baseline', 'asset-enabled'] },
18
+ },
19
+ required: ['status', 'task_family', 'input_digest', 'mode'],
20
+ };
21
+ function flag(argv, name) {
22
+ const index = argv.indexOf(name);
23
+ return index >= 0 ? argv[index + 1] : undefined;
24
+ }
25
+ function output(value) { process.stdout.write(`${JSON.stringify(value)}\n`); }
26
+ function fail(message, code) { process.stderr.write(`[model-compatibility-replay] ${message}\n`); return code; }
27
+ function object(value, label) {
28
+ if (!value || typeof value !== 'object' || Array.isArray(value))
29
+ throw new Error(`${label} must be an object`);
30
+ return value;
31
+ }
32
+ function boundedJson(path) {
33
+ const raw = readFileSync(path, 'utf8');
34
+ if (Buffer.byteLength(raw) > MAX_INPUT)
35
+ throw new Error('input exceeds 2 MiB');
36
+ return JSON.parse(raw);
37
+ }
38
+ function positiveNumber(value, label) {
39
+ if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0)
40
+ throw new Error(`${label} must be positive`);
41
+ return value;
42
+ }
43
+ function runnerDefinition(value) {
44
+ if (value === undefined)
45
+ return { kind: 'claude-cli' };
46
+ const input = object(value, 'runner');
47
+ const kind = input.kind === 'fixture' ? 'fixture' : input.kind === 'claude-cli' ? 'claude-cli' : undefined;
48
+ if (!kind)
49
+ throw new Error('runner.kind must be claude-cli or fixture');
50
+ return {
51
+ kind,
52
+ ...(typeof input.executable === 'string' ? { executable: input.executable.slice(0, 512) } : {}),
53
+ ...(Array.isArray(input.argv) ? { argv: input.argv.filter((item) => typeof item === 'string').slice(0, 64) } : {}),
54
+ ...(Array.isArray(input.setupFiles) ? { setupFiles: input.setupFiles.filter((item) => typeof item === 'string').slice(0, 64) } : {}),
55
+ };
56
+ }
57
+ function assertWithinRoot(root, value, label) {
58
+ if (isAbsolute(value))
59
+ throw new Error(`${label} must be relative to --cwd`);
60
+ const target = resolve(root, value);
61
+ const rel = relative(root, target);
62
+ if (rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel))
63
+ throw new Error(`${label} escapes --cwd`);
64
+ return target;
65
+ }
66
+ function replayCase(value, root) {
67
+ const input = object(value, 'case');
68
+ const asset = object(input.asset, 'asset');
69
+ for (const key of ['type', 'id', 'revision'])
70
+ if (typeof asset[key] !== 'string' || !asset[key])
71
+ throw new Error(`asset.${key} is required`);
72
+ if (typeof input.requestedModelId !== 'string' || !input.requestedModelId)
73
+ throw new Error('requestedModelId is required');
74
+ if (typeof input.taskFamily !== 'string' || !input.taskFamily)
75
+ throw new Error('taskFamily is required');
76
+ const budgetInput = object(input.budget, 'budget');
77
+ const timeoutMs = positiveNumber(budgetInput.timeoutMs, 'budget.timeoutMs');
78
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs > 120_000)
79
+ throw new Error('budget.timeoutMs must be an integer up to 120000');
80
+ const validation = Array.isArray(input.validation)
81
+ ? input.validation.filter((item) => typeof item === 'string').slice(0, 64)
82
+ : [];
83
+ if (validation.length === 0)
84
+ throw new Error('validation must contain at least one command');
85
+ for (const command of validation) {
86
+ if (!verify.isValidationCommandAllowed(command))
87
+ throw new Error('validation commands must be safe node scripts');
88
+ const script = verify.validationScriptPath(command);
89
+ if (script)
90
+ assertWithinRoot(root, script, 'validation script');
91
+ }
92
+ return {
93
+ asset: { type: asset.type, id: asset.id, revision: asset.revision },
94
+ requestedModelId: input.requestedModelId,
95
+ taskFamily: input.taskFamily,
96
+ input: input.input,
97
+ environment: input.environment ?? {},
98
+ budget: { maxUsd: positiveNumber(budgetInput.maxUsd, 'budget.maxUsd'), timeoutMs },
99
+ validation,
100
+ };
101
+ }
102
+ function copySandbox(root, files) {
103
+ const sandbox = mkdtempSync(join(tmpdir(), 'evolver-model-compatibility-'));
104
+ try {
105
+ for (const file of files) {
106
+ const source = assertWithinRoot(root, file, 'setup file');
107
+ if (!existsSync(source) || lstatSync(source).isSymbolicLink())
108
+ throw new Error(`setup file is missing or symlinked: ${file}`);
109
+ const target = join(sandbox, file);
110
+ const parent = dirname(target);
111
+ const parentRel = relative(sandbox, parent);
112
+ if (parentRel === '..' || parentRel.startsWith(`..${sep}`))
113
+ throw new Error('setup target escapes sandbox');
114
+ cpSync(source, target, { recursive: statSync(source).isDirectory(), dereference: false, force: true });
115
+ }
116
+ return sandbox;
117
+ }
118
+ catch (error) {
119
+ rmSync(sandbox, { recursive: true, force: true });
120
+ throw error;
121
+ }
122
+ }
123
+ function claudeArgs(test) {
124
+ return [
125
+ '--print', '--safe-mode', '--no-session-persistence', '--tools', '', '--permission-mode', 'dontAsk',
126
+ '--model', test.requestedModelId, '--effort', 'low', '--output-format', 'json',
127
+ '--json-schema', JSON.stringify(RESULT_SCHEMA), '--max-budget-usd', String(test.budget.maxUsd),
128
+ ];
129
+ }
130
+ function fixtureArgs(definition, test, mode) {
131
+ const argv = [...(definition.argv ?? [])];
132
+ if (argv.some((item) => /[;&|`$<>\n\r]/.test(item)))
133
+ throw new Error('unsafe fixture argv');
134
+ return [...argv, '--model', test.requestedModelId, '--mode', mode];
135
+ }
136
+ function prompt(test, mode) {
137
+ return JSON.stringify({
138
+ instruction: 'Execute the fixed compatibility replay task. Do not use fallback models. Return only the schema result.',
139
+ task_family: test.taskFamily,
140
+ input_digest: compatibility.canonicalDigest(test.input),
141
+ mode,
142
+ asset: mode === 'asset-enabled' ? test.asset : null,
143
+ input: test.input,
144
+ });
145
+ }
146
+ function finiteInteger(value) {
147
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined;
148
+ }
149
+ function finiteNumber(value) {
150
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined;
151
+ }
152
+ function parseStructuredResult(value, test, mode) {
153
+ let result = value;
154
+ if (typeof result === 'string') {
155
+ try {
156
+ result = JSON.parse(result);
157
+ }
158
+ catch {
159
+ return null;
160
+ }
161
+ }
162
+ if (!result || typeof result !== 'object' || Array.isArray(result))
163
+ return null;
164
+ const row = result;
165
+ if (Object.keys(row).some((key) => !['status', 'task_family', 'input_digest', 'mode'].includes(key)))
166
+ return null;
167
+ return row.status === 'completed'
168
+ && row.task_family === test.taskFamily
169
+ && row.input_digest === compatibility.canonicalDigest(test.input)
170
+ && row.mode === mode ? row : null;
171
+ }
172
+ function parseClaudeEnvelope(raw, test, mode, processResult) {
173
+ let envelope;
174
+ try {
175
+ envelope = object(JSON.parse(raw), 'Claude CLI envelope');
176
+ }
177
+ catch {
178
+ envelope = undefined;
179
+ }
180
+ const usage = envelope?.usage && typeof envelope.usage === 'object' ? envelope.usage : undefined;
181
+ const modelUsage = envelope?.modelUsage && typeof envelope.modelUsage === 'object' && !Array.isArray(envelope.modelUsage)
182
+ ? envelope.modelUsage : undefined;
183
+ const servedIds = modelUsage ? Object.keys(modelUsage) : [];
184
+ const servedModel = servedIds.length === 1 && servedIds[0] === test.requestedModelId
185
+ ? { id: servedIds[0], source: 'claude-cli-envelope' }
186
+ : null;
187
+ const inputTokens = finiteInteger(usage?.input_tokens);
188
+ const outputTokens = finiteInteger(usage?.output_tokens);
189
+ const cacheCreation = finiteInteger(usage?.cache_creation_input_tokens);
190
+ const cacheRead = finiteInteger(usage?.cache_read_input_tokens);
191
+ const cost = finiteNumber(envelope?.total_cost_usd);
192
+ const parsedUsage = inputTokens !== undefined && outputTokens !== undefined && cacheCreation !== undefined && cacheRead !== undefined && cost !== undefined
193
+ ? { inputTokens, outputTokens, cacheCreationInputTokens: cacheCreation, cacheReadInputTokens: cacheRead, costUsd: cost }
194
+ : null;
195
+ const structuredResult = parseStructuredResult(envelope?.structured_output ?? envelope?.result, test, mode);
196
+ const sessionId = typeof envelope?.session_id === 'string' && envelope.session_id.length > 0 ? envelope.session_id : null;
197
+ const envelopeSuccess = envelope?.type === 'result' && envelope.subtype === 'success' && envelope.is_error === false;
198
+ return {
199
+ trust: 'claude-cli', mode,
200
+ ok: processResult.code === 0 && processResult.termination === 'exit' && envelopeSuccess,
201
+ exitCode: processResult.code,
202
+ termination: processResult.termination,
203
+ requestedModel: { id: test.requestedModelId }, servedModel, sessionId, usage: parsedUsage, structuredResult,
204
+ stdoutTruncated: processResult.stdoutTruncated === true,
205
+ stderrTruncated: processResult.stderrTruncated === true,
206
+ };
207
+ }
208
+ function fixtureObservation(test, mode, result) {
209
+ return {
210
+ trust: 'fixture', mode, ok: result.code === 0 && result.termination === 'exit', exitCode: result.code,
211
+ termination: result.termination, requestedModel: { id: test.requestedModelId }, servedModel: null,
212
+ sessionId: null, usage: null, structuredResult: null,
213
+ stdoutTruncated: result.stdoutTruncated === true, stderrTruncated: result.stderrTruncated === true,
214
+ };
215
+ }
216
+ async function execute(definition, test, mode, cwd, deps) {
217
+ const spawn = deps.spawn ?? exec.spawnCapture;
218
+ const executable = definition.kind === 'claude-cli' ? definition.executable ?? 'claude' : definition.executable ?? process.execPath;
219
+ if (definition.kind === 'claude-cli' && executable !== 'claude')
220
+ throw new Error('claude-cli runner executable must be claude');
221
+ if (definition.kind === 'fixture' && ![process.execPath, 'node', 'nodejs'].includes(executable))
222
+ throw new Error('fixture executable is not allowlisted');
223
+ const result = await spawn(executable, definition.kind === 'claude-cli' ? claudeArgs(test) : fixtureArgs(definition, test, mode), {
224
+ cwd, timeoutMs: test.budget.timeoutMs, input: prompt(test, mode), maxOutputBytes: 256 * 1024,
225
+ env: { PATH: process.env.PATH ?? '/usr/bin:/bin', HOME: cwd, NODE_ENV: 'production' },
226
+ });
227
+ const processEvidence = definition.kind === 'claude-cli'
228
+ ? parseClaudeEnvelope(result.stdout, test, mode, result)
229
+ : fixtureObservation(test, mode, result);
230
+ const validate = deps.validation ?? verify.runSandboxedValidation;
231
+ const validation = await validate(test.validation, cwd, {
232
+ timeoutMs: Math.min(test.budget.timeoutMs, 30_000), requireIsolation: true, readOnlyRoot: cwd,
233
+ ...(deps.isolationAvailable ? { unshareCheck: deps.isolationAvailable } : {}),
234
+ });
235
+ const steps = validation.results.map((item) => ({
236
+ command: item.cmd, exitCode: item.exitCode, passed: item.passed, executed: true, termination: 'exit',
237
+ }));
238
+ for (const skipped of validation.skipped)
239
+ steps.push({
240
+ command: skipped.cmd, exitCode: null, passed: false, executed: false, termination: 'not-started',
241
+ });
242
+ return { ...processEvidence, validation: compatibility.validationTrace(validation.isolated, steps) };
243
+ }
244
+ export async function runModelCompatibilityReplay(argv, deps = {}) {
245
+ if (argv.includes('--help')) {
246
+ output({ usage: 'evolver model-compatibility-replay --input <json> [--ledger <json>] [--cwd <dir>] [--retries <n>] [--transition quarantine|revalidate|release --request-id <id> --reason <text>]' });
247
+ return 0;
248
+ }
249
+ const inputPath = flag(argv, '--input');
250
+ if (!inputPath)
251
+ return fail('Usage: evolver model-compatibility-replay --input <json>', EXIT_USAGE);
252
+ try {
253
+ const root = resolve(flag(argv, '--cwd') ?? process.cwd());
254
+ const source = boundedJson(resolve(inputPath));
255
+ const body = Array.isArray(source) ? { cases: source } : object(source, 'input');
256
+ const cases = Array.isArray(body.cases) ? body.cases : null;
257
+ if (!cases || cases.length === 0 || cases.length > MAX_CASES)
258
+ throw new Error('input must contain 1 to 256 cases');
259
+ const corpus = cases.map((item) => replayCase(item, root));
260
+ const ledgerPath = flag(argv, '--ledger');
261
+ const transition = flag(argv, '--transition');
262
+ if (transition) {
263
+ if (!ledgerPath || corpus.length !== 1 || !['quarantine', 'revalidate', 'release'].includes(transition))
264
+ throw new Error('transition requires --ledger, one case, and a valid transition');
265
+ const requestId = flag(argv, '--request-id');
266
+ const reason = flag(argv, '--reason');
267
+ if (!requestId || !reason)
268
+ throw new Error('transition requires --request-id and --reason');
269
+ const ledger = new compatibility.CompatibilityLedger(resolve(ledgerPath));
270
+ const changed = ledger.transition(compatibility.compatibilityKey(corpus[0]), transition, requestId, reason);
271
+ output({ changed, resolved: ledger.resolve(compatibility.compatibilityKey(corpus[0])) });
272
+ return 0;
273
+ }
274
+ const definition = runnerDefinition(body.runner);
275
+ const retries = Math.max(0, Math.min(Number(flag(argv, '--retries') ?? '1') || 0, 5));
276
+ const setupFiles = definition.setupFiles ?? [];
277
+ const run = await compatibility.replayCorpus(corpus, async ({ mode, test }) => {
278
+ const sandbox = copySandbox(root, setupFiles);
279
+ try {
280
+ return await execute(definition, test, mode, sandbox, deps);
281
+ }
282
+ finally {
283
+ rmSync(sandbox, { recursive: true, force: true });
284
+ }
285
+ }, { requestId: flag(argv, '--request-id'), retries });
286
+ if (ledgerPath)
287
+ new compatibility.CompatibilityLedger(resolve(ledgerPath)).appendRun(run);
288
+ const decisions = run.evidence.map((item) => compatibility.evaluateEvidence(item));
289
+ output({ ...run, decisions });
290
+ return decisions.includes('quarantine') ? EXIT_QUARANTINE : 0;
291
+ }
292
+ catch (error) {
293
+ return fail(error instanceof Error ? error.message : String(error), EXIT_RUNTIME);
294
+ }
295
+ }
296
+ export const modelCompatibilityClaudeArgs = claudeArgs;
package/dist/recipe.d.ts CHANGED
@@ -54,7 +54,13 @@ export interface RecipeFromSkillsOptions {
54
54
  publish: boolean;
55
55
  jsonOut: boolean;
56
56
  }
57
- export type RecipeOptions = RecipeBuildOptions | RecipeReuseOptions | RecipeFromSkillsOptions;
57
+ export interface RecipeSearchOptions {
58
+ sub: 'search';
59
+ q?: string;
60
+ limit?: number;
61
+ jsonOut: boolean;
62
+ }
63
+ export type RecipeOptions = RecipeBuildOptions | RecipeReuseOptions | RecipeFromSkillsOptions | RecipeSearchOptions;
58
64
  export declare function runRecipeCommand(argv: readonly string[], deps?: RecipeCliDeps): Promise<number>;
59
65
  export declare function createRecipeHubFromEnv(env?: NodeJS.ProcessEnv, connectHub?: (opts: ConnectPublicOptions) => {
60
66
  hub: PublicHubCapability;
package/dist/recipe.js CHANGED
@@ -16,10 +16,24 @@ const MAX_RECIPE_INPUT_BYTES = 1024 * 1024;
16
16
  const MAX_ID_LENGTH = 200;
17
17
  const SENSITIVE_ERROR_KEYS = new Set(['authorization', 'node_secret', 'nodesecret', 'token', 'access_token', 'refresh_token', 'secret']);
18
18
  const STALE_NODE_SECRET_ERRORS = new Set(['node_secret_invalid', 'node_secret_not_set']);
19
+ const RECIPE_SEARCH_VALUE_OPTIONS = new Set(['--q', '--query', '--limit']);
20
+ const RECIPE_REUSE_COMMAND = 'evolver recipe reuse --id <recipe_id>';
19
21
  function recipeIdempotencyKey(operation, value) {
20
22
  const digest = createHash('sha256').update(JSON.stringify(value)).digest('hex');
21
23
  return `evolver-recipe-${operation}-${digest}`;
22
24
  }
25
+ function terminalSafeText(value) {
26
+ return String(value ?? '').replace(/\p{Cc}/gu, '');
27
+ }
28
+ function terminalSafeJson(value, space) {
29
+ const json = JSON.stringify(value === undefined ? {} : value, null, space);
30
+ return json.replace(/\p{Cc}/gu, (char) => {
31
+ const codePoint = char.codePointAt(0);
32
+ if (codePoint === undefined || codePoint < 0x7f)
33
+ return char;
34
+ return `\\u${codePoint.toString(16).padStart(4, '0')}`;
35
+ });
36
+ }
23
37
  const recipeIdentityBootstraps = new WeakMap();
24
38
  export async function runRecipeCommand(argv, deps = {}) {
25
39
  const parsed = parseRecipeArgs(argv);
@@ -37,6 +51,8 @@ export async function runRecipeCommand(argv, deps = {}) {
37
51
  return await runRecipeBuildDryRun(parsed.value, deps.store, { log, err });
38
52
  if (parsed.value.sub === 'from-skills')
39
53
  return await runRecipeFromSkills(parsed.value, undefined, deps, { log, err }, true);
54
+ if (parsed.value.sub === 'search')
55
+ return runRecipeSearchDryRun(parsed.value, { log });
40
56
  return runRecipeReuseDryRun(parsed.value, { log });
41
57
  }
42
58
  const hub = deps.hub ?? createRecipeHubFromEnv(env, deps.connectHub ?? connectPublicHub);
@@ -49,6 +65,8 @@ export async function runRecipeCommand(argv, deps = {}) {
49
65
  return await runRecipeBuild(parsed.value, hub, deps.store, { log, err });
50
66
  if (parsed.value.sub === 'from-skills')
51
67
  return await runRecipeFromSkills(parsed.value, hub, deps, { log, err }, false);
68
+ if (parsed.value.sub === 'search')
69
+ return await runRecipeSearch(parsed.value, hub, { log, err });
52
70
  return await runRecipeReuse(parsed.value, hub, { log, err });
53
71
  }
54
72
  catch (e) {
@@ -71,16 +89,63 @@ async function runRecipeBuildDryRun(opts, store, io) {
71
89
  }
72
90
  return 0;
73
91
  }
92
+ function runRecipeSearchDryRun(opts, io) {
93
+ const action = opts.q ? 'search_recipe' : 'list_recipe';
94
+ const displayQuery = terminalSafeText(opts.q);
95
+ io.log(`[recipe search] dry-run: would ${opts.q ? `search recipes q=${JSON.stringify(displayQuery)}` : 'list published recipes'}.`);
96
+ if (opts.jsonOut) {
97
+ io.log(terminalSafeJson({
98
+ dry_run: true,
99
+ would: action,
100
+ ...(opts.q ? { q: opts.q } : {}),
101
+ ...(opts.limit !== undefined ? { limit: opts.limit } : {}),
102
+ recipes: [],
103
+ }, 2));
104
+ }
105
+ return 0;
106
+ }
107
+ async function runRecipeSearch(opts, hub, io) {
108
+ const recipes = hub.recipes;
109
+ if (!recipes) {
110
+ io.err('recipe capability is not available for the configured Hub adapter');
111
+ return 1;
112
+ }
113
+ const request = {
114
+ ...(opts.q ? { q: opts.q } : {}),
115
+ ...(opts.limit !== undefined ? { limit: opts.limit } : {}),
116
+ };
117
+ const receipt = opts.q
118
+ ? await callRecipeWithAuthRetry(hub, 'recipe search', () => recipes.search(request), io)
119
+ : await callRecipeWithAuthRetry(hub, 'recipe search', () => recipes.list(request), io);
120
+ io.log(`[recipe search] ${receipt.recipes.length} recipe(s). Express with: ${RECIPE_REUSE_COMMAND}`);
121
+ if (opts.jsonOut) {
122
+ io.log(terminalSafeJson(receipt.raw ?? receipt, 2));
123
+ return 0;
124
+ }
125
+ for (const recipe of receipt.recipes) {
126
+ const row = recipe && typeof recipe === 'object' && !Array.isArray(recipe) ? recipe : {};
127
+ const id = typeof row['id'] === 'string' ? row['id']
128
+ : typeof row['recipe_id'] === 'string' ? row['recipe_id']
129
+ : typeof row['recipeId'] === 'string' ? row['recipeId']
130
+ : undefined;
131
+ const title = typeof row['title'] === 'string' ? row['title'] : undefined;
132
+ const displayId = id ? terminalSafeText(id) : undefined;
133
+ const displayTitle = title ? terminalSafeText(title) : undefined;
134
+ io.log(displayId && displayTitle ? ` ${displayId} ${displayTitle}` : displayId ? ` ${displayId}` : ` ${terminalSafeJson(recipe)}`);
135
+ }
136
+ return 0;
137
+ }
74
138
  function runRecipeReuseDryRun(opts, io) {
75
- io.log(`[recipe reuse] dry-run: would fetch recipe ${opts.recipeId}.`);
76
- io.log(`[recipe reuse] dry-run: would express recipe ${opts.recipeId}.`);
139
+ const displayRecipeId = terminalSafeText(opts.recipeId);
140
+ io.log(`[recipe reuse] dry-run: would fetch recipe ${displayRecipeId}.`);
141
+ io.log(`[recipe reuse] dry-run: would express recipe ${displayRecipeId}.`);
77
142
  if (opts.jsonOut) {
78
- io.log(JSON.stringify({
143
+ io.log(terminalSafeJson({
79
144
  dry_run: true,
80
145
  would: 'express_recipe',
81
146
  recipe_id: opts.recipeId,
82
147
  input_payload: opts.inputPayload,
83
- }, null, 2));
148
+ }, 2));
84
149
  }
85
150
  return 0;
86
151
  }
@@ -153,13 +218,16 @@ function resolveRecipeHubUrl(env) {
153
218
  }
154
219
  export function parseRecipeArgs(argv) {
155
220
  const sub = argv[0];
156
- if (sub !== 'build' && sub !== 'reuse' && sub !== 'from-skills')
157
- return { ok: false, error: 'recipe subcommand must be build|reuse|from-skills' };
221
+ if (sub !== 'build' && sub !== 'reuse' && sub !== 'from-skills' && sub !== 'search') {
222
+ return { ok: false, error: 'recipe subcommand must be build|reuse|from-skills|search' };
223
+ }
158
224
  const args = argv.slice(1);
159
225
  if (sub === 'build')
160
226
  return parseBuildArgs(args);
161
227
  if (sub === 'from-skills')
162
228
  return parseFromSkillsArgs(args);
229
+ if (sub === 'search')
230
+ return parseSearchArgs(args);
163
231
  return parseReuseArgs(args);
164
232
  }
165
233
  async function runRecipeBuild(opts, hub, store, io) {
@@ -385,9 +453,9 @@ async function runRecipeFromSkills(opts, hub, deps, io, dryRun) {
385
453
  async function runRecipeReuse(opts, hub, io) {
386
454
  await callRecipeWithAuthRetry(hub, 'recipe reuse', () => hub.recipes.get(opts.recipeId), io);
387
455
  const receipt = await callRecipeWithAuthRetry(hub, 'recipe reuse', () => hub.recipes.express(opts.recipeId, { inputPayload: opts.inputPayload }), io);
388
- io.log(`[recipe reuse] Expressed recipe ${opts.recipeId}.`);
456
+ io.log(`[recipe reuse] Expressed recipe ${terminalSafeText(opts.recipeId)}.`);
389
457
  if (opts.jsonOut)
390
- io.log(JSON.stringify(receipt.raw, null, 2));
458
+ io.log(terminalSafeJson(receipt.raw, 2));
391
459
  return 0;
392
460
  }
393
461
  async function recipeStepsFromLocalAssets(assetIds, store) {
@@ -445,8 +513,8 @@ async function verifyRecipeFromSkillsSteps(steps, runValidation) {
445
513
  };
446
514
  }
447
515
  if (validation.skipped.length > 0) {
448
- const skipped = validation.skipped.map((item) => item.script).join(', ');
449
- return { ok: false, error: `recipe from-skills step ${i + 1} validation incomplete: missing ${skipped}` };
516
+ const skipped = validation.skipped.map((item) => `${item.script} (${item.reason})`).join(', ');
517
+ return { ok: false, error: `recipe from-skills step ${i + 1} validation incomplete: skipped or rejected ${skipped}` };
450
518
  }
451
519
  if (!validation.passed) {
452
520
  return { ok: false, error: `recipe from-skills step ${i + 1} validation failed` };
@@ -829,7 +897,7 @@ async function callRecipeWithAuthRetry(hub, tag, fn, io) {
829
897
  if (!authErrorIndicatesStaleNodeSecret(e))
830
898
  throw e;
831
899
  io.err(`[${tag}] Hub reported a stale node secret; rotating credentials once and retrying...`);
832
- const hello = await hub.hello({ rotate: true });
900
+ const hello = await hub.hello({ rotate: true, evolverVersion: getCliVersion() });
833
901
  if (!hello.ok) {
834
902
  io.err(`[${tag}] Could not auto-rotate credentials: ${hello.error ?? 'unknown'}`);
835
903
  io.err(' Recover by resetting the Hub credential, then re-run `evolver login` or update EVOMAP_NODE_SECRET.');
@@ -881,6 +949,23 @@ function parseFromSkillsArgs(args) {
881
949
  },
882
950
  };
883
951
  }
952
+ function parseSearchArgs(args) {
953
+ const q = flagValue(args, '--q') ?? flagValue(args, '--query') ?? firstSearchPositional(args) ?? undefined;
954
+ const limitRaw = flagValue(args, '--limit');
955
+ const limit = limitRaw === null ? undefined : Number(limitRaw);
956
+ if (limit !== undefined && (!Number.isSafeInteger(limit) || limit <= 0)) {
957
+ return { ok: false, error: '--limit must be a positive integer' };
958
+ }
959
+ return {
960
+ ok: true,
961
+ value: {
962
+ sub: 'search',
963
+ ...(q ? { q } : {}),
964
+ ...(limit !== undefined ? { limit } : {}),
965
+ jsonOut: args.includes('--json'),
966
+ },
967
+ };
968
+ }
884
969
  function parseReuseArgs(args) {
885
970
  const recipeId = flagValue(args, '--id') ?? firstPositional(args);
886
971
  if (!recipeId)
@@ -913,6 +998,21 @@ function flagValue(args, flag) {
913
998
  function firstPositional(args) {
914
999
  return args.find((a) => typeof a === 'string' && !a.startsWith('--')) ?? null;
915
1000
  }
1001
+ function firstSearchPositional(args) {
1002
+ for (let i = 0; i < args.length; i += 1) {
1003
+ const token = args[i];
1004
+ if (token === undefined)
1005
+ continue;
1006
+ if (!token.startsWith('--'))
1007
+ return token;
1008
+ if (!token.includes('=') && RECIPE_SEARCH_VALUE_OPTIONS.has(token)) {
1009
+ const next = args[i + 1];
1010
+ if (next !== undefined && !next.startsWith('--'))
1011
+ i += 1;
1012
+ }
1013
+ }
1014
+ return null;
1015
+ }
916
1016
  function parseJsonObject(raw) {
917
1017
  try {
918
1018
  const parsed = JSON.parse(raw);
@@ -1278,5 +1378,7 @@ function recipeUsage() {
1278
1378
  ' evolver recipe from-skills --manifest <file> [--publish] [--json]',
1279
1379
  ' Distills ordered SKILL.md steps with execution evidence, then creates a recipe.',
1280
1380
  ' evolver recipe reuse --id <recipe_id> [--input <json-object>] [--json]',
1381
+ ' evolver recipe search [--q <text>] [--limit <n>] [--json]',
1382
+ ` Default agent lookup. Express a hit with \`${RECIPE_REUSE_COMMAND}\`. Gene/Capsule search is fallback.`,
1281
1383
  ].join('\n');
1282
1384
  }
@@ -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
@@ -14,7 +14,10 @@ export interface ReuseEnvelope {
14
14
  /** Minimal hub surface this command needs: a single fetch-by-id, plus an optional trust-establishing hello
15
15
  * (PublicHubCapability satisfies both; a bare fetcher in tests may omit hello). */
16
16
  type AssetByIdFetcher = {
17
- fetchAssetById(assetId: string): Promise<assetstore.AssetRecord | null>;
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 = {