Every AI system collects bugs over time: runtime errors, edge-case regressions, memory entries that drift from what is true. A human engineer usually catches them in code review or an incident postmortem, and then the cycle repeats. We got tired of the cycle, so we built a loop that closes it, and we open-sourced the result at github.com/muninnravenbot-ux/agent-self-improvement.
This post walks through every stage of that loop, why each stage exists and the failure each one prevents. It runs in production on the same agent system we build client automations on, including the AI employees we run for clients.
Stage 1: gathering signals that matter
Most self-improvement proposals start with external feedback: user ratings, thumbs-down buttons, helpfulness scores. We start with the agent's own error log, because a runtime exception is a verified fact and a user rating is an opinion. When you are deciding whether to apply a patch automatically, you want facts.
The signal gatherer reads from four sources in parallel: the structured error log (exception type, stack frame, frequency), the agent's reasoning output where it flagged its own uncertainty, the diff of newly merged changes, and the memory store's own staleness markers. Each source produces typed records with a severity, a location and a reproducibility count, rather than raw log lines. Anything seen fewer than twice gets held, because single-occurrence noise is not worth an automated patch.
The reproducibility filter matters. Without it, the loop burns compute chasing one-off environment quirks and produces patches for conditions that never recur.
Stage 2: an applicability review before touching a file
The gathered signals go to an LLM review pass. It asks whether the signal comes from code we own, and whether an automated fix is appropriate, before anyone asks how to fix it. That distinction matters in practice.
Some errors are upstream library regressions. Some are environment-specific, such as a missing env var in staging that is set in production. Some are policy failures: the agent did something it should not do, and the fix is a change in behaviour rather than in code. An automated code patch for any of these would make things worse.
The reviewer returns one of three verdicts: patch (owned code, clear root cause, automatable), escalate (needs a human or a policy decision), or defer (worth watching but not acting on yet). Only patch verdicts go on. The other two go into a human-readable queue. That is deliberate: the loop handles the mechanical majority and hands over the hard remainder cleanly, instead of pretending every problem can be solved without judgment.
Stage 3: drafting the fix in an isolated worktree
Once a signal is cleared for patching, the loop checks out an isolated git worktree: a fresh directory pointing at the same repository, on its own branch. The main working tree is never touched during this phase, and that isolation is a correctness requirement.
If drafting the patch crashes, runs too long or produces garbage, the main tree is unaffected. There is no partial-write state to clean up: the worktree branch gets deleted. Patching in place would mean any failure leaves the agent in an inconsistent state, and an AI agent in an inconsistent state is far worse than one that failed cleanly.
The drafter gets the signal record, the relevant source files and a strict constraint: touch only the files the signal implicates. No opportunistic clean-ups and no "while I'm here" refactors. The diff must be minimal and traceable to the specific error, and the structure enforces it: the drafter only has write access to the files the signal analysis identified.
Stage 4: smoke-testing with the real build tool
This is the stage most self-healing proposals skip or paper over, and it is the stage that makes everything else trustworthy.
A test that never runs what production runs is a false guarantee. We learned this directly: an earlier version of the loop ran tsc --noEmit as its smoke test, declared the patch valid when it passed, and merged. The type-checker passed and the runtime exploded. TypeScript's type system proves types without executing code, so a patch can be type-correct and functionally broken.
The smoke test now runs the actual build command: bun build in our case, whatever produces the artefact that runs in production in yours. Then it launches the agent process under a test fixture that replays the exact message sequence that triggered the error. The test passes only when the agent completes that sequence without the error. Anything less is a hope.
// not this — type-correct ≠ runtime-correct
npx tsc --noEmit
// this — run what production actually runs
bun build && bun run test:replay --fixture=error-${signalId}
If the smoke test fails, the worktree branch is deleted, the signal goes to the human queue with the failed test output attached, and the loop moves on. Nothing merges, and no state is corrupted.
Stage 5: a gated merge, not an auto-merge
A patch that passes the smoke test still does not merge on its own. It opens a pull request and pings a guardian: in our setup, a human approver for anything touching core agent logic, and an automated guardian for peripheral tooling. Core logic changes have a blast radius across the whole agent, while a bug in the tool that formats output stays contained.
The guardian receives a structured summary: the signal record, the root cause analysis, the diff, the smoke test output and the result of the reproduction fixture. That is enough to approve or reject in under two minutes. The aim is to make every human decision cost two minutes instead of two hours of archaeology.
On the automated guardian path, the merge gate enforces two hard rules: the diff must touch fewer than five files, and the patch must not modify any file that a human commit also changed in the last 24 hours. Both rules keep the loop from merging into an area under active development and creating conflicts that cost more time than the loop saves.
Stage 6: memory consolidation that never drops critical entries
After a successful merge, the loop updates the agent's memory with a structured consolidation step that answers three questions: what was the error pattern, what was the fix, and what invariant does this establish from now on?
The third question pays compounding returns. Once the loop has established that "the build tool for this project is bun build, not tsc", every later patch for this project uses the right tool, and the loop never learns the same lesson twice.
Memory consolidation has its own protection rule. Critical entries, meaning anything tagged as a safety constraint, a gating rule or a verified production fact, can only be modified by the consolidation step and are never silently overwritten. If a patch's consolidation would contradict a critical entry, the loop logs a warning and escalates. That prevents a subtle failure where the loop "improves" itself into a state where it bypasses its own safety gates. Keeping stored facts honest is a problem of its own, and we solved it for a client in the memory reliability case study.
What the loop does not do
This loop does not replace code review for features, apply speculative improvements, or change agent policy or behaviour rules without human approval. Those are the three areas where "the agent made this change automatically" is not a defensible answer.
It handles the mechanical majority: reproducible runtime errors with clear root causes in code we own. That category is large in a production agent, and once the loop handles it, engineering attention goes to the cases that need judgment.
The design principle underneath all of it
Every stage follows one principle: nothing gets promoted to production without a verified artefact of correctness. An LLM's confidence doesn't count, and neither do passing types. It takes a real build, a real replay and a real diff in a real pull request. The moment you accept a symbolic check, such as a type-check, a lint pass or an LLM confidence score, in place of the artefact, you have brought back the original problem: a guarantee that exists only in theory.
The isolated worktree, the gated merge and the critical-entry protection all enforce that idea. The loop is only as trustworthy as its weakest verification step.
Read next: Why your AI's memory stores your questions as facts

