/** * AutoImproveJob — Phase 5 auto-improvement loop (G7). * * Reviews recent observations for a project, detects recurring patterns * (repeated queries, frequently-referenced files, common fixes), and * proposes memory edits as `pending` proposals with an audit trail. * * Contract (spec.md R1–R8): * - Trigger-driven with a debounce (every minObservations OR minIntervalMs), * fired from the observation-ingest path. Fire-and-forget; never throws. * - Pattern detection is RULE-BASED and never requires the LLM. LLM * enrichment is optional (only when `llm.isEnabled()`), best-effort, and * silent-degrades to the rule-based candidates on `{ok:false}`/throw. * - Review gate (`memory.autoImprove.reviewGate`, default false = auto-approve): * when false, each generated proposal is auto-applied in the same run * (apply via memoryRepo + flip status → approved + emit memory:auto-improved * + log). When true, proposals stay pending for surfacing via tools. * - apply/reject state machine: pending → approved | rejected (both terminal). * Missing / non-pending / project-mismatch / apply-throw → {ok:false, reason}. * * Test-isolation (mirrors Phase-3/4/6): the ctor accepts injectable * `observationStore`, `proposalStore`, `memoryRepo`, `llm`, and `idFactory` * seams. Defaults resolve lazily at run time so the closed-MemoryRepository * landmine (memory-crud.test.ts) does not poison auto-improve tests. */ import { z } from "zod"; import { type ProposalKind, type ProposalRecord, type ProposalStore } from "../../data/proposal/proposal-repository.js"; import { type Observation, type ObservationStore } from "../../data/memory/observation-repository.js"; import type { InsertMemoryInput, UpdateMemoryPatch } from "../../data/memory/memory-repository.js"; import type { LlmSurface } from "../memory/consolidator.js"; export interface PatternThresholds { minQueryHits: number; minFileHits: number; minFixHits: number; } export interface PatternCandidate { kind: ProposalKind; targetMemoryId: string | null; payload: ProposalRecord["payload"]; rationale: string; /** Dedup key within a single run (stable signature of the signal). */ signalKey: string; /** Origin of the candidate content draft. */ source: "rule-based" | "llm"; } export interface AutoImproveResult { improved: boolean; proposalsCreated: number; proposalsApplied: number; /** "llm" when the LLM enriched ≥1 candidate, else "rule-based". */ source: "llm" | "rule-based"; } export interface ApproveRejectResult { ok: boolean; proposal?: ProposalRecord; reason?: string; } /** * Injectable memory-apply seam. The default implementation resolves * getMemoryRepository() lazily inside each method (test-isolation). */ export interface MemoryApplySeam { insert(input: InsertMemoryInput): void | Promise; update(id: string, patch: UpdateMemoryPatch): boolean; } export interface AutoImproveJobOptions { llm?: LlmSurface; observationStore?: ObservationStore; proposalStore?: ProposalStore; memoryRepo?: MemoryApplySeam; minObservations?: number; minIntervalMs?: number; maxWindow?: number; thresholds?: Partial; /** Override the review-gate flag (else read from config). */ reviewGate?: boolean; idFactory?: () => string; } export declare const ProposalEnrichmentSchema: z.ZodObject<{ items: z.ZodArray>; }, z.core.$strip>; export type ProposalEnrichment = z.infer; /** * Count frequency signals from observation payloads. Pure + total: bad/missing * payload fields are skipped, never thrown. Returns one candidate per distinct * signal that meets its threshold. */ export declare function detectPatterns(observations: Observation[], thresholds: PatternThresholds): PatternCandidate[]; /** * Refine candidate content + rationale via a single LLM call. Silent-degrade: * on `{ok:false}`/throw/invalid → return the rule-based candidates verbatim. * Never throws. */ export declare function enrichWithLlm(candidates: PatternCandidate[], observations: Observation[], surface: LlmSurface): Promise<{ candidates: PatternCandidate[]; used: boolean; }>; export declare class AutoImproveJob { private readonly llm; private readonly observationStore; private readonly proposalStore; private readonly memoryRepo; private readonly thresholds; private readonly minObservations; private readonly minIntervalMs; private readonly maxWindow; private readonly reviewGateOverride; private readonly idFactory; private lastRunAt; private newSinceRun; /** Calls observed by tests. */ runCalls: number; constructor(opts?: AutoImproveJobOptions); private reviewGate; /** * Debounce-gated trigger from the observation-ingest path. Never awaits; * never throws. Resets counters and fires `runOnce` (fire-and-forget) when * either threshold is crossed. */ maybeRun(projectId: string): void; /** * Run one auto-improve pass for `projectId`. Detects patterns, persists * pending proposals, and (when reviewGate is false) auto-applies them. * Never throws. */ runOnce(projectId: string): Promise; approve(id: string, projectId?: string, source?: "llm" | "rule-based"): Promise; reject(id: string, projectId?: string, _reason?: string): Promise; /** * Apply a proposal's edit to the memory store. Returns the affected memory * id (fresh for create, existing for update/tag). Throws on failure * (caller catches → apply-failed). * * The payload is a loose union; we dispatch on `kind` and treat the payload * as a plain record within each branch (defensive reads, never throws to * the caller — the outer approve() catches). */ private applyProposal; listPending(projectId: string): ProposalRecord[]; } export declare function getAutoImproveJob(): AutoImproveJob; export declare function resetAutoImproveJob(): void; export declare const autoImproveJob: AutoImproveJob; //# sourceMappingURL=auto-improve-job.d.ts.map