@evomap/evolver-cli 2.0.0-beta.1 → 2.0.0-beta.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/dist/antiGeneBenchmark.js +12 -0
  2. package/dist/antiGeneEvidence.d.ts +15 -0
  3. package/dist/antiGeneEvidence.js +49 -0
  4. package/dist/antiGeneRollout.d.ts +3 -1
  5. package/dist/antiGeneRollout.js +16 -2
  6. package/dist/assetHealth.d.ts +6 -0
  7. package/dist/assetHealth.js +107 -0
  8. package/dist/assetSidecarRecovery.d.ts +14 -0
  9. package/dist/assetSidecarRecovery.js +171 -0
  10. package/dist/assetTrust.d.ts +24 -0
  11. package/dist/assetTrust.js +218 -0
  12. package/dist/atp.js +4 -2
  13. package/dist/autoDistillLlm.d.ts +6 -0
  14. package/dist/autoDistillLlm.js +44 -7
  15. package/dist/autoexec.d.ts +14 -12
  16. package/dist/autoexec.js +84 -34
  17. package/dist/autoexecConfig.d.ts +10 -0
  18. package/dist/autoexecConfig.js +68 -0
  19. package/dist/cli.js +12 -5
  20. package/dist/cliContracts.js +30 -3
  21. package/dist/cliLifecycle.d.ts +7 -0
  22. package/dist/cliLifecycle.js +9 -0
  23. package/dist/cycleConsumer.d.ts +61 -1
  24. package/dist/cycleConsumer.js +551 -16
  25. package/dist/dashboard.d.ts +33 -0
  26. package/dist/dashboard.js +352 -0
  27. package/dist/dispatch.d.ts +10 -1
  28. package/dist/dispatch.js +40 -2
  29. package/dist/distillAdmission.d.ts +13 -0
  30. package/dist/distillAdmission.js +35 -0
  31. package/dist/distillObserver.js +6 -8
  32. package/dist/distillPrimitives.d.ts +9 -7
  33. package/dist/distillPrimitives.js +65 -12
  34. package/dist/doctor.d.ts +2 -0
  35. package/dist/doctor.js +49 -3
  36. package/dist/index.d.ts +8 -2
  37. package/dist/index.js +350 -42
  38. package/dist/issueReport.d.ts +7 -0
  39. package/dist/issueReport.js +291 -0
  40. package/dist/lifecycle.d.ts +22 -1
  41. package/dist/lifecycle.js +226 -29
  42. package/dist/localMemoryGraph.d.ts +97 -0
  43. package/dist/localMemoryGraph.js +889 -0
  44. package/dist/login.d.ts +20 -4
  45. package/dist/login.js +58 -8
  46. package/dist/materialPackage.d.ts +52 -0
  47. package/dist/materialPackage.js +401 -0
  48. package/dist/materialSnapshot.d.ts +54 -0
  49. package/dist/materialSnapshot.js +370 -0
  50. package/dist/memoryEventMirror.d.ts +23 -0
  51. package/dist/memoryEventMirror.js +140 -0
  52. package/dist/migrate/fieldMap.js +25 -0
  53. package/dist/migrate/v1Import.d.ts +7 -1
  54. package/dist/migrate/v1Import.js +132 -11
  55. package/dist/nonGitWorkspaceNotice.d.ts +24 -0
  56. package/dist/nonGitWorkspaceNotice.js +122 -0
  57. package/dist/proxyToken.d.ts +10 -0
  58. package/dist/proxyToken.js +80 -0
  59. package/dist/recipe.d.ts +12 -2
  60. package/dist/recipe.js +381 -8
  61. package/dist/reuse.d.ts +5 -3
  62. package/dist/reuse.js +126 -15
  63. package/dist/reuseReport.js +16 -16
  64. package/dist/runtimeCapabilities.d.ts +18 -0
  65. package/dist/runtimeCapabilities.js +81 -0
  66. package/dist/runtimeSessionSource.d.ts +10 -0
  67. package/dist/runtimeSessionSource.js +32 -5
  68. package/dist/setupHooks.d.ts +11 -1
  69. package/dist/setupHooks.js +235 -16
  70. package/dist/skill2gep.d.ts +38 -9
  71. package/dist/skill2gep.js +147 -14
  72. package/dist/skillDistill.d.ts +1 -0
  73. package/dist/skillDistill.js +4 -4
  74. package/dist/skillFetch.d.ts +18 -0
  75. package/dist/skillFetch.js +391 -0
  76. package/dist/solo/mode.js +5 -0
  77. package/dist/sync.d.ts +38 -0
  78. package/dist/sync.js +1981 -0
  79. package/dist/trajectoryExport.js +23 -12
  80. package/dist/v1Compat.d.ts +24 -0
  81. package/dist/v1Compat.js +249 -0
  82. package/dist/workflow.d.ts +39 -0
  83. package/dist/workflow.js +386 -0
  84. package/dist/workflowRuntime.d.ts +66 -0
  85. package/dist/workflowRuntime.js +631 -0
  86. package/package.json +12 -6
@@ -4,14 +4,17 @@
4
4
  // (the real device-wide scope); `--scope=project` (default) writes the project's own .mcp.json. Deny-nothing:
5
5
  // it only writes the runtime's own config, is idempotent, refuses symlinked adapter paths, and `--uninstall`
6
6
  // cleanly removes only evolver's entries.
7
- import { planInjection, installInjection, uninstallInjection, runtimeSupport, renderManualWiring, renderServiceGuidance, SETUP_RUNTIMES, SERVICE_TARGETS } from '@evomap/evolver-mcp';
7
+ import { planInjection, installInjection, uninstallInjection, runtimeSupport, renderManualWiring, renderServiceGuidance, SETUP_RUNTIMES, SERVICE_TARGETS, kiroConfigRoot, resolveOpenCodeConfig, McpConfigConflictError, McpConfigOwnershipError, McpConfigVerificationError, McpServerValidationError } from '@evomap/evolver-mcp';
8
8
  import { assetstore, events } from '@evomap/evolver-core';
9
- import { readFileSync } from 'node:fs';
9
+ import { accessSync, constants, existsSync, readFileSync, statSync } from 'node:fs';
10
10
  import { createRequire } from 'node:module';
11
+ import { homedir } from 'node:os';
12
+ import { delimiter, dirname, isAbsolute, join, relative, sep } from 'node:path';
11
13
  import { fileURLToPath } from 'node:url';
12
14
  import { currentTopCursorGenes } from './cursorRewrite.js';
13
15
  import { resolveProxyBinPath, resolveStableNodePath } from './lifecycle.js';
14
16
  import { reviewLedgerForStore } from './reviewFilter.js';
17
+ import { maybeEmitNonGitWorkspaceNotice } from './nonGitWorkspaceNotice.js';
15
18
  const requireFromHere = createRequire(import.meta.url);
16
19
  function parseFlags(argv) {
17
20
  const out = {};
@@ -33,7 +36,133 @@ function parseFlags(argv) {
33
36
  }
34
37
  return out;
35
38
  }
36
- const USAGE = `usage: evolver setup-hooks [--runtime=${SETUP_RUNTIMES.join('|')}] [--scope=user|project|global] [--root=<dir>] [--env-file=<path>] [--profile-descriptor=<json>] [--service=${SERVICE_TARGETS.join('|')}] [--uninstall] [--force] [--json] [--hook-command="evolver inject session-start"] [--server-command=<cmd>] [--server-args=a,b] [--service-command=<cmd>] [--service-args=a,b]\n`;
39
+ const USAGE = `usage: evolver setup-hooks [--runtime=${SETUP_RUNTIMES.join('|')}] [--scope=user|project|global] [--root=<dir>] [--env-file=<path>] [--profile-descriptor=<json>] [--service=${SERVICE_TARGETS.join('|')}] [--uninstall] [--dry-run] [--force] [--json] [--hook-command="evolver inject session-start"] [--server-command=<cmd>] [--server-args=a,b] [--service-command=<cmd>] [--service-args=a,b]\n`;
40
+ export function commandNamesForPath(command, platform, pathExt) {
41
+ if (platform !== 'win32' || /\.[^\\/]+$/.test(command))
42
+ return [command];
43
+ const extensions = (pathExt?.trim() || '.COM;.EXE;.BAT;.CMD')
44
+ .split(';')
45
+ .map((extension) => extension.trim())
46
+ .filter((extension) => /^\.?[A-Za-z\d]+$/.test(extension))
47
+ .map((extension) => extension.startsWith('.') ? extension : `.${extension}`);
48
+ return [command, ...extensions.map((extension) => `${command}${extension}`)];
49
+ }
50
+ function commandOnPath(command) {
51
+ const names = commandNamesForPath(command, process.platform, process.env['PATHEXT']);
52
+ for (const directory of (process.env['PATH'] ?? '').split(delimiter).filter(Boolean)) {
53
+ for (const name of names) {
54
+ try {
55
+ const candidate = join(directory, name);
56
+ if (!statSync(candidate).isFile())
57
+ continue;
58
+ accessSync(candidate, constants.X_OK);
59
+ return true;
60
+ }
61
+ catch {
62
+ // Continue searching PATH.
63
+ }
64
+ }
65
+ }
66
+ return false;
67
+ }
68
+ function defaultRuntimeAvailable(runtime, configRoot, scope) {
69
+ if (runtime === 'opencode') {
70
+ const resolution = resolveOpenCodeConfig({
71
+ configRoot,
72
+ scope,
73
+ homeDir: homedir(),
74
+ xdgConfigHome: process.env['XDG_CONFIG_HOME'],
75
+ opencodeConfig: process.env['OPENCODE_CONFIG'],
76
+ opencodeConfigDir: process.env['OPENCODE_CONFIG_DIR'],
77
+ });
78
+ return commandOnPath('opencode') || (resolution.evidencePaths ?? [resolution.configPath]).some(existsSync);
79
+ }
80
+ const pathOptions = {
81
+ configRoot,
82
+ homeDir: homedir(),
83
+ kiroHome: process.env['KIRO_HOME'],
84
+ };
85
+ const evidenceRoots = scope === 'project'
86
+ ? [
87
+ kiroConfigRoot({ ...pathOptions, scope: 'project' }),
88
+ kiroConfigRoot({ ...pathOptions, scope: 'user' }),
89
+ ]
90
+ : [kiroConfigRoot({ ...pathOptions, scope: 'user' })];
91
+ return commandOnPath('kiro') || commandOnPath('kiro-cli') || evidenceRoots.some(existsSync);
92
+ }
93
+ function displaySetupPath(path, configRoot, scope) {
94
+ if (scope === 'user') {
95
+ const home = homedir();
96
+ const homePath = safeRelativePath(home, path);
97
+ if (homePath === '')
98
+ return '~';
99
+ if (homePath !== undefined)
100
+ return `~/${homePath.replaceAll('\\', '/')}`;
101
+ }
102
+ const projectPath = safeProjectRelativePath(configRoot, path);
103
+ if (projectPath === '')
104
+ return '.';
105
+ return projectPath !== undefined ? projectPath.replaceAll('\\', '/') : '<config-path>';
106
+ }
107
+ function safeRelativePath(root, path) {
108
+ const candidate = relative(root, path);
109
+ if (isAbsolute(candidate) || candidate === '..' || candidate.startsWith(`..${sep}`))
110
+ return undefined;
111
+ return candidate;
112
+ }
113
+ function safeProjectRelativePath(root, path) {
114
+ const descendant = safeRelativePath(root, path);
115
+ if (descendant !== undefined)
116
+ return descendant;
117
+ return safeRelativePath(dirname(path), root) === undefined ? undefined : relative(root, path);
118
+ }
119
+ function displayResultPaths(paths, configRoot, scope) {
120
+ return paths?.map((path) => displaySetupPath(path, configRoot, scope));
121
+ }
122
+ export function safeSetupOperationError(error) {
123
+ if (error instanceof McpConfigConflictError)
124
+ return error.message;
125
+ if (error instanceof McpConfigOwnershipError)
126
+ return error.message;
127
+ if (error instanceof McpConfigVerificationError) {
128
+ return error.restored
129
+ ? '[setup-hooks] runtime configuration verification failed; the previous configuration was restored.'
130
+ : '[setup-hooks] runtime configuration verification failed; rollback could not be confirmed. Inspect the runtime config before retrying.';
131
+ }
132
+ if (error instanceof McpServerValidationError)
133
+ return error.message;
134
+ const name = error instanceof Error ? error.name : '';
135
+ switch (name) {
136
+ case 'McpConfigConflictError': return '[setup-hooks] existing Evolver configuration conflicts; use --force to replace only the Evolver entry.';
137
+ case 'McpConfigOwnershipError': return '[setup-hooks] Evolver ownership metadata is ambiguous or no longer matches the runtime configuration; inspect it before retrying.';
138
+ case 'McpConfigShapeError': return '[setup-hooks] runtime configuration has an invalid JSON shape.';
139
+ case 'McpConfigVerificationError': return error.restored === true
140
+ ? '[setup-hooks] runtime configuration verification failed; the previous configuration was restored.'
141
+ : '[setup-hooks] runtime configuration verification failed; rollback could not be confirmed. Inspect the runtime config before retrying.';
142
+ case 'McpConfigChangedError': return '[setup-hooks] runtime configuration changed during the operation; retry after the runtime finishes writing it.';
143
+ case 'EmptySharedConfigError': return '[setup-hooks] runtime configuration is empty; repair or remove it before retrying.';
144
+ case 'UnparseableConfigError': return '[setup-hooks] runtime configuration is not valid JSON; repair it before retrying.';
145
+ case 'SymlinkRefusedError': return '[setup-hooks] refused an unsafe symbolic-link configuration path.';
146
+ default: return '[setup-hooks] runtime configuration operation failed.';
147
+ }
148
+ }
149
+ export function safeSetupResultError(error) {
150
+ if (typeof error !== 'string')
151
+ return safeSetupOperationError(error);
152
+ const reason = error.replace(/\s+/g, ' ').trim();
153
+ const passive = reason.match(/^passive runtime ([a-z0-9][a-z0-9-]{0,63}): no tool injection$/);
154
+ const unimplementedInstall = reason.match(/^installer not yet implemented for ([a-z0-9][a-z0-9-]{0,63}) \(supported: [a-z0-9, -]+\)$/);
155
+ const unimplementedUninstall = reason.match(/^uninstall not implemented for ([a-z0-9][a-z0-9-]{0,63})$/);
156
+ const runtime = passive?.[1] ?? unimplementedInstall?.[1] ?? unimplementedUninstall?.[1];
157
+ if (!runtime || !SETUP_RUNTIMES.includes(runtime)) {
158
+ return safeSetupOperationError(error);
159
+ }
160
+ if (passive)
161
+ return `[setup-hooks] passive runtime ${runtime}: no tool injection`;
162
+ if (unimplementedInstall)
163
+ return `[setup-hooks] installer not yet implemented for ${runtime}`;
164
+ return `[setup-hooks] uninstall not implemented for ${runtime}`;
165
+ }
37
166
  const PROFILE_DESCRIPTOR_FLAG = 'profile-descriptor';
38
167
  const SECRET_ASSIGNMENT_RE = /\b(?:A2A_NODE_SECRET|EVOMAP_ENTERPRISE_TOKEN|EVOMAP_PRIVATE_HUB_TOKEN|EVOMAP_NODE_SECRET|EVOLVER_IPC_TOKEN|EVOLVER_LLM_TOKEN|PHUB_ENTERPRISE_TOKEN|PRIVATE_HUB_ENTERPRISE_TOKEN)\b\s*[:=]\s*["']?[^"'\s<]+/;
39
168
  const INLINE_BEARER_RE = /\bBearer\s+(?!<|\$|%|REDACTED\b|TOKEN\b|token\b|env:)[A-Za-z0-9._~+/=-]{12,}/i;
@@ -273,7 +402,7 @@ function appendAdapterNotes(text, hints) {
273
402
  ? `${text}\n\nAdapter notes:\n${hints.map((hint) => ` - ${hint}`).join('\n')}`
274
403
  : text;
275
404
  }
276
- export async function runSetupHooks(argv, store, review) {
405
+ export async function runSetupHooks(argv, store, review, deps = {}) {
277
406
  const f = parseFlags(argv);
278
407
  const runtimeRaw = typeof f['runtime'] === 'string'
279
408
  ? f['runtime']
@@ -300,24 +429,62 @@ export async function runSetupHooks(argv, store, review) {
300
429
  process.stderr.write(`${support.reason}\n${USAGE}`);
301
430
  return 1;
302
431
  }
303
- // installed class: claude-code / codex / cursor: v2 owns a real config writer + uninstaller for these.
432
+ // Installed runtimes have a real config writer + uninstaller (including Antigravity MCP config).
304
433
  const runtime = runtimeRaw;
305
434
  const configRoot = typeof f['root'] === 'string' ? f['root'] : process.cwd();
306
435
  // claude-code: user scope targets ~/.claude.json regardless of --root; project scope uses configRoot.
307
436
  const scope = scopeResult.scope;
437
+ if (f['dry-run'] === true && runtime !== 'opencode' && runtime !== 'kiro') {
438
+ const error = `--dry-run is currently supported for opencode and kiro setup only; no config was written.`;
439
+ if (json)
440
+ emit({ runtime, outcome: 'error', files: [], error });
441
+ else
442
+ process.stderr.write(`${error}\n`);
443
+ return 1;
444
+ }
308
445
  if (support.outcome === 'installed' && f['uninstall']) {
309
- const r = uninstallInjection(runtime, { configRoot, scope });
446
+ let r;
447
+ try {
448
+ r = uninstallInjection(runtime, {
449
+ configRoot,
450
+ scope,
451
+ homeDir: homedir(),
452
+ kiroHome: process.env['KIRO_HOME'],
453
+ xdgConfigHome: process.env['XDG_CONFIG_HOME'],
454
+ opencodeConfig: process.env['OPENCODE_CONFIG'],
455
+ opencodeConfigDir: process.env['OPENCODE_CONFIG_DIR'],
456
+ dryRun: f['dry-run'] === true,
457
+ });
458
+ }
459
+ catch (error) {
460
+ const message = safeSetupOperationError(error);
461
+ if (json)
462
+ emit({ runtime, action: 'uninstall', files: [], error: message });
463
+ else
464
+ process.stderr.write(`${message}\n`);
465
+ return 1;
466
+ }
467
+ const files = displayResultPaths(r.files, configRoot, scope) ?? [];
468
+ const backups = displayResultPaths(r.backups, configRoot, scope);
310
469
  if (!r.ok) {
470
+ const message = safeSetupResultError(r.error);
311
471
  if (json)
312
- emit({ runtime, action: 'uninstall', files: [], error: r.error ?? 'uninstall failed' });
472
+ emit({ runtime, action: 'uninstall', files: [], error: message });
313
473
  else
314
- process.stderr.write(`${r.error ?? 'uninstall failed'}\n`);
474
+ process.stderr.write(`${message}\n`);
315
475
  return 1;
316
476
  }
477
+ if (r.dryRun) {
478
+ if (json)
479
+ emit({ runtime, action: 'uninstall', files, backups, dryRun: true });
480
+ else
481
+ process.stdout.write(files.length ? `dry-run: would remove evolver from: ${files.join(', ')}\n` : 'dry-run: nothing to remove\n');
482
+ return 0;
483
+ }
317
484
  if (json)
318
- emit({ runtime, action: 'uninstall', files: r.files });
485
+ emit({ runtime, action: 'uninstall', files, backups });
319
486
  else
320
- process.stdout.write(r.files.length ? `removed evolver from: ${r.files.join(', ')}\n` : 'nothing to remove\n');
487
+ process.stdout.write(files.length ? `removed evolver from: ${files.join(', ')}\n` : 'nothing to remove\n');
321
488
  return 0;
322
489
  }
323
490
  const profileDescriptor = profileDescriptorFromFlag(f);
@@ -359,6 +526,30 @@ export async function runSetupHooks(argv, store, review) {
359
526
  return 0;
360
527
  }
361
528
  const server = buildServer(f, descriptor);
529
+ if ((runtime === 'opencode' || runtime === 'kiro') && f['dry-run'] !== true) {
530
+ let runtimeDetected;
531
+ try {
532
+ runtimeDetected = (deps.runtimeAvailable ?? defaultRuntimeAvailable)(runtime, configRoot, scope);
533
+ }
534
+ catch (error) {
535
+ const message = safeSetupOperationError(error);
536
+ if (json)
537
+ emit({ runtime, outcome: 'error', files: [], error: message });
538
+ else
539
+ process.stderr.write(`${message}\n`);
540
+ return 1;
541
+ }
542
+ if (!runtimeDetected) {
543
+ const error = `${runtime} runtime was not detected; install or launch ${runtime === 'opencode' ? 'OpenCode' : 'Kiro'} first, then rerun. No config was written.`;
544
+ if (json)
545
+ emit({ runtime, outcome: 'error', files: [], error });
546
+ else
547
+ process.stderr.write(`${error}\n`);
548
+ return 1;
549
+ }
550
+ }
551
+ if (runtime === 'cursor')
552
+ (deps.emitNonGitWorkspaceNotice ?? maybeEmitNonGitWorkspaceNotice)({ cwd: configRoot });
362
553
  // cursor seeds .cursor/rules/evolver.mdc with the CURRENT top REVIEW-APPROVED genes so the file is useful
363
554
  // immediately (before the first daemon rewrite) without seeding an unapproved draft (A2a). The renderer thus
364
555
  // has a real production caller even without the daemon running.
@@ -373,6 +564,12 @@ export async function runSetupHooks(argv, store, review) {
373
564
  ...(typeof f['hook-command'] === 'string' ? { hookCommand: f['hook-command'] } : {}),
374
565
  ...(cursorGenes ? { genes: cursorGenes } : {}),
375
566
  force: f['force'] === true,
567
+ dryRun: f['dry-run'] === true,
568
+ homeDir: homedir(),
569
+ kiroHome: process.env['KIRO_HOME'],
570
+ xdgConfigHome: process.env['XDG_CONFIG_HOME'],
571
+ opencodeConfig: process.env['OPENCODE_CONFIG'],
572
+ opencodeConfigDir: process.env['OPENCODE_CONFIG_DIR'],
376
573
  });
377
574
  }
378
575
  catch (e) {
@@ -380,7 +577,7 @@ export async function runSetupHooks(argv, store, review) {
380
577
  // `unsupported` runtime. Reporting `unsupported` here would tell a bootstrapper the runtime isn't supported and
381
578
  // make it stop trying, when the real cause is operational. `error` is a CLI result status (the attempt failed),
382
579
  // distinct from the support-matrix `unsupported` (an unrecognized runtime id) (Bugbot #264).
383
- const msg = e instanceof Error ? e.message : String(e);
580
+ const msg = safeSetupOperationError(e);
384
581
  if (json)
385
582
  emit({ runtime, outcome: 'error', files: [], error: msg });
386
583
  else
@@ -389,22 +586,44 @@ export async function runSetupHooks(argv, store, review) {
389
586
  }
390
587
  if (!r.ok) {
391
588
  // Same reasoning for an ok:false install result: a failed install of a supported runtime is `error`, not `unsupported`.
589
+ const message = safeSetupResultError(r.error);
392
590
  if (json)
393
- emit({ runtime, outcome: 'error', files: [], error: r.error ?? 'install failed' });
591
+ emit({ runtime, outcome: 'error', files: [], error: message });
394
592
  else
395
- process.stderr.write(`${r.error ?? 'install failed'}\n`);
593
+ process.stderr.write(`${message}\n`);
396
594
  return 1;
397
595
  }
596
+ const files = displayResultPaths(r.files, configRoot, scope) ?? [];
597
+ const backups = displayResultPaths(r.backups, configRoot, scope);
598
+ if (r.dryRun) {
599
+ if (json) {
600
+ emit({
601
+ runtime,
602
+ outcome: 'installed',
603
+ files,
604
+ backups,
605
+ dryRun: true,
606
+ ...(r.alreadyInstalled ? { alreadyInstalled: true } : {}),
607
+ });
608
+ }
609
+ else if (r.alreadyInstalled) {
610
+ process.stdout.write('dry-run: evolver already installed (no changes)\n');
611
+ }
612
+ else {
613
+ process.stdout.write(`dry-run: would install evolver (${r.mode}) → ${files.join(', ')}\n`);
614
+ }
615
+ return 0;
616
+ }
398
617
  if (r.alreadyInstalled) {
399
618
  if (json)
400
- emit({ runtime, outcome: 'installed', files: r.files, alreadyInstalled: true });
619
+ emit({ runtime, outcome: 'installed', files, alreadyInstalled: true });
401
620
  else
402
621
  process.stdout.write('evolver already installed (use --force to reinstall)\n');
403
622
  return 0;
404
623
  }
405
624
  if (json)
406
- emit({ runtime, outcome: 'installed', files: r.files, mode: r.mode });
625
+ emit({ runtime, outcome: 'installed', files, backups, mode: r.mode, verified: r.verified });
407
626
  else
408
- process.stdout.write(`installed evolver (${r.mode}) → ${r.files.join(', ')}\n`);
627
+ process.stdout.write(`installed evolver (${r.mode}) → ${files.join(', ')}\n`);
409
628
  return 0;
410
629
  }
@@ -1,4 +1,5 @@
1
- import { type algo } from '@evomap/evolver-core';
1
+ import { type algo, type wire } from '@evomap/evolver-core';
2
+ type GenerationSource = wire.GenerationSource;
2
3
  /** Max strategy steps kept from a skill (v1 parity: MAX_STRATEGY_STEPS). */
3
4
  export declare const MAX_STRATEGY_STEPS = 28;
4
5
  /** Structured view of a SKILL.md (the input to gene/capsule synthesis). */
@@ -34,18 +35,32 @@ export interface SynthesizeOptions {
34
35
  export interface SynthesizeResult {
35
36
  gene: algo.GeneCandidate | null;
36
37
  errors: string[];
38
+ /** The provenance + quality metadata derived from the execution trace (v1 #302). Null when no gene is produced. */
39
+ generation_meta?: wire.GenerationMeta;
37
40
  }
41
+ /**
42
+ * Classify a Gene's provenance from its execution trace (faithful port of v1 #302 `classifyProvenance`). PURE,
43
+ * mechanical, reads only trajectory fields (status / blast_radius / rollouts / mutation_log / reference_distilled):
44
+ * evolved — a verified success that overcame a real failure (mutation_log non-empty, or rollouts went fail→pass)
45
+ * with a non-zero blast radius. The corrective_insight that flipped the outcome is the payload.
46
+ * distilled — has execution evidence (a status, rollouts, mutation_log, or an explicit reference_distilled flag)
47
+ * but did NOT clear the evolved bar. A first-try success or a zero-blast success lands here.
48
+ * manual — no execution evidence at all (pure SKILL.md transcription).
49
+ */
50
+ export declare function classifyProvenance(execution: SkillExecution): GenerationSource;
38
51
  /**
39
52
  * Assemble a draft GeneCandidate from a parsed skill + its execution trace (B2a — faithful port of v1
40
53
  * `synthesizeGene`'s Gene half, mapped onto v2 `GeneCandidate`; pool intake/dedup/asset_id is the caller's
41
- * `algo.intakeGene`). Signals merge skill + trace; strategy pads to ≥3 generic steps; validation keeps only the
42
- * allowed `node …` commands. STRICT mode + no allowed validation → refuse (errors, no gene); non-strict falls back
43
- * to `node --version` so Gene.validation is never empty (an empty validation would silently defeat the Capsule
44
- * coverage check in B2b). `avoid` / `_source` are dropped here (not on GeneCandidate) — re-added if the schema grows.
54
+ * `algo.intakeGene`). Signals merge skill + trace. Provenance is classified from the execution trace (v1 #302):
55
+ * - evolved → corrective_insight leads strategy; mutation_log → verifiable preconditions.
56
+ * - otherwise → Skill transcription (legacy behavior), tagged so consumers know it was not learned from a real run.
57
+ *
58
+ * Validation keeps only the allowed `node …` commands (v1 #302 DISTILL contract: do NOT inject a bogus
59
+ * `node --version` fallback — an empty validation list is the CORRECT outcome for a Gene with nothing runnable,
60
+ * not a near-trivial check that would silently pass). STRICT mode + no allowed validation → refuse (errors, no gene).
61
+ * `avoid` is dropped here (not on GeneCandidate); `generation_meta` carries the provenance + quality metadata.
45
62
  */
46
- export declare function synthesizeGene(parsed: ParsedSkill, execution: {
47
- signals?: readonly string[];
48
- }, opts?: SynthesizeOptions): SynthesizeResult;
63
+ export declare function synthesizeGene(parsed: ParsedSkill, execution?: SkillExecution, opts?: SynthesizeOptions): SynthesizeResult;
49
64
  /** One real command run while the skill executed. */
50
65
  export interface SkillTraceEntry {
51
66
  step?: number;
@@ -68,6 +83,19 @@ export interface SkillExecution {
68
83
  summary?: string;
69
84
  success_reason?: string;
70
85
  content_summary?: string;
86
+ /** Error categories the trajectory overcame (drives evolved preconditions + quality_score). */
87
+ mutation_log?: readonly string[];
88
+ /** The corrective insight that flipped a fail -> pass (the high-value payload of an evolved Gene). */
89
+ corrective_insight?: string;
90
+ /** Explicit signal that this is a transcription of reference/teacher text (forces `distilled`). */
91
+ reference_distilled?: boolean;
92
+ /** Per-attempt rollout records (a fail-then-pass sequence here is an evolved signal). */
93
+ rollouts?: readonly {
94
+ step?: number;
95
+ kind?: 'solve' | 'mutate';
96
+ status?: string;
97
+ error_type?: string;
98
+ }[];
71
99
  }
72
100
  /**
73
101
  * Forgery guard (v1 detectForgery) — RED LINE #1. A status=success Capsule with no real execution evidence is
@@ -141,4 +169,5 @@ export interface ReverseDistillResult {
141
169
  */
142
170
  export declare function reverseDistill(parsed: ParsedSkill, execution?: SkillExecution, opts?: SynthesizeOptions & {
143
171
  scenario?: string;
144
- }): ReverseDistillResult;
172
+ }): ReverseDistillResult;
173
+ export {};
package/dist/skill2gep.js CHANGED
@@ -165,21 +165,130 @@ export function inferCategory(signals, description) {
165
165
  return 'innovate';
166
166
  return 'optimize';
167
167
  }
168
+ // ── v1 #302: provenance classification + quality scoring (aligned with TaskGenome Bench §3.1) ────────────────
169
+ // A Gene's value depends on WHERE it came from, not on being short. Evolved Genes (distilled from a verified
170
+ // solve→fail→mutate→pass trajectory) beat Skills +8.7..+15.5pp; reference-distilled Genes are 3-11pp WORSE.
171
+ /**
172
+ * Classify a Gene's provenance from its execution trace (faithful port of v1 #302 `classifyProvenance`). PURE,
173
+ * mechanical, reads only trajectory fields (status / blast_radius / rollouts / mutation_log / reference_distilled):
174
+ * evolved — a verified success that overcame a real failure (mutation_log non-empty, or rollouts went fail→pass)
175
+ * with a non-zero blast radius. The corrective_insight that flipped the outcome is the payload.
176
+ * distilled — has execution evidence (a status, rollouts, mutation_log, or an explicit reference_distilled flag)
177
+ * but did NOT clear the evolved bar. A first-try success or a zero-blast success lands here.
178
+ * manual — no execution evidence at all (pure SKILL.md transcription).
179
+ */
180
+ export function classifyProvenance(execution) {
181
+ const rollouts = Array.isArray(execution?.rollouts) ? execution.rollouts : [];
182
+ const mutationLog = Array.isArray(execution?.mutation_log) ? execution.mutation_log : [];
183
+ const status = execution?.status ? String(execution.status) : null;
184
+ const blast = execution?.blast_radius || null;
185
+ const hasBlast = blast !== null && (Number(blast.files || 0) > 0 || Number(blast.lines || 0) > 0);
186
+ const failedRollouts = rollouts.filter((r) => r && String(r.status) === 'failed').length;
187
+ const passedRollouts = rollouts.some((r) => r && String(r.status) === 'success');
188
+ const overcameFailure = mutationLog.length > 0 || (failedRollouts > 0 && (passedRollouts || status === 'success'));
189
+ if (status === 'success' && hasBlast && overcameFailure)
190
+ return 'evolved';
191
+ // Anything carrying real execution evidence but not meeting the evolved bar is "distilled" — it has evidence, just
192
+ // not a verified fail→pass-with-blast trajectory. A success with mutation_log but ZERO blast radius must therefore
193
+ // be distilled, not manual (otherwise a zero-blast success would masquerade as a no-evidence transcription).
194
+ if ((execution?.reference_distilled === true) || status !== null || rollouts.length > 0 || mutationLog.length > 0) {
195
+ return 'distilled';
196
+ }
197
+ return 'manual';
198
+ }
199
+ /**
200
+ * Build the corrective-insight strategy for an evolved Gene (v1 #302 `buildEvolvedStrategy`). The insight that
201
+ * flipped fail→pass goes FIRST (the case-study shape), then the Skill's own workflow steps. De-duped, length-bounded.
202
+ */
203
+ function buildEvolvedStrategy(parsed, execution) {
204
+ const strategy = [];
205
+ const insight = execution?.corrective_insight ? String(execution.corrective_insight).trim() : '';
206
+ if (insight.length >= 5)
207
+ strategy.push(insight.length <= 300 ? insight : insight.slice(0, 297) + '...');
208
+ (parsed.strategy || []).forEach((s) => { if (strategy.indexOf(s) === -1)
209
+ strategy.push(s); });
210
+ return strategy;
211
+ }
212
+ /**
213
+ * Turn the error categories a trajectory overcame into verifiable preconditions (v1 #302 `preconditionsFromErrors`):
214
+ * "A prior attempt failed with X; verify this condition is handled before trusting the approach."
215
+ */
216
+ function preconditionsFromErrors(execution) {
217
+ const mutationLog = Array.isArray(execution?.mutation_log) ? execution.mutation_log : [];
218
+ const out = [];
219
+ const seen = new Set();
220
+ for (const err of mutationLog) {
221
+ const e = String(err || '').trim();
222
+ if (!e || seen.has(e))
223
+ continue;
224
+ seen.add(e);
225
+ out.push(`A prior attempt failed with "${e.replace(/_/g, ' ')}"; verify this condition is handled before trusting the approach.`);
226
+ if (out.length >= 4)
227
+ break;
228
+ }
229
+ return out;
230
+ }
231
+ /**
232
+ * Quality score in [0,1] (v1 #302 `computeQualityScore`). Evolved trajectories with a recorded corrective insight
233
+ * score highest (0.7 baseline + bonuses); pure transcription with no evidence scores lowest (0.3).
234
+ */
235
+ function computeQualityScore(source, parsed, execution) {
236
+ const ex = execution || {};
237
+ let score;
238
+ if (source === 'evolved') {
239
+ score = 0.7;
240
+ if (ex.corrective_insight && String(ex.corrective_insight).trim().length >= 5)
241
+ score += 0.15;
242
+ const depth = Array.isArray(ex.mutation_log) ? ex.mutation_log.length
243
+ : (Array.isArray(ex.rollouts) ? ex.rollouts.length - 1 : 0);
244
+ if (depth >= 1)
245
+ score += Math.min(0.15, depth * 0.05);
246
+ }
247
+ else if (source === 'distilled') {
248
+ score = 0.4;
249
+ }
250
+ else {
251
+ score = 0.3;
252
+ }
253
+ const strategySteps = (parsed.strategy || []).length;
254
+ if (strategySteps >= 4)
255
+ score += 0.05;
256
+ if ((parsed.avoid || []).length >= 1)
257
+ score += 0.05;
258
+ return Math.max(0, Math.min(1, Number(score.toFixed(3))));
259
+ }
168
260
  /**
169
261
  * Assemble a draft GeneCandidate from a parsed skill + its execution trace (B2a — faithful port of v1
170
262
  * `synthesizeGene`'s Gene half, mapped onto v2 `GeneCandidate`; pool intake/dedup/asset_id is the caller's
171
- * `algo.intakeGene`). Signals merge skill + trace; strategy pads to ≥3 generic steps; validation keeps only the
172
- * allowed `node …` commands. STRICT mode + no allowed validation → refuse (errors, no gene); non-strict falls back
173
- * to `node --version` so Gene.validation is never empty (an empty validation would silently defeat the Capsule
174
- * coverage check in B2b). `avoid` / `_source` are dropped here (not on GeneCandidate) — re-added if the schema grows.
263
+ * `algo.intakeGene`). Signals merge skill + trace. Provenance is classified from the execution trace (v1 #302):
264
+ * - evolved → corrective_insight leads strategy; mutation_log → verifiable preconditions.
265
+ * - otherwise → Skill transcription (legacy behavior), tagged so consumers know it was not learned from a real run.
266
+ *
267
+ * Validation keeps only the allowed `node …` commands (v1 #302 DISTILL contract: do NOT inject a bogus
268
+ * `node --version` fallback — an empty validation list is the CORRECT outcome for a Gene with nothing runnable,
269
+ * not a near-trivial check that would silently pass). STRICT mode + no allowed validation → refuse (errors, no gene).
270
+ * `avoid` is dropped here (not on GeneCandidate); `generation_meta` carries the provenance + quality metadata.
175
271
  */
176
- export function synthesizeGene(parsed, execution, opts = {}) {
272
+ export function synthesizeGene(parsed, execution = {}, opts = {}) {
177
273
  const traceSignals = Array.isArray(execution?.signals) ? execution.signals : [];
178
274
  // Trace signals come from the REAL execution (ground truth), so put them FIRST — the 8-slot cap below then never
179
275
  // starves them in favor of the skill's DECLARED signals. (Improves on v1's skill-first merge, which dropped
180
276
  // trace-only signals once the skill already filled 8 slots — Bugbot #141.)
181
277
  const mergedSignals = [...new Set([...traceSignals, ...(parsed.signals_match || [])])];
182
- const strategy = [...(parsed.strategy || [])];
278
+ // ── v1 #302: classify provenance, then branch strategy/preconditions on it ────────────────────────────────
279
+ const source = classifyProvenance(execution);
280
+ let strategy;
281
+ let preconditions;
282
+ if (source === 'evolved') {
283
+ strategy = buildEvolvedStrategy(parsed, execution);
284
+ preconditions = preconditionsFromErrors(execution).concat(parsed.preconditions || []);
285
+ }
286
+ else {
287
+ strategy = [...(parsed.strategy || [])];
288
+ preconditions = (parsed.preconditions && parsed.preconditions.length > 0)
289
+ ? [...parsed.preconditions]
290
+ : [`Skill ${parsed.name || 'unknown'} has just been executed locally`];
291
+ }
183
292
  if (strategy.length < 3) {
184
293
  strategy.push('Identify the dominant trigger signals from the Skill description.');
185
294
  strategy.push('Apply the smallest targeted change that satisfies the Skill workflow.');
@@ -187,25 +296,49 @@ export function synthesizeGene(parsed, execution, opts = {}) {
187
296
  }
188
297
  const rawValidations = Array.isArray(parsed.validation) ? parsed.validation : [];
189
298
  const allowedValidations = rawValidations.map((v) => String(v || '').trim()).filter((v) => v && isValidationCommandAllowed(v));
190
- const fallbackUsed = allowedValidations.length === 0;
191
- if (opts.strict && fallbackUsed) {
192
- return { gene: null, errors: ['strict mode: no allowed validation commands found in the Skill (GEP validation only permits "node " prefixes). Rewrite the Skill validation section, or drop strict.'] };
299
+ if (opts.strict && allowedValidations.length === 0) {
300
+ return {
301
+ gene: null,
302
+ errors: ['strict mode: no allowed validation commands found in the Skill (GEP validation only permits "node " prefixes). Rewrite the Skill validation section, or drop strict.'],
303
+ generation_meta: { source, quality_score: computeQualityScore(source, parsed, execution) },
304
+ };
193
305
  }
194
- const validation = fallbackUsed ? ['node --version'] : allowedValidations;
306
+ // v1 #302 DISTILL contract: an empty validation list is correct when nothing runnable exists — do NOT inject a
307
+ // bogus `node --version` fallback. A trivially-passing check would silently defeat the Capsule coverage red line.
308
+ const validation = allowedValidations;
195
309
  const slug = slugify(parsed.name || opts.skillName || 'skill');
310
+ // Quality score + heuristics for the generation_meta block (v1 #302).
311
+ const qualityScore = computeQualityScore(source, parsed, execution);
312
+ const mutationLog = Array.isArray(execution?.mutation_log) ? execution.mutation_log : [];
313
+ const heuristics = {
314
+ strategy_steps: (parsed.strategy || []).length,
315
+ avoid_count: (parsed.avoid || []).length,
316
+ validation_declared_count: rawValidations.length,
317
+ validation_runnable_count: allowedValidations.length,
318
+ signals_extracted: (parsed.signals_match || []).length,
319
+ preconditions_extracted: (parsed.preconditions || []).length,
320
+ trajectory_depth: mutationLog.length > 0 ? mutationLog.length
321
+ : (Array.isArray(execution?.rollouts) ? Math.max(0, execution.rollouts.length - 1) : 0),
322
+ has_corrective_insight: Boolean(execution?.corrective_insight && String(execution.corrective_insight).trim().length >= 5),
323
+ };
324
+ const generation_meta = {
325
+ source,
326
+ quality_score: qualityScore,
327
+ quality_heuristics: heuristics,
328
+ ...(mutationLog.length > 0 ? { overcame_errors: [...mutationLog] } : {}),
329
+ };
196
330
  const gene = {
197
331
  id: SKILL2GEP_ID_PREFIX + slug,
198
332
  category: inferCategory(mergedSignals, parsed.description),
199
333
  signals_match: mergedSignals.slice(0, 8),
200
334
  strategy: strategy.slice(0, MAX_STRATEGY_STEPS),
201
335
  summary: (parsed.description || strategy[0] || 'Reusable strategy distilled from Skill').slice(0, 200),
202
- preconditions: (parsed.preconditions && parsed.preconditions.length > 0)
203
- ? parsed.preconditions
204
- : [`Skill ${parsed.name || 'unknown'} has just been executed locally`],
336
+ preconditions,
205
337
  constraints: { max_files: opts.maxFiles ?? SKILL_MAX_FILES, forbidden_paths: ['.git', 'node_modules'] },
206
338
  validation,
339
+ generation_meta,
207
340
  };
208
- return { gene, errors: [] };
341
+ return { gene, errors: [], generation_meta };
209
342
  }
210
343
  // ── B2b: Capsule from REAL execution evidence + the forgery / coverage red lines ─────────────────────────────
211
344
  /** Gene id prefix for skill-distilled capsules (v1 CAPSULE_ID_PREFIX). */
@@ -26,6 +26,7 @@ export interface SkillDistillDeps {
26
26
  }
27
27
  export interface SkillDistillResult {
28
28
  geneId: string | null;
29
+ geneAssetId: string | null;
29
30
  /** True when the gene landed in the pool QUARANTINED (awaiting human review). */
30
31
  quarantined: boolean;
31
32
  capsuleId: string | null;
@@ -55,14 +55,14 @@ export async function recordSkillDistillation(skillMd, execution, deps, opts = {
55
55
  const { gene, capsule, capsuleDiagnostic } = reverseDistill(parsed, execution, opts);
56
56
  const diag = capsuleDiagnostic ? (capsuleDiagnostic.detail ?? capsuleDiagnostic.reason) : null;
57
57
  if (!gene)
58
- return { geneId: null, quarantined: false, capsuleId: null, capsuleDiagnostic: diag, errors: ['gene synthesis refused (strict mode or empty)'] };
58
+ return { geneId: null, geneAssetId: null, quarantined: false, capsuleId: null, capsuleDiagnostic: diag, errors: ['gene synthesis refused (strict mode or empty)'] };
59
59
  const existing = (await deps.store.list('Gene', 1000)).map((g) => ({
60
60
  id: typeof g['id'] === 'string' ? String(g['id']) : undefined,
61
61
  signals_match: Array.isArray(g['signals_match']) ? g['signals_match'] : [],
62
62
  }));
63
63
  const r = algo.intakeGene(gene, existing);
64
64
  if (!r.ok || !r.gene)
65
- return { geneId: null, quarantined: false, capsuleId: null, capsuleDiagnostic: diag, errors: r.errors };
65
+ return { geneId: null, geneAssetId: null, quarantined: false, capsuleId: null, capsuleDiagnostic: diag, errors: r.errors };
66
66
  const assetId = String(r.gene.asset_id);
67
67
  const geneId = typeof r.gene.id === 'string' ? r.gene.id : assetId;
68
68
  try {
@@ -95,11 +95,11 @@ export async function recordSkillDistillation(skillMd, execution, deps, opts = {
95
95
  capsuleId = pooledCapsule.id;
96
96
  }
97
97
  await deps.store.put(r.gene); // gene LAST = the commit point; until it lands, a retry re-runs the above
98
- return { geneId, quarantined: true, capsuleId, capsuleDiagnostic: diag, errors: [] };
98
+ return { geneId, geneAssetId: assetId, quarantined: true, capsuleId, capsuleDiagnostic: diag, errors: [] };
99
99
  }
100
100
  catch (e) {
101
101
  // A write failed before the gene was committed → keep it recoverable: report the error so the caller retries.
102
- return { geneId: null, quarantined: false, capsuleId: null, capsuleDiagnostic: diag, errors: [e instanceof Error ? e.message : String(e)] };
102
+ return { geneId: null, geneAssetId: null, quarantined: false, capsuleId: null, capsuleDiagnostic: diag, errors: [e instanceof Error ? e.message : String(e)] };
103
103
  }
104
104
  }
105
105
  /** Resolve a `--skill` argument (a SKILL.md file OR a skill directory) to the SKILL.md path. */