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

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 (73) 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 +105 -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.js +4 -1
  14. package/dist/autoexec.d.ts +13 -3
  15. package/dist/autoexec.js +71 -13
  16. package/dist/cli.js +12 -5
  17. package/dist/cliContracts.js +8 -2
  18. package/dist/cliLifecycle.d.ts +7 -0
  19. package/dist/cliLifecycle.js +9 -0
  20. package/dist/cycleConsumer.d.ts +61 -1
  21. package/dist/cycleConsumer.js +551 -16
  22. package/dist/dashboard.d.ts +23 -0
  23. package/dist/dashboard.js +191 -0
  24. package/dist/dispatch.d.ts +10 -1
  25. package/dist/dispatch.js +36 -2
  26. package/dist/distillObserver.js +2 -2
  27. package/dist/distillPrimitives.d.ts +1 -1
  28. package/dist/distillPrimitives.js +29 -2
  29. package/dist/doctor.d.ts +2 -0
  30. package/dist/doctor.js +33 -3
  31. package/dist/index.d.ts +7 -2
  32. package/dist/index.js +292 -36
  33. package/dist/lifecycle.d.ts +19 -1
  34. package/dist/lifecycle.js +226 -29
  35. package/dist/localMemoryGraph.d.ts +97 -0
  36. package/dist/localMemoryGraph.js +889 -0
  37. package/dist/login.d.ts +20 -4
  38. package/dist/login.js +58 -8
  39. package/dist/materialPackage.d.ts +52 -0
  40. package/dist/materialPackage.js +404 -0
  41. package/dist/materialSnapshot.d.ts +30 -0
  42. package/dist/materialSnapshot.js +148 -0
  43. package/dist/memoryEventMirror.d.ts +23 -0
  44. package/dist/memoryEventMirror.js +140 -0
  45. package/dist/migrate/fieldMap.js +25 -0
  46. package/dist/migrate/v1Import.d.ts +7 -1
  47. package/dist/migrate/v1Import.js +132 -11
  48. package/dist/nonGitWorkspaceNotice.d.ts +24 -0
  49. package/dist/nonGitWorkspaceNotice.js +122 -0
  50. package/dist/proxyToken.d.ts +10 -0
  51. package/dist/proxyToken.js +80 -0
  52. package/dist/recipe.d.ts +10 -2
  53. package/dist/recipe.js +349 -7
  54. package/dist/reuseReport.js +16 -16
  55. package/dist/runtimeCapabilities.d.ts +18 -0
  56. package/dist/runtimeCapabilities.js +81 -0
  57. package/dist/runtimeSessionSource.d.ts +10 -0
  58. package/dist/runtimeSessionSource.js +32 -5
  59. package/dist/setupHooks.d.ts +6 -1
  60. package/dist/setupHooks.js +5 -2
  61. package/dist/skill2gep.d.ts +38 -9
  62. package/dist/skill2gep.js +147 -14
  63. package/dist/skillDistill.d.ts +1 -0
  64. package/dist/skillDistill.js +4 -4
  65. package/dist/skillFetch.d.ts +18 -0
  66. package/dist/skillFetch.js +391 -0
  67. package/dist/solo/mode.js +5 -0
  68. package/dist/sync.d.ts +26 -0
  69. package/dist/sync.js +988 -0
  70. package/dist/trajectoryExport.js +23 -12
  71. package/dist/v1Compat.d.ts +24 -0
  72. package/dist/v1Compat.js +249 -0
  73. package/package.json +12 -6
@@ -16,6 +16,7 @@
16
16
  // `--anti-gene` is the read-only operator view for #326: it surfaces local AntiGene assets, review state, shadow
17
17
  // observations, and whether approved warnings have actually appeared in selection decisions.
18
18
  import { events, ops, assetstore, algo } from '@evomap/evolver-core';
19
+ import { formatAntiGeneEvidenceAction, formatAntiGeneEvidenceSummary, summarizeAntiGeneEvidence } from './antiGeneEvidence.js';
19
20
  function parseFlags(argv) {
20
21
  let quarantine = false, promote = false, antiGene = false, minNegative = 3, minUnsafe = 1;
21
22
  for (let i = 0; i < argv.length; i++) {
@@ -70,7 +71,7 @@ async function reportProbation(deps, log) {
70
71
  return 0;
71
72
  }
72
73
  function reviewState(review, assetId) {
73
- return reviewRecord(review, assetId)?.state ?? 'approved';
74
+ return reviewRecord(review, assetId)?.state ?? 'unreviewed';
74
75
  }
75
76
  function reviewRecord(review, assetId) {
76
77
  return review?.get?.(assetId) ?? null;
@@ -81,12 +82,6 @@ function stringArray(value) {
81
82
  function optionalString(value) {
82
83
  return typeof value === 'string' && value.trim().length > 0 ? value.trim() : undefined;
83
84
  }
84
- function countLabel(value) {
85
- return Array.isArray(value) ? String(value.length) : '0';
86
- }
87
- function numberLabel(value) {
88
- return typeof value === 'number' && Number.isFinite(value) ? String(value) : '-';
89
- }
90
85
  function reviewAuditLabel(record) {
91
86
  if (!record)
92
87
  return '';
@@ -146,26 +141,31 @@ async function reportAntiGenes(deps, log) {
146
141
  log('anti-gene: no AntiGene assets or shadow observations recorded yet.');
147
142
  return 0;
148
143
  }
149
- const counts = { approved: 0, quarantined: 0, rejected: 0 };
144
+ const counts = { approved: 0, quarantined: 0, rejected: 0, unreviewed: 0 };
150
145
  for (const asset of assets)
151
146
  counts[reviewState(review, String(asset.asset_id))] += 1;
152
- log(`anti-gene: ${assets.length} stored asset(s); review approved=${counts.approved} quarantined=${counts.quarantined} rejected=${counts.rejected}; shadow candidate=${shadowCandidates.length} declined=${shadowDeclines.length}`);
147
+ log(`anti-gene: ${assets.length} stored asset(s); review approved=${counts.approved} quarantined=${counts.quarantined} rejected=${counts.rejected} unreviewed=${counts.unreviewed}; shadow candidate=${shadowCandidates.length} declined=${shadowDeclines.length}`);
153
148
  for (const asset of assets) {
154
149
  const assetId = String(asset.asset_id);
155
150
  const id = typeof asset['id'] === 'string' ? String(asset['id']) : assetId;
156
151
  const record = reviewRecord(review, assetId);
157
- const state = record?.state ?? 'approved';
152
+ const state = record?.state ?? 'unreviewed';
158
153
  const severity = optionalString(asset['severity']) ?? '-';
159
154
  const trigger = stringArray(asset['trigger']).slice(0, 6).join(',');
160
155
  const avoid = stringArray(asset['avoid']).slice(0, 2).join(' | ');
161
- const evidence = `failures=${numberLabel(asset['failure_count'])} clusters=${countLabel(asset['source_clusters'])} evidence=${countLabel(asset['evidence_capsules'])}`;
162
156
  const audit = reviewAuditLabel(record);
163
157
  const injected = (injectedCounts.get(id) ?? 0) + (id === assetId ? 0 : injectedCounts.get(assetId) ?? 0);
164
- const next = state === 'quarantined'
165
- ? 'approve with evolver review --approve before warning injection'
166
- : state === 'approved'
167
- ? (injected > 0 ? `observed in ${injected} decision(s)` : 'approved; waiting for matching selection')
168
- : 'rejected; withheld from warning injection';
158
+ const evidenceSummary = summarizeAntiGeneEvidence(asset, injected);
159
+ const evidence = `${formatAntiGeneEvidenceSummary(evidenceSummary)} ${formatAntiGeneEvidenceAction(evidenceSummary, state)}`;
160
+ const next = state === 'unreviewed' && injected > 0
161
+ ? `observed historically in ${injected} decision(s); explicit approval required`
162
+ : state === 'quarantined' || state === 'unreviewed'
163
+ ? evidenceSummary.strength === 'weak'
164
+ ? `reject/defer, or approve with evolver review --approve ${id} --allow-weak-evidence before warning injection`
165
+ : 'approve with evolver review --approve before warning injection'
166
+ : state === 'approved'
167
+ ? (injected > 0 ? `observed in ${injected} decision(s)` : 'approved; waiting for matching selection')
168
+ : 'rejected; withheld from warning injection';
169
169
  log(` ${id} {${state}} severity=${severity} trigger=${trigger || '-'} avoid=${avoid || '-'} ${evidence}${audit ? ` ${audit}` : ''} ${next}`);
170
170
  }
171
171
  if (shadowCandidates.length > 0 || shadowDeclines.length > 0) {
@@ -0,0 +1,18 @@
1
+ type RuntimeCapabilityStatus = 'supported' | 'experimental' | 'unsupported';
2
+ type RuntimeCapabilityId = 'claude-code' | 'codex' | 'cursor' | 'gemini' | 'antigravity' | 'kimi' | 'kiro' | 'opencode' | 'generic-chat';
3
+ interface RuntimeCapability {
4
+ status: RuntimeCapabilityStatus;
5
+ evidence: string;
6
+ }
7
+ interface RuntimeCapabilityEntry {
8
+ runtime: RuntimeCapabilityId;
9
+ ingest: RuntimeCapability;
10
+ inject: RuntimeCapability;
11
+ execute: RuntimeCapability;
12
+ verify: RuntimeCapability;
13
+ resume: RuntimeCapability;
14
+ }
15
+ /** Product-level runtime matrix. A transcript parser never implies execution, verification, or resumability. */
16
+ export declare const RUNTIME_CAPABILITY_MATRIX: Readonly<Record<RuntimeCapabilityId, RuntimeCapabilityEntry>>;
17
+ export declare function runtimeCapabilities(): RuntimeCapabilityEntry[];
18
+ export {};
@@ -0,0 +1,81 @@
1
+ const supported = (evidence) => ({ status: 'supported', evidence });
2
+ const experimental = (evidence) => ({ status: 'experimental', evidence });
3
+ const unsupported = (evidence) => ({ status: 'unsupported', evidence });
4
+ /** Product-level runtime matrix. A transcript parser never implies execution, verification, or resumability. */
5
+ export const RUNTIME_CAPABILITY_MATRIX = {
6
+ 'claude-code': {
7
+ runtime: 'claude-code',
8
+ ingest: supported('normalized Claude Code JSONL adapter'),
9
+ inject: supported('MCP registration plus SessionStart hook'),
10
+ execute: supported('run-verified claude -p runner'),
11
+ verify: supported('git diff proof plus external validation hook'),
12
+ resume: unsupported('cycle runner does not bind ingested session ids to claude resume'),
13
+ },
14
+ codex: {
15
+ runtime: 'codex',
16
+ ingest: supported('normalized Codex rollout adapter'),
17
+ inject: supported('project MCP config plus SessionStart hook'),
18
+ execute: supported('run-verified codex exec runner'),
19
+ verify: supported('git diff proof plus external validation hook'),
20
+ resume: unsupported('cycle runner starts a new codex exec session'),
21
+ },
22
+ cursor: {
23
+ runtime: 'cursor',
24
+ ingest: supported('Cursor transcript and state.vscdb adapters'),
25
+ inject: supported('always-on project rules injection'),
26
+ execute: experimental('CLI flags are contract-tested but the repository still treats the runner as a scaffold'),
27
+ verify: supported('git diff proof plus external validation hook'),
28
+ resume: unsupported('no verified headless session resume mapping'),
29
+ },
30
+ gemini: {
31
+ runtime: 'gemini',
32
+ ingest: supported('normalized Gemini CLI session adapter'),
33
+ inject: unsupported('no Evolver Gemini injection installer'),
34
+ execute: experimental('hermetic Gemini CLI 0.46.0 headless JSON contract exists, but provider-backed live E2E smoke is not complete'),
35
+ verify: experimental('hermetic structured-result and git-diff proof contract exists, but provider-backed live E2E verification is not complete'),
36
+ resume: unsupported('Gemini resume accepts latest/index; ingested UUIDs cannot be mapped reliably'),
37
+ },
38
+ antigravity: {
39
+ runtime: 'antigravity',
40
+ ingest: supported('strict Antigravity transcript adapter'),
41
+ inject: supported('user-level MCP tool discovery only; no SessionStart hook'),
42
+ execute: unsupported('agy is not installed or live-verified in the implementation environment'),
43
+ verify: unsupported('no Antigravity runner result is wired to state proof'),
44
+ resume: unsupported('no verified transcript-id to agy resume contract'),
45
+ },
46
+ kimi: {
47
+ runtime: 'kimi',
48
+ ingest: supported('normalized Kimi session adapter'),
49
+ inject: unsupported('no Evolver Kimi injection installer'),
50
+ execute: unsupported('no verified Kimi runner contract'),
51
+ verify: unsupported('no Kimi execution runner exists'),
52
+ resume: unsupported('no verified Kimi resume contract'),
53
+ },
54
+ kiro: {
55
+ runtime: 'kiro',
56
+ ingest: supported('normalized Kiro session adapter'),
57
+ inject: unsupported('automatic Kiro setup is not available on the current main branch'),
58
+ execute: unsupported('no verified Kiro runner contract'),
59
+ verify: unsupported('no Kiro execution runner exists'),
60
+ resume: unsupported('no verified Kiro resume contract'),
61
+ },
62
+ opencode: {
63
+ runtime: 'opencode',
64
+ ingest: supported('normalized OpenCode session adapter'),
65
+ inject: unsupported('automatic OpenCode setup is not available on the current main branch'),
66
+ execute: unsupported('no verified OpenCode runner contract'),
67
+ verify: unsupported('no OpenCode execution runner exists'),
68
+ resume: unsupported('no verified OpenCode resume contract'),
69
+ },
70
+ 'generic-chat': {
71
+ runtime: 'generic-chat',
72
+ ingest: supported('normalized standard OpenAI and Anthropic message JSON/JSONL adapter'),
73
+ inject: unsupported('generic transcript interchange has no Evolver injection installer'),
74
+ execute: unsupported('generic chat transcripts do not identify a runnable provider or CLI contract'),
75
+ verify: unsupported('no provider-backed execution runner exists for generic chat transcripts'),
76
+ resume: unsupported('no provider or session identity contract exists for generic chat transcripts'),
77
+ },
78
+ };
79
+ export function runtimeCapabilities() {
80
+ return Object.values(RUNTIME_CAPABILITY_MATRIX);
81
+ }
@@ -5,5 +5,15 @@ export interface RuntimeSessionSource {
5
5
  sessionId?: string;
6
6
  turns: NormalizedTurn[];
7
7
  }
8
+ export interface RuntimeSessionParseDiagnostics {
9
+ rowsScanned: number;
10
+ rowsRead: number;
11
+ invalidJson: number;
12
+ }
13
+ export interface RuntimeSessionParseResult {
14
+ sources: RuntimeSessionSource[];
15
+ diagnostics: RuntimeSessionParseDiagnostics;
16
+ }
8
17
  export declare function isRuntimeSessionSourcePath(path: string): boolean;
18
+ export declare function parseRuntimeSessionSourcesWithDiagnostics(path: string, readSource?: (path: string) => string): RuntimeSessionParseResult;
9
19
  export declare function parseRuntimeSessionSources(path: string, readSource?: (path: string) => string): RuntimeSessionSource[];
@@ -1,6 +1,7 @@
1
1
  import { readFileSync } from 'node:fs';
2
2
  import { resolve } from 'node:path';
3
- import { adapterForPath, isCursorStateVscdbPath, parseCursorStateVscdb, } from '@evomap/evolver-runtime-adapters';
3
+ import { adapterForPath, isCursorStateVscdbPath, parseJsonlLinesWithStats, parseCursorStateVscdb, stripUtf8Bom, } from '@evomap/evolver-runtime-adapters';
4
+ const EMPTY_DIAGNOSTICS = { rowsScanned: 0, rowsRead: 0, invalidJson: 0 };
4
5
  export function isRuntimeSessionSourcePath(path) {
5
6
  return isCursorStateVscdbPath(path) || adapterForPath(path) !== undefined;
6
7
  }
@@ -15,15 +16,41 @@ function cursorSourceFromSession(session, index) {
15
16
  turns: session.turns,
16
17
  };
17
18
  }
18
- export function parseRuntimeSessionSources(path, readSource = (p) => readFileSync(p, 'utf8')) {
19
+ function diagnosticsForRuntimeSource(raw) {
20
+ const trimmed = stripUtf8Bom(raw).trim();
21
+ if (!trimmed)
22
+ return { ...EMPTY_DIAGNOSTICS };
23
+ try {
24
+ JSON.parse(trimmed);
25
+ return { rowsScanned: 1, rowsRead: 1, invalidJson: 0 };
26
+ }
27
+ catch {
28
+ return parseJsonlLinesWithStats(raw).stats;
29
+ }
30
+ }
31
+ export function parseRuntimeSessionSourcesWithDiagnostics(path, readSource = (p) => readFileSync(p, 'utf8')) {
19
32
  const absPath = resolve(path);
20
33
  if (isCursorStateVscdbPath(absPath)) {
21
- return parseCursorStateVscdb(absPath)
34
+ const sources = parseCursorStateVscdb(absPath)
22
35
  .map(cursorSourceFromSession)
23
36
  .filter((source) => source !== null);
37
+ return { sources, diagnostics: { ...EMPTY_DIAGNOSTICS } };
24
38
  }
25
39
  const adapter = adapterForPath(absPath);
26
40
  if (!adapter)
27
- return [];
28
- return [{ agent: adapter.agent, label: adapter.agent, turns: adapter.parse(readSource(absPath)) }];
41
+ return { sources: [], diagnostics: { ...EMPTY_DIAGNOSTICS } };
42
+ const raw = readSource(absPath);
43
+ const sessionId = adapter.sessionIdFromPath?.(absPath)?.trim();
44
+ return {
45
+ sources: [{
46
+ agent: adapter.agent,
47
+ label: sessionId ? `${adapter.agent}:${sessionId}` : adapter.agent,
48
+ ...(sessionId ? { sessionId } : {}),
49
+ turns: adapter.parse(raw),
50
+ }],
51
+ diagnostics: diagnosticsForRuntimeSource(raw),
52
+ };
53
+ }
54
+ export function parseRuntimeSessionSources(path, readSource = (p) => readFileSync(p, 'utf8')) {
55
+ return parseRuntimeSessionSourcesWithDiagnostics(path, readSource).sources;
29
56
  }
@@ -1,2 +1,7 @@
1
1
  import { assetstore } from '@evomap/evolver-core';
2
- export declare function runSetupHooks(argv: readonly string[], store?: assetstore.AssetStoreProvider, review?: assetstore.ReviewLedger): Promise<number>;
2
+ import { maybeEmitNonGitWorkspaceNotice } from './nonGitWorkspaceNotice.js';
3
+ interface SetupHooksDeps {
4
+ emitNonGitWorkspaceNotice?: typeof maybeEmitNonGitWorkspaceNotice;
5
+ }
6
+ export declare function runSetupHooks(argv: readonly string[], store?: assetstore.AssetStoreProvider, review?: assetstore.ReviewLedger, deps?: SetupHooksDeps): Promise<number>;
7
+ export {};
@@ -12,6 +12,7 @@ import { fileURLToPath } from 'node:url';
12
12
  import { currentTopCursorGenes } from './cursorRewrite.js';
13
13
  import { resolveProxyBinPath, resolveStableNodePath } from './lifecycle.js';
14
14
  import { reviewLedgerForStore } from './reviewFilter.js';
15
+ import { maybeEmitNonGitWorkspaceNotice } from './nonGitWorkspaceNotice.js';
15
16
  const requireFromHere = createRequire(import.meta.url);
16
17
  function parseFlags(argv) {
17
18
  const out = {};
@@ -273,7 +274,7 @@ function appendAdapterNotes(text, hints) {
273
274
  ? `${text}\n\nAdapter notes:\n${hints.map((hint) => ` - ${hint}`).join('\n')}`
274
275
  : text;
275
276
  }
276
- export async function runSetupHooks(argv, store, review) {
277
+ export async function runSetupHooks(argv, store, review, deps = {}) {
277
278
  const f = parseFlags(argv);
278
279
  const runtimeRaw = typeof f['runtime'] === 'string'
279
280
  ? f['runtime']
@@ -300,7 +301,7 @@ export async function runSetupHooks(argv, store, review) {
300
301
  process.stderr.write(`${support.reason}\n${USAGE}`);
301
302
  return 1;
302
303
  }
303
- // installed class: claude-code / codex / cursor: v2 owns a real config writer + uninstaller for these.
304
+ // Installed runtimes have a real config writer + uninstaller (including Antigravity MCP config).
304
305
  const runtime = runtimeRaw;
305
306
  const configRoot = typeof f['root'] === 'string' ? f['root'] : process.cwd();
306
307
  // claude-code: user scope targets ~/.claude.json regardless of --root; project scope uses configRoot.
@@ -359,6 +360,8 @@ export async function runSetupHooks(argv, store, review) {
359
360
  return 0;
360
361
  }
361
362
  const server = buildServer(f, descriptor);
363
+ if (runtime === 'cursor')
364
+ (deps.emitNonGitWorkspaceNotice ?? maybeEmitNonGitWorkspaceNotice)({ cwd: configRoot });
362
365
  // cursor seeds .cursor/rules/evolver.mdc with the CURRENT top REVIEW-APPROVED genes so the file is useful
363
366
  // immediately (before the first daemon rewrite) without seeding an unapproved draft (A2a). The renderer thus
364
367
  // has a real production caller even without the daemon running.
@@ -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. */
@@ -0,0 +1,18 @@
1
+ import { assetstore, type hub as hubNs } from '@evomap/evolver-core';
2
+ import type { ConnectPublicOptions, PublicHubCapability } from '@evomap/evolver-adapter-public';
3
+ export interface SkillFetchHub {
4
+ search(query: assetstore.SearchQuery): Promise<assetstore.AssetRecord[]>;
5
+ fetch(query: assetstore.SearchQuery): Promise<assetstore.AssetRecord[]>;
6
+ fetchAssetById?(assetId: string): Promise<assetstore.AssetRecord | null>;
7
+ }
8
+ export interface SkillFetchDeps {
9
+ hub?: SkillFetchHub;
10
+ env?: NodeJS.ProcessEnv;
11
+ stdout?: (line: string) => void;
12
+ stderr?: (line: string) => void;
13
+ connectHub?: (opts: ConnectPublicOptions) => {
14
+ hub: PublicHubCapability;
15
+ auth: hubNs.AuthProvider;
16
+ };
17
+ }
18
+ export declare function runSkillCommand(argv: readonly string[], deps?: SkillFetchDeps): Promise<number>;