@evomap/evolver-cli 2.0.0-beta.0

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 (91) hide show
  1. package/dist/antiGeneBenchmark.d.ts +9 -0
  2. package/dist/antiGeneBenchmark.js +173 -0
  3. package/dist/antiGeneRollout.d.ts +14 -0
  4. package/dist/antiGeneRollout.js +276 -0
  5. package/dist/atp.d.ts +122 -0
  6. package/dist/atp.js +413 -0
  7. package/dist/atpAutoDeliver.d.ts +53 -0
  8. package/dist/atpAutoDeliver.js +197 -0
  9. package/dist/atpAutobuyPrompt.d.ts +48 -0
  10. package/dist/atpAutobuyPrompt.js +109 -0
  11. package/dist/autoDistillAntiGene.d.ts +63 -0
  12. package/dist/autoDistillAntiGene.js +396 -0
  13. package/dist/autoDistillLlm.d.ts +94 -0
  14. package/dist/autoDistillLlm.js +510 -0
  15. package/dist/autoDistillTranscript.d.ts +87 -0
  16. package/dist/autoDistillTranscript.js +364 -0
  17. package/dist/autoRecall.d.ts +25 -0
  18. package/dist/autoRecall.js +80 -0
  19. package/dist/autoexec.d.ts +237 -0
  20. package/dist/autoexec.js +1041 -0
  21. package/dist/cli.d.ts +2 -0
  22. package/dist/cli.js +7 -0
  23. package/dist/cliContracts.d.ts +72 -0
  24. package/dist/cliContracts.js +815 -0
  25. package/dist/commands.d.ts +9 -0
  26. package/dist/commands.js +10 -0
  27. package/dist/cursorRewrite.d.ts +42 -0
  28. package/dist/cursorRewrite.js +65 -0
  29. package/dist/cycleConsumer.d.ts +42 -0
  30. package/dist/cycleConsumer.js +519 -0
  31. package/dist/daemonLoop.d.ts +33 -0
  32. package/dist/daemonLoop.js +72 -0
  33. package/dist/dispatch.d.ts +10 -0
  34. package/dist/dispatch.js +75 -0
  35. package/dist/distillObserver.d.ts +33 -0
  36. package/dist/distillObserver.js +146 -0
  37. package/dist/distillPrimitives.d.ts +48 -0
  38. package/dist/distillPrimitives.js +142 -0
  39. package/dist/doctor.d.ts +54 -0
  40. package/dist/doctor.js +931 -0
  41. package/dist/geneValue.d.ts +37 -0
  42. package/dist/geneValue.js +97 -0
  43. package/dist/index.d.ts +193 -0
  44. package/dist/index.js +1135 -0
  45. package/dist/lifecycle.d.ts +75 -0
  46. package/dist/lifecycle.js +859 -0
  47. package/dist/login.d.ts +10 -0
  48. package/dist/login.js +38 -0
  49. package/dist/migrate/divergenceAudit.d.ts +29 -0
  50. package/dist/migrate/divergenceAudit.js +37 -0
  51. package/dist/migrate/fieldMap.d.ts +18 -0
  52. package/dist/migrate/fieldMap.js +68 -0
  53. package/dist/migrate/v1Import.d.ts +16 -0
  54. package/dist/migrate/v1Import.js +118 -0
  55. package/dist/phub.d.ts +18 -0
  56. package/dist/phub.js +284 -0
  57. package/dist/recall.d.ts +26 -0
  58. package/dist/recall.js +162 -0
  59. package/dist/recipe.d.ts +61 -0
  60. package/dist/recipe.js +564 -0
  61. package/dist/reflectionObserver.d.ts +8 -0
  62. package/dist/reflectionObserver.js +6 -0
  63. package/dist/reuse.d.ts +48 -0
  64. package/dist/reuse.js +300 -0
  65. package/dist/reuseReport.d.ts +20 -0
  66. package/dist/reuseReport.js +255 -0
  67. package/dist/reviewFilter.d.ts +4 -0
  68. package/dist/reviewFilter.js +6 -0
  69. package/dist/runtimeSessionSource.d.ts +9 -0
  70. package/dist/runtimeSessionSource.js +29 -0
  71. package/dist/setupHooks.d.ts +2 -0
  72. package/dist/setupHooks.js +410 -0
  73. package/dist/skill2gep.d.ts +144 -0
  74. package/dist/skill2gep.js +321 -0
  75. package/dist/skillDistill.d.ts +75 -0
  76. package/dist/skillDistill.js +342 -0
  77. package/dist/solo/breaker.d.ts +14 -0
  78. package/dist/solo/breaker.js +21 -0
  79. package/dist/solo/gitGuard.d.ts +17 -0
  80. package/dist/solo/gitGuard.js +62 -0
  81. package/dist/solo/mode.d.ts +12 -0
  82. package/dist/solo/mode.js +55 -0
  83. package/dist/thesis.d.ts +43 -0
  84. package/dist/thesis.js +179 -0
  85. package/dist/trajectoryExport.d.ts +1 -0
  86. package/dist/trajectoryExport.js +895 -0
  87. package/dist/valueDigest.d.ts +33 -0
  88. package/dist/valueDigest.js +94 -0
  89. package/dist/version.d.ts +2 -0
  90. package/dist/version.js +14 -0
  91. package/package.json +38 -0
@@ -0,0 +1,321 @@
1
+ // skill2gep (#117-B) — reverse-distill a SKILL.md (+ a real execution trace) into GEP assets (Gene + Capsule),
2
+ // ported from v1 `src/gep/skill2gep.js`. This slice (B1) ports `parseSkillMd`: SKILL.md text → a structured
3
+ // intermediate (frontmatter / sections / signals / strategy / validation / preconditions / avoid). PURE (no I/O),
4
+ // faithful to v1 (golden-tested). B2 adds `synthesizeGene` + the Capsule contracts (trace-only / empty→Gene-only /
5
+ // validation-coverage); the human-review + real-trace red lines live there.
6
+ import { createHash } from 'node:crypto';
7
+ import { bootstrap } from '@evomap/evolver-core';
8
+ /** Max strategy steps kept from a skill (v1 parity: MAX_STRATEGY_STEPS). */
9
+ export const MAX_STRATEGY_STEPS = 28;
10
+ /** Gene id prefix for skill-distilled genes (v1 SKILL2GEP_ID_PREFIX). */
11
+ const SKILL2GEP_ID_PREFIX = 'gene_s2g_';
12
+ /** Default max-files constraint for a distilled gene (v1 skillDistiller.DISTILLED_MAX_FILES). */
13
+ const SKILL_MAX_FILES = 12;
14
+ /** Validation-command allowlist prefixes (v1 policyCheck): only `node …` is a runnable Gene.validation entry. */
15
+ const VALIDATION_ALLOWED_PREFIXES = ['node '];
16
+ /**
17
+ * Parse a SKILL.md into a structured intermediate — faithful port of v1 `parseSkillMd`. Pure. Section keywords are
18
+ * matched against lower-cased headings and include CJK synonyms (skills authored in Chinese), though the signal
19
+ * tokenizer keeps ASCII `[a-z0-9_]` only, so a CJK skill's signals come from its (English) frontmatter description.
20
+ */
21
+ export function parseSkillMd(skillMd) {
22
+ const text = String(skillMd || '');
23
+ // --- frontmatter (--- … --- block of key: value lines, keys lower-cased) ---
24
+ const frontmatter = {};
25
+ const fmMatch = text.match(/^---\n([\s\S]*?)\n---\n/);
26
+ let body = text;
27
+ if (fmMatch) {
28
+ fmMatch[1].split(/\n/).forEach((line) => {
29
+ const kv = line.match(/^([A-Za-z0-9_-]+)\s*:\s*(.*)$/);
30
+ if (kv)
31
+ frontmatter[kv[1].trim().toLowerCase()] = kv[2].trim();
32
+ });
33
+ body = text.slice(fmMatch[0].length);
34
+ }
35
+ // --- sections: split by `##+ heading`; content before the first heading is `_preamble`. A repeated heading
36
+ // resets its block (last occurrence wins), matching v1. ---
37
+ const lines = { _preamble: [] };
38
+ let currentKey = '_preamble';
39
+ body.split(/\n/).forEach((line) => {
40
+ const hdr = line.match(/^##+\s+(.+?)\s*$/);
41
+ if (hdr) {
42
+ currentKey = hdr[1].toLowerCase().trim();
43
+ lines[currentKey] = [];
44
+ }
45
+ else {
46
+ (lines[currentKey] ??= []).push(line);
47
+ }
48
+ });
49
+ const sections = {};
50
+ for (const k of Object.keys(lines))
51
+ sections[k] = lines[k].join('\n').trim();
52
+ /** First section whose (lower-cased) heading contains any keyword. */
53
+ const pickSection = (keywords) => {
54
+ for (const kw of keywords)
55
+ for (const k of Object.keys(sections))
56
+ if (k.indexOf(kw) !== -1)
57
+ return sections[k];
58
+ return '';
59
+ };
60
+ /** ALL matching sections concatenated in document order, de-duped by key (keeps a governance tail like
61
+ * "## Human Gate" that a first-match would drop). */
62
+ const pickSectionsAll = (keywords) => {
63
+ const seen = new Set();
64
+ const out = [];
65
+ for (const k of Object.keys(sections)) {
66
+ if (keywords.some((kw) => k.indexOf(kw) !== -1) && !seen.has(k)) {
67
+ seen.add(k);
68
+ out.push(sections[k]);
69
+ }
70
+ }
71
+ return out.join('\n');
72
+ };
73
+ /** Every markdown list item → one step, in document order, length-bounded (default 5..300). */
74
+ const extractSteps = (block, opts) => {
75
+ const minLen = opts && typeof opts.minLen === 'number' ? opts.minLen : 5;
76
+ const maxLen = opts && typeof opts.maxLen === 'number' ? opts.maxLen : 300;
77
+ const steps = [];
78
+ for (const line of String(block || '').split(/\n/)) {
79
+ const m = line.match(/^\s*(?:\d+\.|[-*])\s+(.+?)\s*$/);
80
+ if (!m)
81
+ continue;
82
+ const txt = m[1].trim();
83
+ if (txt.length >= minLen && txt.length <= maxLen)
84
+ steps.push(txt);
85
+ }
86
+ return steps;
87
+ };
88
+ // --- signals: frontmatter.description + the trigger/when section, tokenized to [a-z0-9_] (3..40, has-letter) ---
89
+ const signals = [];
90
+ const signalSource = (frontmatter['description'] || '') + '\n' + pickSection([
91
+ 'trigger', 'when to use', 'when', 'use when', 'scenario',
92
+ '何时使用', '什么时候使用', '触发条件', '触发', '使用场景', '核心目标', '适用',
93
+ ]);
94
+ signalSource.split(/[`,.\n]/).forEach((tok) => {
95
+ const s = tok.trim().toLowerCase().replace(/[^a-z0-9_]/g, '_').replace(/^_+|_+$/g, '');
96
+ if (s.length >= 3 && s.length <= 40 && /[a-z]/.test(s) && signals.indexOf(s) === -1 && !/^\d+$/.test(s))
97
+ signals.push(s);
98
+ });
99
+ // --- strategy: workflow + governance-tail sections; avoid: anti-pattern sections ---
100
+ const strategy = extractSteps(pickSectionsAll([
101
+ 'workflow', 'strategy', 'steps', 'procedure', 'quick start', 'how to',
102
+ 'human gate', 'output contract', 'release', 'rollback', 'promotion',
103
+ '工作流', '流程', '步骤', '核心方法', '方法', '快速规则', '规则',
104
+ '输出门', '输出门槛', '人工确认', '人工门', '回滚', '发布', '晋级',
105
+ ]));
106
+ const avoid = extractSteps(pickSectionsAll([
107
+ 'avoid', 'pitfall', 'anti-pattern', 'common mistake', 'do not', 'forbidden', "don't",
108
+ '不要做', '不要', '常见错误', '避免', '陷阱', '禁止',
109
+ ]));
110
+ // --- validation: the bash/sh fenced commands in the validation/test section (non-comment, ≤300) ---
111
+ const validation = [];
112
+ const valBlock = pickSection(['validation', 'test', 'verify', 'check', '校验', '验证', '测试', '检查']);
113
+ const fenceRe = /```(?:bash|sh|shell)?\s*\n([\s\S]*?)\n```/g;
114
+ let fence;
115
+ while ((fence = fenceRe.exec(valBlock)) !== null) {
116
+ fence[1].split(/\n/).forEach((ln) => {
117
+ const t = ln.trim();
118
+ if (t && !t.startsWith('#') && t.length <= 300)
119
+ validation.push(t);
120
+ });
121
+ }
122
+ // --- preconditions: no length gate (short prereqs like "Git"/"npm" survive) ---
123
+ const preconditions = extractSteps(pickSection(['precondition', 'requirement', 'prerequisite', '前置条件', '前置', '先决条件', '要求']), { minLen: 1, maxLen: Infinity });
124
+ return {
125
+ frontmatter,
126
+ sections,
127
+ name: frontmatter['name'] || (sections['_preamble'] || '').split(/\n/)[0].replace(/^#+\s*/, '').trim(),
128
+ description: frontmatter['description'] || '',
129
+ signals_match: signals.slice(0, 8),
130
+ strategy: strategy.slice(0, MAX_STRATEGY_STEPS),
131
+ avoid: avoid.slice(0, 5),
132
+ validation: validation.slice(0, 5),
133
+ preconditions: preconditions.slice(0, 4),
134
+ };
135
+ }
136
+ /** Whether a validation command is safe to run as a Gene.validation entry (faithful port of v1
137
+ * policyCheck.isValidationCommandAllowed): a `node …` command with no command substitution, no shell
138
+ * metacharacters (outside quoted strings), and no node eval flags (-e/--eval/--print/-p). */
139
+ export function isValidationCommandAllowed(cmd) {
140
+ const c = String(cmd || '').trim();
141
+ if (!c)
142
+ return false;
143
+ if (!VALIDATION_ALLOWED_PREFIXES.some((p) => c.startsWith(p)))
144
+ return false;
145
+ if (/`|\$\(/.test(c))
146
+ return false; // no command substitution
147
+ const stripped = c.replace(/"[^"]*"/g, '').replace(/'[^']*'/g, ''); // ignore metachars inside quotes
148
+ if (/[;&|><]/.test(stripped))
149
+ return false; // no chaining / redirection
150
+ if (/^node\s+(-e|--eval|--print|-p)\b/.test(c))
151
+ return false; // no inline eval
152
+ return true;
153
+ }
154
+ /** Stable slug for a skill-distilled gene id (v1 slugify). */
155
+ function slugify(s) {
156
+ return String(s || '').toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '').slice(0, 60);
157
+ }
158
+ /** Infer a gene category from signals + description (v1 inferCategory): priority repair > innovate > optimize,
159
+ * substring match (catches inflections + underscore signal tokens like `log_error`). */
160
+ export function inferCategory(signals, description) {
161
+ const hay = ((description || '') + ' ' + (signals || []).join(' ')).toLowerCase();
162
+ if (/error|fail|bug|crash|broken|incident|regress|debug|repair|fix/.test(hay))
163
+ return 'repair';
164
+ if (/feature|\badd\b|implement|new capability|capability|innovate|greenfield|prototype/.test(hay))
165
+ return 'innovate';
166
+ return 'optimize';
167
+ }
168
+ /**
169
+ * Assemble a draft GeneCandidate from a parsed skill + its execution trace (B2a — faithful port of v1
170
+ * `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.
175
+ */
176
+ export function synthesizeGene(parsed, execution, opts = {}) {
177
+ const traceSignals = Array.isArray(execution?.signals) ? execution.signals : [];
178
+ // Trace signals come from the REAL execution (ground truth), so put them FIRST — the 8-slot cap below then never
179
+ // starves them in favor of the skill's DECLARED signals. (Improves on v1's skill-first merge, which dropped
180
+ // trace-only signals once the skill already filled 8 slots — Bugbot #141.)
181
+ const mergedSignals = [...new Set([...traceSignals, ...(parsed.signals_match || [])])];
182
+ const strategy = [...(parsed.strategy || [])];
183
+ if (strategy.length < 3) {
184
+ strategy.push('Identify the dominant trigger signals from the Skill description.');
185
+ strategy.push('Apply the smallest targeted change that satisfies the Skill workflow.');
186
+ strategy.push('Run the Skill validation commands and abort if any fails.');
187
+ }
188
+ const rawValidations = Array.isArray(parsed.validation) ? parsed.validation : [];
189
+ 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.'] };
193
+ }
194
+ const validation = fallbackUsed ? ['node --version'] : allowedValidations;
195
+ const slug = slugify(parsed.name || opts.skillName || 'skill');
196
+ const gene = {
197
+ id: SKILL2GEP_ID_PREFIX + slug,
198
+ category: inferCategory(mergedSignals, parsed.description),
199
+ signals_match: mergedSignals.slice(0, 8),
200
+ strategy: strategy.slice(0, MAX_STRATEGY_STEPS),
201
+ 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`],
205
+ constraints: { max_files: opts.maxFiles ?? SKILL_MAX_FILES, forbidden_paths: ['.git', 'node_modules'] },
206
+ validation,
207
+ };
208
+ return { gene, errors: [] };
209
+ }
210
+ // ── B2b: Capsule from REAL execution evidence + the forgery / coverage red lines ─────────────────────────────
211
+ /** Gene id prefix for skill-distilled capsules (v1 CAPSULE_ID_PREFIX). */
212
+ const CAPSULE_ID_PREFIX = 'cap_s2g_';
213
+ const normalizeCmd = (s) => String(s ?? '').replace(/\s+/g, ' ').trim();
214
+ const shortHash = (s) => createHash('sha256').update(String(s ?? '')).digest('hex').slice(0, 10);
215
+ /**
216
+ * Forgery guard (v1 detectForgery) — RED LINE #1. A status=success Capsule with no real execution evidence is
217
+ * refused outright: empty trace, zero blast radius, or no recorded exit code. The core defence against an agent
218
+ * hallucinating a successful run to pad the registry. Non-success executions are honest, so not checked. Returns
219
+ * the rejection reason, or null when clean.
220
+ */
221
+ export function detectForgery(execution) {
222
+ const trace = Array.isArray(execution?.trace) ? execution.trace : [];
223
+ const files = Number(execution?.blast_radius?.files ?? 0);
224
+ const lines = Number(execution?.blast_radius?.lines ?? 0);
225
+ if ((execution?.status ?? 'failed') !== 'success')
226
+ return null;
227
+ if (trace.length === 0)
228
+ return 'empty_execution_trace';
229
+ if (files === 0 && lines === 0)
230
+ return 'zero_blast_radius_with_success';
231
+ if (!trace.some((t) => Number.isInteger(t?.exit)))
232
+ return 'no_exit_code_in_trace';
233
+ return null;
234
+ }
235
+ const buildContentSummary = (trace, blast) => {
236
+ const okCount = trace.filter((t) => Number(t?.exit) === 0).length;
237
+ return `Ran ${trace.length} validation command(s), ${okCount} passed. Blast radius: ${Number(blast?.files ?? 0)} files, ${Number(blast?.lines ?? 0)} lines.`;
238
+ };
239
+ /**
240
+ * Assemble a Capsule from a gene + real execution evidence (v1 assembleCapsule) — RED LINE #2/#3. Every
241
+ * `Gene.validation` command MUST appear in `execution.trace` (whitespace-normalized exact match) AND carry an
242
+ * integer exit code; otherwise refuse → the caller degrades to Gene-only. No coverage = no Capsule.
243
+ */
244
+ export function assembleCapsule(gene, execution, opts = {}) {
245
+ const trace = Array.isArray(execution?.trace) ? execution.trace : [];
246
+ const geneValidations = Array.isArray(gene.validation) ? gene.validation : [];
247
+ const traceCmds = new Set(trace.map((t) => normalizeCmd(t?.cmd)));
248
+ const missing = geneValidations.filter((v) => !traceCmds.has(normalizeCmd(v)));
249
+ if (missing.length > 0)
250
+ return { ok: false, reason: 'validation_coverage_missing', missing: [...missing] };
251
+ for (const v of geneValidations) {
252
+ // Consider ALL trace rows for this command, not just the first: coverage holds if ANY run of it recorded an
253
+ // integer exit — a duplicate earlier row without one must not mask a later real result (Bugbot #142).
254
+ const matches = trace.filter((tt) => normalizeCmd(tt?.cmd) === normalizeCmd(v));
255
+ if (matches.length > 0 && !matches.some((t) => Number.isInteger(t.exit)))
256
+ return { ok: false, reason: 'validation_missing_exit_code', cmd: v };
257
+ }
258
+ const scoreRaw = execution?.score != null ? Number(execution.score) : null;
259
+ const status = execution?.status ?? 'failed';
260
+ const score = Number.isFinite(scoreRaw) ? Math.max(0, Math.min(1, scoreRaw)) : (status === 'success' ? 0.8 : 0.2);
261
+ const files = Number(execution?.blast_radius?.files ?? 0);
262
+ const lines = Number(execution?.blast_radius?.lines ?? 0);
263
+ const geneIdSuffix = String(gene.id).replace(/^gene_[a-z0-9]+_/, '').replace(/^gene_/, '');
264
+ // The capsule id distinguishes DIFFERENT runs of the same gene. Prefer the real start time; when it is absent,
265
+ // fall back to a DETERMINISTIC digest of the execution itself (status/score/blast/trace) — NOT a fresh wall clock
266
+ // — so re-distilling the same execution (e.g. a retry after a write failure) yields the SAME id and store.put
267
+ // dedups by content address, instead of persisting a duplicate capsule (Bugbot #143).
268
+ const stableExecKey = execution?.started_at ??
269
+ JSON.stringify({ s: status, sc: score, f: files, l: lines, t: trace.map((t) => `${normalizeCmd(t?.cmd)}:${Number.isInteger(t?.exit) ? t.exit : 'x'}`) });
270
+ const idKey = shortHash(`${String(gene.id)}|${stableExecKey}`);
271
+ const capsule = {
272
+ type: 'Capsule',
273
+ id: CAPSULE_ID_PREFIX + slugify(geneIdSuffix) + '_' + idKey,
274
+ gene: String(gene.id),
275
+ trigger: Array.isArray(execution?.trigger) ? [...execution.trigger] : [...(gene.signals_match ?? [])].slice(0, 6),
276
+ summary: execution?.summary || `Applied ${gene.id} on scenario ${opts.scenario || 'local skill invocation'}`,
277
+ confidence: Math.max(0, Math.min(1, score)),
278
+ blast_radius: { files, lines },
279
+ outcome: { status, score },
280
+ success_reason: status === 'success' ? (execution?.success_reason || 'Skill workflow completed and all declared validations passed.') : null,
281
+ env_fingerprint: bootstrap.captureEnvFingerprint(),
282
+ source_type: 'skill2gep_hook',
283
+ strategy: Array.isArray(gene.strategy) ? [...gene.strategy] : [],
284
+ content: execution?.content_summary || buildContentSummary(trace, execution?.blast_radius),
285
+ execution_trace: trace.map((t, i) => ({
286
+ step: Number.isInteger(t?.step) ? t.step : i + 1,
287
+ cmd: String(t?.cmd ?? ''),
288
+ exit: Number.isInteger(t?.exit) ? t.exit : null,
289
+ stdout_tail: t?.stdout_tail ? String(t.stdout_tail).slice(0, 300) : '',
290
+ })),
291
+ schema_version: '1.6.0',
292
+ };
293
+ return { ok: true, capsule };
294
+ }
295
+ /**
296
+ * Reverse-distill a parsed SKILL.md + its execution into GEP assets — the PURE core of v1 runOnSkillInvocation
297
+ * (file read / persist / idempotency are B3's wiring). RED LINE: a Capsule is emitted ONLY when the execution is a
298
+ * real, forgery-clear success AND its trace covers every Gene.validation; otherwise Gene-only + a diagnostic. The
299
+ * human-review gate stays the caller's — a skill-distilled Gene is a draft like any other.
300
+ */
301
+ export function reverseDistill(parsed, execution = {}, opts = {}) {
302
+ const { gene, errors } = synthesizeGene(parsed, execution, opts);
303
+ if (!gene)
304
+ return { gene: null, capsule: null, capsuleDiagnostic: null, errors };
305
+ let capsule = null;
306
+ let capsuleDiagnostic = null;
307
+ if (execution?.status) {
308
+ const forgery = detectForgery(execution);
309
+ if (forgery) {
310
+ capsuleDiagnostic = { reason: 'capsule_rejected_forgery', detail: forgery };
311
+ }
312
+ else {
313
+ const r = assembleCapsule(gene, execution, opts.scenario ? { scenario: opts.scenario } : {});
314
+ if (r.ok)
315
+ capsule = r.capsule;
316
+ else
317
+ capsuleDiagnostic = { reason: r.reason, ...(r.missing ? { missing: r.missing } : {}), ...(r.cmd ? { cmd: r.cmd } : {}) };
318
+ }
319
+ }
320
+ return { gene, capsule, capsuleDiagnostic, errors: [] };
321
+ }
@@ -0,0 +1,75 @@
1
+ import { assetstore, events } from '@evomap/evolver-core';
2
+ import { type SkillExecution, type SynthesizeOptions } from './skill2gep.js';
3
+ export interface DiscoveredSkill {
4
+ /** The skill's directory name (`<dir>/skills/<name>/`) — its canonical id, used for dedup. */
5
+ name: string;
6
+ /** Absolute path to the SKILL.md. */
7
+ path: string;
8
+ /** Raw SKILL.md content (read once at discovery; the caller parses it). */
9
+ skillMd: string;
10
+ }
11
+ /**
12
+ * Discover procedural skills under the given roots (B3b-i): each `<root>/skills/<name>/SKILL.md`. Pure enumeration
13
+ * + read — it does NOT distill (that is the deliberate, invocation-bounded wiring of B3b-ii: a host has hundreds of
14
+ * skills on disk, so we never auto-draft a gene from every file just for existing). Absent/unreadable roots and
15
+ * unreadable skills are silently skipped (a daemon must not crash on a missing home dir). Deduped by absolute path;
16
+ * sorted by `name` for a stable scan order.
17
+ */
18
+ export declare function discoverSkills(roots: readonly string[]): DiscoveredSkill[];
19
+ export interface SkillDistillDeps {
20
+ /** Asset store the gene (+ capsule) is written to. */
21
+ store: assetstore.AssetStoreProvider;
22
+ /** Review ledger the gene draft is quarantined in. Default co-located with the store. */
23
+ review?: assetstore.ReviewLedger;
24
+ /** Ingestor for the gene.distilled audit event. */
25
+ ingestor: events.Ingestor;
26
+ }
27
+ export interface SkillDistillResult {
28
+ geneId: string | null;
29
+ /** True when the gene landed in the pool QUARANTINED (awaiting human review). */
30
+ quarantined: boolean;
31
+ capsuleId: string | null;
32
+ /** Why no Capsule was emitted (forgery / coverage), if applicable. */
33
+ capsuleDiagnostic: string | null;
34
+ errors: string[];
35
+ }
36
+ /**
37
+ * Distill a SKILL.md + its real execution into a pooled gene (+ capsule evidence) (B3a). The gene lands
38
+ * QUARANTINED — same human-review gate (A2a/A2b) as every auto-draft, so a skill-distilled gene never enters a
39
+ * live agent's context unapproved. A Capsule is persisted only when reverseDistill's red lines pass (real,
40
+ * forgery-clear success whose trace covers Gene.validation); otherwise the gene is recorded alone with a
41
+ * diagnostic. Idempotent on the gene (intake dedups by signals; quarantine is sticky). NEVER throws on a bad
42
+ * skill — returns errors instead, so a daemon scanning many skills is not broken by one.
43
+ */
44
+ export declare function recordSkillDistillation(skillMd: string, execution: SkillExecution, deps: SkillDistillDeps, opts?: SynthesizeOptions & {
45
+ scenario?: string;
46
+ }): Promise<SkillDistillResult>;
47
+ /**
48
+ * `evolver skill-distill --skill <SKILL.md|dir> [--execution <json|@file>] [--scenario <name>] [--strict]` (B3b-ii).
49
+ *
50
+ * The faithful v2 analog of v1's skill-run hook: the CALLER (a skill-run hook, or an operator) supplies the REAL
51
+ * execution — session logs carry no skill-invocation marker, so an after-the-fact daemon cannot honestly attribute
52
+ * a trace to a skill (verified against on-disk logs). Passing the execution in keeps the Capsule's evidence real.
53
+ * With no `--execution`, only the (quarantined) gene is drafted — no Capsule, which is correct: no evidence, no
54
+ * proof. Output reports the gene id, quarantine state, and either the capsule id or why it was withheld.
55
+ */
56
+ export declare function runSkillDistill(argv: readonly string[], injected?: Partial<SkillDistillDeps>): Promise<number>;
57
+ /**
58
+ * Render a gene back into SKILL.md text (B4) — the reverse of `parseSkillMd`. Sections use headings `parseSkillMd`
59
+ * recognizes, so the round-trip recovers signals / validation / preconditions. `opts.name` preserves an existing
60
+ * skill's identity on update; otherwise a readable name is derived. Pure — the proven-gate + file write live in
61
+ * `runSkillMdUpdate`.
62
+ */
63
+ export declare function geneToSkillMd(gene: Record<string, unknown>, opts?: {
64
+ name?: string;
65
+ }): string;
66
+ /**
67
+ * `evolver skill-md-update --gene <id> --skill <SKILL.md|dir> [--dry-run]` (B4).
68
+ *
69
+ * Write a PROVEN gene back into its SKILL.md — closing the skill2gep loop (SKILL.md → gene → proven → improved
70
+ * SKILL.md). **Proven gate**: refuses unless the gene is human-APPROVED (`review --approve`) AND has ≥1 Capsule
71
+ * (real execution evidence). An unproven/unapproved draft must NEVER overwrite a human's SKILL.md — that is exactly
72
+ * the confident-hallucination the system guards against. On update, the existing SKILL.md's frontmatter `name` is
73
+ * preserved (stable identity); `--dry-run` prints the rendered SKILL.md without writing.
74
+ */
75
+ export declare function runSkillMdUpdate(argv: readonly string[], injected?: Partial<SkillDistillDeps>): Promise<number>;