@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,87 @@
1
+ import { algo, assetstore, events, signals } from '@evomap/evolver-core';
2
+ import { type LlmDistillRunner } from './autoDistillLlm.js';
3
+ export type AutoDistillTranscriptMode = 'off' | 'shadow' | 'enforce';
4
+ export type AutoDistillTranscriptResult = {
5
+ ok: true;
6
+ mode: 'enforce';
7
+ gene: assetstore.AssetRecord;
8
+ stored: boolean;
9
+ } | {
10
+ ok: false;
11
+ mode: AutoDistillTranscriptMode;
12
+ reason: string;
13
+ candidate?: algo.GeneCandidate;
14
+ };
15
+ export interface AutoDistillTranscriptOptions {
16
+ /** The parsed session turns (from a runtime adapter). The gate + prompt read these; never the raw file. */
17
+ turns: readonly signals.SignalSourceTurn[];
18
+ store: assetstore.AssetStoreProvider;
19
+ review?: assetstore.ReviewLedger;
20
+ ingestor?: events.Ingestor;
21
+ mode?: AutoDistillTranscriptMode;
22
+ env?: NodeJS.ProcessEnv;
23
+ cwd?: string;
24
+ /** Test seam: inject a fake LLM runner so the path is deterministic without spawning a real agent. */
25
+ runner?: LlmDistillRunner;
26
+ timeoutMs?: number;
27
+ validationTimeoutMs?: number;
28
+ /** A short, non-secret label for the gene.distilled event (e.g. the session basename). */
29
+ sourceLabel?: string;
30
+ }
31
+ export interface TranscriptDistillGateOptions {
32
+ /** Min non-meta turns with text for the session to be worth an LLM call. */
33
+ minTurns?: number;
34
+ /** Min total prose characters across turns. */
35
+ minChars?: number;
36
+ }
37
+ export interface TranscriptDistillVerdict {
38
+ distill: boolean;
39
+ reason: string;
40
+ }
41
+ /** The resolved mode (off|shadow|enforce) — the daemon wiring reads this to decide whether to build the producer. */
42
+ export declare function transcriptDistillMode(env?: NodeJS.ProcessEnv): AutoDistillTranscriptMode;
43
+ /**
44
+ * Pure gate: should this session go to the LLM-over-transcript path? YES only when it is prose-rich enough to be
45
+ * worth an LLM call AND the structural extractor found NO strong/agent signal (a strong signal means the fast
46
+ * structural distill already handles it — do not double-spend an LLM). A weak `difficulty` signal does not block:
47
+ * weak is exactly what the structural path drops, so the LLM is the intended fallback for it.
48
+ */
49
+ export declare function shouldTranscriptDistill(turns: readonly signals.SignalSourceTurn[], opts?: TranscriptDistillGateOptions): TranscriptDistillVerdict;
50
+ /** Build the LLM prompt from the session's prose. Redacted + capped (off-box egress). Mirrors the Gene JSON shape
51
+ * the autoDistillLlm path uses so parseDistillOutput/asGeneCandidate handle the response unchanged. */
52
+ export declare function buildTranscriptDistillPrompt(turns: readonly signals.SignalSourceTurn[]): string;
53
+ /**
54
+ * Run the LLM-over-transcript distill for ONE session. Default OFF. Gated by shouldTranscriptDistill. The output
55
+ * gene is QUARANTINED (review/probation decides), never auto-trusted. Best-effort and side-effect-safe; persistent
56
+ * per-session idempotency is the producer's job (#319 slice 2), so this is single-shot.
57
+ */
58
+ export declare function autoDistillTranscript(options: AutoDistillTranscriptOptions): Promise<AutoDistillTranscriptResult>;
59
+ export declare function autoDistillTranscriptStatePath(home?: string): string;
60
+ export interface TranscriptDistillTickDeps {
61
+ /** Candidate session files (the resolver supplies scanSessionDirs(...) output). */
62
+ files: readonly string[];
63
+ store: assetstore.AssetStoreProvider;
64
+ review?: assetstore.ReviewLedger;
65
+ ingestor?: events.Ingestor;
66
+ env?: NodeJS.ProcessEnv;
67
+ runner?: LlmDistillRunner;
68
+ cwd?: string;
69
+ statePath?: string;
70
+ now?: () => number;
71
+ maxPerTick?: number;
72
+ /** Test seam: read a session file. Default readFileSync utf8. */
73
+ readFile?: (path: string) => string;
74
+ }
75
+ export interface TranscriptDistillTickResult {
76
+ scanned: number;
77
+ distilled: number;
78
+ shadowed: number;
79
+ skipped: number;
80
+ transient: number;
81
+ }
82
+ /**
83
+ * One idle-beat pass: scan candidate session files, gate (prose-rich + weak/zero structural signal), apply
84
+ * per-session dedup/cooldown (p3Decide), and LLM-distill up to maxPerTick of the survivors. Default OFF. Bounds
85
+ * LLM spend by the per-tick cap + per-session state. Best-effort: a bad file never breaks the scan.
86
+ */
87
+ export declare function runTranscriptDistillTick(deps: TranscriptDistillTickDeps): Promise<TranscriptDistillTickResult>;
@@ -0,0 +1,364 @@
1
+ // LLM-over-transcript distillation (#319) — the counterpart to the capsule-based autoDistillLlm. Some runtimes
2
+ // (cursor especially) write PROSE-RICH but tool-result-POOR transcripts: the agent narrates "root cause … fix …
3
+ // verified" but emits no tool_result/error turns, so the structural signal extractor (extractor.ts) finds only a
4
+ // weak/zero signal and the fast structural distill never drafts a gene. An LLM can READ that narration and
5
+ // synthesize a reusable gene where keyword matching cannot. This module is that path: it runs an LLM over a single
6
+ // session's transcript text and produces a QUARANTINED gene draft (A2a-safe).
7
+ //
8
+ // Boundaries (zero blast to the proven paths): it does NOT touch extractor.ts (claude/codex keep their fast
9
+ // structural path) and does NOT touch autoDistillLlm (the capsule meta-distill). It only ADDS an LLM bypass for
10
+ // prose-rich sessions whose structural signal is weak/zero. Default OFF; output is quarantined; the transcript is
11
+ // an off-box egress, so the same reverse env-value leak block the publish/LLM-distill paths use guards it.
12
+ import { createHash } from 'node:crypto';
13
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
14
+ import { basename, dirname, join } from 'node:path';
15
+ import { algo, assetstore, events, hub, verify, signals } from '@evomap/evolver-core';
16
+ import { adapterForPath } from '@evomap/evolver-runtime-adapters';
17
+ import { asGeneCandidate, parseDistillOutput, normalizeValidation, jaccardDuplicate, resolveDistillRunner, p3Decide, } from './autoDistillLlm.js';
18
+ const DEFAULT_MIN_TURNS = 2;
19
+ const DEFAULT_MIN_CHARS = 200;
20
+ const DEFAULT_TIMEOUT_MS = 180_000;
21
+ const DEFAULT_VALIDATION_TIMEOUT_MS = 20_000;
22
+ const TRANSCRIPT_CHAR_CAP = 24_000; // bound the off-box prompt; narration beyond this rarely adds reusable signal
23
+ function resolveMode(env, explicit) {
24
+ const raw = String(explicit ?? env['EVOLVER_AUTO_DISTILL_TRANSCRIPT'] ?? 'off').trim().toLowerCase();
25
+ return raw === 'shadow' || raw === 'enforce' ? raw : 'off';
26
+ }
27
+ /** The resolved mode (off|shadow|enforce) — the daemon wiring reads this to decide whether to build the producer. */
28
+ export function transcriptDistillMode(env = process.env) {
29
+ return resolveMode(env);
30
+ }
31
+ /** Positive-int env read (fallback otherwise), so this path honors the SAME distill timeout knobs as autoDistillLlm. */
32
+ function envInt(env, name, fallback) {
33
+ const n = Number.parseInt(String(env[name] ?? ''), 10);
34
+ return Number.isFinite(n) && n > 0 ? n : fallback;
35
+ }
36
+ function proseText(turns) {
37
+ return turns.filter((t) => !t.isMeta && typeof t.text === 'string' && t.text.trim()).map((t) => String(t.text)).join('\n');
38
+ }
39
+ /**
40
+ * Pure gate: should this session go to the LLM-over-transcript path? YES only when it is prose-rich enough to be
41
+ * worth an LLM call AND the structural extractor found NO strong/agent signal (a strong signal means the fast
42
+ * structural distill already handles it — do not double-spend an LLM). A weak `difficulty` signal does not block:
43
+ * weak is exactly what the structural path drops, so the LLM is the intended fallback for it.
44
+ */
45
+ export function shouldTranscriptDistill(turns, opts = {}) {
46
+ const minTurns = opts.minTurns ?? DEFAULT_MIN_TURNS;
47
+ const minChars = opts.minChars ?? DEFAULT_MIN_CHARS;
48
+ const textTurns = turns.filter((t) => !t.isMeta && typeof t.text === 'string' && t.text.trim());
49
+ const chars = textTurns.reduce((n, t) => n + String(t.text).length, 0);
50
+ if (textTurns.length < minTurns || chars < minChars)
51
+ return { distill: false, reason: 'insufficient_substance' };
52
+ const sig = signals.extractSignals(turns);
53
+ if (sig.some((s) => s.strength === 'strong' || s.strength === 'agent'))
54
+ return { distill: false, reason: 'structural_signal_present' };
55
+ return { distill: true, reason: 'prose_rich_weak_or_zero_signal' };
56
+ }
57
+ /** Build the LLM prompt from the session's prose. Redacted + capped (off-box egress). Mirrors the Gene JSON shape
58
+ * the autoDistillLlm path uses so parseDistillOutput/asGeneCandidate handle the response unchanged. */
59
+ export function buildTranscriptDistillPrompt(turns) {
60
+ const redacted = hub.redactString(proseText(turns)).slice(0, TRANSCRIPT_CHAR_CAP);
61
+ return [
62
+ 'You are synthesizing ONE high-quality reusable EvoMap Gene from a single coding session transcript.',
63
+ 'The transcript narrates a problem the agent solved. Capture the GENERAL, reusable lesson — not one-off file names or secrets.',
64
+ 'Return only JSON. Do not use markdown. Do not include commentary.',
65
+ '',
66
+ 'If the transcript contains NO concrete, reusable engineering lesson — e.g. it is only orientation/exploration/',
67
+ 'chatter, asks for clarification, or solved nothing — return exactly {"type":"none"} and nothing else. Do NOT',
68
+ 'manufacture a vague process or meta lesson just to return a gene.',
69
+ '',
70
+ 'Otherwise produce a Gene:',
71
+ '- Produce a single Gene object.',
72
+ '- signals_match: the generic problem signals this gene applies to (not file names).',
73
+ '- strategy: concrete, defensive, reusable steps.',
74
+ '- Validation must be light. Prefer ["node --version"]. Do not use test suites, node --test, jest, mocha, or node -e.',
75
+ '',
76
+ 'Required JSON shape:',
77
+ '{"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"]}',
78
+ '',
79
+ 'SESSION_TRANSCRIPT:',
80
+ redacted,
81
+ ].join('\n');
82
+ }
83
+ function existingGeneRefs(records) {
84
+ return records.map((r) => ({
85
+ id: typeof r['id'] === 'string' ? r['id'] : undefined,
86
+ signals_match: Array.isArray(r['signals_match']) ? r['signals_match'].map(String).filter(Boolean) : [],
87
+ }));
88
+ }
89
+ /** Emit gene.distilled ONCE per (assetId, source): a re-run / duplicate-content put must not re-emit (mirrors
90
+ * autoDistillLlm.emitDistilledEventIfAbsent), so the event rail stays idempotent even when store.put is a no-op. */
91
+ async function emitDistilledEventIfAbsent(ingestor, gene, sourceLabel) {
92
+ if (!ingestor)
93
+ return;
94
+ const assetId = gene.asset_id;
95
+ const exists = ingestor.readAll().some((e) => {
96
+ const p = e.payload;
97
+ return e.type === 'gene.distilled' && p?.['assetId'] === assetId && p?.['source'] === 'auto-distill-transcript';
98
+ });
99
+ if (exists)
100
+ return;
101
+ await ingestor.ingest({
102
+ type: 'gene.distilled',
103
+ payload: { geneId: gene['id'], assetId, source: 'auto-distill-transcript', ...(sourceLabel ? { sourceLabel } : {}) },
104
+ human: { title: `transcript-distilled gene ${String(gene['id'] ?? assetId)}`, severity: 'info' },
105
+ actor: { kind: 'machine', id: 'auto-distill-transcript' },
106
+ });
107
+ }
108
+ /** Shadow observability (A1): shadow mode computes a candidate but stores nothing, so without this the operator
109
+ * has no way to judge what enforce mode WOULD distill. Emit ONE gene.distill_shadowed per (content hash, source)
110
+ * carrying the candidate's summary + signals (no strategy body — keep the event light). Idempotent: a re-scan of
111
+ * the same session never re-emits. */
112
+ async function emitShadowObservationIfAbsent(ingestor, sourceLabel, contentHash, candidate) {
113
+ if (!ingestor || !candidate)
114
+ return;
115
+ const exists = ingestor.readAll().some((e) => {
116
+ const p = e.payload;
117
+ return e.type === 'gene.distill_shadowed' && p?.['contentHash'] === contentHash && p?.['source'] === 'auto-distill-transcript';
118
+ });
119
+ if (exists)
120
+ return;
121
+ await ingestor.ingest({
122
+ type: 'gene.distill_shadowed',
123
+ payload: { contentHash, source: 'auto-distill-transcript', sourceLabel, summary: candidate.summary ?? '', signals_match: [...(candidate.signals_match ?? [])] },
124
+ human: { title: `shadow transcript-distill candidate (${sourceLabel})`, severity: 'info' },
125
+ actor: { kind: 'machine', id: 'auto-distill-transcript' },
126
+ });
127
+ }
128
+ /**
129
+ * Run the LLM-over-transcript distill for ONE session. Default OFF. Gated by shouldTranscriptDistill. The output
130
+ * gene is QUARANTINED (review/probation decides), never auto-trusted. Best-effort and side-effect-safe; persistent
131
+ * per-session idempotency is the producer's job (#319 slice 2), so this is single-shot.
132
+ */
133
+ export async function autoDistillTranscript(options) {
134
+ const env = options.env ?? process.env;
135
+ const mode = resolveMode(env, options.mode);
136
+ if (mode === 'off')
137
+ return { ok: false, mode, reason: 'disabled' };
138
+ const gate = shouldTranscriptDistill(options.turns);
139
+ if (!gate.distill)
140
+ return { ok: false, mode, reason: gate.reason };
141
+ const cwd = options.cwd ?? process.cwd();
142
+ const prompt = buildTranscriptDistillPrompt(options.turns);
143
+ // Off-box egress (stdin to a spawned LLM): hold it to the publish-path floor — a reverse env-value scan that
144
+ // flags any process-env secret appearing verbatim, catching custom-format secrets no pattern matches. Fail CLOSED.
145
+ if (hub.detectEnvValueLeaks(prompt, env).length > 0)
146
+ return { ok: false, mode, reason: 'prompt_env_leak_blocked' };
147
+ const runner = options.runner ?? resolveDistillRunner(env);
148
+ const timeoutMs = options.timeoutMs ?? envInt(env, 'EVOLVE_DISTILL_TIMEOUT_MS', DEFAULT_TIMEOUT_MS);
149
+ const llm = await runner(prompt, { cwd, timeoutMs, env });
150
+ if (llm.exitCode !== 0)
151
+ return { ok: false, mode, reason: llm.exitCode === null ? 'llm_spawn_error' : 'llm_nonzero_exit' };
152
+ const parsed = parseDistillOutput(llm.stdout);
153
+ // The LLM's explicit decline ({"type":"none"}): the session had no reusable lesson, so do NOT manufacture a
154
+ // vague process/meta gene (the trial showed an LLM will otherwise always invent one, polluting the pool).
155
+ if (parsed && typeof parsed === 'object' && parsed['type'] === 'none') {
156
+ return { ok: false, mode, reason: 'no_reusable_lesson' };
157
+ }
158
+ const candidate0 = asGeneCandidate(parsed);
159
+ if (!candidate0)
160
+ return { ok: false, mode, reason: 'no_gene_in_response' };
161
+ const existing = existingGeneRefs(await options.store.list('Gene', 10_000));
162
+ const normalized = normalizeValidation(candidate0, cwd).candidate;
163
+ // Near-duplicate guard (mirrors autoDistillLlm): intakeGene only rejects when an existing gene's signals are a
164
+ // SUPERSET of the candidate's, so a highly-similar but non-subset signal set would otherwise slip through and
165
+ // emit a redundant gene.distilled. Jaccard catches those before intake.
166
+ const duplicate = jaccardDuplicate(normalized, existing);
167
+ if (duplicate)
168
+ return { ok: false, mode, reason: 'near_duplicate', candidate: normalized };
169
+ const intake = algo.intakeGene(normalized, existing);
170
+ if (!intake.ok || !intake.gene)
171
+ return { ok: false, mode, reason: 'validation_failed', candidate: normalized };
172
+ const validation = await verify.runSandboxedValidation(intake.gene.validation, cwd, {
173
+ timeoutMs: options.validationTimeoutMs ?? envInt(env, 'EVOLVE_DISTILL_VALIDATION_TIMEOUT_MS', DEFAULT_VALIDATION_TIMEOUT_MS),
174
+ });
175
+ if (!validation.passed)
176
+ return { ok: false, mode, reason: 'light_validation_failed', candidate: normalized };
177
+ if (mode === 'shadow')
178
+ return { ok: false, mode, reason: 'shadow_logged', candidate: normalized };
179
+ const gene = intake.gene;
180
+ // Order mirrors autoDistillLlm: emit + quarantine BEFORE store.put, so the LAST step is the store. A throw after a
181
+ // successful put would leave a stored gene the producer never marks enforced (it treats the throw as transient) and
182
+ // re-distill the same content every beat. With store.put last, a throw can only happen before anything is stored,
183
+ // so a transient retry is correct; both emit and quarantine are idempotent if a later step fails and we retry.
184
+ await emitDistilledEventIfAbsent(options.ingestor, gene, options.sourceLabel);
185
+ options.review?.quarantineIfAbsent(gene.asset_id, 'transcript LLM-distilled — review before use'); // A2a: never auto-trusted
186
+ const put = await options.store.put(gene);
187
+ return { ok: true, mode, gene, stored: put.stored };
188
+ }
189
+ const TSTATE_CAP = 64;
190
+ const DEFAULT_TCOOLDOWN_MS = 1_800_000; // 30 min between retries of a bad-result session
191
+ const DEFAULT_TMAX_ATTEMPTS = 3;
192
+ const DEFAULT_MAX_PER_TICK = 3; // cap LLM calls per idle beat (cost)
193
+ // Transient outcomes do NOT count toward failed_attempts (mirror autoDistillLlm): an env hiccup must not exhaust a
194
+ // session. A leak-block is a data-hygiene stop, also not a deterministic LLM failure. Everything else deterministic.
195
+ const TRANSIENT_REASONS = new Set(['llm_spawn_error', 'llm_nonzero_exit', 'prompt_env_leak_blocked']);
196
+ // The LLM's explicit "no reusable lesson" decline is a TERMINAL decision for this session — mark it resolved so it
197
+ // is never re-asked (treated like enforced: decided, no gene needed).
198
+ const RESOLVED_REASONS = new Set(['no_reusable_lesson']);
199
+ export function autoDistillTranscriptStatePath(home = events.evomapHome()) {
200
+ return join(home, 'evolution', 'auto-distill-transcript-state.json');
201
+ }
202
+ function readTState(path) {
203
+ if (!existsSync(path))
204
+ return { version: 1, by_hash: {} };
205
+ try {
206
+ const parsed = JSON.parse(readFileSync(path, 'utf8'));
207
+ return { version: 1, by_hash: parsed.by_hash && typeof parsed.by_hash === 'object' ? parsed.by_hash : {} };
208
+ }
209
+ catch {
210
+ return { version: 1, by_hash: {} };
211
+ }
212
+ }
213
+ function patchTState(path, hash, patch, cap = TSTATE_CAP) {
214
+ try {
215
+ const state = readTState(path);
216
+ const cur = state.by_hash[hash] ?? { shadowed_at: null, enforced_at: null, enforced_gene_id: null, failed_attempts: 0, last_attempt_at: null };
217
+ const next = { ...cur, ...patch };
218
+ if (patch.failed_attempts_inc)
219
+ next.failed_attempts = (cur.failed_attempts ?? 0) + 1;
220
+ delete next.failed_attempts_inc;
221
+ state.by_hash[hash] = next;
222
+ // Cap eviction (mirrors autoDistillLlm.capByHash): evict NON-terminal rows (in-progress / retryable) oldest-first,
223
+ // and only touch terminal rows (enforced_at = distilled/declined, shadowed_at = shadow-logged) if still over cap.
224
+ // Otherwise a finished session could be dropped and re-distilled though its transcript is unchanged (Bugbot Low).
225
+ const keys = Object.keys(state.by_hash);
226
+ if (keys.length > cap) {
227
+ const age = (k) => Date.parse(state.by_hash[k]?.last_attempt_at ?? '') || 0;
228
+ const terminal = (k) => Boolean(state.by_hash[k]?.enforced_at || state.by_hash[k]?.shadowed_at);
229
+ const order = [
230
+ ...keys.filter((k) => !terminal(k)).sort((a, b) => age(a) - age(b)),
231
+ ...keys.filter((k) => terminal(k)).sort((a, b) => age(a) - age(b)),
232
+ ];
233
+ for (const k of order) {
234
+ if (Object.keys(state.by_hash).length <= cap)
235
+ break;
236
+ delete state.by_hash[k];
237
+ }
238
+ }
239
+ mkdirSync(dirname(path), { recursive: true });
240
+ const tmp = `${path}.${process.pid}.${Date.now()}.tmp`;
241
+ writeFileSync(tmp, `${JSON.stringify(state, null, 2)}\n`);
242
+ renameSync(tmp, path);
243
+ return true;
244
+ }
245
+ catch {
246
+ return false;
247
+ }
248
+ }
249
+ /**
250
+ * One idle-beat pass: scan candidate session files, gate (prose-rich + weak/zero structural signal), apply
251
+ * per-session dedup/cooldown (p3Decide), and LLM-distill up to maxPerTick of the survivors. Default OFF. Bounds
252
+ * LLM spend by the per-tick cap + per-session state. Best-effort: a bad file never breaks the scan.
253
+ */
254
+ export async function runTranscriptDistillTick(deps) {
255
+ const env = deps.env ?? process.env;
256
+ const mode = resolveMode(env);
257
+ const out = { scanned: 0, distilled: 0, shadowed: 0, skipped: 0, transient: 0 };
258
+ if (mode === 'off')
259
+ return out;
260
+ const readFile = deps.readFile ?? ((p) => readFileSync(p, 'utf8'));
261
+ const statePath = deps.statePath ?? autoDistillTranscriptStatePath();
262
+ const now = deps.now ?? (() => Date.now());
263
+ const maxPerTick = deps.maxPerTick ?? envInt(env, 'EVOLVER_AUTO_DISTILL_TRANSCRIPT_MAX_PER_TICK', DEFAULT_MAX_PER_TICK);
264
+ const cooldownMs = envInt(env, 'EVOLVER_AUTO_DISTILL_TRANSCRIPT_COOLDOWN_MS', DEFAULT_TCOOLDOWN_MS);
265
+ const maxAttempts = envInt(env, 'EVOLVER_AUTO_DISTILL_TRANSCRIPT_MAX_ATTEMPTS', DEFAULT_TMAX_ATTEMPTS);
266
+ const stateCap = envInt(env, 'EVOLVER_AUTO_DISTILL_TRANSCRIPT_STATE_CAP', TSTATE_CAP);
267
+ const tpatch = (hash, patch) => patchTState(statePath, hash, patch, stateCap);
268
+ let spawned = 0;
269
+ const seenThisTick = new Set(); // dedup identical-content files within ONE beat (state only dedups ACROSS beats)
270
+ for (const file of deps.files) {
271
+ if (spawned >= maxPerTick)
272
+ break;
273
+ const adapter = adapterForPath(file);
274
+ if (!adapter)
275
+ continue;
276
+ let turns;
277
+ let content;
278
+ try {
279
+ content = readFile(file);
280
+ turns = adapter.parse(content);
281
+ }
282
+ catch {
283
+ continue;
284
+ } // unreadable/unparseable → skip
285
+ out.scanned += 1;
286
+ if (!shouldTranscriptDistill(turns).distill) {
287
+ out.skipped += 1;
288
+ continue;
289
+ } // structural path / too thin
290
+ const hash = createHash('sha256').update(content).digest('hex');
291
+ // Same transcript bytes already attempted THIS beat (duplicate file): skip so identical content cannot consume
292
+ // multiple maxPerTick LLM slots in one tick — the first attempt's state decides it for subsequent beats.
293
+ if (seenThisTick.has(hash)) {
294
+ out.skipped += 1;
295
+ continue;
296
+ }
297
+ seenThisTick.add(hash);
298
+ const state = readTState(statePath);
299
+ if (p3Decide(mode, state.by_hash[hash], now(), { cooldownMs, maxAttempts }) !== 'spawn') {
300
+ out.skipped += 1;
301
+ continue;
302
+ }
303
+ // Pre-attempt state write MUST persist before spending an LLM call: without durable last_attempt_at there is
304
+ // no dedup, so the same session would be re-distilled every tick. If the write fails, skip (don't spawn).
305
+ if (!tpatch(hash, { last_attempt_at: new Date(now()).toISOString() })) {
306
+ out.skipped += 1;
307
+ continue;
308
+ }
309
+ spawned += 1;
310
+ let r;
311
+ // Best-effort scan: a store/validation/ingest throw on ONE session must not abort the whole idle tick (mirrors
312
+ // runSessionIngestTick's per-file guard). A throw is environmental → treat as transient (retry next tick).
313
+ try {
314
+ r = await autoDistillTranscript({
315
+ turns, store: deps.store, env, mode, sourceLabel: basename(file),
316
+ ...(deps.review ? { review: deps.review } : {}), ...(deps.ingestor ? { ingestor: deps.ingestor } : {}),
317
+ ...(deps.runner ? { runner: deps.runner } : {}), ...(deps.cwd ? { cwd: deps.cwd } : {}),
318
+ });
319
+ }
320
+ catch {
321
+ out.transient += 1;
322
+ continue;
323
+ }
324
+ if (r.ok) {
325
+ tpatch(hash, { enforced_at: new Date(now()).toISOString(), enforced_gene_id: String(r.gene['id'] ?? '') });
326
+ out.distilled += 1;
327
+ }
328
+ else if (r.reason === 'shadow_logged') {
329
+ // Shadow stores nothing, so this event is the ONLY artifact of what enforce mode WOULD distill (A1 probation).
330
+ // Mirror the enforce path's "durable artifact before completion state": emit BEFORE writing shadowed_at. If the
331
+ // state were written first, a failed/throwing emit would mark the session shadow-complete (p3Decide skips it
332
+ // forever) with no event ever produced, while `shadowed` over-counts. On emit failure, treat as transient and
333
+ // retry next tick, so the count and the emitted events stay exactly in step. The emit is idempotent per hash,
334
+ // so a retry after a partial failure never double-emits.
335
+ try {
336
+ await emitShadowObservationIfAbsent(deps.ingestor, basename(file), hash, r.candidate);
337
+ }
338
+ catch {
339
+ out.transient += 1;
340
+ continue;
341
+ }
342
+ tpatch(hash, { shadowed_at: new Date(now()).toISOString() });
343
+ out.shadowed += 1;
344
+ }
345
+ else if (RESOLVED_REASONS.has(r.reason)) {
346
+ tpatch(hash, { enforced_at: new Date(now()).toISOString() }); // LLM declined → resolved, never re-ask
347
+ out.skipped += 1;
348
+ }
349
+ else if (TRANSIENT_REASONS.has(r.reason)) {
350
+ out.transient += 1; // no state change → retry next tick
351
+ }
352
+ else if (tpatch(hash, { failed_attempts_inc: true })) {
353
+ out.skipped += 1; // deterministic bad result, increment persisted → toward exhaust + cooldown
354
+ }
355
+ else {
356
+ // The attempt increment did not persist; without it p3Decide never advances toward failed_exhausted, so this
357
+ // is a (transient) state-write failure, not a counted attempt. Classify as transient: retry next beat rather
358
+ // than silently treating the unpersisted failure as handled. The pre-attempt write guard already stops us
359
+ // from spending an LLM call when state cannot be written at all.
360
+ out.transient += 1;
361
+ }
362
+ }
363
+ return out;
364
+ }
@@ -0,0 +1,25 @@
1
+ import { events, ops, assetstore } from '@evomap/evolver-core';
2
+ export interface AutoRecallDeps {
3
+ /** Read root_events (to find the session's value.inject + the idempotency marker). Default: live root log. */
4
+ readEvents?: (eventsPath?: string) => events.ReportEvent[];
5
+ /** Resolve injected geneIds to Gene records. Default: live local store. */
6
+ store?: Pick<assetstore.AssetStoreProvider, 'get' | 'list'>;
7
+ /** Sink for the emitted `value.recall` events. */
8
+ ingestor: {
9
+ ingest(raw: {
10
+ type: string;
11
+ human: {
12
+ title: string;
13
+ detail?: string;
14
+ };
15
+ payload?: Record<string, unknown>;
16
+ }): Promise<unknown>;
17
+ };
18
+ }
19
+ /**
20
+ * Derive + emit `value.recall` for ONE session transcript. Returns the number of verdicts emitted (0 when there is
21
+ * no matching inject, no resolvable gene, or the session was already recalled). Idempotent: a session whose
22
+ * `value.recall` already exists is skipped, so a polling daemon never re-emits. Best-effort: any failure → 0, never
23
+ * throws (session ingest must not break on a recall side-effect).
24
+ */
25
+ export declare function emitSessionRecall(transcriptPath: string, turns: readonly ops.RecallTurn[], deps: AutoRecallDeps): Promise<number>;
@@ -0,0 +1,80 @@
1
+ // Auto-recall observation (#274) — derive a session's recall verdicts from its TRANSCRIPT, not from an agent
2
+ // self-reporting via a tool it will skip. For a session that had a `value.inject` (tied by #205 sessionId), run
3
+ // the recallVerifier over the transcript turns and emit one `value.recall` per injected gene (used/unused/unknown).
4
+ // This feeds the experience loop with OBSERVED data, turning the inert manual `evolver recall` into the loop's
5
+ // real, unbiased input. PURE-ish + injectable; best-effort + never throws (it must never break session ingest).
6
+ import { events, ops, assetstore } from '@evomap/evolver-core';
7
+ import { sessionIdFromTranscript, pickInjectEvent, geneIdsOf, geneFromAsset, resolveGene } from './recall.js';
8
+ /**
9
+ * Derive + emit `value.recall` for ONE session transcript. Returns the number of verdicts emitted (0 when there is
10
+ * no matching inject, no resolvable gene, or the session was already recalled). Idempotent: a session whose
11
+ * `value.recall` already exists is skipped, so a polling daemon never re-emits. Best-effort: any failure → 0, never
12
+ * throws (session ingest must not break on a recall side-effect).
13
+ */
14
+ export async function emitSessionRecall(transcriptPath, turns, deps) {
15
+ try {
16
+ if (turns.length === 0)
17
+ return 0;
18
+ const sessionId = sessionIdFromTranscript(transcriptPath);
19
+ if (!sessionId)
20
+ return 0; // no stable session key → cannot dedup safely → skip (never risk re-emitting)
21
+ const read = deps.readEvents ?? events.readEvents;
22
+ const evts = read();
23
+ const inject = pickInjectEvent(evts, sessionId);
24
+ // Only auto-recall when the inject is PROVABLY this session's (#205 stamped match). Without a stamped match we
25
+ // would be guessing which inject produced this transcript — too weak a basis to emit observed verdicts.
26
+ if (!inject || inject.payload?.['sessionId'] !== sessionId)
27
+ return 0;
28
+ const geneIds = [...new Set(geneIdsOf(inject))]; // dedup: a duplicated inject id must not double-emit (#275 Bugbot)
29
+ if (geneIds.length === 0)
30
+ return 0;
31
+ // Per-gene state from prior ticks (#275 Bugbot). A `used` verdict is TERMINAL — using a gene is monotonic as the
32
+ // transcript grows, so once used it stays used. `unused`/`unknown` are PROVISIONAL: the ingest tick can run while
33
+ // a transcript is still growing, so a later tick (longer transcript) may UPGRADE them to `used`. Therefore: skip
34
+ // genes already `used`; emit a first verdict; for a gene that only has a provisional verdict, emit ONLY when it
35
+ // now upgrades to `used` — never duplicate the same provisional, and never lock a stale `unused`.
36
+ const usedGenes = new Set();
37
+ const seenGenes = new Set();
38
+ for (const e of evts) {
39
+ if (e.type !== ops.VALUE_RECALL_EVENT || e.payload?.['sessionId'] !== sessionId)
40
+ continue;
41
+ const gid = e.payload['geneId'];
42
+ if (typeof gid !== 'string')
43
+ continue;
44
+ seenGenes.add(gid);
45
+ if (e.payload['recalled'] === 'used')
46
+ usedGenes.add(gid);
47
+ }
48
+ const store = deps.store ?? new assetstore.LocalJsonlProvider(events.assetsDir());
49
+ const genes = [];
50
+ for (const id of geneIds) {
51
+ const a = await resolveGene(store, id);
52
+ if (a)
53
+ genes.push(geneFromAsset(a));
54
+ }
55
+ if (genes.length === 0)
56
+ return 0;
57
+ const results = ops.verifyInjectedGenes(genes, turns);
58
+ let emitted = 0;
59
+ for (const r of results) {
60
+ if (usedGenes.has(r.geneId))
61
+ continue; // terminal: already used
62
+ if (seenGenes.has(r.geneId) && r.recalled !== 'used')
63
+ continue; // provisional already recorded; only an upgrade to `used` is new
64
+ const payload = { geneId: r.geneId, recalled: r.recalled, score: r.score, sessionId };
65
+ try {
66
+ await deps.ingestor.ingest({
67
+ type: ops.VALUE_RECALL_EVENT,
68
+ human: { title: `recall ${r.recalled}: ${r.geneId}`, detail: `session ${sessionId}` },
69
+ payload: payload,
70
+ });
71
+ emitted += 1;
72
+ }
73
+ catch { /* per-gene best-effort; keep going */ }
74
+ }
75
+ return emitted;
76
+ }
77
+ catch {
78
+ return 0;
79
+ }
80
+ }