@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,342 @@
1
+ // skill2gep B3a/B3b — the wiring that turns a SKILL.md + its execution into a POOLED (quarantined) gene + capsule.
2
+ // skill2gep.ts stays pure (parse / synthesize / capsule contracts); this layer owns the side effects: skill-dir
3
+ // discovery (B3b-i), gene intake (structural + dedup + asset_id via algo.intakeGene), the human-review gate
4
+ // (ReviewLedger.quarantineIfAbsent — a skill-distilled gene is a draft like any other, withheld until approved),
5
+ // the gene.distilled audit event, and persisting the capsule evidence. The session→execution-trace extraction that
6
+ // turns a discovered skill into a Capsule-bearing distillation is B3b-ii (a separate slice).
7
+ import { readdirSync, readFileSync, statSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';
8
+ import { join, resolve, dirname } from 'node:path';
9
+ import { assetstore, algo, events } from '@evomap/evolver-core';
10
+ import { parseSkillMd, reverseDistill } from './skill2gep.js';
11
+ import { reviewLedgerForStore } from './reviewFilter.js';
12
+ /**
13
+ * Discover procedural skills under the given roots (B3b-i): each `<root>/skills/<name>/SKILL.md`. Pure enumeration
14
+ * + read — it does NOT distill (that is the deliberate, invocation-bounded wiring of B3b-ii: a host has hundreds of
15
+ * skills on disk, so we never auto-draft a gene from every file just for existing). Absent/unreadable roots and
16
+ * unreadable skills are silently skipped (a daemon must not crash on a missing home dir). Deduped by absolute path;
17
+ * sorted by `name` for a stable scan order.
18
+ */
19
+ export function discoverSkills(roots) {
20
+ const byPath = new Map();
21
+ for (const root of roots) {
22
+ const skillsRoot = join(resolve(root), 'skills');
23
+ let entries;
24
+ try {
25
+ entries = readdirSync(skillsRoot);
26
+ }
27
+ catch {
28
+ continue;
29
+ } // no skills/ under this root → skip
30
+ for (const name of entries) {
31
+ const mdPath = join(skillsRoot, name, 'SKILL.md');
32
+ try {
33
+ if (!statSync(mdPath).isFile())
34
+ continue; // a `skills/<name>` that is not a skill dir → skip
35
+ if (byPath.has(mdPath))
36
+ continue;
37
+ byPath.set(mdPath, { name, path: mdPath, skillMd: readFileSync(mdPath, 'utf8') });
38
+ }
39
+ catch { /* not a dir / no SKILL.md / unreadable → skip */ }
40
+ }
41
+ }
42
+ return [...byPath.values()].sort((a, b) => a.name.localeCompare(b.name));
43
+ }
44
+ /**
45
+ * Distill a SKILL.md + its real execution into a pooled gene (+ capsule evidence) (B3a). The gene lands
46
+ * QUARANTINED — same human-review gate (A2a/A2b) as every auto-draft, so a skill-distilled gene never enters a
47
+ * live agent's context unapproved. A Capsule is persisted only when reverseDistill's red lines pass (real,
48
+ * forgery-clear success whose trace covers Gene.validation); otherwise the gene is recorded alone with a
49
+ * diagnostic. Idempotent on the gene (intake dedups by signals; quarantine is sticky). NEVER throws on a bad
50
+ * skill — returns errors instead, so a daemon scanning many skills is not broken by one.
51
+ */
52
+ export async function recordSkillDistillation(skillMd, execution, deps, opts = {}) {
53
+ const review = deps.review ?? reviewLedgerForStore(deps.store);
54
+ const parsed = parseSkillMd(skillMd);
55
+ const { gene, capsule, capsuleDiagnostic } = reverseDistill(parsed, execution, opts);
56
+ const diag = capsuleDiagnostic ? (capsuleDiagnostic.detail ?? capsuleDiagnostic.reason) : null;
57
+ if (!gene)
58
+ return { geneId: null, quarantined: false, capsuleId: null, capsuleDiagnostic: diag, errors: ['gene synthesis refused (strict mode or empty)'] };
59
+ const existing = (await deps.store.list('Gene', 1000)).map((g) => ({
60
+ id: typeof g['id'] === 'string' ? String(g['id']) : undefined,
61
+ signals_match: Array.isArray(g['signals_match']) ? g['signals_match'] : [],
62
+ }));
63
+ const r = algo.intakeGene(gene, existing);
64
+ if (!r.ok || !r.gene)
65
+ return { geneId: null, quarantined: false, capsuleId: null, capsuleDiagnostic: diag, errors: r.errors };
66
+ const assetId = String(r.gene.asset_id);
67
+ const geneId = typeof r.gene.id === 'string' ? r.gene.id : assetId;
68
+ try {
69
+ // Failure-safe order (Bugbot #143). intakeGene dedups an already-pooled gene by signal overlap, so a retry can
70
+ // only recover a partial write while the gene is NOT yet pooled. We therefore commit the gene LAST and emit the
71
+ // audit AT MOST ONCE (guarded by the spine) BEFORE it: if any step before the gene write fails, the gene stays
72
+ // unpooled → a retry re-runs everything (audit skipped if already on the spine, capsule re-put idempotently by
73
+ // content address) and finishes cleanly — never an un-audited pooled gene, never a duplicate audit.
74
+ const alreadyAudited = deps.ingestor
75
+ .readAll()
76
+ .some((e) => e.type === 'gene.distilled' && String(e.payload?.['assetId']) === assetId);
77
+ if (!alreadyAudited) {
78
+ await deps.ingestor.ingest({
79
+ type: 'gene.distilled',
80
+ payload: { geneId, assetId: r.gene.asset_id, category: r.gene.category, source: 'skill2gep', skill: parsed.name },
81
+ human: { title: `skill-distilled gene ${geneId} (UNPROVEN — awaiting review)`, severity: 'info' },
82
+ actor: { kind: 'machine', id: 'skill2gep' },
83
+ });
84
+ }
85
+ // Quarantine AFTER the audit (no dangling quarantine for a never-audited asset): a skill-distilled gene is a
86
+ // draft, withheld from inject/cursor (A2a) until a human `review --approve`s it. Sticky across a re-distill.
87
+ review.quarantineIfAbsent(assetId);
88
+ let capsuleId = null;
89
+ if (capsule) {
90
+ // intakeGene may REWRITE the gene id (it only keeps an id already in the distilled-prefix namespace), so the
91
+ // capsule — built from the pre-intake candidate id — must be re-pointed to the POOLED gene id, else it
92
+ // references a gene that is not in the store.
93
+ const pooledCapsule = { ...capsule, gene: geneId };
94
+ await deps.store.put(pooledCapsule); // evidence; references the (gated) gene
95
+ capsuleId = pooledCapsule.id;
96
+ }
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: [] };
99
+ }
100
+ catch (e) {
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)] };
103
+ }
104
+ }
105
+ /** Resolve a `--skill` argument (a SKILL.md file OR a skill directory) to the SKILL.md path. */
106
+ function resolveSkillMdPath(skillArg) {
107
+ const p = resolve(skillArg);
108
+ try {
109
+ if (statSync(p).isDirectory())
110
+ return join(p, 'SKILL.md');
111
+ }
112
+ catch { /* missing → reported by the read */ }
113
+ return p;
114
+ }
115
+ /**
116
+ * `evolver skill-distill --skill <SKILL.md|dir> [--execution <json|@file>] [--scenario <name>] [--strict]` (B3b-ii).
117
+ *
118
+ * The faithful v2 analog of v1's skill-run hook: the CALLER (a skill-run hook, or an operator) supplies the REAL
119
+ * execution — session logs carry no skill-invocation marker, so an after-the-fact daemon cannot honestly attribute
120
+ * a trace to a skill (verified against on-disk logs). Passing the execution in keeps the Capsule's evidence real.
121
+ * With no `--execution`, only the (quarantined) gene is drafted — no Capsule, which is correct: no evidence, no
122
+ * proof. Output reports the gene id, quarantine state, and either the capsule id or why it was withheld.
123
+ */
124
+ export async function runSkillDistill(argv, injected = {}) {
125
+ const flags = {};
126
+ for (let i = 0; i < argv.length; i++) {
127
+ const a = argv[i];
128
+ if (a?.startsWith('--')) {
129
+ const next = argv[i + 1];
130
+ if (next !== undefined && !next.startsWith('--')) {
131
+ flags[a.slice(2)] = next;
132
+ i++;
133
+ }
134
+ else
135
+ flags[a.slice(2)] = '';
136
+ }
137
+ }
138
+ if (!flags['skill']) {
139
+ process.stderr.write('用法: evolver skill-distill --skill <SKILL.md|dir> [--execution <json|@file>] [--scenario <name>] [--strict]\n');
140
+ return 1;
141
+ }
142
+ const mdPath = resolveSkillMdPath(flags['skill']);
143
+ let skillMd;
144
+ try {
145
+ skillMd = readFileSync(mdPath, 'utf8');
146
+ }
147
+ catch (e) {
148
+ process.stderr.write(`skill-distill: cannot read SKILL.md: ${mdPath} (${e instanceof Error ? e.message : String(e)})\n`);
149
+ return 1;
150
+ }
151
+ // The execution is the caller's REAL run record. Accept inline JSON or `@file`. Absent → Gene-only (no evidence).
152
+ let execution = {};
153
+ const exFlag = flags['execution'];
154
+ if (exFlag) {
155
+ let raw = exFlag;
156
+ if (exFlag.startsWith('@')) {
157
+ try {
158
+ raw = readFileSync(resolve(exFlag.slice(1)), 'utf8');
159
+ }
160
+ catch (e) {
161
+ process.stderr.write(`skill-distill: cannot read --execution file: ${exFlag.slice(1)} (${e instanceof Error ? e.message : String(e)})\n`);
162
+ return 1;
163
+ }
164
+ }
165
+ let parsed;
166
+ try {
167
+ parsed = JSON.parse(raw);
168
+ }
169
+ catch (e) {
170
+ process.stderr.write(`skill-distill: --execution is not valid JSON (${e instanceof Error ? e.message : String(e)})\n`);
171
+ return 1;
172
+ }
173
+ // A cast alone lets null / arrays / primitives through (Bugbot #145): a malformed hook payload would then pool
174
+ // a gene yet silently never produce the intended capsule. Require a plain object so a bad payload fails loudly.
175
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
176
+ process.stderr.write('skill-distill: --execution must be a JSON object (got ' + (parsed === null ? 'null' : Array.isArray(parsed) ? 'array' : typeof parsed) + ')\n');
177
+ return 1;
178
+ }
179
+ execution = parsed;
180
+ }
181
+ const store = injected.store ?? new assetstore.LocalJsonlProvider(events.assetsDir());
182
+ const deps = {
183
+ store,
184
+ review: injected.review ?? reviewLedgerForStore(store),
185
+ ingestor: injected.ingestor ?? new events.Ingestor({ path: events.rootEventsPath() }),
186
+ };
187
+ const opts = { strict: 'strict' in flags };
188
+ if (flags['scenario'])
189
+ opts.scenario = flags['scenario'];
190
+ const res = await recordSkillDistillation(skillMd, execution, deps, opts);
191
+ if (!res.geneId) {
192
+ process.stderr.write(`skill-distill: no gene produced — ${res.errors.join('; ') || 'refused'}\n`);
193
+ return 1;
194
+ }
195
+ process.stdout.write(`skill-distill: gene ${res.geneId} ${res.quarantined ? 'QUARANTINED (awaiting `evolver review --approve`)' : 'recorded'}\n`);
196
+ if (res.capsuleId)
197
+ process.stdout.write(` → capsule ${res.capsuleId} (real execution evidence)\n`);
198
+ else {
199
+ // "(no execution provided)" only fits when the flag was OMITTED. With a flag present but no status (e.g. `{}`),
200
+ // reverseDistill skips the capsule WITHOUT a diagnostic — say so honestly rather than claim none was provided (Bugbot #145).
201
+ const why = res.capsuleDiagnostic ? ` (${res.capsuleDiagnostic})`
202
+ : exFlag ? ' (execution lacks a status — no capsule)'
203
+ : ' (no execution provided)';
204
+ process.stdout.write(` → no capsule${why}\n`);
205
+ }
206
+ if (res.errors.length)
207
+ process.stdout.write(` ⚠ ${res.errors.join('; ')}\n`);
208
+ return 0;
209
+ }
210
+ const strList = (v) => (Array.isArray(v) ? v.map((x) => String(x).trim()).filter(Boolean) : []);
211
+ const titleCase = (s) => s.replace(/[-_]+/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase()).trim();
212
+ /** Derive a readable skill name from a gene when the target SKILL.md has none to preserve. */
213
+ function deriveSkillName(gene) {
214
+ const sigs = strList(gene['signals_match']);
215
+ if (sigs.length)
216
+ return sigs.slice(0, 3).join('-').replace(/_/g, '-');
217
+ const id = String(gene['id'] ?? 'distilled-skill').replace(/^gene_(?:s2g|distilled)_/, '').replace(/^gene_/, '');
218
+ return id || 'distilled-skill';
219
+ }
220
+ /**
221
+ * Render a gene back into SKILL.md text (B4) — the reverse of `parseSkillMd`. Sections use headings `parseSkillMd`
222
+ * recognizes, so the round-trip recovers signals / validation / preconditions. `opts.name` preserves an existing
223
+ * skill's identity on update; otherwise a readable name is derived. Pure — the proven-gate + file write live in
224
+ * `runSkillMdUpdate`.
225
+ */
226
+ export function geneToSkillMd(gene, opts = {}) {
227
+ const name = (opts.name && opts.name.trim()) || deriveSkillName(gene);
228
+ const display = titleCase(name);
229
+ let desc = String(gene['summary'] ?? '').replace(/[\r\n]+/g, ' ').trim();
230
+ if (desc.length < 10)
231
+ desc = 'AI agent skill distilled from a human-approved, capsule-proven evolution gene.';
232
+ const signals = strList(gene['signals_match']);
233
+ const preconditions = strList(gene['preconditions']);
234
+ const strategy = strList(gene['strategy']);
235
+ const avoid = strList(gene['avoid']); // read defensively — not on GeneCandidate, but stored genes may carry it
236
+ const validation = strList(gene['validation']);
237
+ const constraints = (gene['constraints'] && typeof gene['constraints'] === 'object') ? gene['constraints'] : null;
238
+ const out = ['---', `name: ${name}`, `description: ${desc}`, '---', '', `# ${display}`, '', desc, ''];
239
+ if (signals.length) {
240
+ out.push('## When to Use', '', `- When your project encounters: ${signals.slice(0, 4).map((s) => `\`${s}\``).join(', ')}`, '');
241
+ out.push('## Trigger Signals', '', ...signals.map((s) => `- \`${s}\``), '');
242
+ }
243
+ if (preconditions.length)
244
+ out.push('## Preconditions', '', ...preconditions.map((p) => `- ${p}`), '');
245
+ if (strategy.length)
246
+ out.push('## Strategy', '', ...strategy.map((s, i) => `${i + 1}. ${s}`), '');
247
+ if (avoid.length)
248
+ out.push('## Avoid', '', ...avoid.map((a) => `- ${a}`), '');
249
+ if (constraints) {
250
+ const c = [];
251
+ if (constraints['max_files'] != null)
252
+ c.push(`- Max files per invocation: ${String(constraints['max_files'])}`);
253
+ const fp = strList(constraints['forbidden_paths']);
254
+ if (fp.length)
255
+ c.push(`- Forbidden paths: ${fp.map((p) => `\`${p}\``).join(', ')}`);
256
+ if (c.length)
257
+ out.push('## Constraints', '', ...c, '');
258
+ }
259
+ if (validation.length) {
260
+ out.push('## Validation', '');
261
+ for (const cmd of validation)
262
+ out.push('```bash', cmd, '```', '');
263
+ }
264
+ out.push('## Metadata', '', `- Category: \`${String(gene['category'] ?? 'innovate')}\``, `- Gene: \`${String(gene['id'] ?? '')}\``, '');
265
+ out.push('---', '', '*Maintained by Evolver — regenerated from a human-approved, capsule-proven gene.*', '');
266
+ return out.join('\n');
267
+ }
268
+ /**
269
+ * `evolver skill-md-update --gene <id> --skill <SKILL.md|dir> [--dry-run]` (B4).
270
+ *
271
+ * Write a PROVEN gene back into its SKILL.md — closing the skill2gep loop (SKILL.md → gene → proven → improved
272
+ * SKILL.md). **Proven gate**: refuses unless the gene is human-APPROVED (`review --approve`) AND has ≥1 Capsule
273
+ * (real execution evidence). An unproven/unapproved draft must NEVER overwrite a human's SKILL.md — that is exactly
274
+ * the confident-hallucination the system guards against. On update, the existing SKILL.md's frontmatter `name` is
275
+ * preserved (stable identity); `--dry-run` prints the rendered SKILL.md without writing.
276
+ */
277
+ export async function runSkillMdUpdate(argv, injected = {}) {
278
+ const flags = {};
279
+ for (let i = 0; i < argv.length; i++) {
280
+ const a = argv[i];
281
+ if (a?.startsWith('--')) {
282
+ const next = argv[i + 1];
283
+ if (next !== undefined && !next.startsWith('--')) {
284
+ flags[a.slice(2)] = next;
285
+ i++;
286
+ }
287
+ else
288
+ flags[a.slice(2)] = '';
289
+ }
290
+ }
291
+ if (!flags['gene'] || !flags['skill']) {
292
+ process.stderr.write('用法: evolver skill-md-update --gene <id> --skill <SKILL.md|dir> [--dry-run]\n');
293
+ return 1;
294
+ }
295
+ const store = injected.store ?? new assetstore.LocalJsonlProvider(events.assetsDir());
296
+ const review = injected.review ?? reviewLedgerForStore(store);
297
+ const genes = await store.list('Gene', 10000);
298
+ const gene = genes.find((g) => String(g['id']) === flags['gene'] || String(g['asset_id']) === flags['gene']);
299
+ if (!gene) {
300
+ process.stderr.write(`skill-md-update: gene not found: ${flags['gene']}\n`);
301
+ return 1;
302
+ }
303
+ const geneId = String(gene['id']);
304
+ const assetId = String(gene['asset_id']);
305
+ // Proven gate — both legs required. A gene reaches a human's SKILL.md only after a human approved it AND a real
306
+ // execution produced capsule evidence for it; an unproven draft writing to disk is the red line we defend.
307
+ if (!review.isApproved(assetId)) {
308
+ process.stderr.write(`skill-md-update: gene ${geneId} is NOT approved — run \`evolver review --approve ${assetId}\` first (refusing to overwrite a SKILL.md with an unapproved gene)\n`);
309
+ return 1;
310
+ }
311
+ const capsules = await store.search({ kind: 'Capsule', gene: geneId, limit: 1 });
312
+ if (capsules.length === 0) {
313
+ process.stderr.write(`skill-md-update: gene ${geneId} has NO capsule evidence — it is unproven; refusing to write it to a SKILL.md\n`);
314
+ return 1;
315
+ }
316
+ const target = resolveSkillMdPath(flags['skill']);
317
+ const existed = existsSync(target);
318
+ // Preserve an existing skill's identity (frontmatter name) across the update.
319
+ let name;
320
+ if (existed) {
321
+ try {
322
+ name = parseSkillMd(readFileSync(target, 'utf8')).name || undefined;
323
+ }
324
+ catch { /* unreadable → derive */ }
325
+ }
326
+ const md = geneToSkillMd(gene, name ? { name } : {});
327
+ if ('dry-run' in flags) {
328
+ process.stdout.write(md.endsWith('\n') ? md : md + '\n');
329
+ process.stdout.write(`\n(dry-run — would ${existed ? 'update' : 'create'} ${target})\n`);
330
+ return 0;
331
+ }
332
+ try {
333
+ mkdirSync(dirname(target), { recursive: true });
334
+ writeFileSync(target, md);
335
+ }
336
+ catch (e) {
337
+ process.stderr.write(`skill-md-update: cannot write ${target} (${e instanceof Error ? e.message : String(e)})\n`);
338
+ return 1;
339
+ }
340
+ process.stdout.write(`skill-md-update: ${existed ? 'updated' : 'created'} ${target} from proven gene ${geneId}\n`);
341
+ return 0;
342
+ }
@@ -0,0 +1,14 @@
1
+ export interface BreakerState {
2
+ consecutiveFailures: number;
3
+ }
4
+ export interface BreakerStep {
5
+ state: BreakerState;
6
+ /** Whether the caller should trip: stop the loop / exit. */
7
+ tripped: boolean;
8
+ }
9
+ /**
10
+ * Advance the breaker by one cycle result.
11
+ * ok: did the cycle succeed?
12
+ * maxConsecutiveFailures: threshold (clamped to >= 1)
13
+ */
14
+ export declare function step(state: BreakerState | undefined, ok: boolean, maxConsecutiveFailures: number): BreakerStep;
@@ -0,0 +1,21 @@
1
+ // Solo-mode circuit breaker (pure decision logic), TypeScript port of v1.
2
+ //
3
+ // The wild Mad Dog loop, on a crash, sleeps and blindly retries forever. Solo
4
+ // replaces that with a bounded breaker: count consecutive failed cycles, reset
5
+ // on any success, and once the count hits the threshold, signal STOP so the
6
+ // caller can hard-stop instead of thrashing. Pure (no git, no exit, no clock)
7
+ // so solo/breaker.test.ts can exercise every transition without a daemon.
8
+ /**
9
+ * Advance the breaker by one cycle result.
10
+ * ok: did the cycle succeed?
11
+ * maxConsecutiveFailures: threshold (clamped to >= 1)
12
+ */
13
+ export function step(state, ok, maxConsecutiveFailures) {
14
+ const max = Math.max(1, Math.trunc(maxConsecutiveFailures) || 0);
15
+ const prev = state?.consecutiveFailures ?? 0;
16
+ const consecutiveFailures = ok ? 0 : prev + 1;
17
+ return {
18
+ state: { consecutiveFailures },
19
+ tripped: !ok && consecutiveFailures >= max,
20
+ };
21
+ }
@@ -0,0 +1,17 @@
1
+ /** True if the repo has any staged/unstaged/untracked changes. */
2
+ export declare function hasUncommittedChanges(repoDir: string): boolean;
3
+ /**
4
+ * Capture a rollback point for the current cycle. Returns the HEAD sha, or null
5
+ * if the repo can't be snapshotted (not a git repo, no commits, git missing).
6
+ * A null snapshot disables rollback for that cycle rather than throwing — solo
7
+ * must not crash because the target isn't a git repo.
8
+ */
9
+ export declare function snapshot(repoDir: string): string | null;
10
+ /**
11
+ * Roll the target repo back to a snapshot sha: discard tracked-file edits
12
+ * (reset --hard) AND remove new files the cycle created (clean -fd), so the
13
+ * working tree matches the pre-cycle state. No-op when sha is null. Returns true
14
+ * on success, false if the rollback itself failed (surfaced by the caller so a
15
+ * wedged repo doesn't masquerade as a clean recovery).
16
+ */
17
+ export declare function rollbackTo(repoDir: string, sha: string | null): boolean;
@@ -0,0 +1,62 @@
1
+ // Solo-mode git safety net (--solo), TypeScript port of the v1 gitGuard.
2
+ //
3
+ // The wild Mad Dog loop self-modifies its target project every cycle with no
4
+ // undo. Solo trades the human-review gate for a mechanical one: snapshot the
5
+ // target repo before each cycle, and on a failed cycle hard-reset back to that
6
+ // snapshot so a broken self-edit cannot accumulate. This guards the TARGET
7
+ // project repo (autoexec's first allowlisted root), NOT evolver's own source.
8
+ //
9
+ // All git calls go through execFileSync (never a shell) so a repo path or
10
+ // branch name can't be interpreted as a command. Pure and dependency-free so
11
+ // solo/gitGuard.test.ts can exercise it against a throwaway repo.
12
+ import { execFileSync } from 'node:child_process';
13
+ function git(repoDir, args) {
14
+ return execFileSync('git', ['-C', repoDir, ...args], {
15
+ encoding: 'utf8',
16
+ stdio: ['ignore', 'pipe', 'pipe'],
17
+ });
18
+ }
19
+ /** True if the repo has any staged/unstaged/untracked changes. */
20
+ export function hasUncommittedChanges(repoDir) {
21
+ try {
22
+ return git(repoDir, ['status', '--porcelain']).trim().length > 0;
23
+ }
24
+ catch {
25
+ // Not a git repo / git missing: treat as "can't tell" → no clean baseline.
26
+ return false;
27
+ }
28
+ }
29
+ /**
30
+ * Capture a rollback point for the current cycle. Returns the HEAD sha, or null
31
+ * if the repo can't be snapshotted (not a git repo, no commits, git missing).
32
+ * A null snapshot disables rollback for that cycle rather than throwing — solo
33
+ * must not crash because the target isn't a git repo.
34
+ */
35
+ export function snapshot(repoDir) {
36
+ try {
37
+ const sha = git(repoDir, ['rev-parse', 'HEAD']).trim();
38
+ return sha || null;
39
+ }
40
+ catch {
41
+ return null;
42
+ }
43
+ }
44
+ /**
45
+ * Roll the target repo back to a snapshot sha: discard tracked-file edits
46
+ * (reset --hard) AND remove new files the cycle created (clean -fd), so the
47
+ * working tree matches the pre-cycle state. No-op when sha is null. Returns true
48
+ * on success, false if the rollback itself failed (surfaced by the caller so a
49
+ * wedged repo doesn't masquerade as a clean recovery).
50
+ */
51
+ export function rollbackTo(repoDir, sha) {
52
+ if (!sha)
53
+ return false;
54
+ try {
55
+ git(repoDir, ['reset', '--hard', sha]);
56
+ git(repoDir, ['clean', '-fd']);
57
+ return true;
58
+ }
59
+ catch {
60
+ return false;
61
+ }
62
+ }
@@ -0,0 +1,12 @@
1
+ export declare const SOLO_DEFAULT_MAX_FAILS = 5;
2
+ /** True when this autoexec invocation is solo (CLI flag or explicit env). */
3
+ export declare function isSoloRun(argv: readonly string[], env?: NodeJS.ProcessEnv): boolean;
4
+ /** Circuit-breaker threshold; tunable via EVOLVER_SOLO_MAX_FAILS, clamped to >= 1. */
5
+ export declare function soloMaxFails(env?: NodeJS.ProcessEnv): number;
6
+ /**
7
+ * Hard-cut the network + autonomous spend at the source, in-process. Returns the
8
+ * keys it forced (for logging/tests). Idempotent.
9
+ */
10
+ export declare function applySoloLockdown(env?: NodeJS.ProcessEnv): Record<string, string>;
11
+ /** The solo startup banner lines (returned so the caller writes them and tests assert them). */
12
+ export declare function soloBanner(repoRoot: string): string[];
@@ -0,0 +1,55 @@
1
+ // Solo-mode detection, source-level lockdown, and banner for `evolver autoexec --solo`.
2
+ //
3
+ // Solo = the "constrained wild" profile: the immediacy of Mad Dog (no human-
4
+ // review gate) plus four mechanical backstops — offline, ATP disabled, per-cycle
5
+ // git snapshot/rollback, and a consecutive-failure circuit breaker.
6
+ //
7
+ // The lockdown mutates process.env IN-PROCESS before autoexec reads any gate, so
8
+ // that BOTH the startup wiring and any in-cycle path see the network + ATP as
9
+ // disabled. These are OVERWRITES, not defaults: under --solo a user cannot re-
10
+ // enable hub/ATP by setting the env themselves — that is the "no escape valve"
11
+ // requirement. Numeric knobs (EVOLVER_SOLO_MAX_FAILS) stay tunable; the four
12
+ // safety cuts do not.
13
+ export const SOLO_DEFAULT_MAX_FAILS = 5;
14
+ /** True when this autoexec invocation is solo (CLI flag or explicit env). */
15
+ export function isSoloRun(argv, env = process.env) {
16
+ return argv.includes('--solo') || env['EVOLVER_SOLO'] === '1';
17
+ }
18
+ /** Circuit-breaker threshold; tunable via EVOLVER_SOLO_MAX_FAILS, clamped to >= 1. */
19
+ export function soloMaxFails(env = process.env) {
20
+ const raw = Number(env['EVOLVER_SOLO_MAX_FAILS']);
21
+ return Number.isFinite(raw) && raw >= 1 ? Math.trunc(raw) : SOLO_DEFAULT_MAX_FAILS;
22
+ }
23
+ /**
24
+ * Hard-cut the network + autonomous spend at the source, in-process. Returns the
25
+ * keys it forced (for logging/tests). Idempotent.
26
+ */
27
+ export function applySoloLockdown(env = process.env) {
28
+ const forced = {
29
+ // Offline: the hub-reuse + question links are gated on this flag; forcing it
30
+ // off means resolveHubLink/resolveHubQuestionLink return undefined → zero hub calls.
31
+ EVOLVER_REUSE_BEFORE_SOLVE: '0',
32
+ EVOLVER_REUSE_SIGNAL: '0',
33
+ // ATP: disable autonomous spend on every path (autobuy + autodeliver).
34
+ EVOLVER_ATP: 'off',
35
+ EVOLVER_ATP_AUTOBUY: 'off',
36
+ EVOLVER_ATP_AUTODELIVER: 'off',
37
+ // Empty hub creds so any lower-level connector short-circuits.
38
+ A2A_HUB_URL: '',
39
+ EVOMAP_HUB_URL: '',
40
+ };
41
+ for (const [k, v] of Object.entries(forced))
42
+ env[k] = v;
43
+ return forced;
44
+ }
45
+ /** The solo startup banner lines (returned so the caller writes them and tests assert them). */
46
+ export function soloBanner(repoRoot) {
47
+ return [
48
+ '════════════════════════════════════════════════════════',
49
+ '[Solo] Mad Dog · 受约束的野性模式已启动',
50
+ '[Solo] 兜底四道:断网 · 禁ATP · 每 cycle git 快照/失败回滚 · 连续失败熔断',
51
+ '[Solo] 默认免人审。目标仓:' + repoRoot,
52
+ '[Solo] 无 hub 审计,仅本地 git 可追溯。',
53
+ '════════════════════════════════════════════════════════',
54
+ ];
55
+ }
@@ -0,0 +1,43 @@
1
+ import { assetstore } from '@evomap/evolver-core';
2
+ export interface ThesisTaskSpec {
3
+ id: string;
4
+ signals: string[];
5
+ category?: string;
6
+ target?: string;
7
+ expectedEffect?: string;
8
+ summary?: string;
9
+ confidence?: number;
10
+ }
11
+ export interface ThesisSuite {
12
+ name: string;
13
+ /** Verifier commands run in the worktree after each attempt; their all-pass decides `passed`. */
14
+ validation?: string[];
15
+ tasks: ThesisTaskSpec[];
16
+ }
17
+ type CycleExecute = (mutation: never, decision: {
18
+ selectedGeneId?: string | null;
19
+ }) => Promise<{
20
+ outcome: {
21
+ status: 'success' | 'failed';
22
+ score: number;
23
+ };
24
+ }> | {
25
+ outcome: {
26
+ status: 'success' | 'failed';
27
+ score: number;
28
+ };
29
+ };
30
+ export interface ThesisCommandDeps {
31
+ /** evolver-arm store (the learned-gene pool). Default: the live asset store. */
32
+ pool?: assetstore.AssetStoreProvider;
33
+ /** Inject a deterministic agent for tests / a dry simulation. Default: makeSafeExecute against `--repo` (live). */
34
+ execute?: CycleExecute;
35
+ now?: () => number;
36
+ }
37
+ /**
38
+ * `evolver thesis --suite <file> [--repo <allowlisted>] [--min-samples N] [--min-delta D] [--interleave] [--json]`.
39
+ * Runs the controlled A/B and prints baseline-vs-evolver pass rates + the verdict. A LIVE run needs `--repo` (the
40
+ * single allowlisted root the agent may touch); tests inject `deps.execute` instead.
41
+ */
42
+ export declare function runThesisCommand(argv: readonly string[], deps?: ThesisCommandDeps): Promise<number>;
43
+ export {};