@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,94 @@
1
+ import { algo, assetstore, events } from '@evomap/evolver-core';
2
+ export type AutoDistillLlmMode = 'off' | 'shadow' | 'enforce';
3
+ export interface AutoDistillLlmRecord {
4
+ shadowed_at?: string | null;
5
+ enforced_at?: string | null;
6
+ enforced_gene_id?: string | null;
7
+ failed_attempts?: number;
8
+ last_attempt_at?: string | null;
9
+ }
10
+ export interface AutoDistillLlmState {
11
+ version: 1;
12
+ p3_llm: {
13
+ by_hash: Record<string, AutoDistillLlmRecord>;
14
+ };
15
+ }
16
+ export type AutoDistillLlmResult = {
17
+ ok: true;
18
+ mode: 'enforce';
19
+ gene: assetstore.AssetRecord;
20
+ dataHash: string;
21
+ stored: boolean;
22
+ } | {
23
+ ok: false;
24
+ mode: AutoDistillLlmMode;
25
+ reason: string;
26
+ dataHash?: string;
27
+ candidate?: algo.GeneCandidate;
28
+ };
29
+ export interface LlmDistillRunnerResult {
30
+ exitCode: number | null;
31
+ stdout: string;
32
+ stderr?: string;
33
+ }
34
+ export type LlmDistillRunner = (prompt: string, ctx: {
35
+ cwd: string;
36
+ timeoutMs: number;
37
+ env: NodeJS.ProcessEnv;
38
+ }) => Promise<LlmDistillRunnerResult>;
39
+ export interface AutoDistillLlmOptions {
40
+ mode?: AutoDistillLlmMode;
41
+ env?: NodeJS.ProcessEnv;
42
+ store: assetstore.AssetStoreProvider;
43
+ review?: assetstore.ReviewLedger;
44
+ ingestor?: events.Ingestor;
45
+ statePath?: string;
46
+ cwd?: string;
47
+ now?: () => number;
48
+ runner?: LlmDistillRunner;
49
+ validationTimeoutMs?: number;
50
+ minCapsules?: number;
51
+ maxCapsules?: number;
52
+ }
53
+ export interface AutoDistillLlmWiring {
54
+ enabled: boolean;
55
+ mode: AutoDistillLlmMode;
56
+ reason?: 'off';
57
+ tick: () => Promise<AutoDistillLlmResult>;
58
+ }
59
+ export declare function autoDistillLlmStatePath(home?: string): string;
60
+ export declare function p3Decide(mode: Exclude<AutoDistillLlmMode, 'off'>, rec: AutoDistillLlmRecord | null | undefined, nowMs: number, opts?: {
61
+ cooldownMs?: number;
62
+ maxAttempts?: number;
63
+ }): 'spawn' | 'enforced_idempotent_skip' | 'shadow_idempotent_skip' | 'failed_exhausted' | 'p3_cooldown';
64
+ export declare function parseDistillOutput(stdout: string): unknown | null;
65
+ export declare function asGeneCandidate(value: unknown): algo.GeneCandidate | null;
66
+ export declare function jaccardDuplicate(candidate: algo.GeneCandidate, existing: readonly algo.ExistingGeneRef[], threshold?: number): string | null;
67
+ export declare function normalizeValidation(candidate: algo.GeneCandidate, cwd?: string): {
68
+ candidate: algo.GeneCandidate;
69
+ dropped: string[];
70
+ injected: boolean;
71
+ };
72
+ export declare function runClaudeDistill(prompt: string, ctx: {
73
+ cwd: string;
74
+ timeoutMs: number;
75
+ env: NodeJS.ProcessEnv;
76
+ }): Promise<LlmDistillRunnerResult>;
77
+ /** Build the read-only `codex exec` argv for a distill run (pure, testable). SAFETY INVARIANT: `--sandbox read-only`
78
+ * is ALWAYS present — a distiller only reads the transcript (carried in the prompt) and emits a gene; it must never
79
+ * edit files. `--skip-git-repo-check`: the distill cwd may not be a git repo (codex exec otherwise refuses).
80
+ * `--output-last-message <file>`: capture ONLY the final assistant message (the gene JSON), avoiding codex's stdout
81
+ * preamble/token-count noise. Prompt arrives via stdin (the trailing `-`). Verified live against codex-cli 0.137.0. */
82
+ export declare function codexDistillArgs(cwd: string, lastMessageFile: string, model?: string): string[];
83
+ /** Distill a prompt with `codex exec` (read-only). Reads the clean final message from --output-last-message so
84
+ * parseDistillOutput sees a bare gene JSON; falls back to raw stdout (pickGeneObject scans it) if the file is absent.
85
+ * Windows: codex is a `.cmd` npm shim, so route through resolveSpawnCommand (shell-free). */
86
+ export declare function runCodexDistill(prompt: string, ctx: {
87
+ cwd: string;
88
+ timeoutMs: number;
89
+ env: NodeJS.ProcessEnv;
90
+ }): Promise<LlmDistillRunnerResult>;
91
+ /** Pick the distill runner from EVOLVE_DISTILL_PROVIDER. Unknown/unset → claude (cursor is never a distill provider). */
92
+ export declare function resolveDistillRunner(env: NodeJS.ProcessEnv): LlmDistillRunner;
93
+ export declare function autoDistillLlm(options: AutoDistillLlmOptions): Promise<AutoDistillLlmResult>;
94
+ export declare function resolveAutoDistillLlm(env: NodeJS.ProcessEnv, opts: Omit<AutoDistillLlmOptions, 'env' | 'mode'>): AutoDistillLlmWiring;
@@ -0,0 +1,510 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { existsSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
5
+ import { algo, assetstore, events, exec, hub, verify } from '@evomap/evolver-core';
6
+ const DEFAULT_MIN_CAPSULES = 10;
7
+ const DEFAULT_MAX_CAPSULES = 24;
8
+ const DEFAULT_MIN_SUCCESS_SCORE = 0.7;
9
+ const DEFAULT_TIMEOUT_MS = 180_000;
10
+ const DEFAULT_VALIDATION_TIMEOUT_MS = 20_000;
11
+ const DEFAULT_COOLDOWN_MS = 1_800_000;
12
+ const DEFAULT_MAX_ATTEMPTS = 3;
13
+ const DEFAULT_HASH_CAP = 32;
14
+ const DEFAULT_DUP_JACCARD = 0.8;
15
+ const HEAVY_VALIDATION_RE = /\b(validate-suite|jest|mocha)\b|(?:^|\s)--test\b|\b(?:pnpm|npm)\s+(?:test|vitest)\b|test\/[^ ]*\.test\.(?:c|m)?js/i;
16
+ export function autoDistillLlmStatePath(home = events.evomapHome()) {
17
+ return join(home, 'evolution', 'auto-distill-llm-state.json');
18
+ }
19
+ function envInt(env, name, fallback) {
20
+ const n = Number.parseInt(String(env[name] ?? ''), 10);
21
+ return Number.isFinite(n) && n > 0 ? n : fallback;
22
+ }
23
+ function envFloat(env, name, fallback) {
24
+ const n = Number.parseFloat(String(env[name] ?? ''));
25
+ return Number.isFinite(n) && n > 0 ? n : fallback;
26
+ }
27
+ function resolveMode(env, explicit) {
28
+ const raw = String(explicit ?? env['EVOLVER_AUTO_DISTILL_LLM'] ?? 'off').trim().toLowerCase();
29
+ return raw === 'shadow' || raw === 'enforce' ? raw : 'off';
30
+ }
31
+ function emptyState() {
32
+ return { version: 1, p3_llm: { by_hash: {} } };
33
+ }
34
+ function readState(path) {
35
+ if (!existsSync(path))
36
+ return emptyState();
37
+ const parsed = JSON.parse(readFileSync(path, 'utf8'));
38
+ const byHash = parsed.p3_llm && typeof parsed.p3_llm === 'object' && parsed.p3_llm.by_hash && typeof parsed.p3_llm.by_hash === 'object'
39
+ ? parsed.p3_llm.by_hash
40
+ : {};
41
+ return { version: 1, p3_llm: { by_hash: byHash } };
42
+ }
43
+ function writeState(path, state) {
44
+ mkdirSync(dirname(path), { recursive: true });
45
+ const tmp = `${path}.${process.pid}.${Date.now()}.tmp`;
46
+ writeFileSync(tmp, `${JSON.stringify(state, null, 2)}\n`);
47
+ renameSync(tmp, path);
48
+ }
49
+ function capByHash(byHash, cap) {
50
+ const keys = Object.keys(byHash);
51
+ if (keys.length <= cap)
52
+ return byHash;
53
+ const age = (key) => {
54
+ const rec = byHash[key] ?? {};
55
+ return Math.max(Date.parse(rec.shadowed_at ?? '') || 0, Date.parse(rec.enforced_at ?? '') || 0, Date.parse(rec.last_attempt_at ?? '') || 0);
56
+ };
57
+ const evictionOrder = [
58
+ ...keys.filter((key) => !byHash[key]?.enforced_at).sort((a, b) => age(a) - age(b)),
59
+ ...keys.filter((key) => byHash[key]?.enforced_at).sort((a, b) => age(a) - age(b)),
60
+ ];
61
+ for (const key of evictionOrder) {
62
+ if (Object.keys(byHash).length <= cap)
63
+ break;
64
+ delete byHash[key];
65
+ }
66
+ return byHash;
67
+ }
68
+ function patchState(path, dataHash, patch, cap) {
69
+ try {
70
+ const state = readState(path);
71
+ const current = state.p3_llm.by_hash[dataHash] ?? { shadowed_at: null, enforced_at: null, enforced_gene_id: null, failed_attempts: 0, last_attempt_at: null };
72
+ const next = { ...current, ...patch };
73
+ if (patch.failed_attempts_inc)
74
+ next.failed_attempts = (current.failed_attempts ?? 0) + 1;
75
+ delete next.failed_attempts_inc;
76
+ state.p3_llm.by_hash[dataHash] = next;
77
+ state.p3_llm.by_hash = capByHash(state.p3_llm.by_hash, cap);
78
+ writeState(path, state);
79
+ return true;
80
+ }
81
+ catch {
82
+ return false;
83
+ }
84
+ }
85
+ export function p3Decide(mode, rec, nowMs, opts = {}) {
86
+ if (rec?.enforced_at)
87
+ return 'enforced_idempotent_skip';
88
+ if (mode === 'shadow' && rec?.shadowed_at)
89
+ return 'shadow_idempotent_skip';
90
+ if ((rec?.failed_attempts ?? 0) >= (opts.maxAttempts ?? DEFAULT_MAX_ATTEMPTS))
91
+ return 'failed_exhausted';
92
+ const lastAttempt = Date.parse(rec?.last_attempt_at ?? '');
93
+ if ((rec?.failed_attempts ?? 0) > 0 && lastAttempt > 0 && nowMs - lastAttempt < (opts.cooldownMs ?? DEFAULT_COOLDOWN_MS))
94
+ return 'p3_cooldown';
95
+ return 'spawn';
96
+ }
97
+ function normalizedSignals(record) {
98
+ const raw = record['signals_match'];
99
+ return Array.isArray(raw) ? raw.map(String).filter(Boolean) : [];
100
+ }
101
+ function existingGeneRefs(records) {
102
+ return records.map((record) => ({
103
+ id: typeof record['id'] === 'string' ? record['id'] : undefined,
104
+ signals_match: normalizedSignals(record),
105
+ }));
106
+ }
107
+ function isSuccessCapsule(record, minSuccessScore) {
108
+ const outcome = record['outcome'];
109
+ if (!outcome || typeof outcome !== 'object' || Array.isArray(outcome))
110
+ return false;
111
+ const typedOutcome = outcome;
112
+ if (typedOutcome.status !== 'success')
113
+ return false;
114
+ if (typedOutcome.score === undefined || typedOutcome.score === null)
115
+ return true;
116
+ const score = typeof typedOutcome.score === 'number' ? typedOutcome.score : Number.parseFloat(String(typedOutcome.score));
117
+ return Number.isFinite(score) && score >= minSuccessScore;
118
+ }
119
+ function capsuleDigestView(record) {
120
+ return {
121
+ id: record['id'],
122
+ asset_id: record.asset_id,
123
+ gene: record['gene'],
124
+ trigger: record['trigger'],
125
+ summary: record['summary'],
126
+ outcome: record['outcome'],
127
+ };
128
+ }
129
+ function hashCapsules(capsules) {
130
+ const stable = capsules.map(capsuleDigestView).sort((a, b) => String(a['asset_id'] ?? a['id']).localeCompare(String(b['asset_id'] ?? b['id'])));
131
+ return createHash('sha256').update(JSON.stringify(stable)).digest('hex');
132
+ }
133
+ async function collectDistillInput(store, maxCapsules, minSuccessScore) {
134
+ const [capsules, existingGenes] = await Promise.all([store.list('Capsule', 10_000), store.list('Gene', 10_000)]);
135
+ const successCapsules = capsules.filter((record) => isSuccessCapsule(record, minSuccessScore)).slice(-maxCapsules);
136
+ return { dataHash: hashCapsules(successCapsules), successCapsules, existingGenes };
137
+ }
138
+ function buildDistillPrompt(input) {
139
+ const capsules = hub.redactDeep(input.successCapsules.map(capsuleDigestView));
140
+ const genes = hub.redactDeep(input.existingGenes.map((gene) => ({
141
+ id: gene['id'],
142
+ category: gene['category'],
143
+ signals_match: gene['signals_match'],
144
+ summary: gene['summary'],
145
+ })));
146
+ return [
147
+ 'You are synthesizing one high-quality EvoMap Gene from recurring successful Capsules.',
148
+ 'Return only JSON. Do not use markdown. Do not include commentary.',
149
+ '',
150
+ 'Rules:',
151
+ '- Produce a single Gene object.',
152
+ '- Prefer generic reusable signals, not one-off file names or secrets.',
153
+ '- Strategy steps must be concrete, defensive, and reusable.',
154
+ '- Validation must be light. Prefer ["node --version"]. Do not use test suites, node --test, jest, mocha, or node -e.',
155
+ '- Avoid duplicating existing genes.',
156
+ '',
157
+ 'Required JSON shape:',
158
+ '{"type":"Gene","id":"gene_distilled_<descriptive-kebab-name>","summary":"...","category":"repair|optimize|innovate|explore","signals_match":["signal"],"preconditions":["condition"],"strategy":["step"],"constraints":{"max_files":3,"forbidden_paths":[".git","node_modules"]},"validation":["node --version"]}',
159
+ '',
160
+ `DATA_HASH: ${input.dataHash}`,
161
+ 'SUCCESS_CAPSULES:',
162
+ JSON.stringify(capsules, null, 2),
163
+ '',
164
+ 'EXISTING_GENES:',
165
+ JSON.stringify(genes, null, 2),
166
+ ].join('\n');
167
+ }
168
+ function isRecord(value) {
169
+ return Boolean(value && typeof value === 'object' && !Array.isArray(value));
170
+ }
171
+ function findJsonObjects(text) {
172
+ const s = String(text ?? '');
173
+ const out = [];
174
+ let start = s.indexOf('{');
175
+ while (start >= 0) {
176
+ let depth = 0;
177
+ let inString = false;
178
+ let escaped = false;
179
+ let advanced = -1;
180
+ for (let i = start; i < s.length; i += 1) {
181
+ const ch = s[i];
182
+ if (inString) {
183
+ if (escaped) {
184
+ escaped = false;
185
+ continue;
186
+ }
187
+ if (ch === '\\') {
188
+ escaped = true;
189
+ continue;
190
+ }
191
+ if (ch === '"')
192
+ inString = false;
193
+ continue;
194
+ }
195
+ if (ch === '"') {
196
+ inString = true;
197
+ continue;
198
+ }
199
+ if (ch === '{')
200
+ depth += 1;
201
+ if (ch === '}') {
202
+ depth -= 1;
203
+ if (depth === 0) {
204
+ try {
205
+ out.push(JSON.parse(s.slice(start, i + 1)));
206
+ advanced = i + 1;
207
+ }
208
+ catch { /* not valid JSON; resume scanning from the next opening brace */ }
209
+ break;
210
+ }
211
+ }
212
+ }
213
+ start = s.indexOf('{', advanced >= 0 ? advanced : start + 1);
214
+ }
215
+ return out;
216
+ }
217
+ // Prefer an explicit Gene-shaped object: an LLM may emit reasoning/wrapper objects BEFORE the gene, and
218
+ // taking the first parseable object (the prior behavior) would lock onto the wrong one and burn an attempt.
219
+ // Falls back to the first object so a gene that omits `type` still parses (asGeneCandidate allows that). (V1 parity.)
220
+ function pickGeneObject(text) {
221
+ const objects = findJsonObjects(text);
222
+ const gene = objects.find((o) => isRecord(o) && o['type'] === 'Gene');
223
+ if (gene)
224
+ return gene;
225
+ return objects.length > 0 ? (objects[0] ?? null) : null;
226
+ }
227
+ export function parseDistillOutput(stdout) {
228
+ const lines = String(stdout ?? '').split('\n').map((line) => line.trim()).filter(Boolean);
229
+ const last = lines.at(-1);
230
+ if (last) {
231
+ try {
232
+ const parsed = JSON.parse(last);
233
+ if (isRecord(parsed) && 'is_error' in parsed) {
234
+ if (parsed['is_error'])
235
+ return null;
236
+ const result = parsed['result'];
237
+ return typeof result === 'string' ? pickGeneObject(result) : result;
238
+ }
239
+ return parsed;
240
+ }
241
+ catch {
242
+ return pickGeneObject(stdout);
243
+ }
244
+ }
245
+ return null;
246
+ }
247
+ export function asGeneCandidate(value) {
248
+ if (!isRecord(value))
249
+ return null;
250
+ if (typeof value['type'] === 'string' && value['type'] !== 'Gene')
251
+ return null;
252
+ return {
253
+ ...(typeof value['id'] === 'string' ? { id: value['id'] } : {}),
254
+ ...(typeof value['category'] === 'string' ? { category: value['category'] } : {}),
255
+ signals_match: Array.isArray(value['signals_match']) ? value['signals_match'].map(String) : [],
256
+ strategy: Array.isArray(value['strategy']) ? value['strategy'].map(String) : [],
257
+ ...(typeof value['summary'] === 'string' ? { summary: value['summary'] } : {}),
258
+ ...(Array.isArray(value['preconditions']) ? { preconditions: value['preconditions'].map(String) } : {}),
259
+ ...(isRecord(value['constraints']) ? {
260
+ constraints: {
261
+ ...(typeof value['constraints']['max_files'] === 'number' ? { max_files: value['constraints']['max_files'] } : {}),
262
+ // Only carry a NON-EMPTY forbidden_paths through. intakeGene defaults the field with `?? DEFAULT`,
263
+ // and nullish-coalescing does NOT replace an empty array — so an LLM-supplied `[]` would drop the
264
+ // default `.git`/`node_modules` guard on an autonomously-stored gene. Omit it so the default kicks in. (V1 parity.)
265
+ ...(Array.isArray(value['constraints']['forbidden_paths']) && value['constraints']['forbidden_paths'].length > 0
266
+ ? { forbidden_paths: value['constraints']['forbidden_paths'].map(String) } : {}),
267
+ },
268
+ } : {}),
269
+ ...(Array.isArray(value['validation']) ? { validation: value['validation'].map(String) } : {}),
270
+ };
271
+ }
272
+ export function jaccardDuplicate(candidate, existing, threshold = DEFAULT_DUP_JACCARD) {
273
+ const a = new Set((candidate.signals_match ?? []).map((s) => String(s).toLowerCase()).filter(Boolean));
274
+ if (a.size === 0)
275
+ return null;
276
+ for (const eg of existing) {
277
+ if (eg.id && eg.id === candidate.id)
278
+ continue;
279
+ const b = new Set((eg.signals_match ?? []).map((s) => String(s).toLowerCase()).filter(Boolean));
280
+ if (b.size === 0)
281
+ continue;
282
+ const inter = [...a].filter((s) => b.has(s)).length;
283
+ const union = new Set([...a, ...b]).size;
284
+ if (union > 0 && inter / union >= threshold)
285
+ return eg.id ?? '?';
286
+ }
287
+ return null;
288
+ }
289
+ function isLightValidationCommand(cmd, cwd) {
290
+ const trimmed = cmd.trim();
291
+ if (!trimmed || HEAVY_VALIDATION_RE.test(trimmed) || verify.SHELL_METACHARS.test(trimmed))
292
+ return false;
293
+ const [head = '', ...args] = trimmed.split(/\s+/);
294
+ if (!verify.isNodeExecutable(head))
295
+ return false;
296
+ if (verify.nodeFlagViolation(head, args))
297
+ return false;
298
+ const script = verify.validationScriptPath(trimmed);
299
+ if (!script)
300
+ return args.length === 1 && args[0] === '--version';
301
+ if (isAbsolute(script))
302
+ return false;
303
+ const root = resolve(cwd);
304
+ const resolvedScript = resolve(root, script);
305
+ if (!existsSync(resolvedScript))
306
+ return false;
307
+ const relativeScript = relative(realpathSync(root), realpathSync(resolvedScript));
308
+ if (!relativeScript || relativeScript === '..' || relativeScript.startsWith(`..${sep}`) || isAbsolute(relativeScript))
309
+ return false;
310
+ return true;
311
+ }
312
+ export function normalizeValidation(candidate, cwd = process.cwd()) {
313
+ const original = candidate.validation?.map(String) ?? [];
314
+ const dropped = [];
315
+ const kept = original.filter((cmd) => {
316
+ const keep = isLightValidationCommand(cmd, cwd);
317
+ if (!keep)
318
+ dropped.push(cmd);
319
+ return keep;
320
+ });
321
+ const validation = kept.length > 0 ? kept : ['node --version'];
322
+ return { candidate: { ...candidate, validation }, dropped, injected: kept.length === 0 };
323
+ }
324
+ export async function runClaudeDistill(prompt, ctx) {
325
+ const args = [
326
+ '-p', '--output-format', 'json',
327
+ '--permission-mode', 'plan',
328
+ '--model', ctx.env['EVOLVE_DISTILL_MODEL'] ?? 'sonnet',
329
+ '--session-id', randomUUID(),
330
+ '--max-turns', String(envInt(ctx.env, 'EVOLVE_DISTILL_MAX_TURNS', 3)),
331
+ ];
332
+ // Per-vendor auth scoping comes from the execution runner registry's single source of truth (claude → ANTHROPIC_/
333
+ // CLAUDE_), so a distiller and an executor of the same vendor never diverge and one vendor's key never reaches
334
+ // another agent. Value is byte-identical to the previous hardcoded ['ANTHROPIC_','CLAUDE_'].
335
+ const env = exec.scrubAgentEnv(ctx.env, { allowPrefixes: exec.getRunnerSpec('claude').envAllow.prefixes });
336
+ try {
337
+ const r = await exec.spawnCapture('claude', args, { cwd: ctx.cwd, timeoutMs: ctx.timeoutMs, input: prompt, env });
338
+ return { exitCode: r.code, stdout: r.stdout, stderr: r.stderr };
339
+ }
340
+ catch (e) {
341
+ return { exitCode: null, stdout: '', stderr: e instanceof Error ? e.message : String(e) };
342
+ }
343
+ }
344
+ /** Build the read-only `codex exec` argv for a distill run (pure, testable). SAFETY INVARIANT: `--sandbox read-only`
345
+ * is ALWAYS present — a distiller only reads the transcript (carried in the prompt) and emits a gene; it must never
346
+ * edit files. `--skip-git-repo-check`: the distill cwd may not be a git repo (codex exec otherwise refuses).
347
+ * `--output-last-message <file>`: capture ONLY the final assistant message (the gene JSON), avoiding codex's stdout
348
+ * preamble/token-count noise. Prompt arrives via stdin (the trailing `-`). Verified live against codex-cli 0.137.0. */
349
+ export function codexDistillArgs(cwd, lastMessageFile, model) {
350
+ const args = ['exec', '--sandbox', 'read-only', '--skip-git-repo-check', '--cd', cwd, '--output-last-message', lastMessageFile];
351
+ if (model)
352
+ args.push('--model', model);
353
+ args.push('-');
354
+ return args;
355
+ }
356
+ /** Distill a prompt with `codex exec` (read-only). Reads the clean final message from --output-last-message so
357
+ * parseDistillOutput sees a bare gene JSON; falls back to raw stdout (pickGeneObject scans it) if the file is absent.
358
+ * Windows: codex is a `.cmd` npm shim, so route through resolveSpawnCommand (shell-free). */
359
+ export async function runCodexDistill(prompt, ctx) {
360
+ const env = exec.scrubAgentEnv(ctx.env, { allowPrefixes: exec.getRunnerSpec('codex').envAllow.prefixes });
361
+ const lastMessageFile = join(tmpdir(), `evolver-codex-distill-${randomUUID()}.txt`);
362
+ const args = codexDistillArgs(ctx.cwd, lastMessageFile, ctx.env['EVOLVE_DISTILL_MODEL']);
363
+ const resolved = exec.resolveSpawnCommand('codex', args, env);
364
+ try {
365
+ const r = await exec.spawnCapture(resolved.cmd, resolved.args, { cwd: ctx.cwd, timeoutMs: ctx.timeoutMs, input: prompt, env });
366
+ let stdout = r.stdout;
367
+ try {
368
+ const last = readFileSync(lastMessageFile, 'utf8').trim();
369
+ if (last)
370
+ stdout = last;
371
+ }
372
+ catch { /* file absent (codex failed early) → keep raw stdout for pickGeneObject */ }
373
+ return { exitCode: r.code, stdout, stderr: r.stderr };
374
+ }
375
+ catch (e) {
376
+ return { exitCode: null, stdout: '', stderr: e instanceof Error ? e.message : String(e) };
377
+ }
378
+ finally {
379
+ try {
380
+ rmSync(lastMessageFile, { force: true });
381
+ }
382
+ catch { /* best-effort temp cleanup */ }
383
+ }
384
+ }
385
+ const DISTILL_RUNNERS = { claude: runClaudeDistill, codex: runCodexDistill };
386
+ /** Pick the distill runner from EVOLVE_DISTILL_PROVIDER. Unknown/unset → claude (cursor is never a distill provider). */
387
+ export function resolveDistillRunner(env) {
388
+ const raw = String(env['EVOLVE_DISTILL_PROVIDER'] ?? '').trim().toLowerCase();
389
+ const provider = Object.prototype.hasOwnProperty.call(DISTILL_RUNNERS, raw) ? raw : 'claude';
390
+ return DISTILL_RUNNERS[provider];
391
+ }
392
+ async function emitDistilledEventIfAbsent(ingestor, gene, dataHash, capsuleCount) {
393
+ if (!ingestor)
394
+ return;
395
+ const assetId = gene.asset_id;
396
+ const exists = ingestor.readAll().some((event) => {
397
+ const payload = event.payload;
398
+ return event.type === 'gene.distilled' && payload?.['assetId'] === assetId && payload?.['source'] === 'auto-distill-llm';
399
+ });
400
+ if (exists)
401
+ return;
402
+ await ingestor.ingest({
403
+ type: 'gene.distilled',
404
+ payload: {
405
+ geneId: gene['id'],
406
+ assetId,
407
+ source: 'auto-distill-llm',
408
+ dataHash,
409
+ capsuleCount,
410
+ },
411
+ human: { title: `LLM auto-distilled gene ${String(gene['id'] ?? assetId)}`, severity: 'info' },
412
+ actor: { kind: 'machine', id: 'auto-distill-llm' },
413
+ });
414
+ }
415
+ export async function autoDistillLlm(options) {
416
+ const env = options.env ?? process.env;
417
+ const mode = resolveMode(env, options.mode);
418
+ if (mode === 'off')
419
+ return { ok: false, mode, reason: 'disabled' };
420
+ const cwd = options.cwd ?? process.cwd();
421
+ const now = options.now?.() ?? Date.now();
422
+ const statePath = options.statePath ?? autoDistillLlmStatePath();
423
+ const maxCapsules = options.maxCapsules ?? envInt(env, 'EVOLVER_AUTO_DISTILL_LLM_MAX_CAPSULES', DEFAULT_MAX_CAPSULES);
424
+ const minCapsules = options.minCapsules ?? envInt(env, 'EVOLVER_AUTO_DISTILL_LLM_MIN_CAPSULES', DEFAULT_MIN_CAPSULES);
425
+ const minSuccessScore = envFloat(env, 'EVOLVER_AUTO_DISTILL_LLM_MIN_SUCCESS_SCORE', DEFAULT_MIN_SUCCESS_SCORE);
426
+ const input = await collectDistillInput(options.store, maxCapsules, minSuccessScore);
427
+ if (input.successCapsules.length < minCapsules)
428
+ return { ok: false, mode, reason: 'insufficient_data', dataHash: input.dataHash };
429
+ let state;
430
+ try {
431
+ state = readState(statePath);
432
+ }
433
+ catch {
434
+ return { ok: false, mode, reason: 'state_read_failed', dataHash: input.dataHash };
435
+ }
436
+ const cooldownMs = envInt(env, 'EVOLVER_AUTO_DISTILL_LLM_COOLDOWN_MS', DEFAULT_COOLDOWN_MS);
437
+ const maxAttempts = envInt(env, 'EVOLVER_AUTO_DISTILL_LLM_MAX_ATTEMPTS', DEFAULT_MAX_ATTEMPTS);
438
+ const decision = p3Decide(mode, state.p3_llm.by_hash[input.dataHash], now, { cooldownMs, maxAttempts });
439
+ if (decision !== 'spawn')
440
+ return { ok: false, mode, reason: decision, dataHash: input.dataHash };
441
+ const hashCap = envInt(env, 'EVOLVER_AUTO_DISTILL_LLM_HASH_CAP', DEFAULT_HASH_CAP);
442
+ if (!patchState(statePath, input.dataHash, { last_attempt_at: new Date(now).toISOString() }, hashCap)) {
443
+ return { ok: false, mode, reason: 'state_write_failed', dataHash: input.dataHash };
444
+ }
445
+ const runner = options.runner ?? resolveDistillRunner(env);
446
+ const timeoutMs = envInt(env, 'EVOLVE_DISTILL_TIMEOUT_MS', DEFAULT_TIMEOUT_MS);
447
+ const prompt = buildDistillPrompt(input);
448
+ // Egress-floor parity: buildDistillPrompt already pattern-redacts via hub.redactDeep, but the Hub publish path
449
+ // additionally runs a REVERSE env-value scan (hub.detectEnvValueLeaks) that flags any process-env value
450
+ // appearing verbatim in the payload — catching custom-format secrets no pattern matches. The prompt is an
451
+ // off-box egress (stdin to a spawned `claude`), so hold it to the same floor the repo enforces on publish: if a
452
+ // daemon env secret leaked into a capsule, fail CLOSED and never send it. This is a data-hygiene block, not a
453
+ // deterministic claude failure, so — like a transient exit below — it does NOT bump failed_attempts.
454
+ if (hub.detectEnvValueLeaks(prompt, env).length > 0) {
455
+ return { ok: false, mode, reason: 'prompt_env_leak_blocked', dataHash: input.dataHash };
456
+ }
457
+ const llm = await runner(prompt, { cwd, timeoutMs, env });
458
+ if (llm.exitCode !== 0) {
459
+ // V1 parity: a PROCESS-level claude failure — spawn error/ENOENT or timeout→SIGKILL (exitCode === null), OR a
460
+ // non-null nonzero exit code — is TRANSIENT and must NOT count toward failed_attempts. Only a usable-but-bad
461
+ // RESULT (is_error / no-gene / validation / near-duplicate / light-validation, below) is deterministic and
462
+ // bumps toward failed_exhausted. V1 buckets a raw nonzero exit with spawn-error/timeout and keeps retrying it;
463
+ // bumping here would let an environmental hiccup (e.g. a rate-limit surfacing as exit 1 rather than null)
464
+ // permanently exhaust this data hash after MAX_ATTEMPTS — the exact silent stall this exemption prevents.
465
+ return { ok: false, mode, reason: llm.exitCode === null ? 'claude_spawn_error' : 'claude_nonzero_exit', dataHash: input.dataHash };
466
+ }
467
+ const raw = parseDistillOutput(llm.stdout);
468
+ const candidate0 = asGeneCandidate(raw);
469
+ if (!candidate0) {
470
+ patchState(statePath, input.dataHash, { failed_attempts_inc: true }, hashCap);
471
+ return { ok: false, mode, reason: 'no_gene_in_response', dataHash: input.dataHash };
472
+ }
473
+ const existing = existingGeneRefs(input.existingGenes);
474
+ const normalized = normalizeValidation(candidate0, cwd).candidate;
475
+ const duplicate = jaccardDuplicate(normalized, existing, envFloat(env, 'EVOLVER_AUTO_DISTILL_LLM_DUP_JACCARD', DEFAULT_DUP_JACCARD));
476
+ if (duplicate) {
477
+ patchState(statePath, input.dataHash, { failed_attempts_inc: true }, hashCap);
478
+ return { ok: false, mode, reason: 'near_duplicate', dataHash: input.dataHash };
479
+ }
480
+ const intake = algo.intakeGene(normalized, existing);
481
+ if (!intake.ok || !intake.gene) {
482
+ patchState(statePath, input.dataHash, { failed_attempts_inc: true }, hashCap);
483
+ return { ok: false, mode, reason: 'validation_failed', dataHash: input.dataHash };
484
+ }
485
+ const validation = await verify.runSandboxedValidation(intake.gene.validation, cwd, {
486
+ timeoutMs: options.validationTimeoutMs ?? envInt(env, 'EVOLVE_DISTILL_VALIDATION_TIMEOUT_MS', DEFAULT_VALIDATION_TIMEOUT_MS),
487
+ });
488
+ if (!validation.passed) {
489
+ patchState(statePath, input.dataHash, { failed_attempts_inc: true }, hashCap);
490
+ return { ok: false, mode, reason: 'light_validation_failed', dataHash: input.dataHash };
491
+ }
492
+ if (mode === 'shadow') {
493
+ patchState(statePath, input.dataHash, { shadowed_at: new Date(now).toISOString() }, hashCap);
494
+ return { ok: false, mode, reason: 'shadow_logged', dataHash: input.dataHash, candidate: normalized };
495
+ }
496
+ const gene = intake.gene;
497
+ await emitDistilledEventIfAbsent(options.ingestor, gene, input.dataHash, input.successCapsules.length);
498
+ options.review?.quarantineIfAbsent(gene.asset_id, 'LLM auto-distilled — review before use');
499
+ const put = await options.store.put(gene);
500
+ const stateWritten = patchState(statePath, input.dataHash, { enforced_at: new Date(now).toISOString(), enforced_gene_id: String(gene['id'] ?? '') }, hashCap);
501
+ if (!stateWritten)
502
+ return { ok: false, mode, reason: 'state_write_failed_after_store', dataHash: input.dataHash };
503
+ return { ok: true, mode, gene, dataHash: input.dataHash, stored: put.stored };
504
+ }
505
+ export function resolveAutoDistillLlm(env, opts) {
506
+ const mode = resolveMode(env);
507
+ if (mode === 'off')
508
+ return { enabled: false, mode, reason: 'off', tick: async () => ({ ok: false, mode, reason: 'disabled' }) };
509
+ return { enabled: true, mode, tick: () => autoDistillLlm({ ...opts, env, mode }) };
510
+ }