@evomap/evolver-cli 2.0.0-beta.2 → 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 (124) hide show
  1. package/dist/antiGeneBenchmark.js +2 -0
  2. package/dist/antiGeneRollout.js +9 -3
  3. package/dist/assetHealth.d.ts +6 -0
  4. package/dist/assetHealth.js +107 -0
  5. package/dist/assetRepair.d.ts +24 -0
  6. package/dist/assetRepair.js +172 -0
  7. package/dist/assetSidecarRecovery.d.ts +14 -0
  8. package/dist/assetSidecarRecovery.js +171 -0
  9. package/dist/assetTrust.d.ts +24 -0
  10. package/dist/assetTrust.js +231 -0
  11. package/dist/atp.d.ts +10 -5
  12. package/dist/atp.js +119 -26
  13. package/dist/atpAutoBuyer.d.ts +120 -0
  14. package/dist/atpAutoBuyer.js +814 -0
  15. package/dist/atpAutoDeliver.js +2 -2
  16. package/dist/autoDistillAntiGene.js +7 -5
  17. package/dist/autoDistillLlm.d.ts +26 -0
  18. package/dist/autoDistillLlm.js +119 -22
  19. package/dist/autoDistillTranscript.js +3 -2
  20. package/dist/autoexec.d.ts +111 -24
  21. package/dist/autoexec.js +887 -120
  22. package/dist/autoexecConfig.d.ts +10 -0
  23. package/dist/autoexecConfig.js +69 -0
  24. package/dist/cli.js +13 -0
  25. package/dist/cliContracts.d.ts +33 -2
  26. package/dist/cliContracts.js +818 -78
  27. package/dist/commandCatalog.d.ts +72 -0
  28. package/dist/commandCatalog.js +120 -0
  29. package/dist/commands.d.ts +1 -0
  30. package/dist/commands.js +1 -0
  31. package/dist/curriculumCapabilityGaps.d.ts +6 -0
  32. package/dist/curriculumCapabilityGaps.js +24 -0
  33. package/dist/cycleConsumer.d.ts +17 -2
  34. package/dist/cycleConsumer.js +374 -50
  35. package/dist/dashboard.d.ts +13 -1
  36. package/dist/dashboard.js +235 -18
  37. package/dist/dispatch.d.ts +9 -2
  38. package/dist/dispatch.js +29 -6
  39. package/dist/distillAdmission.d.ts +13 -0
  40. package/dist/distillAdmission.js +35 -0
  41. package/dist/distillObserver.js +27 -12
  42. package/dist/distillPrimitives.d.ts +11 -8
  43. package/dist/distillPrimitives.js +116 -22
  44. package/dist/doctor.d.ts +13 -0
  45. package/dist/doctor.js +177 -10
  46. package/dist/identityHome.d.ts +9 -0
  47. package/dist/identityHome.js +47 -0
  48. package/dist/index.d.ts +73 -40
  49. package/dist/index.js +745 -207
  50. package/dist/issueReport.d.ts +7 -0
  51. package/dist/issueReport.js +291 -0
  52. package/dist/learningTrace.d.ts +15 -0
  53. package/dist/learningTrace.js +73 -0
  54. package/dist/lifecycle.d.ts +199 -2
  55. package/dist/lifecycle.js +4999 -152
  56. package/dist/lifecycleBootstrapTransaction.d.ts +235 -0
  57. package/dist/lifecycleBootstrapTransaction.js +2182 -0
  58. package/dist/localMemoryGraph.d.ts +184 -0
  59. package/dist/localMemoryGraph.js +2689 -0
  60. package/dist/login.d.ts +1 -1
  61. package/dist/login.js +3 -3
  62. package/dist/materialPackage.js +3 -6
  63. package/dist/materialSnapshot.d.ts +35 -1
  64. package/dist/materialSnapshot.js +265 -18
  65. package/dist/memoryGraphOps.d.ts +8 -0
  66. package/dist/memoryGraphOps.js +140 -0
  67. package/dist/migrate/assetFormatMap.d.ts +61 -0
  68. package/dist/migrate/assetFormatMap.js +53 -0
  69. package/dist/migrate/envTranslate.d.ts +26 -0
  70. package/dist/migrate/envTranslate.js +147 -0
  71. package/dist/migrate/fieldMap.d.ts +7 -5
  72. package/dist/migrate/fieldMap.js +20 -14
  73. package/dist/migrate/oauthImport.d.ts +66 -0
  74. package/dist/migrate/oauthImport.js +667 -0
  75. package/dist/migrate/v1Import.d.ts +98 -1
  76. package/dist/migrate/v1Import.js +1532 -71
  77. package/dist/modelCompatibility.d.ts +10 -0
  78. package/dist/modelCompatibility.js +296 -0
  79. package/dist/promptRecallHook.d.ts +24 -0
  80. package/dist/promptRecallHook.js +425 -0
  81. package/dist/recallVerifyReport.d.ts +37 -0
  82. package/dist/recallVerifyReport.js +244 -0
  83. package/dist/recipe.d.ts +14 -2
  84. package/dist/recipe.js +543 -65
  85. package/dist/repairedAssetStore.d.ts +2 -0
  86. package/dist/repairedAssetStore.js +12 -0
  87. package/dist/requiredSandboxValidation.d.ts +5 -0
  88. package/dist/requiredSandboxValidation.js +4 -0
  89. package/dist/reuse.d.ts +18 -4
  90. package/dist/reuse.js +375 -107
  91. package/dist/reviewFilter.d.ts +3 -1
  92. package/dist/reviewFilter.js +3 -1
  93. package/dist/runtimeCapabilities.d.ts +18 -0
  94. package/dist/runtimeCapabilities.js +81 -0
  95. package/dist/runtimeSessionSource.d.ts +8 -2
  96. package/dist/runtimeSessionSource.js +63 -11
  97. package/dist/selectionPolicyConfig.d.ts +8 -0
  98. package/dist/selectionPolicyConfig.js +18 -0
  99. package/dist/semanticIdfConfig.d.ts +2 -0
  100. package/dist/semanticIdfConfig.js +4 -0
  101. package/dist/sessionIngest.d.ts +43 -0
  102. package/dist/sessionIngest.js +180 -0
  103. package/dist/setupHooks.d.ts +5 -0
  104. package/dist/setupHooks.js +330 -14
  105. package/dist/skill2gep.d.ts +13 -9
  106. package/dist/skill2gep.js +99 -36
  107. package/dist/skillDistill.d.ts +8 -4
  108. package/dist/skillDistill.js +39 -9
  109. package/dist/solo/mode.js +1 -0
  110. package/dist/sync.d.ts +13 -1
  111. package/dist/sync.js +1947 -265
  112. package/dist/thesis.d.ts +1 -1
  113. package/dist/thesis.js +20 -3
  114. package/dist/trajectoryExport.js +21 -3
  115. package/dist/v1Compat.d.ts +1 -0
  116. package/dist/v1Compat.js +9 -0
  117. package/dist/valueDigest.js +8 -1
  118. package/dist/windowsLegacyTaskCleanup.d.ts +228 -0
  119. package/dist/windowsLegacyTaskCleanup.js +1475 -0
  120. package/dist/workflow.d.ts +39 -0
  121. package/dist/workflow.js +386 -0
  122. package/dist/workflowRuntime.d.ts +66 -0
  123. package/dist/workflowRuntime.js +638 -0
  124. package/package.json +14 -7
package/dist/recipe.js CHANGED
@@ -1,16 +1,40 @@
1
- import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';
1
+ import { existsSync, mkdirSync, readFileSync, realpathSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
2
+ import { createHash } from 'node:crypto';
2
3
  import { homedir } from 'node:os';
3
- import { dirname, isAbsolute, join, resolve } from 'node:path';
4
- import { assetstore, events, mailbox } from '@evomap/evolver-core';
4
+ import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
5
+ import { assetstore, events, mailbox, verify } from '@evomap/evolver-core';
5
6
  import { AuthError, HubClientError, HubUnreachableError, connectPublicHub, isHubDryRunEnabled, isNodeSecret, parseNodeSecretVersion, resolveHubUrl } from '@evomap/evolver-adapter-public';
6
7
  import { loadEnvFileFromEnv } from '@evomap/evolver-mcp';
7
- import { resolveAtpSenderId } from './atp.js';
8
- import { parseSkillMd, reverseDistill } from './skill2gep.js';
8
+ import { resolveExplicitNodeCredentials } from './identityHome.js';
9
+ import { getCliVersion } from './version.js';
10
+ import { parseSkillMd, reverseDistill, synthesizeGene } from './skill2gep.js';
9
11
  import { recordSkillDistillation } from './skillDistill.js';
12
+ import { buildPublishBundle } from './cliContracts.js';
10
13
  const MAX_RECIPE_STEPS = 20;
14
+ const MAX_RECIPE_VALIDATION_COMMANDS = 5;
15
+ const MAX_RECIPE_INPUT_BYTES = 1024 * 1024;
11
16
  const MAX_ID_LENGTH = 200;
12
17
  const SENSITIVE_ERROR_KEYS = new Set(['authorization', 'node_secret', 'nodesecret', 'token', 'access_token', 'refresh_token', 'secret']);
13
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>';
21
+ function recipeIdempotencyKey(operation, value) {
22
+ const digest = createHash('sha256').update(JSON.stringify(value)).digest('hex');
23
+ return `evolver-recipe-${operation}-${digest}`;
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
+ }
37
+ const recipeIdentityBootstraps = new WeakMap();
14
38
  export async function runRecipeCommand(argv, deps = {}) {
15
39
  const parsed = parseRecipeArgs(argv);
16
40
  const err = deps.err ?? ((line) => { process.stderr.write(`${line}\n`); });
@@ -21,14 +45,18 @@ export async function runRecipeCommand(argv, deps = {}) {
21
45
  }
22
46
  try {
23
47
  const env = deps.env ?? process.env;
48
+ loadEnvFileFromEnv(env);
24
49
  if (isHubDryRunEnabled(env)) {
25
50
  if (parsed.value.sub === 'build')
26
51
  return await runRecipeBuildDryRun(parsed.value, deps.store, { log, err });
27
52
  if (parsed.value.sub === 'from-skills')
28
53
  return await runRecipeFromSkills(parsed.value, undefined, deps, { log, err }, true);
54
+ if (parsed.value.sub === 'search')
55
+ return runRecipeSearchDryRun(parsed.value, { log });
29
56
  return runRecipeReuseDryRun(parsed.value, { log });
30
57
  }
31
58
  const hub = deps.hub ?? createRecipeHubFromEnv(env, deps.connectHub ?? connectPublicHub);
59
+ await recipeIdentityBootstraps.get(hub)?.();
32
60
  if (!hub.recipes) {
33
61
  err('recipe capability is not available for the configured Hub adapter');
34
62
  return 1;
@@ -37,6 +65,8 @@ export async function runRecipeCommand(argv, deps = {}) {
37
65
  return await runRecipeBuild(parsed.value, hub, deps.store, { log, err });
38
66
  if (parsed.value.sub === 'from-skills')
39
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 });
40
70
  return await runRecipeReuse(parsed.value, hub, { log, err });
41
71
  }
42
72
  catch (e) {
@@ -59,16 +89,63 @@ async function runRecipeBuildDryRun(opts, store, io) {
59
89
  }
60
90
  return 0;
61
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
+ }
62
138
  function runRecipeReuseDryRun(opts, io) {
63
- io.log(`[recipe reuse] dry-run: would fetch recipe ${opts.recipeId}.`);
64
- 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}.`);
65
142
  if (opts.jsonOut) {
66
- io.log(JSON.stringify({
143
+ io.log(terminalSafeJson({
67
144
  dry_run: true,
68
145
  would: 'express_recipe',
69
146
  recipe_id: opts.recipeId,
70
147
  input_payload: opts.inputPayload,
71
- }, null, 2));
148
+ }, 2));
72
149
  }
73
150
  return 0;
74
151
  }
@@ -82,6 +159,7 @@ export function createRecipeHubFromEnv(env = process.env, connectHub = connectPu
82
159
  if (!credentials.nodeSecret && !credentials.senderId) {
83
160
  throw new Error('recipe OAuth mode requires a node identity: register a node first, set EVOMAP_NODE_ID or A2A_NODE_ID, or ensure the Evolver proxy store contains node_id');
84
161
  }
162
+ let senderId = credentials.senderId;
85
163
  const connected = credentials.nodeSecret
86
164
  ? connectHub({
87
165
  hubUrl,
@@ -89,25 +167,67 @@ export function createRecipeHubFromEnv(env = process.env, connectHub = connectPu
89
167
  evomapDir: credentials.evomapDir,
90
168
  nodeSecret: credentials.nodeSecret,
91
169
  ...(credentials.nodeSecretVersion !== undefined ? { nodeSecretVersion: credentials.nodeSecretVersion } : {}),
92
- senderId: () => credentials.senderId,
93
- onNodeSecretRotated: (secret, version) => persistRotatedNodeSecret(secret, version, env, credentials.rotatePersistDir),
170
+ senderId: () => senderId,
171
+ onNodeSecretRotated: (secret, version) => persistRotatedNodeSecret(secret, version, senderId, env, credentials.rotatePersistDir),
94
172
  onNodeSecretVersionUpdated: (version) => persistNodeSecretVersion(version, env, credentials.rotatePersistDir),
95
173
  })
96
- : connectHub({ hubUrl, authMode: 'oauth', evomapDir: credentials.evomapDir, senderId: () => credentials.senderId });
174
+ : connectHub({ hubUrl, authMode: 'oauth', evomapDir: credentials.evomapDir, senderId: () => senderId });
175
+ if (credentials.nodeSecret && !senderId) {
176
+ recipeIdentityBootstraps.set(connected.hub, async () => {
177
+ const hello = await connected.hub.hello({
178
+ rotate: false,
179
+ evolverVersion: getCliVersion(),
180
+ preserveCredentials: true,
181
+ });
182
+ if (!hello.ok || !hello.nodeId) {
183
+ throw new Error(`recipe could not establish Hub node identity: ${hello.error ?? 'node_id_missing'}`);
184
+ }
185
+ senderId = hello.nodeId;
186
+ persistRecipeNodeId(senderId, env, credentials.rotatePersistDir);
187
+ recipeIdentityBootstraps.delete(connected.hub);
188
+ });
189
+ }
97
190
  return connected.hub;
98
191
  }
192
+ /** Opaque identity for resume isolation; raw credentials, account ids, and local paths never leave this helper. */
193
+ export function resolveRecipeHubResumeIdentityFingerprint(env) {
194
+ loadEnvFileFromEnv(env);
195
+ const credentials = resolveRecipeHubCredentials(env);
196
+ let credential;
197
+ if (credentials.nodeSecret) {
198
+ credential = credentials.nodeSecret;
199
+ }
200
+ else {
201
+ try {
202
+ credential = createHash('sha256')
203
+ .update(readFileSync(join(credentials.evomapDir, 'token.json'), 'utf8'))
204
+ .digest('hex');
205
+ }
206
+ catch {
207
+ throw new Error('Hub resume identity credentials are unavailable');
208
+ }
209
+ }
210
+ return createHash('sha256').update(JSON.stringify({
211
+ authMode: credentials.nodeSecret ? 'legacy' : 'oauth',
212
+ senderId: credentials.senderId ?? '',
213
+ credential,
214
+ })).digest('hex');
215
+ }
99
216
  function resolveRecipeHubUrl(env) {
100
217
  return resolveHubUrl(env);
101
218
  }
102
219
  export function parseRecipeArgs(argv) {
103
220
  const sub = argv[0];
104
- if (sub !== 'build' && sub !== 'reuse' && sub !== 'from-skills')
105
- 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
+ }
106
224
  const args = argv.slice(1);
107
225
  if (sub === 'build')
108
226
  return parseBuildArgs(args);
109
227
  if (sub === 'from-skills')
110
228
  return parseFromSkillsArgs(args);
229
+ if (sub === 'search')
230
+ return parseSearchArgs(args);
111
231
  return parseReuseArgs(args);
112
232
  }
113
233
  async function runRecipeBuild(opts, hub, store, io) {
@@ -116,20 +236,32 @@ async function runRecipeBuild(opts, hub, store, io) {
116
236
  io.err('recipe build requires at least one asset id');
117
237
  return 1;
118
238
  }
119
- const createReceipt = await callRecipeWithAuthRetry(hub, 'recipe build', () => hub.recipes.create({
239
+ const createRequest = {
120
240
  title: opts.title,
121
241
  steps,
122
242
  ...(opts.description ? { description: opts.description } : {}),
123
243
  ...(opts.pricePerExecution !== undefined ? { pricePerExecution: opts.pricePerExecution } : {}),
124
- }), io);
244
+ };
245
+ createRequest.idempotencyKey = recipeIdempotencyKey('create', createRequest);
246
+ const createReceipt = await callRecipeWithAuthRetry(hub, 'recipe build', () => hub.recipes.create(createRequest), io);
125
247
  const recipeId = createReceipt.recipeId;
248
+ if (createReceipt.status !== 'draft') {
249
+ io.err(`[recipe build] Hub returned unexpected create status: ${createReceipt.status ?? 'unknown'}.`);
250
+ return 1;
251
+ }
126
252
  io.log(`[recipe build] Created DRAFT recipe ${recipeId ?? '(id pending)'} ("${opts.title}", ${steps.length} step${steps.length === 1 ? '' : 's'}).`);
127
253
  if (opts.publish) {
128
254
  if (!recipeId) {
129
255
  io.err('[recipe build] Hub did not return a recipe id; cannot publish.');
130
256
  return 1;
131
257
  }
132
- await callRecipeWithAuthRetry(hub, 'recipe build', () => hub.recipes.publish(recipeId), io);
258
+ const publishReceipt = await callRecipeWithAuthRetry(hub, 'recipe build', () => hub.recipes.publish(recipeId, {
259
+ idempotencyKey: recipeIdempotencyKey('publish', recipeId),
260
+ }), io);
261
+ if (publishReceipt.status !== 'published') {
262
+ io.err(`[recipe build] Hub returned unexpected publish status: ${publishReceipt.status ?? 'unknown'}.`);
263
+ return 1;
264
+ }
133
265
  io.log(`[recipe build] Published recipe ${recipeId}.`);
134
266
  }
135
267
  else {
@@ -143,7 +275,12 @@ async function runRecipeFromSkills(opts, hub, deps, io, dryRun) {
143
275
  io.err(loaded.error);
144
276
  return 1;
145
277
  }
146
- const preflight = preflightRecipeFromSkillsSteps(loaded.value.steps);
278
+ const verified = await verifyRecipeFromSkillsSteps(loaded.value.steps, deps.runValidation ?? verify.runSandboxedValidation);
279
+ if (!verified.ok) {
280
+ io.err(verified.error);
281
+ return 1;
282
+ }
283
+ const preflight = preflightRecipeFromSkillsSteps(verified.value);
147
284
  if (!preflight.ok) {
148
285
  io.err(preflight.error);
149
286
  return 1;
@@ -163,7 +300,12 @@ async function runRecipeFromSkills(opts, hub, deps, io, dryRun) {
163
300
  store,
164
301
  ...(deps.review ? { review: deps.review } : {}),
165
302
  ingestor,
166
- }, step.scenario ? { scenario: step.scenario } : {});
303
+ }, {
304
+ evidenceMode: 'validation_only',
305
+ geneIdentity: 'semantic',
306
+ completeValidationPlan: true,
307
+ ...(step.scenario ? { scenario: step.scenario } : {}),
308
+ });
167
309
  if (!res.geneId || !res.geneAssetId) {
168
310
  const recovered = await findReusableRecipeStep(store, prepared);
169
311
  if (recovered) {
@@ -188,6 +330,13 @@ async function runRecipeFromSkills(opts, hub, deps, io, dryRun) {
188
330
  capsuleId: res.capsuleId,
189
331
  });
190
332
  }
333
+ const publishPrepared = await prepareRecipeFromSkillsAssets(distilled, store, dryRun ? undefined : hub, deps.env ?? process.env, io);
334
+ if (!publishPrepared.ok) {
335
+ io.err(publishPrepared.error);
336
+ return 1;
337
+ }
338
+ steps.splice(0, steps.length, ...publishPrepared.value.steps);
339
+ distilled.splice(0, distilled.length, ...publishPrepared.value.distilled);
191
340
  if (dryRun) {
192
341
  const payload = recipeFromSkillsPayload({
193
342
  mode: 'dry_run',
@@ -210,13 +359,32 @@ async function runRecipeFromSkills(opts, hub, deps, io, dryRun) {
210
359
  io.err('recipe capability is not available for the configured Hub adapter');
211
360
  return 1;
212
361
  }
213
- const createReceipt = await callRecipeWithAuthRetry(hub, 'recipe from-skills', () => hub.recipes.create({
362
+ const createRequest = {
214
363
  title: loaded.value.title,
215
364
  steps,
216
365
  ...(loaded.value.description ? { description: loaded.value.description } : {}),
217
366
  ...(loaded.value.pricePerExecution !== undefined ? { pricePerExecution: loaded.value.pricePerExecution } : {}),
218
- }), io);
367
+ };
368
+ createRequest.idempotencyKey = recipeIdempotencyKey('create', createRequest);
369
+ const createReceipt = await callRecipeWithAuthRetry(hub, 'recipe from-skills', () => hub.recipes.create(createRequest), io);
219
370
  const recipeId = createReceipt.recipeId;
371
+ if (createReceipt.status !== 'draft') {
372
+ if (opts.jsonOut) {
373
+ io.log(JSON.stringify(recipeFromSkillsPayload({
374
+ ok: false,
375
+ mode: 'failed',
376
+ title: loaded.value.title,
377
+ publish: opts.publish,
378
+ steps: distilled,
379
+ recipeId,
380
+ error: 'create_failed',
381
+ }), null, 2));
382
+ }
383
+ else {
384
+ io.err(`[recipe from-skills] Hub did not confirm draft creation for recipe ${recipeId ?? '(id missing)'} (status: ${createReceipt.status ?? 'missing'}).`);
385
+ }
386
+ return 1;
387
+ }
220
388
  if (!opts.jsonOut) {
221
389
  io.log(`[recipe from-skills] Created DRAFT recipe ${recipeId ?? '(id pending)'} ("${loaded.value.title}", ${steps.length} step${steps.length === 1 ? '' : 's'}).`);
222
390
  }
@@ -226,7 +394,26 @@ async function runRecipeFromSkills(opts, hub, deps, io, dryRun) {
226
394
  return 1;
227
395
  }
228
396
  try {
229
- await callRecipeWithAuthRetry(hub, 'recipe from-skills', () => hub.recipes.publish(recipeId), io);
397
+ const publishReceipt = await callRecipeWithAuthRetry(hub, 'recipe from-skills', () => hub.recipes.publish(recipeId, {
398
+ idempotencyKey: recipeIdempotencyKey('publish', recipeId),
399
+ }), io);
400
+ if (publishReceipt.status !== 'published') {
401
+ if (opts.jsonOut) {
402
+ io.log(JSON.stringify(recipeFromSkillsPayload({
403
+ ok: false,
404
+ mode: 'draft',
405
+ title: loaded.value.title,
406
+ publish: opts.publish,
407
+ steps: distilled,
408
+ recipeId,
409
+ error: 'publish_failed',
410
+ }), null, 2));
411
+ }
412
+ else {
413
+ io.err(`[recipe from-skills] Created DRAFT recipe ${recipeId}; Hub did not confirm publish (status: ${publishReceipt.status ?? 'missing'}).`);
414
+ }
415
+ return 1;
416
+ }
230
417
  }
231
418
  catch (e) {
232
419
  if (opts.jsonOut) {
@@ -266,9 +453,9 @@ async function runRecipeFromSkills(opts, hub, deps, io, dryRun) {
266
453
  async function runRecipeReuse(opts, hub, io) {
267
454
  await callRecipeWithAuthRetry(hub, 'recipe reuse', () => hub.recipes.get(opts.recipeId), io);
268
455
  const receipt = await callRecipeWithAuthRetry(hub, 'recipe reuse', () => hub.recipes.express(opts.recipeId, { inputPayload: opts.inputPayload }), io);
269
- io.log(`[recipe reuse] Expressed recipe ${opts.recipeId}.`);
456
+ io.log(`[recipe reuse] Expressed recipe ${terminalSafeText(opts.recipeId)}.`);
270
457
  if (opts.jsonOut)
271
- io.log(JSON.stringify(receipt.raw, null, 2));
458
+ io.log(terminalSafeJson(receipt.raw, 2));
272
459
  return 0;
273
460
  }
274
461
  async function recipeStepsFromLocalAssets(assetIds, store) {
@@ -284,12 +471,96 @@ async function recipeStepsFromLocalAssets(assetIds, store) {
284
471
  return { assetId, assetType, position: index };
285
472
  });
286
473
  }
474
+ async function verifyRecipeFromSkillsSteps(steps, runValidation) {
475
+ const verified = [];
476
+ for (let i = 0; i < steps.length; i += 1) {
477
+ const step = steps[i];
478
+ const parsed = parseSkillMd(step.skill, { completeValidationPlan: true });
479
+ if (parsed.validation.length > MAX_RECIPE_VALIDATION_COMMANDS) {
480
+ return {
481
+ ok: false,
482
+ error: `recipe from-skills step ${i + 1} supports at most ${MAX_RECIPE_VALIDATION_COMMANDS} validation commands`,
483
+ };
484
+ }
485
+ const synthesized = synthesizeGene(parsed, step.execution, { strict: true });
486
+ if (!synthesized.gene) {
487
+ return {
488
+ ok: false,
489
+ error: `recipe from-skills step ${i + 1} did not produce a Gene: ${synthesized.errors.join('; ') || 'refused'}`,
490
+ };
491
+ }
492
+ if (!recipeValidationPlanIsComplete(parsed.validation, synthesized.gene.validation)) {
493
+ return {
494
+ ok: false,
495
+ error: `recipe from-skills step ${i + 1} contains unsupported validation commands; every declared command must be allowed`,
496
+ };
497
+ }
498
+ const startedAt = new Date().toISOString();
499
+ let validation;
500
+ try {
501
+ validation = await runValidation(synthesized.gene.validation ?? [], step.validationCwd, {
502
+ requireIsolation: true,
503
+ readOnlyRoot: step.validationRoot,
504
+ });
505
+ }
506
+ catch {
507
+ return { ok: false, error: `recipe from-skills step ${i + 1} validation execution failed` };
508
+ }
509
+ if (!validation.isolated) {
510
+ return {
511
+ ok: false,
512
+ error: `recipe from-skills step ${i + 1} requires Linux namespace isolation and cgroup v2 resource limits`,
513
+ };
514
+ }
515
+ if (validation.skipped.length > 0) {
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}` };
518
+ }
519
+ if (!validation.passed) {
520
+ return { ok: false, error: `recipe from-skills step ${i + 1} validation failed` };
521
+ }
522
+ const execution = {
523
+ ...(Array.isArray(step.execution.signals)
524
+ ? { signals: step.execution.signals.map((value) => String(value)).filter(Boolean) }
525
+ : {}),
526
+ ...(Array.isArray(step.execution.trigger)
527
+ ? { trigger: step.execution.trigger.map((value) => String(value)).filter(Boolean) }
528
+ : {}),
529
+ ...(typeof step.execution.summary === 'string' && step.execution.summary.trim()
530
+ ? { summary: step.execution.summary.trim() }
531
+ : {}),
532
+ status: 'success',
533
+ score: validation.score,
534
+ started_at: startedAt,
535
+ blast_radius: { files: 0, lines: 0 },
536
+ reference_distilled: true,
537
+ success_reason: 'All declared validation commands passed in the local verifier.',
538
+ trace: validation.results.map((result, index) => ({
539
+ step: index + 1,
540
+ cmd: result.cmd,
541
+ exit: result.exitCode ?? undefined,
542
+ stdout_tail: '',
543
+ })),
544
+ };
545
+ verified.push({ ...step, execution });
546
+ }
547
+ return { ok: true, value: verified };
548
+ }
549
+ function recipeValidationPlanIsComplete(declared, runnable) {
550
+ const declaredCommands = normalizedStringList(declared);
551
+ const runnableCommands = normalizedStringList(runnable);
552
+ return declaredCommands.length === runnableCommands.length &&
553
+ declaredCommands.every((command, index) => command === runnableCommands[index]);
554
+ }
287
555
  function preflightRecipeFromSkillsSteps(steps) {
288
556
  const prepared = [];
289
557
  for (let i = 0; i < steps.length; i += 1) {
290
558
  const step = steps[i];
291
- const parsed = parseSkillMd(step.skill);
292
- const preview = reverseDistill(parsed, step.execution, step.scenario ? { scenario: step.scenario } : {});
559
+ const parsed = parseSkillMd(step.skill, { completeValidationPlan: true });
560
+ const preview = reverseDistill(parsed, step.execution, {
561
+ evidenceMode: 'validation_only',
562
+ ...(step.scenario ? { scenario: step.scenario } : {}),
563
+ });
293
564
  if (!preview.gene) {
294
565
  return {
295
566
  ok: false,
@@ -309,11 +580,74 @@ function preflightRecipeFromSkillsSteps(steps) {
309
580
  position: i,
310
581
  step,
311
582
  candidateSignals: normalizedSignalList(preview.gene.signals_match),
312
- candidateCapsuleId: preview.capsule.id,
583
+ candidateValidations: Array.isArray(preview.gene.validation) ? [...preview.gene.validation] : [],
584
+ candidateDefinition: reusableGeneDefinition(preview.gene),
313
585
  });
314
586
  }
315
587
  return { ok: true, value: prepared };
316
588
  }
589
+ async function prepareRecipeFromSkillsAssets(distilled, store, hub, env, io) {
590
+ const steps = [];
591
+ const prepared = [];
592
+ const publishedByBundle = new Map();
593
+ for (const step of distilled) {
594
+ const bundle = await buildPublishBundle([step.geneAssetId, step.capsuleId], { assetStore: store, env });
595
+ if (!bundle.ok) {
596
+ return { ok: false, error: `recipe from-skills step ${step.position + 1} asset bundle rejected: ${bundle.reason}` };
597
+ }
598
+ if (bundle.blockReasons.length > 0) {
599
+ return { ok: false, error: `recipe from-skills step ${step.position + 1} asset bundle rejected: ${bundle.blockReasons.join(',')}` };
600
+ }
601
+ const gene = bundle.sanitized.find((asset) => asset.type === 'Gene');
602
+ const capsule = bundle.sanitized.find((asset) => asset.type === 'Capsule');
603
+ if (!gene?.asset_id || !capsule?.asset_id) {
604
+ return { ok: false, error: `recipe from-skills step ${step.position + 1} asset bundle is missing Gene or Capsule` };
605
+ }
606
+ const bundleKey = `${gene.asset_id}\n${capsule.asset_id}`;
607
+ let geneAssetId = publishedByBundle.get(bundleKey);
608
+ if (!geneAssetId && hub) {
609
+ const receipt = await callRecipeWithAuthRetry(hub, 'recipe from-skills asset publish', () => hub.publish(bundle.sanitized), io);
610
+ if (!assetPublishSucceeded(receipt, bundle.sanitized)) {
611
+ const duplicateIsIncomplete = receipt.status === 'rejected' &&
612
+ (receipt.reason === 'already_published' || receipt.reason === 'duplicate');
613
+ return {
614
+ ok: false,
615
+ error: duplicateIsIncomplete
616
+ ? `recipe from-skills step ${step.position + 1} duplicate asset publish did not identify the published Gene and Capsule bundle`
617
+ : `recipe from-skills step ${step.position + 1} asset publish rejected: ${receipt.reason ?? receipt.status}`,
618
+ };
619
+ }
620
+ geneAssetId = publishedGeneAssetId(receipt, gene.asset_id);
621
+ if (!geneAssetId) {
622
+ return {
623
+ ok: false,
624
+ error: `recipe from-skills step ${step.position + 1} duplicate asset publish did not identify the published Gene`,
625
+ };
626
+ }
627
+ publishedByBundle.set(bundleKey, geneAssetId);
628
+ }
629
+ geneAssetId ??= gene.asset_id;
630
+ steps.push({ assetId: geneAssetId, assetType: 'Gene', position: step.position });
631
+ prepared.push({ ...step, geneAssetId });
632
+ }
633
+ return { ok: true, value: { steps, distilled: prepared } };
634
+ }
635
+ function assetPublishSucceeded(receipt, submitted) {
636
+ if (receipt.status === 'accepted')
637
+ return true;
638
+ if (receipt.status !== 'rejected' ||
639
+ (receipt.reason !== 'already_published' && receipt.reason !== 'duplicate'))
640
+ return false;
641
+ const published = new Set(receipt.assetIds ?? []);
642
+ return submitted.every((asset) => typeof asset.asset_id === 'string' && published.has(asset.asset_id));
643
+ }
644
+ function publishedGeneAssetId(receipt, localAssetId) {
645
+ if (receipt.status === 'accepted')
646
+ return localAssetId;
647
+ if (receipt.assetId === localAssetId || receipt.assetIds?.includes(localAssetId))
648
+ return localAssetId;
649
+ return undefined;
650
+ }
317
651
  async function findReusableRecipeStep(store, prepared) {
318
652
  const candidateSignals = prepared.candidateSignals;
319
653
  if (candidateSignals.length === 0)
@@ -321,8 +655,11 @@ async function findReusableRecipeStep(store, prepared) {
321
655
  const genes = await store.list('Gene', 10_000);
322
656
  const capsules = await store.list('Capsule', 10_000);
323
657
  for (const gene of genes) {
324
- const signals = new Set(normalizedSignalList(gene['signals_match']));
325
- if (!candidateSignals.every((signal) => signals.has(signal)))
658
+ const signals = normalizedSignalList(gene['signals_match']);
659
+ if (signals.length !== candidateSignals.length ||
660
+ !candidateSignals.every((signal, index) => signal === signals[index]))
661
+ continue;
662
+ if (reusableGeneDefinition(gene) !== prepared.candidateDefinition)
326
663
  continue;
327
664
  const geneId = typeof gene['id'] === 'string' && gene['id'].trim()
328
665
  ? gene['id'].trim()
@@ -330,8 +667,8 @@ async function findReusableRecipeStep(store, prepared) {
330
667
  const geneAssetId = typeof gene['asset_id'] === 'string' ? gene['asset_id'] : '';
331
668
  if (!geneId || !geneAssetId)
332
669
  continue;
333
- const capsule = capsules.find((record) => String(record['id']) === prepared.candidateCapsuleId &&
334
- String(record['gene']) === geneId);
670
+ const capsule = capsules.find((record) => String(record['gene']) === geneId &&
671
+ capsuleProvesValidations(record, prepared.candidateValidations));
335
672
  if (!capsule)
336
673
  continue;
337
674
  return {
@@ -343,6 +680,41 @@ async function findReusableRecipeStep(store, prepared) {
343
680
  }
344
681
  return null;
345
682
  }
683
+ function capsuleProvesValidations(capsule, validations) {
684
+ if (capsule['source_type'] !== 'skill2gep_validation')
685
+ return false;
686
+ const outcome = isPlainRecord(capsule['outcome']) ? capsule['outcome'] : null;
687
+ if (outcome?.['status'] !== 'success')
688
+ return false;
689
+ const trace = Array.isArray(capsule['execution_trace']) ? capsule['execution_trace'] : [];
690
+ return validations.every((validation) => trace.some((entry) => {
691
+ if (!isPlainRecord(entry))
692
+ return false;
693
+ return normalizeValidationCommand(entry['cmd']) === normalizeValidationCommand(validation) && entry['exit'] === 0;
694
+ }));
695
+ }
696
+ function normalizeValidationCommand(value) {
697
+ return String(value ?? '').replace(/\s+/g, ' ').trim();
698
+ }
699
+ function reusableGeneDefinition(gene) {
700
+ const constraints = isPlainRecord(gene['constraints']) ? gene['constraints'] : {};
701
+ return JSON.stringify({
702
+ category: String(gene['category'] ?? ''),
703
+ strategy: normalizedStringList(gene['strategy']),
704
+ summary: String(gene['summary'] ?? ''),
705
+ preconditions: normalizedStringList(gene['preconditions']),
706
+ constraints: {
707
+ maxFiles: Number(constraints['max_files'] ?? 0),
708
+ forbiddenPaths: normalizedStringList(constraints['forbidden_paths']),
709
+ },
710
+ validation: normalizedStringList(gene['validation']).map(normalizeValidationCommand),
711
+ });
712
+ }
713
+ function normalizedStringList(value) {
714
+ return Array.isArray(value)
715
+ ? value.map((item) => String(item).trim()).filter(Boolean)
716
+ : [];
717
+ }
346
718
  function addRecipeFromSkillsStep(steps, distilled, result) {
347
719
  steps.push({ assetId: result.geneAssetId, assetType: 'Gene', position: result.position });
348
720
  distilled.push(result);
@@ -354,14 +726,14 @@ async function hasCapsuleEvidence(store, capsuleId, geneId) {
354
726
  }
355
727
  function normalizedSignalList(value) {
356
728
  return Array.isArray(value)
357
- ? value.map((item) => String(item).trim().toLowerCase()).filter(Boolean)
729
+ ? value.map((item) => String(item).trim().toLowerCase()).filter(Boolean).sort()
358
730
  : [];
359
731
  }
360
732
  function loadRecipeFromSkillsManifest(path) {
361
733
  let raw;
362
734
  const manifestPath = resolve(path);
363
735
  try {
364
- raw = readFileSync(manifestPath, 'utf8');
736
+ raw = readRecipeInputFile(manifestPath);
365
737
  }
366
738
  catch {
367
739
  return { ok: false, error: 'recipe from-skills cannot read --manifest file' };
@@ -390,6 +762,13 @@ function loadRecipeFromSkillsManifest(path) {
390
762
  if (price !== undefined && (!Number.isFinite(price) || price < 0))
391
763
  return { ok: false, error: 'recipe from-skills pricePerExecution must be a non-negative number' };
392
764
  const baseDir = dirname(manifestPath);
765
+ let validationRoot;
766
+ try {
767
+ validationRoot = realpathSync(baseDir);
768
+ }
769
+ catch {
770
+ return { ok: false, error: 'recipe from-skills cannot resolve the manifest directory' };
771
+ }
393
772
  const steps = [];
394
773
  for (let i = 0; i < rawSteps.length; i += 1) {
395
774
  const rawStep = rawSteps[i];
@@ -398,14 +777,24 @@ function loadRecipeFromSkillsManifest(path) {
398
777
  const skillRef = typeof rawStep['skill'] === 'string' ? rawStep['skill'].trim() : '';
399
778
  if (!skillRef)
400
779
  return { ok: false, error: `recipe from-skills step ${i + 1} requires skill` };
780
+ let skillPath;
781
+ try {
782
+ skillPath = realpathSync(resolveManifestRef(baseDir, skillRef));
783
+ }
784
+ catch {
785
+ return { ok: false, error: `recipe from-skills step ${i + 1} cannot read skill` };
786
+ }
787
+ if (!pathIsWithin(validationRoot, skillPath)) {
788
+ return { ok: false, error: `recipe from-skills step ${i + 1} skill must stay within the manifest directory` };
789
+ }
401
790
  let skill;
402
791
  try {
403
- skill = readFileSync(resolveManifestRef(baseDir, skillRef), 'utf8');
792
+ skill = readRecipeInputFile(skillPath);
404
793
  }
405
794
  catch {
406
795
  return { ok: false, error: `recipe from-skills step ${i + 1} cannot read skill` };
407
796
  }
408
- const execution = loadSkillExecution(rawStep['execution'], baseDir, i + 1);
797
+ const execution = loadSkillExecution(rawStep['execution'], baseDir, validationRoot, i + 1);
409
798
  if (!execution.ok)
410
799
  return execution;
411
800
  const scenario = typeof rawStep['scenario'] === 'string' && rawStep['scenario'].trim()
@@ -414,6 +803,8 @@ function loadRecipeFromSkillsManifest(path) {
414
803
  steps.push({
415
804
  skill,
416
805
  execution: execution.value,
806
+ validationCwd: dirname(skillPath),
807
+ validationRoot,
417
808
  ...(scenario ? { scenario } : {}),
418
809
  });
419
810
  }
@@ -430,11 +821,25 @@ function loadRecipeFromSkillsManifest(path) {
430
821
  },
431
822
  };
432
823
  }
433
- function loadSkillExecution(raw, baseDir, stepNumber) {
824
+ function pathIsWithin(root, target) {
825
+ const rel = relative(root, target);
826
+ return rel === '' || (rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));
827
+ }
828
+ function loadSkillExecution(raw, baseDir, validationRoot, stepNumber) {
434
829
  if (typeof raw === 'string' && raw.trim()) {
830
+ let executionPath;
831
+ try {
832
+ executionPath = realpathSync(resolveManifestRef(baseDir, raw.trim()));
833
+ }
834
+ catch {
835
+ return { ok: false, error: `recipe from-skills step ${stepNumber} cannot read execution` };
836
+ }
837
+ if (!pathIsWithin(validationRoot, executionPath)) {
838
+ return { ok: false, error: `recipe from-skills step ${stepNumber} execution must stay within the manifest directory` };
839
+ }
435
840
  let text;
436
841
  try {
437
- text = readFileSync(resolveManifestRef(baseDir, raw.trim()), 'utf8');
842
+ text = readRecipeInputFile(executionPath);
438
843
  }
439
844
  catch {
440
845
  return { ok: false, error: `recipe from-skills step ${stepNumber} cannot read execution` };
@@ -453,6 +858,12 @@ function loadSkillExecution(raw, baseDir, stepNumber) {
453
858
  return { ok: true, value: raw };
454
859
  return { ok: false, error: `recipe from-skills step ${stepNumber} requires execution evidence` };
455
860
  }
861
+ function readRecipeInputFile(path) {
862
+ const stat = statSync(path);
863
+ if (!stat.isFile() || stat.size > MAX_RECIPE_INPUT_BYTES)
864
+ throw new Error('invalid recipe input file');
865
+ return readFileSync(path, 'utf8');
866
+ }
456
867
  function resolveManifestRef(baseDir, ref) {
457
868
  return isAbsolute(ref) ? ref : resolve(baseDir, ref);
458
869
  }
@@ -485,8 +896,8 @@ async function callRecipeWithAuthRetry(hub, tag, fn, io) {
485
896
  throw e;
486
897
  if (!authErrorIndicatesStaleNodeSecret(e))
487
898
  throw e;
488
- io.log(`[${tag}] Hub reported a stale node secret; rotating credentials once and retrying...`);
489
- const hello = await hub.hello({ rotate: true });
899
+ io.err(`[${tag}] Hub reported a stale node secret; rotating credentials once and retrying...`);
900
+ const hello = await hub.hello({ rotate: true, evolverVersion: getCliVersion() });
490
901
  if (!hello.ok) {
491
902
  io.err(`[${tag}] Could not auto-rotate credentials: ${hello.error ?? 'unknown'}`);
492
903
  io.err(' Recover by resetting the Hub credential, then re-run `evolver login` or update EVOMAP_NODE_SECRET.');
@@ -538,6 +949,23 @@ function parseFromSkillsArgs(args) {
538
949
  },
539
950
  };
540
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
+ }
541
969
  function parseReuseArgs(args) {
542
970
  const recipeId = flagValue(args, '--id') ?? firstPositional(args);
543
971
  if (!recipeId)
@@ -570,6 +998,21 @@ function flagValue(args, flag) {
570
998
  function firstPositional(args) {
571
999
  return args.find((a) => typeof a === 'string' && !a.startsWith('--')) ?? null;
572
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
+ }
573
1016
  function parseJsonObject(raw) {
574
1017
  try {
575
1018
  const parsed = JSON.parse(raw);
@@ -642,27 +1085,38 @@ function redactSensitiveString(value) {
642
1085
  function resolveRecipeHubCredentials(env) {
643
1086
  const homeCandidates = recipeHomeCandidates(env);
644
1087
  const defaultHome = homeCandidates[0] ?? events.evomapHome();
645
- const fromEnv = env['EVOMAP_NODE_SECRET']?.trim() || env['A2A_NODE_SECRET']?.trim();
646
- const envNodeSecretVersion = parseNodeSecretVersion(env['EVOMAP_NODE_SECRET_VERSION'] ?? env['A2A_NODE_SECRET_VERSION']);
647
- const stored = readRecipeStoreNodeCredentials(env);
648
- const explicitSenderId = explicitRecipeSenderId(env);
649
- if (stored?.source === 'hub_rotate' && stored.nodeSecret) {
1088
+ const explicitCredentials = resolveExplicitNodeCredentials(env);
1089
+ const fromEnv = explicitCredentials.nodeSecret;
1090
+ const envNodeSecretVersion = parseNodeSecretVersion(explicitCredentials.nodeSecretVersion);
1091
+ const storedCandidate = readRecipeStoreNodeCredentials(env);
1092
+ const stored = storedCandidate?.source?.startsWith('pending_') ? undefined : storedCandidate;
1093
+ const explicitSenderId = explicitCredentials.senderId;
1094
+ const legacy = firstLegacyNodeCredentials(homeCandidates);
1095
+ const pairedStoredSenderId = stored?.nodeSecret
1096
+ ? stored.nodeId
1097
+ ?? (fromEnv === stored.nodeSecret ? explicitSenderId : undefined)
1098
+ ?? (legacy?.nodeSecret === stored.nodeSecret ? legacy.nodeId : undefined)
1099
+ : undefined;
1100
+ const completeExplicitOverridesOrphan = Boolean(fromEnv
1101
+ && explicitSenderId
1102
+ && fromEnv !== stored?.nodeSecret
1103
+ && pairedStoredSenderId !== explicitSenderId);
1104
+ if (stored?.source === 'hub_rotate' && stored.nodeSecret && !completeExplicitOverridesOrphan) {
650
1105
  return {
651
1106
  evomapDir: defaultHome,
652
1107
  nodeSecret: stored.nodeSecret,
653
1108
  ...(stored.nodeSecretVersion !== undefined ? { nodeSecretVersion: stored.nodeSecretVersion } : {}),
654
- senderId: explicitSenderId ?? firstLegacyNodeId(homeCandidates) ?? resolveAtpSenderId(env),
1109
+ senderId: pairedStoredSenderId,
655
1110
  rotatePersistDir: defaultHome,
656
1111
  };
657
1112
  }
658
1113
  if (fromEnv) {
659
- const legacyNodeId = firstLegacyNodeId(homeCandidates);
660
1114
  const nodeSecretVersion = envNodeSecretVersion ?? pairedStoreNodeSecretVersion(fromEnv, stored) ?? pairedLegacyNodeSecretVersion(fromEnv, homeCandidates);
661
1115
  return {
662
1116
  evomapDir: defaultHome,
663
1117
  nodeSecret: fromEnv,
664
1118
  ...(nodeSecretVersion !== undefined ? { nodeSecretVersion } : {}),
665
- senderId: explicitSenderId ?? legacyNodeId ?? resolveAtpSenderId(env),
1119
+ senderId: explicitSenderId ?? (legacy?.nodeSecret === fromEnv ? legacy.nodeId : undefined),
666
1120
  rotatePersistDir: defaultHome,
667
1121
  };
668
1122
  }
@@ -671,27 +1125,38 @@ function resolveRecipeHubCredentials(env) {
671
1125
  evomapDir: defaultHome,
672
1126
  nodeSecret: stored.nodeSecret,
673
1127
  ...(stored.nodeSecretVersion !== undefined ? { nodeSecretVersion: stored.nodeSecretVersion } : {}),
674
- senderId: explicitSenderId ?? firstLegacyNodeId(homeCandidates) ?? resolveAtpSenderId(env),
1128
+ senderId: pairedStoredSenderId,
675
1129
  rotatePersistDir: defaultHome,
676
1130
  };
677
1131
  }
678
- const legacy = firstLegacyNodeCredentials(homeCandidates);
679
1132
  if (legacy) {
680
1133
  return {
681
1134
  evomapDir: legacy.dir,
682
1135
  nodeSecret: legacy.nodeSecret,
683
1136
  ...(legacy.nodeSecretVersion !== undefined ? { nodeSecretVersion: legacy.nodeSecretVersion } : {}),
684
- senderId: legacy.nodeId ?? explicitSenderId ?? firstLegacyNodeId(homeCandidates) ?? resolveAtpSenderId(env),
1137
+ senderId: legacy.nodeId,
685
1138
  rotatePersistDir: legacy.dir,
686
1139
  };
687
1140
  }
688
1141
  const oauthDir = homeCandidates.find((dir) => existsSync(join(dir, 'token.json'))) ?? defaultHome;
689
1142
  return {
690
1143
  evomapDir: oauthDir,
691
- senderId: explicitSenderId ?? firstLegacyNodeId(homeCandidates) ?? resolveAtpSenderId(env),
1144
+ senderId: resolveRecipeOAuthSenderId(env, oauthDir),
692
1145
  rotatePersistDir: oauthDir,
693
1146
  };
694
1147
  }
1148
+ function resolveRecipeOAuthSenderId(env, oauthDir) {
1149
+ const evomapNodeId = env['EVOMAP_NODE_ID']?.trim();
1150
+ if (evomapNodeId)
1151
+ return evomapNodeId;
1152
+ const identityNodeId = readLegacyNodeId(oauthDir);
1153
+ if (identityNodeId)
1154
+ return identityNodeId;
1155
+ const a2aNodeId = env['A2A_NODE_ID']?.trim();
1156
+ if (a2aNodeId)
1157
+ return a2aNodeId;
1158
+ return readRecipeStoreNodeCredentials(env)?.nodeId;
1159
+ }
695
1160
  /**
696
1161
  * The EXPLICIT home overrides (EVOMAP_DIR / EVOLVER_HOME / EVOMAP_HOME) the recipe credential layer honors,
697
1162
  * resolved purely from the passed env with no process.env fallback. Exported so `reset-local-secret` (index.ts)
@@ -701,10 +1166,16 @@ function resolveRecipeHubCredentials(env) {
701
1166
  * the next recipe run (H3). Kept env-pure (no events.evomapHome()) so reset stays hermetic under an injected env.
702
1167
  */
703
1168
  export function explicitRecipeHomes(env) {
1169
+ // Identity-first order (#555 T2): EVOMAP_HOME is THE identity home and outranks the state root
1170
+ // (EVOLVER_HOME). This order decides BOTH the read fall-through AND rotatePersistDir (= homes[0]),
1171
+ // so under the evox agentDir split (EVOMAP_HOME=<agentDir>/evomap, EVOLVER_HOME=<agentDir>/evolver)
1172
+ // a hub-rotated secret persists into the evomap dir the desktop actually reads — the old
1173
+ // EVOLVER_HOME-first order would strand it in the state root and split-brain the node on rotation.
1174
+ // Read-your-writes holds because read and persist share this one order; single-home setups are unchanged.
704
1175
  const explicit = [
1176
+ env['EVOMAP_HOME'],
705
1177
  env['EVOMAP_DIR'],
706
1178
  env['EVOLVER_HOME'],
707
- env['EVOMAP_HOME'],
708
1179
  ];
709
1180
  return uniqueStrings(explicit.map((value) => value?.trim()).filter((value) => Boolean(value)));
710
1181
  }
@@ -718,20 +1189,19 @@ function recipeHomeCandidates(env) {
718
1189
  ];
719
1190
  return uniqueStrings(candidates.map((value) => value?.trim()).filter((value) => Boolean(value)));
720
1191
  }
721
- function explicitRecipeSenderId(env) {
722
- return env['EVOMAP_NODE_ID']?.trim() || env['A2A_NODE_ID']?.trim();
723
- }
724
1192
  function readRecipeStoreNodeCredentials(env) {
725
1193
  const storePath = recipeProxyStorePath(env);
726
1194
  if (!existsSync(storePath))
727
1195
  return undefined;
728
1196
  const store = new mailbox.MailboxStore({ path: storePath });
729
1197
  try {
1198
+ const nodeId = store.getState('node_id')?.trim() || undefined;
730
1199
  const storedSecret = store.getState('node_secret');
731
1200
  const nodeSecret = storedSecret && isNodeSecret(storedSecret) ? storedSecret : undefined;
732
1201
  const nodeSecretVersion = parseNodeSecretVersion(store.getState('node_secret_version'));
733
1202
  const source = store.getState('node_secret_source') || undefined;
734
1203
  return {
1204
+ ...(nodeId ? { nodeId } : {}),
735
1205
  ...(nodeSecret ? { nodeSecret } : {}),
736
1206
  ...(nodeSecretVersion !== undefined ? { nodeSecretVersion } : {}),
737
1207
  ...(source ? { source } : {}),
@@ -783,14 +1253,6 @@ function firstLegacyNodeCredentials(dirs) {
783
1253
  }
784
1254
  return undefined;
785
1255
  }
786
- function firstLegacyNodeId(dirs) {
787
- for (const dir of dirs) {
788
- const nodeId = readLegacyNodeId(dir);
789
- if (nodeId)
790
- return nodeId;
791
- }
792
- return undefined;
793
- }
794
1256
  function uniqueStrings(values) {
795
1257
  const seen = new Set();
796
1258
  const out = [];
@@ -819,19 +1281,33 @@ function recipeProxyStorePath(env) {
819
1281
  function setOptionalStoreState(store, key, value) {
820
1282
  store.setState(key, value ?? '');
821
1283
  }
822
- function persistRotatedNodeSecret(secret, version, env, legacyDir) {
1284
+ function persistRotatedNodeSecret(secret, version, nodeId, env, legacyDir) {
823
1285
  const storePath = recipeProxyStorePath(env);
824
1286
  const store = new mailbox.MailboxStore({ path: storePath });
825
1287
  try {
1288
+ store.setState('node_secret_source', 'pending_rotate');
1289
+ if (nodeId)
1290
+ store.setState('node_id', nodeId);
826
1291
  store.setState('node_secret', secret);
827
- store.setState('node_secret_source', 'hub_rotate');
828
1292
  setOptionalStoreState(store, 'node_secret_version', version !== undefined ? String(version) : undefined);
1293
+ store.setState('node_secret_source', 'hub_rotate');
829
1294
  }
830
1295
  finally {
831
1296
  store.close();
832
1297
  }
833
1298
  persistLegacyNodeSecret(secret, version, legacyDir);
834
1299
  }
1300
+ function persistRecipeNodeId(nodeId, env, legacyDir) {
1301
+ const store = new mailbox.MailboxStore({ path: recipeProxyStorePath(env) });
1302
+ try {
1303
+ store.setState('node_id', nodeId);
1304
+ }
1305
+ finally {
1306
+ store.close();
1307
+ }
1308
+ mkdirSync(legacyDir, { recursive: true, mode: 0o700 });
1309
+ writeFileSync(join(legacyDir, 'node_id'), nodeId, { encoding: 'utf8', mode: 0o600 });
1310
+ }
835
1311
  function persistNodeSecretVersion(version, env, legacyDir) {
836
1312
  const storePath = recipeProxyStorePath(env);
837
1313
  const store = new mailbox.MailboxStore({ path: storePath });
@@ -902,5 +1378,7 @@ function recipeUsage() {
902
1378
  ' evolver recipe from-skills --manifest <file> [--publish] [--json]',
903
1379
  ' Distills ordered SKILL.md steps with execution evidence, then creates a recipe.',
904
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.`,
905
1383
  ].join('\n');
906
1384
  }