@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,75 @@
1
+ // The CLI command registry — the single source of truth for which verbs `evolver <verb>` resolves to.
2
+ // `cli.ts` is the executable shim (it reads process.argv at import time, so it must NOT be imported by tests);
3
+ // this module holds the dispatch DATA so the surface is importable and assertable (see commandSurface.test.ts).
4
+ // The "phantom command" trap this guards against: an installer baking `evolver <verb>` into a user's runtime
5
+ // config for a verb the CLI never actually dispatches — a green build hides it, the user hits a usage error.
6
+ import { runCli, runMigrate, runAssetLog, runDistill, runIngest, runInject, runReview, } from './index.js';
7
+ import { runAutoExec } from './autoexec.js';
8
+ import { runAtpCommand, runBuyCommand, runOrdersCommand, runVerifyCommand } from './atp.js';
9
+ import { runLogin } from './login.js';
10
+ import { runSetupHooks } from './setupHooks.js';
11
+ import { runSkillDistill, runSkillMdUpdate } from './skillDistill.js';
12
+ import { runThesisCommand } from './thesis.js';
13
+ import { getCliVersion } from './version.js';
14
+ import { runRecipeCommand } from './recipe.js';
15
+ import { runReuseCommand } from './reuse.js';
16
+ import { runPublishCommand } from './cliContracts.js';
17
+ import { runRecallCommand } from './recall.js';
18
+ import { runReuseReportCommand } from './reuseReport.js';
19
+ import { runDoctorCommand } from './doctor.js';
20
+ import { runPhubCommand } from './phub.js';
21
+ import { runTrajectoryExport } from './trajectoryExport.js';
22
+ import { runAntiGeneBenchmarkCommand } from './antiGeneBenchmark.js';
23
+ import { runAntiGeneRolloutCommand } from './antiGeneRollout.js';
24
+ import { runLifecycleCommand } from './lifecycle.js';
25
+ import { runCycleCommand } from './cycleConsumer.js';
26
+ /** Verbs dispatched asynchronously ahead of the synchronous runCli core. cli.ts drives its dispatch from this. */
27
+ export const ASYNC_COMMANDS = {
28
+ migrate: runMigrate,
29
+ 'asset-log': runAssetLog,
30
+ distill: runDistill,
31
+ ingest: runIngest,
32
+ inject: runInject,
33
+ review: runReview,
34
+ 'skill-distill': runSkillDistill,
35
+ 'skill-md-update': runSkillMdUpdate,
36
+ thesis: runThesisCommand,
37
+ autoexec: runAutoExec,
38
+ login: runLogin,
39
+ 'setup-hooks': runSetupHooks,
40
+ buy: runBuyCommand,
41
+ orders: runOrdersCommand,
42
+ verify: runVerifyCommand,
43
+ atp: runAtpCommand,
44
+ recipe: runRecipeCommand,
45
+ reuse: runReuseCommand,
46
+ publish: runPublishCommand,
47
+ recall: runRecallCommand,
48
+ 'reuse-report': runReuseReportCommand,
49
+ doctor: runDoctorCommand,
50
+ phub: runPhubCommand,
51
+ lifecycle: runLifecycleCommand,
52
+ cycle: runCycleCommand,
53
+ 'trajectory-export': runTrajectoryExport,
54
+ 'anti-gene-benchmark': runAntiGeneBenchmarkCommand,
55
+ 'anti-gene-rollout': runAntiGeneRolloutCommand,
56
+ };
57
+ /** Verbs handled by the synchronous runCli core (read-only views + local ops). Kept in sync with runCli's switch
58
+ * — the source of truth for these stays runCli; this list completes the surface for the registry contract. */
59
+ export const SYNC_COMMANDS = [
60
+ 'status', 'cycles', 'trigger', 'value', 'narrative', 'retention', 'gene-value', 'replay', 'rebuild-views', 'reset-local-secret',
61
+ ];
62
+ /** Every top-level verb `evolver` resolves to (async-dispatched ∪ runCli core). */
63
+ export const ALL_COMMANDS = new Set([
64
+ ...Object.keys(ASYNC_COMMANDS),
65
+ ...SYNC_COMMANDS,
66
+ ]);
67
+ /** Run a top-level argv against the registry: async handler if present, else the synchronous runCli core. */
68
+ export function dispatch(argv) {
69
+ if (argv[0] === '--version' || argv[0] === '-v') {
70
+ process.stdout.write(`${getCliVersion()}\n`);
71
+ return 0;
72
+ }
73
+ const handler = ASYNC_COMMANDS[argv[0] ?? ''];
74
+ return handler ? handler(argv.slice(1)) : runCli(argv);
75
+ }
@@ -0,0 +1,33 @@
1
+ import { assetstore, events, observers, type material as materialNs } from '@evomap/evolver-core';
2
+ /** Consumer group the distill drain claims under — independent cursor from any other material consumer. */
3
+ export declare const DISTILL_CONSUMER_GROUP = "distill";
4
+ export interface DistillComposition {
5
+ /** Consumer group cursor over the MaterialStore (at-least-once claim/ack). */
6
+ consumer: materialNs.ConsumerGroups;
7
+ /** Asset store the draft gene is written to. */
8
+ store: assetstore.AssetStoreProvider;
9
+ /** Review ledger the draft is quarantined in. Default co-located with the store (same gate as the read side). */
10
+ review?: assetstore.ReviewLedger;
11
+ /** Ingestor that records the gene.distilled audit event — MUST be the daemon's bus Ingestor (#117). */
12
+ ingestor: events.Ingestor;
13
+ /** Max drafts per drain tick. Default 3. */
14
+ maxPerTick?: number;
15
+ /** Backoff before the observer retries a STALLED drain (stuck head). Default 30s (see distillObserver). */
16
+ retryDelayMs?: number;
17
+ /** Read a session source file → raw chunk. Default fs read; injectable for tests. */
18
+ readSource?: (path: string) => string;
19
+ }
20
+ /**
21
+ * The injected drain side-effect: claim ready material → draft + quarantine genes. `runtime_session` material is
22
+ * distilled (its narration drafts a strategy); `proxy_trace` is observation-only (metadata, no narration) and is
23
+ * acked without drafting. Best-effort per material: a missing/unparseable source never blocks the rest of the
24
+ * batch. Every material in the claimed batch is acked (drafted, skipped, or failed) so the cursor always advances.
25
+ */
26
+ export declare function makeDistillDrain(c: DistillComposition): () => Promise<{
27
+ drafted: number;
28
+ stalled: boolean;
29
+ }>;
30
+ /** Compose the live distill observer from the daemon's material/store/ingestor — register the result on the bus.
31
+ * The observer only needs the `stalled` signal (to self-schedule a backoff retry); the drafted count is for the
32
+ * direct-drain tests / callers. */
33
+ export declare function resolveDistillObserver(c: DistillComposition): ReturnType<typeof observers.distillObserver>;
@@ -0,0 +1,146 @@
1
+ // Distill observer composition (#117 A1) — the CLI layer that turns core's `distillObserver` into a LIVE drain of
2
+ // M1 material into quarantined gene drafts. Core owns the trigger policy (material.batch_ready + single-flight);
3
+ // this layer owns the side effects core must not: claim from the consumer group, re-read + parse the session via
4
+ // the runtime adapters, draft via the SHARED distill primitive, quarantine in the ReviewLedger, and emit
5
+ // gene.distilled. It reuses the exact same `draftGeneCandidate` as `evolver ingest --distill`, so the one-shot and
6
+ // the auto path never drift.
7
+ //
8
+ // WIRING (#117 / #106): this composition is ready to register on the resident daemon's ObserverBus, but the
9
+ // PRODUCER of material.batch_ready (a daemon ingesting session dirs onto the same bus Ingestor) is a #106 item.
10
+ // Until that lands, the composition is verified by its integration test (real bus + Ingestor dispatch) but not yet
11
+ // wired into autoexec — a tracked dependency, not dead code. See distillObserver.test.ts.
12
+ import { assetstore, events, observers, signals, algo } from '@evomap/evolver-core';
13
+ import { readFileSync } from 'node:fs';
14
+ import { draftGeneCandidate, assessDraftAdmission } from './distillPrimitives.js';
15
+ import { reviewLedgerForStore } from './reviewFilter.js';
16
+ import { parseRuntimeSessionSources } from './runtimeSessionSource.js';
17
+ /** Consumer group the distill drain claims under — independent cursor from any other material consumer. */
18
+ export const DISTILL_CONSUMER_GROUP = 'distill';
19
+ /** Drafts created per tick — bound the auto-draft rate so an idle daemon does not flood the human review queue. */
20
+ const DEFAULT_MAX_PER_TICK = 3;
21
+ /**
22
+ * The injected drain side-effect: claim ready material → draft + quarantine genes. `runtime_session` material is
23
+ * distilled (its narration drafts a strategy); `proxy_trace` is observation-only (metadata, no narration) and is
24
+ * acked without drafting. Best-effort per material: a missing/unparseable source never blocks the rest of the
25
+ * batch. Every material in the claimed batch is acked (drafted, skipped, or failed) so the cursor always advances.
26
+ */
27
+ export function makeDistillDrain(c) {
28
+ const review = c.review ?? reviewLedgerForStore(c.store);
29
+ const maxPerTick = c.maxPerTick ?? DEFAULT_MAX_PER_TICK;
30
+ const readSource = c.readSource ?? ((p) => readFileSync(p, 'utf8'));
31
+ // Process ONE claimed material. `ack:true` ⇒ advance the cursor past it; `ack:false` ⇒ either a persist/audit
32
+ // write failed OR the remaining per-tick draft budget was reached — leave it for a retry tick. A bad/unparseable/
33
+ // missing source, a proxy_trace, a too-thin session, or a duplicate are all "handled" (skip + ack).
34
+ async function processOne(m, audited, draftLimit) {
35
+ // Only session narration distills; proxy_trace is observation-only (no turns to draft a strategy from).
36
+ if (m.sourceKind !== 'runtime_session' || m.kind !== 'session_log')
37
+ return { ack: true, drafted: 0 };
38
+ let sources;
39
+ try {
40
+ sources = parseRuntimeSessionSources(m.sourcePath, readSource);
41
+ }
42
+ catch {
43
+ return { ack: true, drafted: 0 }; // bad / missing / unparseable source — nothing to retry
44
+ }
45
+ let drafted = 0;
46
+ for (const source of sources) {
47
+ if (drafted >= draftLimit)
48
+ return { ack: false, drafted };
49
+ const candidate = draftGeneCandidate(source.turns, signals.extractSignals(source.turns), source.agent);
50
+ if (!candidate)
51
+ continue; // too thin to distill
52
+ const existing = (await c.store.list('Gene', 1000)).map((g) => ({
53
+ id: typeof g['id'] === 'string' ? String(g['id']) : undefined,
54
+ signals_match: Array.isArray(g['signals_match']) ? g['signals_match'] : [],
55
+ }));
56
+ // Value/novelty gate (#117 improvement 3): drop thin / near-duplicate drafts BEFORE they reach the human
57
+ // review queue. Ack the material (a deliberate skip, not a failure — nothing to retry).
58
+ if (!assessDraftAdmission(candidate, existing).admit)
59
+ continue;
60
+ const r = algo.intakeGene(candidate, existing);
61
+ if (!r.ok || !r.gene)
62
+ continue; // duplicate / rejected
63
+ // WRITE phase — three NON-ATOMIC writes (audit / quarantine / persist). Make each idempotent so ANY partial
64
+ // failure self-heals on the next-tick retry with NO duplicate and NO dangling record:
65
+ // 1. emit gene.distilled ONCE, gated on `audited` (the spine's existing gene.distilled asset_ids) — a retry
66
+ // after a later failure never double-records the audit.
67
+ // 2. quarantine AFTER the audit succeeds — a failed emit leaves no quarantine for a never-audited asset.
68
+ // 3. persist LAST (the commit). store.put is asset_id-idempotent, so a retry re-put is a no-op.
69
+ // Any throw → leave the material UN-acked to retry. Invariant: gene in pool ⟹ exactly one gene.distilled.
70
+ const assetId = String(r.gene.asset_id);
71
+ try {
72
+ if (!audited.has(assetId)) {
73
+ await c.ingestor.ingest({
74
+ type: 'gene.distilled',
75
+ payload: { geneId: r.gene.id, assetId: r.gene.asset_id, category: r.gene.category, source: 'distill-observer', materialId: m.materialId, ...(source.sessionId ? { sessionId: source.sessionId } : {}) },
76
+ human: { title: `auto-distilled gene ${r.gene.id} (UNPROVEN — awaiting review)`, severity: 'info' },
77
+ actor: { kind: 'machine', id: 'distill-observer' },
78
+ });
79
+ audited.add(assetId);
80
+ }
81
+ review.quarantineIfAbsent(assetId);
82
+ const put = await c.store.put(r.gene);
83
+ if (put.stored)
84
+ drafted += 1;
85
+ }
86
+ catch {
87
+ return { ack: false, drafted }; // retryable persist/audit failure — do NOT ack
88
+ }
89
+ }
90
+ return { ack: true, drafted };
91
+ }
92
+ return async () => {
93
+ // Asset_ids already recorded as gene.distilled on the spine — the idempotency set that makes a retry never
94
+ // re-emit. Built once per drain (in-tick emits extend it); a fresh drain re-reads the now-durable event.
95
+ const audited = new Set(c.ingestor.readAll()
96
+ .filter((e) => e.type === 'gene.distilled')
97
+ .map((e) => String(e.payload?.['assetId'] ?? ''))
98
+ .filter(Boolean));
99
+ let totalDrafted = 0;
100
+ let stalled = false;
101
+ // Draft up to maxPerTick new genes, then stop. A remaining backlog OR a stuck head (a material whose write keeps
102
+ // failing, or a multi-session source that hit the rate cap mid-file) reports `stalled` so the observer
103
+ // self-schedules a backoff retry rather than waiting for a future material.batch_ready that may never come.
104
+ for (;;) {
105
+ const before = c.consumer.position(DISTILL_CONSUMER_GROUP);
106
+ const batch = c.consumer.claim(DISTILL_CONSUMER_GROUP, maxPerTick);
107
+ if (batch.length === 0)
108
+ break; // queue drained
109
+ const acked = [];
110
+ for (const m of batch) {
111
+ if (totalDrafted >= maxPerTick) {
112
+ stalled = true;
113
+ break;
114
+ }
115
+ const { ack, drafted } = await processOne(m, audited, maxPerTick - totalDrafted);
116
+ totalDrafted += drafted;
117
+ if (ack)
118
+ acked.push(m.materialId);
119
+ else {
120
+ stalled = true;
121
+ break;
122
+ }
123
+ }
124
+ c.consumer.ack(DISTILL_CONSUMER_GROUP, acked);
125
+ if (stalled || c.consumer.position(DISTILL_CONSUMER_GROUP) === before) {
126
+ stalled = true;
127
+ break;
128
+ } // stuck head → retry later
129
+ if (totalDrafted >= maxPerTick) {
130
+ stalled = c.consumer.claim(DISTILL_CONSUMER_GROUP, 1).length > 0;
131
+ break;
132
+ }
133
+ }
134
+ return { drafted: totalDrafted, stalled };
135
+ };
136
+ }
137
+ /** Compose the live distill observer from the daemon's material/store/ingestor — register the result on the bus.
138
+ * The observer only needs the `stalled` signal (to self-schedule a backoff retry); the drafted count is for the
139
+ * direct-drain tests / callers. */
140
+ export function resolveDistillObserver(c) {
141
+ const drain = makeDistillDrain(c);
142
+ return observers.distillObserver({
143
+ distill: async () => (await drain()).stalled,
144
+ ...(c.retryDelayMs !== undefined ? { retryDelayMs: c.retryDelayMs } : {}),
145
+ });
146
+ }
@@ -0,0 +1,48 @@
1
+ import type { signals, algo } from '@evomap/evolver-core';
2
+ import type { NormalizedTurn } from '@evomap/evolver-runtime-adapters';
3
+ /** Short matchable signal tokens from the STRONG signals only (toolName + a known error class). Every strong
4
+ * signal yields ≥1 token: if it has no toolName and matches no known error class (e.g. `FAILED: …` or
5
+ * `Error: connection refused`), it falls back to its kind (`structured_error`/`error_result`) so a real strong
6
+ * signal is never silently tokenless — keeping `signals_match.length === 0` an honest "no strong signal" gate.
7
+ * Deduped, ≤8. */
8
+ export declare function signalTokens(sigs: readonly signals.ExtractedSignal[]): string[];
9
+ /** Draft strategy steps = the agent's own substantive (non-meta) turns — boundary-trimmed (never chopped
10
+ * mid-word); turns that are PURELY narration ("let me look around" with no cause/action) are dropped, and a
11
+ * narration-opening turn that also states a cause/fix keeps that substance (its narration opener is stripped so
12
+ * the capped step leads with the fix). NOT fabricated: real transcript excerpts; the gene lands UNPROVEN and is
13
+ * curated by `review` + pruned by the cycle, so a noisy draft self-corrects. */
14
+ export declare function draftStrategy(turns: readonly NormalizedTurn[]): string[];
15
+ /**
16
+ * Assemble an UNPROVEN draft GeneCandidate from a parsed session, or null when too thin to distill (no strong
17
+ * signal OR no substantive step). The single source of the "what makes a draftable session" gate + candidate
18
+ * shape, shared by `evolver ingest --distill` and the distillObserver so the two never drift. `sigs` is passed in
19
+ * (already extracted by the caller) to avoid a second extraction pass.
20
+ */
21
+ export declare function draftGeneCandidate(turns: readonly NormalizedTurn[], sigs: readonly signals.ExtractedSignal[], agent: string): algo.GeneCandidate | null;
22
+ /** Minimal reference to an existing pool gene for the novelty check (id + its signals). */
23
+ export interface ExistingGeneSignals {
24
+ id?: string;
25
+ signals_match?: readonly string[];
26
+ }
27
+ export interface DraftAdmissionOptions {
28
+ /** Reject a draft with fewer matchable signals than this (default 2): a single generic signal is too broad. */
29
+ minSignals?: number;
30
+ /** Reject a draft with fewer strategy steps than this (default 1, i.e. just non-empty like intakeGene; raise it
31
+ * for a stricter substance floor). A real fix can be one concrete step, so the default does not over-filter. */
32
+ minStrategy?: number;
33
+ /** Reject a draft whose signal-set Jaccard similarity to ANY existing gene is >= this (default 0.8). */
34
+ maxSimilarity?: number;
35
+ }
36
+ export interface DraftAdmission {
37
+ admit: boolean;
38
+ reason?: string;
39
+ }
40
+ /**
41
+ * Value/novelty gate run BEFORE a draft is quarantined (#117 improvement 3). `intakeGene` already rejects
42
+ * empty/structurally-invalid candidates and EXACT signal subsets (fullyOverlaps), but two kinds of noise still
43
+ * reach the human review queue: drafts too thin to be worth reviewing (one weak signal, one vague step), and
44
+ * near-duplicates that escape the subset check by carrying one extra signal. Unattended auto-distill turns that
45
+ * trickle into a flood, and a review gate nobody reads is no gate. This adds a substance floor + a SOFT similarity
46
+ * reject. Pure and deterministic; the caller decides what to do with a non-admit (skip, never an error).
47
+ */
48
+ export declare function assessDraftAdmission(candidate: algo.GeneCandidate, existing?: readonly ExistingGeneSignals[], opts?: DraftAdmissionOptions): DraftAdmission;
@@ -0,0 +1,142 @@
1
+ // Map a strong signal's free-text to a SHORT, matchable token (so a gene's signals_match stays a few
2
+ // keywords, not a dumped error blob). Deterministic + testable; unknown errors fall back to the tool name only.
3
+ const SIGNAL_ERROR_CLASSES = [
4
+ [/exit code:?\s*[1-9]/i, 'exit-code'],
5
+ [/ENOENT|no such file|does not exist|cannot access|did not match/i, 'file-not-found'],
6
+ [/command not found/i, 'command-not-found'],
7
+ [/Traceback|Exception|panic:/i, 'exception'],
8
+ [/SyntaxError/i, 'syntax-error'],
9
+ [/permission denied/i, 'permission-denied'],
10
+ [/timed?\s?out/i, 'timeout'],
11
+ ];
12
+ /** Short matchable signal tokens from the STRONG signals only (toolName + a known error class). Every strong
13
+ * signal yields ≥1 token: if it has no toolName and matches no known error class (e.g. `FAILED: …` or
14
+ * `Error: connection refused`), it falls back to its kind (`structured_error`/`error_result`) so a real strong
15
+ * signal is never silently tokenless — keeping `signals_match.length === 0` an honest "no strong signal" gate.
16
+ * Deduped, ≤8. */
17
+ export function signalTokens(sigs) {
18
+ const set = new Set();
19
+ for (const s of sigs) {
20
+ if (s.strength !== 'strong')
21
+ continue;
22
+ let matched = false;
23
+ if (s.toolName) {
24
+ set.add(s.toolName);
25
+ matched = true;
26
+ }
27
+ for (const [re, tok] of SIGNAL_ERROR_CLASSES)
28
+ if (re.test(s.text)) {
29
+ set.add(tok);
30
+ matched = true;
31
+ break;
32
+ }
33
+ if (!matched)
34
+ set.add(s.kind);
35
+ }
36
+ return [...set].slice(0, 8);
37
+ }
38
+ /** Trim free text to a clean step: collapse whitespace, and when longer than `cap` keep as much as fits, cutting
39
+ * at the last word boundary within the cap (marked `…`) — never mid-word, and never shorter than the cap allows
40
+ * (an earlier sentence end is NOT preferred, so substance later in the turn is not dropped). */
41
+ function trimToBoundary(text, cap = 200) {
42
+ const t = text.replace(/\s+/g, ' ').trim();
43
+ if (t.length <= cap)
44
+ return t;
45
+ const slice = t.slice(0, cap);
46
+ const sp = slice.lastIndexOf(' ');
47
+ return `${(sp > 0 ? slice.slice(0, sp) : slice).trim()}…`;
48
+ }
49
+ /** Narration openers ("let me take a look / check / see …") — the agent saying it will go inspect. */
50
+ const NARRATION_OPENER = /^(let me (take a (closer )?)?look|let me (check|see|inspect|investigate)|i'?ll (take a look|check|look|see)|let'?s (take a )?(look|see)|now,? let me (look|check|see))\b/i;
51
+ /** Reusable substance: a named cause, a decision/action verb, or a concrete code target (path / `code`). A turn
52
+ * that opens with narration is dropped ONLY when it has none of these — so "let me check … the root cause is X,
53
+ * fix by Y" keeps its substantive remainder rather than being discarded for its opener. */
54
+ const HAS_SUBSTANCE = /\b(because|so that|root cause|the (issue|bug|problem|fix|error)|fix(ed|es|ing)?|add(ed|ing)?|remov(e|ed|ing)|delet(e|ed|ing)|chang(e|ed|ing)?|updat(e|ed|ing)?|replac(e|ed|ing)?|renam(e|ed|ing)?|implement(ed|ing)?|revert(ed)?|switch(ed|ing)?|configur(e|ed|ing)?|install(ed|ing)?|return(s|ed)?|throw(s|n)?|catch|wrap(ped)?|guard|import(ed|s)?|export(ed|s)?|re-?run|retry|set\s)\b/i;
55
+ function isNarrationOnly(raw) {
56
+ return NARRATION_OPENER.test(raw) && !HAS_SUBSTANCE.test(raw) && !/[`]|[\w/-]+\.[a-z]{2,5}\b|\/[\w./-]+/.test(raw);
57
+ }
58
+ /** When a turn opens with narration but states real substance, drop the leading narration sentence so the step
59
+ * LEADS with the cause/fix — otherwise the (capped) step could be narration while the substance is trimmed off.
60
+ * Keeps the original when there is no clean sentence split or the remainder is too thin to stand alone. */
61
+ function dropNarrationOpener(raw) {
62
+ if (!NARRATION_OPENER.test(raw))
63
+ return raw;
64
+ const m = /^.*?[.!?。]\s+/.exec(raw);
65
+ if (!m)
66
+ return raw;
67
+ const rest = raw.slice(m[0].length).trim();
68
+ return rest.length >= 40 ? rest : raw;
69
+ }
70
+ /** Draft strategy steps = the agent's own substantive (non-meta) turns — boundary-trimmed (never chopped
71
+ * mid-word); turns that are PURELY narration ("let me look around" with no cause/action) are dropped, and a
72
+ * narration-opening turn that also states a cause/fix keeps that substance (its narration opener is stripped so
73
+ * the capped step leads with the fix). NOT fabricated: real transcript excerpts; the gene lands UNPROVEN and is
74
+ * curated by `review` + pruned by the cycle, so a noisy draft self-corrects. */
75
+ export function draftStrategy(turns) {
76
+ const steps = [];
77
+ const seen = new Set();
78
+ for (const t of turns) {
79
+ if (t.role !== 'assistant' || t.isMeta)
80
+ continue;
81
+ const raw = (t.text ?? '').replace(/\s+/g, ' ').trim();
82
+ if (raw.length < 40)
83
+ continue; // too short to be a step
84
+ if (isNarrationOnly(raw))
85
+ continue; // "let me look around" with no cause/action — not a strategy
86
+ const step = trimToBoundary(dropNarrationOpener(raw));
87
+ if (seen.has(step))
88
+ continue;
89
+ seen.add(step);
90
+ steps.push(step);
91
+ }
92
+ return steps.slice(-6); // the latest substantive actions (closest to the resolution)
93
+ }
94
+ /**
95
+ * Assemble an UNPROVEN draft GeneCandidate from a parsed session, or null when too thin to distill (no strong
96
+ * signal OR no substantive step). The single source of the "what makes a draftable session" gate + candidate
97
+ * shape, shared by `evolver ingest --distill` and the distillObserver so the two never drift. `sigs` is passed in
98
+ * (already extracted by the caller) to avoid a second extraction pass.
99
+ */
100
+ export function draftGeneCandidate(turns, sigs, agent) {
101
+ const signals_match = signalTokens(sigs);
102
+ const strategy = draftStrategy(turns);
103
+ if (signals_match.length === 0 || strategy.length === 0)
104
+ return null;
105
+ return {
106
+ category: 'repair',
107
+ signals_match,
108
+ strategy,
109
+ summary: `Auto-drafted from ${agent} session (UNPROVEN — curate via review): ${signals_match.slice(0, 3).join(', ')}`,
110
+ };
111
+ }
112
+ /**
113
+ * Value/novelty gate run BEFORE a draft is quarantined (#117 improvement 3). `intakeGene` already rejects
114
+ * empty/structurally-invalid candidates and EXACT signal subsets (fullyOverlaps), but two kinds of noise still
115
+ * reach the human review queue: drafts too thin to be worth reviewing (one weak signal, one vague step), and
116
+ * near-duplicates that escape the subset check by carrying one extra signal. Unattended auto-distill turns that
117
+ * trickle into a flood, and a review gate nobody reads is no gate. This adds a substance floor + a SOFT similarity
118
+ * reject. Pure and deterministic; the caller decides what to do with a non-admit (skip, never an error).
119
+ */
120
+ export function assessDraftAdmission(candidate, existing = [], opts = {}) {
121
+ const minSignals = opts.minSignals ?? 2;
122
+ const minStrategy = opts.minStrategy ?? 1;
123
+ const maxSimilarity = opts.maxSimilarity ?? 0.8;
124
+ const sigs = [...new Set((candidate.signals_match ?? []).map((s) => String(s).toLowerCase()).filter(Boolean))];
125
+ const strategy = (candidate.strategy ?? []).filter((s) => String(s).trim());
126
+ if (sigs.length < minSignals)
127
+ return { admit: false, reason: `too few signals (${sigs.length} < ${minSignals})` };
128
+ if (strategy.length < minStrategy)
129
+ return { admit: false, reason: `strategy too thin (${strategy.length} < ${minStrategy} steps)` };
130
+ const newSet = new Set(sigs);
131
+ for (const eg of existing) {
132
+ const egSet = new Set((eg.signals_match ?? []).map((s) => String(s).toLowerCase()).filter(Boolean));
133
+ if (egSet.size === 0)
134
+ continue;
135
+ const inter = [...newSet].filter((s) => egSet.has(s)).length;
136
+ const union = new Set([...newSet, ...egSet]).size;
137
+ const jaccard = union ? inter / union : 0;
138
+ if (jaccard >= maxSimilarity)
139
+ return { admit: false, reason: `near-duplicate of ${eg.id ?? '?'} (similarity ${jaccard.toFixed(2)})` };
140
+ }
141
+ return { admit: true };
142
+ }
@@ -0,0 +1,54 @@
1
+ type DoctorStatus = 'pass' | 'warn' | 'fail';
2
+ export interface DoctorCheck {
3
+ name: string;
4
+ status: DoctorStatus;
5
+ detail: string;
6
+ }
7
+ type DoctorProfile = 'general' | 'private-runtime';
8
+ type EnvCatalogState = 'set' | 'empty' | 'unset';
9
+ export interface EnvCatalogEntry {
10
+ name: string;
11
+ group: string;
12
+ purpose: string;
13
+ requiredFor?: string;
14
+ defaultValue?: string;
15
+ aliases?: string[];
16
+ secret: boolean;
17
+ state: EnvCatalogState;
18
+ sources: string[];
19
+ setKeys: string[];
20
+ }
21
+ type EnvFileReadiness = {
22
+ status: 'missing_pointer';
23
+ } | {
24
+ status: 'readable';
25
+ } | {
26
+ status: 'unusable';
27
+ detail: string;
28
+ };
29
+ /** Mask token-like runs (>=16 chars of base64/hex/url-safe) so doctor output can never leak a secret value. */
30
+ export declare function redact(s: string): string;
31
+ export interface DoctorDeps {
32
+ env?: Record<string, string | undefined>;
33
+ configRoot?: string;
34
+ readFile?: (p: string) => string;
35
+ exists?: (p: string) => boolean;
36
+ statMode?: (p: string) => number | undefined;
37
+ profile?: DoctorProfile;
38
+ label?: string;
39
+ }
40
+ export interface EnvCatalogResult {
41
+ profile: DoctorProfile;
42
+ envFile: EnvFileReadiness;
43
+ entries: EnvCatalogEntry[];
44
+ }
45
+ /**
46
+ * Run the read-only doctor checks. Pure given its (injectable) deps — no config mutation, no env-file load into the
47
+ * process. Returns the check list; the CLI formats + sets the exit code.
48
+ */
49
+ export declare function runDoctorChecks(deps?: DoctorDeps): DoctorCheck[];
50
+ export declare function buildEnvCatalog(deps?: DoctorDeps): EnvCatalogResult;
51
+ export declare function runDoctor(argv: readonly string[], deps?: DoctorDeps): Promise<number>;
52
+ /** Registry-shaped handler (argv -> exit code). */
53
+ export declare const runDoctorCommand: (argv: string[]) => Promise<number>;
54
+ export {};