@evomap/evolver-cli 2.0.0-beta.14 → 2.0.0-beta.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/recipe.js CHANGED
@@ -1,17 +1,26 @@
1
- import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';
1
+ import { existsSync, mkdirSync, readFileSync, realpathSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
2
2
  import { createHash } from 'node:crypto';
3
3
  import { homedir } from 'node:os';
4
- import { dirname, isAbsolute, join, resolve } from 'node:path';
5
- 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';
6
6
  import { AuthError, HubClientError, HubUnreachableError, connectPublicHub, isHubDryRunEnabled, isNodeSecret, parseNodeSecretVersion, resolveHubUrl } from '@evomap/evolver-adapter-public';
7
7
  import { loadEnvFileFromEnv } from '@evomap/evolver-mcp';
8
- import { resolveAtpSenderId } from './atp.js';
9
- 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';
10
11
  import { recordSkillDistillation } from './skillDistill.js';
12
+ import { buildPublishBundle } from './cliContracts.js';
11
13
  const MAX_RECIPE_STEPS = 20;
14
+ const MAX_RECIPE_VALIDATION_COMMANDS = 5;
15
+ const MAX_RECIPE_INPUT_BYTES = 1024 * 1024;
12
16
  const MAX_ID_LENGTH = 200;
13
17
  const SENSITIVE_ERROR_KEYS = new Set(['authorization', 'node_secret', 'nodesecret', 'token', 'access_token', 'refresh_token', 'secret']);
14
18
  const STALE_NODE_SECRET_ERRORS = new Set(['node_secret_invalid', 'node_secret_not_set']);
19
+ function recipeIdempotencyKey(operation, value) {
20
+ const digest = createHash('sha256').update(JSON.stringify(value)).digest('hex');
21
+ return `evolver-recipe-${operation}-${digest}`;
22
+ }
23
+ const recipeIdentityBootstraps = new WeakMap();
15
24
  export async function runRecipeCommand(argv, deps = {}) {
16
25
  const parsed = parseRecipeArgs(argv);
17
26
  const err = deps.err ?? ((line) => { process.stderr.write(`${line}\n`); });
@@ -22,6 +31,7 @@ export async function runRecipeCommand(argv, deps = {}) {
22
31
  }
23
32
  try {
24
33
  const env = deps.env ?? process.env;
34
+ loadEnvFileFromEnv(env);
25
35
  if (isHubDryRunEnabled(env)) {
26
36
  if (parsed.value.sub === 'build')
27
37
  return await runRecipeBuildDryRun(parsed.value, deps.store, { log, err });
@@ -30,6 +40,7 @@ export async function runRecipeCommand(argv, deps = {}) {
30
40
  return runRecipeReuseDryRun(parsed.value, { log });
31
41
  }
32
42
  const hub = deps.hub ?? createRecipeHubFromEnv(env, deps.connectHub ?? connectPublicHub);
43
+ await recipeIdentityBootstraps.get(hub)?.();
33
44
  if (!hub.recipes) {
34
45
  err('recipe capability is not available for the configured Hub adapter');
35
46
  return 1;
@@ -83,6 +94,7 @@ export function createRecipeHubFromEnv(env = process.env, connectHub = connectPu
83
94
  if (!credentials.nodeSecret && !credentials.senderId) {
84
95
  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');
85
96
  }
97
+ let senderId = credentials.senderId;
86
98
  const connected = credentials.nodeSecret
87
99
  ? connectHub({
88
100
  hubUrl,
@@ -90,11 +102,26 @@ export function createRecipeHubFromEnv(env = process.env, connectHub = connectPu
90
102
  evomapDir: credentials.evomapDir,
91
103
  nodeSecret: credentials.nodeSecret,
92
104
  ...(credentials.nodeSecretVersion !== undefined ? { nodeSecretVersion: credentials.nodeSecretVersion } : {}),
93
- senderId: () => credentials.senderId,
94
- onNodeSecretRotated: (secret, version) => persistRotatedNodeSecret(secret, version, env, credentials.rotatePersistDir),
105
+ senderId: () => senderId,
106
+ onNodeSecretRotated: (secret, version) => persistRotatedNodeSecret(secret, version, senderId, env, credentials.rotatePersistDir),
95
107
  onNodeSecretVersionUpdated: (version) => persistNodeSecretVersion(version, env, credentials.rotatePersistDir),
96
108
  })
97
- : connectHub({ hubUrl, authMode: 'oauth', evomapDir: credentials.evomapDir, senderId: () => credentials.senderId });
109
+ : connectHub({ hubUrl, authMode: 'oauth', evomapDir: credentials.evomapDir, senderId: () => senderId });
110
+ if (credentials.nodeSecret && !senderId) {
111
+ recipeIdentityBootstraps.set(connected.hub, async () => {
112
+ const hello = await connected.hub.hello({
113
+ rotate: false,
114
+ evolverVersion: getCliVersion(),
115
+ preserveCredentials: true,
116
+ });
117
+ if (!hello.ok || !hello.nodeId) {
118
+ throw new Error(`recipe could not establish Hub node identity: ${hello.error ?? 'node_id_missing'}`);
119
+ }
120
+ senderId = hello.nodeId;
121
+ persistRecipeNodeId(senderId, env, credentials.rotatePersistDir);
122
+ recipeIdentityBootstraps.delete(connected.hub);
123
+ });
124
+ }
98
125
  return connected.hub;
99
126
  }
100
127
  /** Opaque identity for resume isolation; raw credentials, account ids, and local paths never leave this helper. */
@@ -141,20 +168,32 @@ async function runRecipeBuild(opts, hub, store, io) {
141
168
  io.err('recipe build requires at least one asset id');
142
169
  return 1;
143
170
  }
144
- const createReceipt = await callRecipeWithAuthRetry(hub, 'recipe build', () => hub.recipes.create({
171
+ const createRequest = {
145
172
  title: opts.title,
146
173
  steps,
147
174
  ...(opts.description ? { description: opts.description } : {}),
148
175
  ...(opts.pricePerExecution !== undefined ? { pricePerExecution: opts.pricePerExecution } : {}),
149
- }), io);
176
+ };
177
+ createRequest.idempotencyKey = recipeIdempotencyKey('create', createRequest);
178
+ const createReceipt = await callRecipeWithAuthRetry(hub, 'recipe build', () => hub.recipes.create(createRequest), io);
150
179
  const recipeId = createReceipt.recipeId;
180
+ if (createReceipt.status !== 'draft') {
181
+ io.err(`[recipe build] Hub returned unexpected create status: ${createReceipt.status ?? 'unknown'}.`);
182
+ return 1;
183
+ }
151
184
  io.log(`[recipe build] Created DRAFT recipe ${recipeId ?? '(id pending)'} ("${opts.title}", ${steps.length} step${steps.length === 1 ? '' : 's'}).`);
152
185
  if (opts.publish) {
153
186
  if (!recipeId) {
154
187
  io.err('[recipe build] Hub did not return a recipe id; cannot publish.');
155
188
  return 1;
156
189
  }
157
- await callRecipeWithAuthRetry(hub, 'recipe build', () => hub.recipes.publish(recipeId), io);
190
+ const publishReceipt = await callRecipeWithAuthRetry(hub, 'recipe build', () => hub.recipes.publish(recipeId, {
191
+ idempotencyKey: recipeIdempotencyKey('publish', recipeId),
192
+ }), io);
193
+ if (publishReceipt.status !== 'published') {
194
+ io.err(`[recipe build] Hub returned unexpected publish status: ${publishReceipt.status ?? 'unknown'}.`);
195
+ return 1;
196
+ }
158
197
  io.log(`[recipe build] Published recipe ${recipeId}.`);
159
198
  }
160
199
  else {
@@ -168,7 +207,12 @@ async function runRecipeFromSkills(opts, hub, deps, io, dryRun) {
168
207
  io.err(loaded.error);
169
208
  return 1;
170
209
  }
171
- const preflight = preflightRecipeFromSkillsSteps(loaded.value.steps);
210
+ const verified = await verifyRecipeFromSkillsSteps(loaded.value.steps, deps.runValidation ?? verify.runSandboxedValidation);
211
+ if (!verified.ok) {
212
+ io.err(verified.error);
213
+ return 1;
214
+ }
215
+ const preflight = preflightRecipeFromSkillsSteps(verified.value);
172
216
  if (!preflight.ok) {
173
217
  io.err(preflight.error);
174
218
  return 1;
@@ -188,7 +232,12 @@ async function runRecipeFromSkills(opts, hub, deps, io, dryRun) {
188
232
  store,
189
233
  ...(deps.review ? { review: deps.review } : {}),
190
234
  ingestor,
191
- }, step.scenario ? { scenario: step.scenario } : {});
235
+ }, {
236
+ evidenceMode: 'validation_only',
237
+ geneIdentity: 'semantic',
238
+ completeValidationPlan: true,
239
+ ...(step.scenario ? { scenario: step.scenario } : {}),
240
+ });
192
241
  if (!res.geneId || !res.geneAssetId) {
193
242
  const recovered = await findReusableRecipeStep(store, prepared);
194
243
  if (recovered) {
@@ -213,6 +262,13 @@ async function runRecipeFromSkills(opts, hub, deps, io, dryRun) {
213
262
  capsuleId: res.capsuleId,
214
263
  });
215
264
  }
265
+ const publishPrepared = await prepareRecipeFromSkillsAssets(distilled, store, dryRun ? undefined : hub, deps.env ?? process.env, io);
266
+ if (!publishPrepared.ok) {
267
+ io.err(publishPrepared.error);
268
+ return 1;
269
+ }
270
+ steps.splice(0, steps.length, ...publishPrepared.value.steps);
271
+ distilled.splice(0, distilled.length, ...publishPrepared.value.distilled);
216
272
  if (dryRun) {
217
273
  const payload = recipeFromSkillsPayload({
218
274
  mode: 'dry_run',
@@ -235,13 +291,32 @@ async function runRecipeFromSkills(opts, hub, deps, io, dryRun) {
235
291
  io.err('recipe capability is not available for the configured Hub adapter');
236
292
  return 1;
237
293
  }
238
- const createReceipt = await callRecipeWithAuthRetry(hub, 'recipe from-skills', () => hub.recipes.create({
294
+ const createRequest = {
239
295
  title: loaded.value.title,
240
296
  steps,
241
297
  ...(loaded.value.description ? { description: loaded.value.description } : {}),
242
298
  ...(loaded.value.pricePerExecution !== undefined ? { pricePerExecution: loaded.value.pricePerExecution } : {}),
243
- }), io);
299
+ };
300
+ createRequest.idempotencyKey = recipeIdempotencyKey('create', createRequest);
301
+ const createReceipt = await callRecipeWithAuthRetry(hub, 'recipe from-skills', () => hub.recipes.create(createRequest), io);
244
302
  const recipeId = createReceipt.recipeId;
303
+ if (createReceipt.status !== 'draft') {
304
+ if (opts.jsonOut) {
305
+ io.log(JSON.stringify(recipeFromSkillsPayload({
306
+ ok: false,
307
+ mode: 'failed',
308
+ title: loaded.value.title,
309
+ publish: opts.publish,
310
+ steps: distilled,
311
+ recipeId,
312
+ error: 'create_failed',
313
+ }), null, 2));
314
+ }
315
+ else {
316
+ io.err(`[recipe from-skills] Hub did not confirm draft creation for recipe ${recipeId ?? '(id missing)'} (status: ${createReceipt.status ?? 'missing'}).`);
317
+ }
318
+ return 1;
319
+ }
245
320
  if (!opts.jsonOut) {
246
321
  io.log(`[recipe from-skills] Created DRAFT recipe ${recipeId ?? '(id pending)'} ("${loaded.value.title}", ${steps.length} step${steps.length === 1 ? '' : 's'}).`);
247
322
  }
@@ -251,7 +326,26 @@ async function runRecipeFromSkills(opts, hub, deps, io, dryRun) {
251
326
  return 1;
252
327
  }
253
328
  try {
254
- await callRecipeWithAuthRetry(hub, 'recipe from-skills', () => hub.recipes.publish(recipeId), io);
329
+ const publishReceipt = await callRecipeWithAuthRetry(hub, 'recipe from-skills', () => hub.recipes.publish(recipeId, {
330
+ idempotencyKey: recipeIdempotencyKey('publish', recipeId),
331
+ }), io);
332
+ if (publishReceipt.status !== 'published') {
333
+ if (opts.jsonOut) {
334
+ io.log(JSON.stringify(recipeFromSkillsPayload({
335
+ ok: false,
336
+ mode: 'draft',
337
+ title: loaded.value.title,
338
+ publish: opts.publish,
339
+ steps: distilled,
340
+ recipeId,
341
+ error: 'publish_failed',
342
+ }), null, 2));
343
+ }
344
+ else {
345
+ io.err(`[recipe from-skills] Created DRAFT recipe ${recipeId}; Hub did not confirm publish (status: ${publishReceipt.status ?? 'missing'}).`);
346
+ }
347
+ return 1;
348
+ }
255
349
  }
256
350
  catch (e) {
257
351
  if (opts.jsonOut) {
@@ -309,12 +403,96 @@ async function recipeStepsFromLocalAssets(assetIds, store) {
309
403
  return { assetId, assetType, position: index };
310
404
  });
311
405
  }
406
+ async function verifyRecipeFromSkillsSteps(steps, runValidation) {
407
+ const verified = [];
408
+ for (let i = 0; i < steps.length; i += 1) {
409
+ const step = steps[i];
410
+ const parsed = parseSkillMd(step.skill, { completeValidationPlan: true });
411
+ if (parsed.validation.length > MAX_RECIPE_VALIDATION_COMMANDS) {
412
+ return {
413
+ ok: false,
414
+ error: `recipe from-skills step ${i + 1} supports at most ${MAX_RECIPE_VALIDATION_COMMANDS} validation commands`,
415
+ };
416
+ }
417
+ const synthesized = synthesizeGene(parsed, step.execution, { strict: true });
418
+ if (!synthesized.gene) {
419
+ return {
420
+ ok: false,
421
+ error: `recipe from-skills step ${i + 1} did not produce a Gene: ${synthesized.errors.join('; ') || 'refused'}`,
422
+ };
423
+ }
424
+ if (!recipeValidationPlanIsComplete(parsed.validation, synthesized.gene.validation)) {
425
+ return {
426
+ ok: false,
427
+ error: `recipe from-skills step ${i + 1} contains unsupported validation commands; every declared command must be allowed`,
428
+ };
429
+ }
430
+ const startedAt = new Date().toISOString();
431
+ let validation;
432
+ try {
433
+ validation = await runValidation(synthesized.gene.validation ?? [], step.validationCwd, {
434
+ requireIsolation: true,
435
+ readOnlyRoot: step.validationRoot,
436
+ });
437
+ }
438
+ catch {
439
+ return { ok: false, error: `recipe from-skills step ${i + 1} validation execution failed` };
440
+ }
441
+ if (!validation.isolated) {
442
+ return {
443
+ ok: false,
444
+ error: `recipe from-skills step ${i + 1} requires Linux namespace isolation and cgroup v2 resource limits`,
445
+ };
446
+ }
447
+ 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}` };
450
+ }
451
+ if (!validation.passed) {
452
+ return { ok: false, error: `recipe from-skills step ${i + 1} validation failed` };
453
+ }
454
+ const execution = {
455
+ ...(Array.isArray(step.execution.signals)
456
+ ? { signals: step.execution.signals.map((value) => String(value)).filter(Boolean) }
457
+ : {}),
458
+ ...(Array.isArray(step.execution.trigger)
459
+ ? { trigger: step.execution.trigger.map((value) => String(value)).filter(Boolean) }
460
+ : {}),
461
+ ...(typeof step.execution.summary === 'string' && step.execution.summary.trim()
462
+ ? { summary: step.execution.summary.trim() }
463
+ : {}),
464
+ status: 'success',
465
+ score: validation.score,
466
+ started_at: startedAt,
467
+ blast_radius: { files: 0, lines: 0 },
468
+ reference_distilled: true,
469
+ success_reason: 'All declared validation commands passed in the local verifier.',
470
+ trace: validation.results.map((result, index) => ({
471
+ step: index + 1,
472
+ cmd: result.cmd,
473
+ exit: result.exitCode ?? undefined,
474
+ stdout_tail: '',
475
+ })),
476
+ };
477
+ verified.push({ ...step, execution });
478
+ }
479
+ return { ok: true, value: verified };
480
+ }
481
+ function recipeValidationPlanIsComplete(declared, runnable) {
482
+ const declaredCommands = normalizedStringList(declared);
483
+ const runnableCommands = normalizedStringList(runnable);
484
+ return declaredCommands.length === runnableCommands.length &&
485
+ declaredCommands.every((command, index) => command === runnableCommands[index]);
486
+ }
312
487
  function preflightRecipeFromSkillsSteps(steps) {
313
488
  const prepared = [];
314
489
  for (let i = 0; i < steps.length; i += 1) {
315
490
  const step = steps[i];
316
- const parsed = parseSkillMd(step.skill);
317
- const preview = reverseDistill(parsed, step.execution, step.scenario ? { scenario: step.scenario } : {});
491
+ const parsed = parseSkillMd(step.skill, { completeValidationPlan: true });
492
+ const preview = reverseDistill(parsed, step.execution, {
493
+ evidenceMode: 'validation_only',
494
+ ...(step.scenario ? { scenario: step.scenario } : {}),
495
+ });
318
496
  if (!preview.gene) {
319
497
  return {
320
498
  ok: false,
@@ -334,11 +512,74 @@ function preflightRecipeFromSkillsSteps(steps) {
334
512
  position: i,
335
513
  step,
336
514
  candidateSignals: normalizedSignalList(preview.gene.signals_match),
337
- candidateCapsuleId: preview.capsule.id,
515
+ candidateValidations: Array.isArray(preview.gene.validation) ? [...preview.gene.validation] : [],
516
+ candidateDefinition: reusableGeneDefinition(preview.gene),
338
517
  });
339
518
  }
340
519
  return { ok: true, value: prepared };
341
520
  }
521
+ async function prepareRecipeFromSkillsAssets(distilled, store, hub, env, io) {
522
+ const steps = [];
523
+ const prepared = [];
524
+ const publishedByBundle = new Map();
525
+ for (const step of distilled) {
526
+ const bundle = await buildPublishBundle([step.geneAssetId, step.capsuleId], { assetStore: store, env });
527
+ if (!bundle.ok) {
528
+ return { ok: false, error: `recipe from-skills step ${step.position + 1} asset bundle rejected: ${bundle.reason}` };
529
+ }
530
+ if (bundle.blockReasons.length > 0) {
531
+ return { ok: false, error: `recipe from-skills step ${step.position + 1} asset bundle rejected: ${bundle.blockReasons.join(',')}` };
532
+ }
533
+ const gene = bundle.sanitized.find((asset) => asset.type === 'Gene');
534
+ const capsule = bundle.sanitized.find((asset) => asset.type === 'Capsule');
535
+ if (!gene?.asset_id || !capsule?.asset_id) {
536
+ return { ok: false, error: `recipe from-skills step ${step.position + 1} asset bundle is missing Gene or Capsule` };
537
+ }
538
+ const bundleKey = `${gene.asset_id}\n${capsule.asset_id}`;
539
+ let geneAssetId = publishedByBundle.get(bundleKey);
540
+ if (!geneAssetId && hub) {
541
+ const receipt = await callRecipeWithAuthRetry(hub, 'recipe from-skills asset publish', () => hub.publish(bundle.sanitized), io);
542
+ if (!assetPublishSucceeded(receipt, bundle.sanitized)) {
543
+ const duplicateIsIncomplete = receipt.status === 'rejected' &&
544
+ (receipt.reason === 'already_published' || receipt.reason === 'duplicate');
545
+ return {
546
+ ok: false,
547
+ error: duplicateIsIncomplete
548
+ ? `recipe from-skills step ${step.position + 1} duplicate asset publish did not identify the published Gene and Capsule bundle`
549
+ : `recipe from-skills step ${step.position + 1} asset publish rejected: ${receipt.reason ?? receipt.status}`,
550
+ };
551
+ }
552
+ geneAssetId = publishedGeneAssetId(receipt, gene.asset_id);
553
+ if (!geneAssetId) {
554
+ return {
555
+ ok: false,
556
+ error: `recipe from-skills step ${step.position + 1} duplicate asset publish did not identify the published Gene`,
557
+ };
558
+ }
559
+ publishedByBundle.set(bundleKey, geneAssetId);
560
+ }
561
+ geneAssetId ??= gene.asset_id;
562
+ steps.push({ assetId: geneAssetId, assetType: 'Gene', position: step.position });
563
+ prepared.push({ ...step, geneAssetId });
564
+ }
565
+ return { ok: true, value: { steps, distilled: prepared } };
566
+ }
567
+ function assetPublishSucceeded(receipt, submitted) {
568
+ if (receipt.status === 'accepted')
569
+ return true;
570
+ if (receipt.status !== 'rejected' ||
571
+ (receipt.reason !== 'already_published' && receipt.reason !== 'duplicate'))
572
+ return false;
573
+ const published = new Set(receipt.assetIds ?? []);
574
+ return submitted.every((asset) => typeof asset.asset_id === 'string' && published.has(asset.asset_id));
575
+ }
576
+ function publishedGeneAssetId(receipt, localAssetId) {
577
+ if (receipt.status === 'accepted')
578
+ return localAssetId;
579
+ if (receipt.assetId === localAssetId || receipt.assetIds?.includes(localAssetId))
580
+ return localAssetId;
581
+ return undefined;
582
+ }
342
583
  async function findReusableRecipeStep(store, prepared) {
343
584
  const candidateSignals = prepared.candidateSignals;
344
585
  if (candidateSignals.length === 0)
@@ -346,8 +587,11 @@ async function findReusableRecipeStep(store, prepared) {
346
587
  const genes = await store.list('Gene', 10_000);
347
588
  const capsules = await store.list('Capsule', 10_000);
348
589
  for (const gene of genes) {
349
- const signals = new Set(normalizedSignalList(gene['signals_match']));
350
- if (!candidateSignals.every((signal) => signals.has(signal)))
590
+ const signals = normalizedSignalList(gene['signals_match']);
591
+ if (signals.length !== candidateSignals.length ||
592
+ !candidateSignals.every((signal, index) => signal === signals[index]))
593
+ continue;
594
+ if (reusableGeneDefinition(gene) !== prepared.candidateDefinition)
351
595
  continue;
352
596
  const geneId = typeof gene['id'] === 'string' && gene['id'].trim()
353
597
  ? gene['id'].trim()
@@ -355,8 +599,8 @@ async function findReusableRecipeStep(store, prepared) {
355
599
  const geneAssetId = typeof gene['asset_id'] === 'string' ? gene['asset_id'] : '';
356
600
  if (!geneId || !geneAssetId)
357
601
  continue;
358
- const capsule = capsules.find((record) => String(record['id']) === prepared.candidateCapsuleId &&
359
- String(record['gene']) === geneId);
602
+ const capsule = capsules.find((record) => String(record['gene']) === geneId &&
603
+ capsuleProvesValidations(record, prepared.candidateValidations));
360
604
  if (!capsule)
361
605
  continue;
362
606
  return {
@@ -368,6 +612,41 @@ async function findReusableRecipeStep(store, prepared) {
368
612
  }
369
613
  return null;
370
614
  }
615
+ function capsuleProvesValidations(capsule, validations) {
616
+ if (capsule['source_type'] !== 'skill2gep_validation')
617
+ return false;
618
+ const outcome = isPlainRecord(capsule['outcome']) ? capsule['outcome'] : null;
619
+ if (outcome?.['status'] !== 'success')
620
+ return false;
621
+ const trace = Array.isArray(capsule['execution_trace']) ? capsule['execution_trace'] : [];
622
+ return validations.every((validation) => trace.some((entry) => {
623
+ if (!isPlainRecord(entry))
624
+ return false;
625
+ return normalizeValidationCommand(entry['cmd']) === normalizeValidationCommand(validation) && entry['exit'] === 0;
626
+ }));
627
+ }
628
+ function normalizeValidationCommand(value) {
629
+ return String(value ?? '').replace(/\s+/g, ' ').trim();
630
+ }
631
+ function reusableGeneDefinition(gene) {
632
+ const constraints = isPlainRecord(gene['constraints']) ? gene['constraints'] : {};
633
+ return JSON.stringify({
634
+ category: String(gene['category'] ?? ''),
635
+ strategy: normalizedStringList(gene['strategy']),
636
+ summary: String(gene['summary'] ?? ''),
637
+ preconditions: normalizedStringList(gene['preconditions']),
638
+ constraints: {
639
+ maxFiles: Number(constraints['max_files'] ?? 0),
640
+ forbiddenPaths: normalizedStringList(constraints['forbidden_paths']),
641
+ },
642
+ validation: normalizedStringList(gene['validation']).map(normalizeValidationCommand),
643
+ });
644
+ }
645
+ function normalizedStringList(value) {
646
+ return Array.isArray(value)
647
+ ? value.map((item) => String(item).trim()).filter(Boolean)
648
+ : [];
649
+ }
371
650
  function addRecipeFromSkillsStep(steps, distilled, result) {
372
651
  steps.push({ assetId: result.geneAssetId, assetType: 'Gene', position: result.position });
373
652
  distilled.push(result);
@@ -379,14 +658,14 @@ async function hasCapsuleEvidence(store, capsuleId, geneId) {
379
658
  }
380
659
  function normalizedSignalList(value) {
381
660
  return Array.isArray(value)
382
- ? value.map((item) => String(item).trim().toLowerCase()).filter(Boolean)
661
+ ? value.map((item) => String(item).trim().toLowerCase()).filter(Boolean).sort()
383
662
  : [];
384
663
  }
385
664
  function loadRecipeFromSkillsManifest(path) {
386
665
  let raw;
387
666
  const manifestPath = resolve(path);
388
667
  try {
389
- raw = readFileSync(manifestPath, 'utf8');
668
+ raw = readRecipeInputFile(manifestPath);
390
669
  }
391
670
  catch {
392
671
  return { ok: false, error: 'recipe from-skills cannot read --manifest file' };
@@ -415,6 +694,13 @@ function loadRecipeFromSkillsManifest(path) {
415
694
  if (price !== undefined && (!Number.isFinite(price) || price < 0))
416
695
  return { ok: false, error: 'recipe from-skills pricePerExecution must be a non-negative number' };
417
696
  const baseDir = dirname(manifestPath);
697
+ let validationRoot;
698
+ try {
699
+ validationRoot = realpathSync(baseDir);
700
+ }
701
+ catch {
702
+ return { ok: false, error: 'recipe from-skills cannot resolve the manifest directory' };
703
+ }
418
704
  const steps = [];
419
705
  for (let i = 0; i < rawSteps.length; i += 1) {
420
706
  const rawStep = rawSteps[i];
@@ -423,14 +709,24 @@ function loadRecipeFromSkillsManifest(path) {
423
709
  const skillRef = typeof rawStep['skill'] === 'string' ? rawStep['skill'].trim() : '';
424
710
  if (!skillRef)
425
711
  return { ok: false, error: `recipe from-skills step ${i + 1} requires skill` };
712
+ let skillPath;
713
+ try {
714
+ skillPath = realpathSync(resolveManifestRef(baseDir, skillRef));
715
+ }
716
+ catch {
717
+ return { ok: false, error: `recipe from-skills step ${i + 1} cannot read skill` };
718
+ }
719
+ if (!pathIsWithin(validationRoot, skillPath)) {
720
+ return { ok: false, error: `recipe from-skills step ${i + 1} skill must stay within the manifest directory` };
721
+ }
426
722
  let skill;
427
723
  try {
428
- skill = readFileSync(resolveManifestRef(baseDir, skillRef), 'utf8');
724
+ skill = readRecipeInputFile(skillPath);
429
725
  }
430
726
  catch {
431
727
  return { ok: false, error: `recipe from-skills step ${i + 1} cannot read skill` };
432
728
  }
433
- const execution = loadSkillExecution(rawStep['execution'], baseDir, i + 1);
729
+ const execution = loadSkillExecution(rawStep['execution'], baseDir, validationRoot, i + 1);
434
730
  if (!execution.ok)
435
731
  return execution;
436
732
  const scenario = typeof rawStep['scenario'] === 'string' && rawStep['scenario'].trim()
@@ -439,6 +735,8 @@ function loadRecipeFromSkillsManifest(path) {
439
735
  steps.push({
440
736
  skill,
441
737
  execution: execution.value,
738
+ validationCwd: dirname(skillPath),
739
+ validationRoot,
442
740
  ...(scenario ? { scenario } : {}),
443
741
  });
444
742
  }
@@ -455,11 +753,25 @@ function loadRecipeFromSkillsManifest(path) {
455
753
  },
456
754
  };
457
755
  }
458
- function loadSkillExecution(raw, baseDir, stepNumber) {
756
+ function pathIsWithin(root, target) {
757
+ const rel = relative(root, target);
758
+ return rel === '' || (rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));
759
+ }
760
+ function loadSkillExecution(raw, baseDir, validationRoot, stepNumber) {
459
761
  if (typeof raw === 'string' && raw.trim()) {
762
+ let executionPath;
763
+ try {
764
+ executionPath = realpathSync(resolveManifestRef(baseDir, raw.trim()));
765
+ }
766
+ catch {
767
+ return { ok: false, error: `recipe from-skills step ${stepNumber} cannot read execution` };
768
+ }
769
+ if (!pathIsWithin(validationRoot, executionPath)) {
770
+ return { ok: false, error: `recipe from-skills step ${stepNumber} execution must stay within the manifest directory` };
771
+ }
460
772
  let text;
461
773
  try {
462
- text = readFileSync(resolveManifestRef(baseDir, raw.trim()), 'utf8');
774
+ text = readRecipeInputFile(executionPath);
463
775
  }
464
776
  catch {
465
777
  return { ok: false, error: `recipe from-skills step ${stepNumber} cannot read execution` };
@@ -478,6 +790,12 @@ function loadSkillExecution(raw, baseDir, stepNumber) {
478
790
  return { ok: true, value: raw };
479
791
  return { ok: false, error: `recipe from-skills step ${stepNumber} requires execution evidence` };
480
792
  }
793
+ function readRecipeInputFile(path) {
794
+ const stat = statSync(path);
795
+ if (!stat.isFile() || stat.size > MAX_RECIPE_INPUT_BYTES)
796
+ throw new Error('invalid recipe input file');
797
+ return readFileSync(path, 'utf8');
798
+ }
481
799
  function resolveManifestRef(baseDir, ref) {
482
800
  return isAbsolute(ref) ? ref : resolve(baseDir, ref);
483
801
  }
@@ -510,7 +828,7 @@ async function callRecipeWithAuthRetry(hub, tag, fn, io) {
510
828
  throw e;
511
829
  if (!authErrorIndicatesStaleNodeSecret(e))
512
830
  throw e;
513
- io.log(`[${tag}] Hub reported a stale node secret; rotating credentials once and retrying...`);
831
+ io.err(`[${tag}] Hub reported a stale node secret; rotating credentials once and retrying...`);
514
832
  const hello = await hub.hello({ rotate: true });
515
833
  if (!hello.ok) {
516
834
  io.err(`[${tag}] Could not auto-rotate credentials: ${hello.error ?? 'unknown'}`);
@@ -667,27 +985,38 @@ function redactSensitiveString(value) {
667
985
  function resolveRecipeHubCredentials(env) {
668
986
  const homeCandidates = recipeHomeCandidates(env);
669
987
  const defaultHome = homeCandidates[0] ?? events.evomapHome();
670
- const fromEnv = env['EVOMAP_NODE_SECRET']?.trim() || env['A2A_NODE_SECRET']?.trim();
671
- const envNodeSecretVersion = parseNodeSecretVersion(env['EVOMAP_NODE_SECRET_VERSION'] ?? env['A2A_NODE_SECRET_VERSION']);
672
- const stored = readRecipeStoreNodeCredentials(env);
673
- const explicitSenderId = explicitRecipeSenderId(env);
674
- if (stored?.source === 'hub_rotate' && stored.nodeSecret) {
988
+ const explicitCredentials = resolveExplicitNodeCredentials(env);
989
+ const fromEnv = explicitCredentials.nodeSecret;
990
+ const envNodeSecretVersion = parseNodeSecretVersion(explicitCredentials.nodeSecretVersion);
991
+ const storedCandidate = readRecipeStoreNodeCredentials(env);
992
+ const stored = storedCandidate?.source?.startsWith('pending_') ? undefined : storedCandidate;
993
+ const explicitSenderId = explicitCredentials.senderId;
994
+ const legacy = firstLegacyNodeCredentials(homeCandidates);
995
+ const pairedStoredSenderId = stored?.nodeSecret
996
+ ? stored.nodeId
997
+ ?? (fromEnv === stored.nodeSecret ? explicitSenderId : undefined)
998
+ ?? (legacy?.nodeSecret === stored.nodeSecret ? legacy.nodeId : undefined)
999
+ : undefined;
1000
+ const completeExplicitOverridesOrphan = Boolean(fromEnv
1001
+ && explicitSenderId
1002
+ && fromEnv !== stored?.nodeSecret
1003
+ && pairedStoredSenderId !== explicitSenderId);
1004
+ if (stored?.source === 'hub_rotate' && stored.nodeSecret && !completeExplicitOverridesOrphan) {
675
1005
  return {
676
1006
  evomapDir: defaultHome,
677
1007
  nodeSecret: stored.nodeSecret,
678
1008
  ...(stored.nodeSecretVersion !== undefined ? { nodeSecretVersion: stored.nodeSecretVersion } : {}),
679
- senderId: explicitSenderId ?? firstLegacyNodeId(homeCandidates) ?? resolveAtpSenderId(env),
1009
+ senderId: pairedStoredSenderId,
680
1010
  rotatePersistDir: defaultHome,
681
1011
  };
682
1012
  }
683
1013
  if (fromEnv) {
684
- const legacyNodeId = firstLegacyNodeId(homeCandidates);
685
1014
  const nodeSecretVersion = envNodeSecretVersion ?? pairedStoreNodeSecretVersion(fromEnv, stored) ?? pairedLegacyNodeSecretVersion(fromEnv, homeCandidates);
686
1015
  return {
687
1016
  evomapDir: defaultHome,
688
1017
  nodeSecret: fromEnv,
689
1018
  ...(nodeSecretVersion !== undefined ? { nodeSecretVersion } : {}),
690
- senderId: explicitSenderId ?? legacyNodeId ?? resolveAtpSenderId(env),
1019
+ senderId: explicitSenderId ?? (legacy?.nodeSecret === fromEnv ? legacy.nodeId : undefined),
691
1020
  rotatePersistDir: defaultHome,
692
1021
  };
693
1022
  }
@@ -696,27 +1025,38 @@ function resolveRecipeHubCredentials(env) {
696
1025
  evomapDir: defaultHome,
697
1026
  nodeSecret: stored.nodeSecret,
698
1027
  ...(stored.nodeSecretVersion !== undefined ? { nodeSecretVersion: stored.nodeSecretVersion } : {}),
699
- senderId: explicitSenderId ?? firstLegacyNodeId(homeCandidates) ?? resolveAtpSenderId(env),
1028
+ senderId: pairedStoredSenderId,
700
1029
  rotatePersistDir: defaultHome,
701
1030
  };
702
1031
  }
703
- const legacy = firstLegacyNodeCredentials(homeCandidates);
704
1032
  if (legacy) {
705
1033
  return {
706
1034
  evomapDir: legacy.dir,
707
1035
  nodeSecret: legacy.nodeSecret,
708
1036
  ...(legacy.nodeSecretVersion !== undefined ? { nodeSecretVersion: legacy.nodeSecretVersion } : {}),
709
- senderId: legacy.nodeId ?? explicitSenderId ?? firstLegacyNodeId(homeCandidates) ?? resolveAtpSenderId(env),
1037
+ senderId: legacy.nodeId,
710
1038
  rotatePersistDir: legacy.dir,
711
1039
  };
712
1040
  }
713
1041
  const oauthDir = homeCandidates.find((dir) => existsSync(join(dir, 'token.json'))) ?? defaultHome;
714
1042
  return {
715
1043
  evomapDir: oauthDir,
716
- senderId: explicitSenderId ?? firstLegacyNodeId(homeCandidates) ?? resolveAtpSenderId(env),
1044
+ senderId: resolveRecipeOAuthSenderId(env, oauthDir),
717
1045
  rotatePersistDir: oauthDir,
718
1046
  };
719
1047
  }
1048
+ function resolveRecipeOAuthSenderId(env, oauthDir) {
1049
+ const evomapNodeId = env['EVOMAP_NODE_ID']?.trim();
1050
+ if (evomapNodeId)
1051
+ return evomapNodeId;
1052
+ const identityNodeId = readLegacyNodeId(oauthDir);
1053
+ if (identityNodeId)
1054
+ return identityNodeId;
1055
+ const a2aNodeId = env['A2A_NODE_ID']?.trim();
1056
+ if (a2aNodeId)
1057
+ return a2aNodeId;
1058
+ return readRecipeStoreNodeCredentials(env)?.nodeId;
1059
+ }
720
1060
  /**
721
1061
  * The EXPLICIT home overrides (EVOMAP_DIR / EVOLVER_HOME / EVOMAP_HOME) the recipe credential layer honors,
722
1062
  * resolved purely from the passed env with no process.env fallback. Exported so `reset-local-secret` (index.ts)
@@ -749,20 +1089,19 @@ function recipeHomeCandidates(env) {
749
1089
  ];
750
1090
  return uniqueStrings(candidates.map((value) => value?.trim()).filter((value) => Boolean(value)));
751
1091
  }
752
- function explicitRecipeSenderId(env) {
753
- return env['EVOMAP_NODE_ID']?.trim() || env['A2A_NODE_ID']?.trim();
754
- }
755
1092
  function readRecipeStoreNodeCredentials(env) {
756
1093
  const storePath = recipeProxyStorePath(env);
757
1094
  if (!existsSync(storePath))
758
1095
  return undefined;
759
1096
  const store = new mailbox.MailboxStore({ path: storePath });
760
1097
  try {
1098
+ const nodeId = store.getState('node_id')?.trim() || undefined;
761
1099
  const storedSecret = store.getState('node_secret');
762
1100
  const nodeSecret = storedSecret && isNodeSecret(storedSecret) ? storedSecret : undefined;
763
1101
  const nodeSecretVersion = parseNodeSecretVersion(store.getState('node_secret_version'));
764
1102
  const source = store.getState('node_secret_source') || undefined;
765
1103
  return {
1104
+ ...(nodeId ? { nodeId } : {}),
766
1105
  ...(nodeSecret ? { nodeSecret } : {}),
767
1106
  ...(nodeSecretVersion !== undefined ? { nodeSecretVersion } : {}),
768
1107
  ...(source ? { source } : {}),
@@ -814,14 +1153,6 @@ function firstLegacyNodeCredentials(dirs) {
814
1153
  }
815
1154
  return undefined;
816
1155
  }
817
- function firstLegacyNodeId(dirs) {
818
- for (const dir of dirs) {
819
- const nodeId = readLegacyNodeId(dir);
820
- if (nodeId)
821
- return nodeId;
822
- }
823
- return undefined;
824
- }
825
1156
  function uniqueStrings(values) {
826
1157
  const seen = new Set();
827
1158
  const out = [];
@@ -850,19 +1181,33 @@ function recipeProxyStorePath(env) {
850
1181
  function setOptionalStoreState(store, key, value) {
851
1182
  store.setState(key, value ?? '');
852
1183
  }
853
- function persistRotatedNodeSecret(secret, version, env, legacyDir) {
1184
+ function persistRotatedNodeSecret(secret, version, nodeId, env, legacyDir) {
854
1185
  const storePath = recipeProxyStorePath(env);
855
1186
  const store = new mailbox.MailboxStore({ path: storePath });
856
1187
  try {
1188
+ store.setState('node_secret_source', 'pending_rotate');
1189
+ if (nodeId)
1190
+ store.setState('node_id', nodeId);
857
1191
  store.setState('node_secret', secret);
858
- store.setState('node_secret_source', 'hub_rotate');
859
1192
  setOptionalStoreState(store, 'node_secret_version', version !== undefined ? String(version) : undefined);
1193
+ store.setState('node_secret_source', 'hub_rotate');
860
1194
  }
861
1195
  finally {
862
1196
  store.close();
863
1197
  }
864
1198
  persistLegacyNodeSecret(secret, version, legacyDir);
865
1199
  }
1200
+ function persistRecipeNodeId(nodeId, env, legacyDir) {
1201
+ const store = new mailbox.MailboxStore({ path: recipeProxyStorePath(env) });
1202
+ try {
1203
+ store.setState('node_id', nodeId);
1204
+ }
1205
+ finally {
1206
+ store.close();
1207
+ }
1208
+ mkdirSync(legacyDir, { recursive: true, mode: 0o700 });
1209
+ writeFileSync(join(legacyDir, 'node_id'), nodeId, { encoding: 'utf8', mode: 0o600 });
1210
+ }
866
1211
  function persistNodeSecretVersion(version, env, legacyDir) {
867
1212
  const storePath = recipeProxyStorePath(env);
868
1213
  const store = new mailbox.MailboxStore({ path: storePath });